code
stringlengths
3
10M
language
stringclasses
31 values
import utils; // send normal label event --> nothing unittest { setAPIExpectations( "/github/repos/dlang/phobos/issues/4921/labels", ); postGitHubHook("dlang_phobos_label_4921.json", "pull_request", (ref Json j, scope HTTPClientRequest req){ j["pull_request"]["state"] = "open"; }.toDelegate); } // send auto-merge label event, but closed PR --> nothing unittest { setAPIExpectations( "/github/repos/dlang/phobos/pulls/4921/commits", "/github/repos/dlang/phobos/issues/4921/labels", (ref Json j) { j[0]["name"] = "auto-merge"; }, ); postGitHubHook("dlang_phobos_label_4921.json"); } // send auto-merge label event --> try merge --> failure unittest { setAPIExpectations( "/github/repos/dlang/phobos/pulls/4921/commits", "/github/repos/dlang/phobos/issues/4921/labels", (ref Json j) { j[0]["name"] = "auto-merge"; }, "/github/repos/dlang/phobos/issues/4921/events", (ref Json j) { assert(j[1]["event"] == "labeled"); j[1]["label"]["name"] = "auto-merge"; }, "/github/users/9il", "/github/repos/dlang/phobos/pulls/4921/merge", (scope HTTPServerRequest req, scope HTTPServerResponse res) { // https://developer.github.com/v3/pulls/#response-if-merge-cannot-be-performed assert(req.json["sha"] == "d2c7d3761b73405ee39da3fd7fe5030dee35a39e"); assert(req.json["merge_method"] == "merge"); assert(req.json["commit_message"] == "Issue 8573 - A simpler Phobos function that returns the index of the …\n"~ "merged-on-behalf-of: Ilya Yaroshenko <testmail@example.com>"); res.statusCode = 405; } ); postGitHubHook("dlang_phobos_label_4921.json", "pull_request", (ref Json j, scope HTTPClientRequest req){ j["pull_request"]["state"] = "open"; }.toDelegate); } // send auto-merge-squash label event --> try merge --> success unittest { setAPIExpectations( "/github/repos/dlang/phobos/pulls/4921/commits", "/github/repos/dlang/phobos/issues/4921/labels", (ref Json j) { j[0]["name"] = "auto-merge-squash"; }, "/github/repos/dlang/phobos/issues/4921/events", (ref Json j) { assert(j[1]["event"] == "labeled"); j[1]["label"]["name"] = "auto-merge-squash"; }, "/github/users/9il", "/github/repos/dlang/phobos/pulls/4921/merge", (scope HTTPServerRequest req, scope HTTPServerResponse res) { assert(req.json["sha"] == "d2c7d3761b73405ee39da3fd7fe5030dee35a39e"); assert(req.json["merge_method"] == "squash"); assert(req.json["commit_message"] == "Issue 8573 - A simpler Phobos function that returns the index of the …\n"~ "merged-on-behalf-of: Ilya Yaroshenko <testmail@example.com>"); res.statusCode = 200; } ); postGitHubHook("dlang_phobos_label_4921.json", "pull_request", (ref Json j, scope HTTPClientRequest req){ j["pull_request"]["state"] = "open"; } ); } // test whether users can label their PR via the title unittest { setAPIExpectations( "/github/repos/dlang/dmd/pulls/6359/commits", (ref Json json) { json = Json.emptyArray; }, "/github/repos/dlang/dmd/issues/6359/comments", "/github/repos/dlang/dmd/issues/6359/comments", "/github/orgs/dlang/public_members", "/github/repos/dlang/dmd/issues/6359/labels", (scope HTTPServerRequest req, scope HTTPServerResponse res) { assert(req.method == HTTPMethod.POST); assert(req.json.deserializeJson!(string[]) == ["trivial"]); res.writeVoidBody; } ); postGitHubHook("dlang_dmd_open_6359.json", "pull_request", (ref Json j, scope HTTPClientRequest req){ j["pull_request"]["title"] = "[Trivial] foo bar"; } ); } // test that not only a selection of labels is accepted unittest { setAPIExpectations( "/github/repos/dlang/dmd/pulls/6359/commits", (ref Json json) { json = Json.emptyArray; }, "/github/repos/dlang/dmd/issues/6359/comments", "/github/repos/dlang/dmd/issues/6359/comments", "/github/orgs/dlang/public_members", ); postGitHubHook("dlang_dmd_open_6359.json", "pull_request", (ref Json j, scope HTTPClientRequest req){ j["pull_request"]["title"] = "[auto-merge] foo bar"; } ); }
D
module ppl.ast.stmt.Statement; import ppl.internal; abstract class Statement : ASTNode { /** True if this Statement is not used and can be removed */ bool isZombie = false; // todo - implement me }
D
// ****************** // NSC benutzt Amboss // ****************** FUNC VOID ZS_Smith_Anvil () { Perception_Set_Normal(); B_UseHat (self); B_ResetAll (self); if (self.aivar[AIV_Schwierigkeitsgrad] < Mod_Schwierigkeit) || (self.aivar[AIV_Schwierigkeitsgrad] > Mod_Schwierigkeit) { B_SetSchwierigkeit(); }; AI_SetWalkmode (self, NPC_WALK); if (Hlp_StrCmp (Npc_GetNearestWP(self), self.wp) == FALSE) { AI_GotoWP (self, self.wp); }; }; FUNC int ZS_Smith_Anvil_Loop () { // ------ Schmieden ------ if (!C_BodyStateContains(self, BS_MOBINTERACT_INTERRUPT)) && (Wld_IsMobAvailable(self,"BSANVIL")) { AI_UseMob (self, "BSANVIL", 1); }; return LOOP_CONTINUE; }; FUNC VOID ZS_Smith_Anvil_End () { AI_UseMob (self, "BSANVIL", -1); };
D
module li_std_vector_runme; import std.algorithm; import std.array; import std.conv; import std.exception; import std.stdio; import li_std_vector.li_std_vector; import li_std_vector.DoubleVector; import li_std_vector.IntVector; import li_std_vector.IntPtrVector; import li_std_vector.IntConstPtrVector; import li_std_vector.RealVector; import li_std_vector.Struct; import li_std_vector.StructVector; import li_std_vector.StructPtrVector; import li_std_vector.StructConstPtrVector; const size_t SIZE = 20; void main() { // Basic functionality tests. { auto vector = new IntVector(); foreach (int i; 0 .. SIZE) { vector ~= i * 10; } enforce(vector.length == SIZE, "length test failed."); vector[0] = 200; enforce(vector[0] == 200, "indexing test failed"); vector[0] = 0 * 10; enforceThrows((){ vector[vector.length] = 777; }, "out of range test failed" ); foreach (i, value; vector) { enforce(value == (i * 10), "foreach test failed, i: " ~ to!string(i)); } enforce(canFind!`a == 0 * 10`(vector[]), "canFind test 1 failed"); enforce(canFind!`a == 10 * 10`(vector[]), "canFind test 2 failed"); enforce(canFind!`a == 19 * 10`(vector[]), "canFind test 3 failed"); enforce(!canFind!`a == 20 * 10`(vector[]), "canFind test 4 failed"); foreach (i, _; vector) { enforce(countUntil(vector[], i * 10) == i, "indexOf test failed, i: " ~ to!string(i)); } enforce(countUntil(vector[], 42) == -1, "non-existant item indexOf test failed"); vector.clear(); enforce(vector.length == 0, "clear test failed"); } // To array conversion tests. { auto dVector = new DoubleVector(); foreach (i; 0 .. SIZE) { dVector ~= i * 10.1f; } double[] dArray = array(dVector[]); foreach (i, value; dArray) { enforce(dVector[i] == value, "slice test 1 failed, i: " ~ to!string(i)); } auto sVector = new StructVector(); foreach (i; 0 .. SIZE) { sVector ~= new Struct(i / 10.0); } Struct[] sArray = array(sVector[]); foreach (i; 0 .. SIZE) { // Make sure that a shallow copy has been made. void* aPtr = Struct.swigGetCPtr(sArray[i]); void* vPtr = Struct.swigGetCPtr(sVector[i]); enforce(aPtr == vPtr, "slice test 2 failed, i: " ~ to!string(i)); } } // remove() tests. { auto iVector = new IntVector(); foreach (int i; 0 .. SIZE) { iVector ~= i; } iVector.remove(iVector.length - 1); iVector.remove(SIZE / 2); iVector.remove(0); enforceThrows((){ iVector.remove(iVector.length); }, "remove test failed"); } // Capacity tests. { auto dv = new DoubleVector(10); enforce(dv.capacity == 10, "constructor setting capacity test failed (1)"); enforce(dv.length == 0, "constructor setting capacity test failed (1)"); dv.reserve(20); enforce(dv.capacity == 20, "capacity test failed"); } // Test the methods being wrapped. { auto iv = new IntVector(); foreach (int i; 0 .. 4) { iv ~= i; } double x = average(iv); x += average(new IntVector([1, 2, 3, 4])); RealVector rv = half(new RealVector([10.0f, 10.5f, 11.0f, 11.5f])); auto dv = new DoubleVector(); foreach (i; 0 .. SIZE) { dv ~= i / 2.0; } halve_in_place(dv); RealVector v0 = vecreal(new RealVector()); float flo = 123.456f; v0 ~= flo; flo = v0[0]; IntVector v1 = vecintptr(new IntVector()); IntPtrVector v2 = vecintptr(new IntPtrVector()); IntConstPtrVector v3 = vecintconstptr(new IntConstPtrVector()); v1 ~= 123; v2.clear(); v3.clear(); StructVector v4 = vecstruct(new StructVector()); StructPtrVector v5 = vecstructptr(new StructPtrVector()); StructConstPtrVector v6 = vecstructconstptr(new StructConstPtrVector()); v4 ~= new Struct(123); v5 ~= new Struct(123); v6 ~= new Struct(123); } // Test vectors of pointers. { auto vector = new StructPtrVector(); foreach (i; 0 .. SIZE) { vector ~= new Struct(i / 10.0); } Struct[] array = array(vector[]); foreach (i; 0 .. SIZE) { // Make sure that a shallow copy has been made. void* aPtr = Struct.swigGetCPtr(array[i]); void* vPtr = Struct.swigGetCPtr(vector[i]); enforce(aPtr == vPtr, "StructConstPtrVector test 1 failed, i: " ~ to!string(i)); } } // Test vectors of const pointers. { auto vector = new StructConstPtrVector(); foreach (i; 0 .. SIZE) { vector ~= new Struct(i / 10.0); } Struct[] array = array(vector[]); foreach (i; 0 .. SIZE) { // Make sure that a shallow copy has been made. void* aPtr = Struct.swigGetCPtr(array[i]); void* vPtr = Struct.swigGetCPtr(vector[i]); enforce(aPtr == vPtr, "StructConstPtrVector test 1 failed, i: " ~ to!string(i)); } } // Test vectors destroyed via scope. { { scope vector = new StructVector(); vector ~= new Struct(0.0); vector ~= new Struct(11.1); } { scope vector = new DoubleVector(); vector ~= 0.0; vector ~= 11.1; } } } private void enforceThrows(void delegate() dg, string errorMessage) { bool hasThrown; try { dg(); } catch (Exception) { hasThrown = true; } finally { if (!hasThrown) { throw new Exception(errorMessage); } } }
D
module https; import requests; import std.experimental.logger; version(vibeD) { } else { unittest { globalLogLevel(LogLevel.info); auto rq = Request(); rq.keepAlive = false; info("Testing https using google.com"); auto rs = rq.get("https://google.com"); assert(rs.responseBody.length > 0); } } version(unittest_fakemain) { void main () {} }
D
var int bartholo_key_removed; instance DIA_BARTHOLO_EXIT(C_INFO) { npc = ebr_106_bartholo; nr = 999; condition = dia_bartholo_exit_condition; information = dia_bartholo_exit_info; permanent = 1; description = DIALOG_ENDE; }; func int dia_bartholo_exit_condition() { return 1; }; func void dia_bartholo_exit_info() { if(!Npc_HasItems(self,itke_storage_01) && bartholo_key_removed == 1) { CreateInvItem(self,itke_storage_01); bartholo_key_removed = 0; }; AI_StopProcessInfos(self); }; instance INFO_BARTHOLO_HALLO(C_INFO) { npc = ebr_106_bartholo; nr = 4; condition = info_bartholo_hallo_condition; information = info_bartholo_hallo_info; permanent = 0; description = "Кто ты?"; }; func int info_bartholo_hallo_condition() { return 1; }; func void info_bartholo_hallo_info() { AI_Output(other,self,"Info_Bartholo_HAllo_15_00"); //Кто ты? AI_Output(self,other,"Info_Bartholo_HAllo_12_01"); //Я Бартоло. Слежу, чтобы Бароны получали припасы вовремя. AI_Output(self,other,"Info_Bartholo_HAllo_12_02"); //Еда, болотник, продовольствие для женщин... AI_Output(self,other,"Info_Bartholo_HAllo_12_03"); //Также приходится следить за этими идиотами поварами. AI_Output(self,other,"Info_Bartholo_HAllo_12_04"); //Гомез не любит оплошностей. Последних двух поваров он скормил речным шныгам. Log_CreateTopic(GE_TRADEROC,LOG_NOTE); b_logentry(GE_TRADEROC,"У Бартоло можно купить еду, болотник и прочие припасы. Я могу найти его в замке Баронов."); }; instance INFO_BARTHOLO_PERM(C_INFO) { npc = ebr_106_bartholo; nr = 4; condition = info_bartholo_perm_condition; information = info_bartholo_perm_info; permanent = 1; description = "Я хочу поторговать с тобой."; trade = 1; }; func int info_bartholo_perm_condition() { if((KAPITEL <= 3) && Npc_KnowsInfo(hero,info_bartholo_hallo)) { return 1; }; }; func void info_bartholo_perm_info() { AI_Output(other,self,"Info_Bartholo_PERM_15_00"); //Я хочу поторговать с тобой. AI_Output(self,other,"Info_Bartholo_PERM_12_01"); //У меня много чего есть для тех, у кого есть руда, конечно. if(Npc_HasItems(self,itke_storage_01)) { Npc_RemoveInvItems(self,itke_storage_01,1); bartholo_key_removed = 1; }; if(Npc_HasItems(self,itmilute)) { Npc_RemoveInvItems(self,itmilute,Npc_HasItems(self,itmilute)); }; }; instance INFO_BARTHOLO_KRAUTBOTE(C_INFO) { npc = ebr_106_bartholo; nr = 4; condition = info_bartholo_krautbote_condition; information = info_bartholo_krautbote_info; permanent = 1; description = "У меня болотник для Гомеза. Его послал Кор Галом."; }; func int info_bartholo_krautbote_condition() { if(KALOM_KRAUTBOTE == LOG_RUNNING && KALOM_DELIVEREDWEED == FALSE) { return 1; }; }; func void info_bartholo_krautbote_info() { AI_Output(other,self,"Info_Bartholo_Krautbote_15_00"); //У меня болотник для Гомеза. Его послал Кор Галом. AI_Output(self,other,"Info_Bartholo_Krautbote_12_01"); //Покажи! if(Npc_HasItems(other,itmijoint_3) >= 30) { b_printtrademsg1("Отдан болотник (30)."); AI_Output(self,other,"Info_Bartholo_Krautbote_12_02"); //М-ммммммммм... AI_Output(self,other,"Info_Bartholo_Krautbote_12_03"); //Это хорошо. А то Гомез уже начал терять терпение. Это просто удача, что ты объявился сегодня. AI_Output(other,self,"Info_Bartholo_Krautbote_15_04"); //Как насчет платы? AI_Output(self,other,"Info_Bartholo_Krautbote_12_05"); //Не так быстро... Вот, держи. Как договаривались - пять сотен. b_printtrademsg2("Получено руды: 500"); b_giveinvitems(other,self,itmijoint_3,30); CreateInvItems(self,itminugget,500); b_giveinvitems(self,other,itminugget,500); KALOM_DELIVEREDWEED = TRUE; b_logentry(CH1_KRAUTBOTE,"Бартоло дал мне 500 кусков руды за болотник, который я принес для Гомеза."); b_givexp(XP_WEEDSHIPMENTDELIVERED); } else { AI_Output(other,self,"KDW_600_Saturas_TIMESUP_Info_15_01"); //Ну... AI_Output(self,other,"Info_Bartholo_Krautbote_NoKraut_12_00"); //У тебя слишком мало болотника! Надеюсь, ты не продал его на сторону. Будет нормальный запас, тогда и приходи. AI_StopProcessInfos(self); }; }; instance DIA_EBR_106_BARTHOLO_WAIT4SC(C_INFO) { npc = ebr_598_bartholo; condition = dia_ebr_106_bartholo_wait4sc_condition; information = dia_ebr_106_bartholo_wait4sc_info; important = 1; permanent = 0; }; func int dia_ebr_106_bartholo_wait4sc_condition() { if(EXPLORESUNKENTOWER && (Npc_CanSeeNpcFreeLOS(self,hero)) && (Npc_GetDistToNpc(self,hero) < 1400) && Npc_HasItems(hero,itarrune_1_3_teleport1)) { return TRUE; }; }; func void dia_ebr_106_bartholo_wait4sc_info() { var C_NPC grd_220; var C_NPC grd_221; AI_SetWalkMode(self,NPC_WALK); AI_UnreadySpell(hero); AI_GotoNpc(self,other); AI_Output(self,other,"Info_Bartholo_12_01"); //Я знал, что кто-нибудь попытается добраться до нас через пентаграмму! AI_Output(self,other,"Info_Bartholo_12_02"); //Но в отличие от этого предателя кузнеца Стоуна, ты нам больше не нужен! AI_Output(other,self,"Info_Bartholo_15_03"); //Где Стоун? AI_Output(self,other,"Info_Bartholo_12_04"); //За решеткой! А ты через минуту окажешься на полметра ниже. AI_Output(self,other,"Info_Bartholo_12_05"); //Взять его, парни! Порубить на куски! AI_StopProcessInfos(self); self.guild = GIL_EBR; Npc_SetTrueGuild(self,GIL_EBR); b_setpermattitude(self,ATT_HOSTILE); grd_220 = Hlp_GetNpc(grd_220_gardist); grd_221 = Hlp_GetNpc(grd_221_gardist); grd_220.guild = GIL_GRD; Npc_SetTrueGuild(grd_220,GIL_GRD); grd_221.guild = GIL_GRD; Npc_SetTrueGuild(grd_221,GIL_GRD); b_setpermattitude(grd_220,ATT_HOSTILE); b_setpermattitude(grd_221,ATT_HOSTILE); }; instance DIA_EBR_106_BARTHOLO_WAIT4SC2(C_INFO) { npc = ebr_598_bartholo; condition = dia_ebr_106_bartholo_wait4sc2_condition; information = dia_ebr_106_bartholo_wait4sc2_info; important = 1; permanent = 0; }; func int dia_ebr_106_bartholo_wait4sc2_condition() { if(KAPITEL > 3 && !Npc_HasItems(hero,itarrune_1_3_teleport1) && (Npc_CanSeeNpcFreeLOS(self,hero)) && (Npc_GetDistToNpc(self,hero) < 1400)) { return TRUE; }; }; func void dia_ebr_106_bartholo_wait4sc2_info() { var C_NPC grd_220; var C_NPC grd_221; AI_SetWalkMode(self,NPC_WALK); AI_UnreadySpell(hero); AI_GotoNpc(self,other); AI_Output(self,other,"SVM_12_YouViolatedForbiddenTerritory"); //Что это ты здесь делаешь? AI_Output(self,other,"Info_Bartholo_12_05"); //Взять его, парни! Порубить на куски! if(!Npc_KnowsInfo(hero,info_cutter_die) && !Npc_KnowsInfo(hero,info_fletcher_die) && !Npc_KnowsInfo(hero,info_grd238_die)) { Wld_ExchangeGuildAttitudes("GIL_ATTITUDES_FMTAKEN"); }; OC_BANNED = TRUE; FREELEARN_OC = FALSE; if(c_npcbelongstooldcamp(hero)) { Npc_SetTrueGuild(hero,GIL_NONE); hero.guild = GIL_NONE; }; AI_StopProcessInfos(self); self.guild = GIL_EBR; Npc_SetTrueGuild(self,GIL_EBR); b_setpermattitude(self,ATT_HOSTILE); grd_220 = Hlp_GetNpc(grd_220_gardist); grd_221 = Hlp_GetNpc(grd_221_gardist); grd_220.guild = GIL_GRD; Npc_SetTrueGuild(grd_220,GIL_GRD); grd_221.guild = GIL_GRD; Npc_SetTrueGuild(grd_221,GIL_GRD); b_setpermattitude(grd_220,ATT_HOSTILE); b_setpermattitude(grd_221,ATT_HOSTILE); };
D
module pegged.examples.xml2; enum XMLgrammar = ` XML: Document <- prolog element Misc* Char <- . # RestrictedChar <- [\u0001-\uD7FF\uE000-\uFFFD] #\U00010000-\U0010FFFF] S <- ('\x20' / '\x09' / '\x0D' / '\x0A')+ NameStartChar <- ":" / [A-Z] / "_" / [a-z] / [\xC0-\xD6\xD8-\xF6] # \xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD] # \U00010000-\U000EFFFF] NameChar <- NameStartChar / "-" / "." / [0-9] / '\xB7' # / [\u0300-\u036F] / [\x203F-\x2040] Name <~ NameStartChar (NameChar)* Names <- Name (' ' Name)* Nmtoken <~ (NameChar)+ nmtokens <- Nmtoken (' ' Nmtoken)* EntityValue <- DoubleQuote (!('%' / '&' / DoubleQuote) Char / PEReference / Reference)* DoubleQuote / Quote (!('%' / '&' / Quote) Char / PEReference / Reference)* Quote AttValue <- DoubleQuote (!('%' / '&' / DoubleQuote) Char / Reference)* DoubleQuote / Quote (!('%' / '&' / Quote) Char / Reference)* Quote SystemLiteral <~ DoubleQuote (!DoubleQuote Char)* DoubleQuote / Quote (!Quote Char)* Quote PubidLiteral <~ DoubleQuote PubidChar* DoubleQuote / Quote (!Quote PubidChar)* Quote PubidChar <- [\x20\x0D\x0A] / [a-zA-Z0-9] / [-'()+,./:=?;!*#@$_%] CharData <~ (!('<' / '&' / "]]>" ) Char)* Comment <- "<!--" ~(!'-' Char / '-' !'-' Char)* "-->" PI <- "<?" PITarget (S (!"?>" Char)*)? "?>" PITarget <- !([xX][mM][lL]) Name CDSect <- CDStart CData CDEnd CDStart <- "<![CDATA[" CData <- (!"]]>" Char)* CDEnd <- "]]>" prolog <- XMLDecl Misc* (doctypedecl Misc*)? XMLDecl <- "<?xml" VersionInfo EncodingDecl? SDDecl? S? "?>" VersionInfo <- S "version" Eq (Quote VersionNum Quote / DoubleQuote VersionNum DoubleQuote) Eq <- S? '=' S? VersionNum <- "1.1" Misc <- Comment / PI / S doctypedecl <- "<!DOCTYPE" S Name (S ExternalID)? S? ('[' intSubset ']' S?)? '>' DeclSep <- PEReference / S intSubset <- (markupdecl / DeclSep)* markupdecl <- elementdecl / AttlistDecl / EntityDecl / NotationDecl / PI / Comment extSubset <- TextDecl? extSubsetDecl extSubsetDecl <- (markupdecl / conditionalSect / DeclSep)* SDDecl <- S 'standalone' Eq ( DoubleQuote ("yes"/"no") DoubleQuote / Quote ("yes"/"no") Quote) element <- EmptyElemTag / STag content ETag STag <- "<" Name (S Attribute)* S? ">" Attribute <- Name Eq AttValue ETag <- "</" Name S? ">" content <- CharData? ((element / Reference / CDSect / PI / Comment) CharData?)* EmptyElemTag <- "<" (S Attribute)* S? "/>" elementdecl <- "<!ELEMENT" S Name S contentspec S? ">" contentspec <- "EMPTY" / "ANY" / Mixed / children children <- (choice / seq) ('?' / '*' / '+')? cp <- (Name / choice / seq) ('?' / '*' / '+')? choice <- '(' S? cp ( S? '|' S? cp )+ S? ')' seq <- '(' S? cp ( S? ',' S? cp )* S? ')' Mixed <- '(' S? "#PCDATA" (S? '|' S? Name)* S? ")*" / '(' S? "#PCDATA" S? ")" AttlistDecl <- "<!ATTLIST" S Name AttDef* S? ">" AttDef <- S Name S AttType S DefaultDecl AttType <- StringType / TokenizedType / EnumeratedType StringType <- "CDATA" TokenizedType <- "IDREFS" / "IDREF" / "ID" / "ENTITIES" / "ENTITY" / "NMTOKENS" / "NMTOKEN" EnumeratedType <- NotationType / Enumeration NotationType <- "NOTATION" S "(" S? Name (S? '|' S? Name)* S? ')' Enumeration <- '(' S? Nmtoken (S? '|' S? Nmtoken)* S? ')' DefaultDecl <- "#REQUIRED" / "#IMPLIED" / (("#FIXED" S)? AttValue) conditionalSect <- includeSect / ignoreSect includeSect <- "<![" S? "INCLUDE" S? "[" extSubsetDecl "]]>" ignoreSect <- "<![" S? "IGNORE" S? "[" ignoreSectContents* "]]>" ignoreSectContents <- Ignore ("<![" ignoreSectContents "]]>" Ignore)* Ignore <- (!("<![" / "]]>") Char)* CharRef <- "&#" [0-9]+ ";" / "&#x" [0-9a-fA-F]+ ";" Reference <- EntityRef / CharRef EntityRef <- '&' Name ';' PEReference <- '%' Name ';' EntityDecl <- GEDecl / PEDecl GEDecl <- "<!ENTITY" S Name S EntityDef S? '>' PEDecl <- "<!ENTITY" S '%' S Name S PEDef S? '>' EntityDef <- EntityValue / (ExternalID NDataDecl?) PEDef <- EntityValue / ExternalID ExternalID <- "SYSTEM" S SystemLiteral / "PUBLIC" S PubidLiteral S SystemLiteral NDataDecl <- S "NDATA" S Name TextDecl <- "<?xml" VersionInfo? EncodingDecl S? "?>" extParsedEnt <- (TextDecl? content) EncodingDecl <- S "encoding" Eq ( DoubleQuote EncName DoubleQuote / Quote EncName Quote) EncName <~ [A-Za-z] ([A-Za-z0-9._] / '-')* NotationDecl <- "<!NOTATION" S Name S (ExternalID / PublicID) S? ">" PublicID <- "PUBLIC" S PubidLiteral `;
D
import vibe.d; void handleRequest(HttpServerRequest req, HttpServerResponse res) { res.redirect("/index.html"); } static this() { auto settings = new HttpServerSettings; settings.port = 8080; auto router = new UrlRouter; router.get("/", &handleRequest); router.get("*", serveStaticFiles("./public/")); listenHttp(settings, router); }
D
/Users/Lambert/Desktop/demo/DerivedData/demo1/Build/Intermediates/demo1.build/Debug/Spectre.build/Objects-normal/x86_64/Global.o : /Users/Lambert/Desktop/demo/Packages/Spectre-0.7.2/Sources/Case.swift /Users/Lambert/Desktop/demo/Packages/Spectre-0.7.2/Sources/Context.swift /Users/Lambert/Desktop/demo/Packages/Spectre-0.7.2/Sources/Expectation.swift /Users/Lambert/Desktop/demo/Packages/Spectre-0.7.2/Sources/Failure.swift /Users/Lambert/Desktop/demo/Packages/Spectre-0.7.2/Sources/Global.swift /Users/Lambert/Desktop/demo/Packages/Spectre-0.7.2/Sources/GlobalContext.swift /Users/Lambert/Desktop/demo/Packages/Spectre-0.7.2/Sources/Reporter.swift /Users/Lambert/Desktop/demo/Packages/Spectre-0.7.2/Sources/Reporters.swift /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Users/Lambert/Desktop/demo/DerivedData/demo1/Build/Intermediates/demo1.build/Debug/Spectre.build/Objects-normal/x86_64/Global~partial.swiftmodule : /Users/Lambert/Desktop/demo/Packages/Spectre-0.7.2/Sources/Case.swift /Users/Lambert/Desktop/demo/Packages/Spectre-0.7.2/Sources/Context.swift /Users/Lambert/Desktop/demo/Packages/Spectre-0.7.2/Sources/Expectation.swift /Users/Lambert/Desktop/demo/Packages/Spectre-0.7.2/Sources/Failure.swift /Users/Lambert/Desktop/demo/Packages/Spectre-0.7.2/Sources/Global.swift /Users/Lambert/Desktop/demo/Packages/Spectre-0.7.2/Sources/GlobalContext.swift /Users/Lambert/Desktop/demo/Packages/Spectre-0.7.2/Sources/Reporter.swift /Users/Lambert/Desktop/demo/Packages/Spectre-0.7.2/Sources/Reporters.swift /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Users/Lambert/Desktop/demo/DerivedData/demo1/Build/Intermediates/demo1.build/Debug/Spectre.build/Objects-normal/x86_64/Global~partial.swiftdoc : /Users/Lambert/Desktop/demo/Packages/Spectre-0.7.2/Sources/Case.swift /Users/Lambert/Desktop/demo/Packages/Spectre-0.7.2/Sources/Context.swift /Users/Lambert/Desktop/demo/Packages/Spectre-0.7.2/Sources/Expectation.swift /Users/Lambert/Desktop/demo/Packages/Spectre-0.7.2/Sources/Failure.swift /Users/Lambert/Desktop/demo/Packages/Spectre-0.7.2/Sources/Global.swift /Users/Lambert/Desktop/demo/Packages/Spectre-0.7.2/Sources/GlobalContext.swift /Users/Lambert/Desktop/demo/Packages/Spectre-0.7.2/Sources/Reporter.swift /Users/Lambert/Desktop/demo/Packages/Spectre-0.7.2/Sources/Reporters.swift /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule
D
/Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Build/Intermediates/Pods.build/Debug-iphonesimulator/TextFieldEffects.build/Objects-normal/x86_64/HoshiTextField.o : /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/MadokaTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/AkiraTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/KaedeTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/HoshiTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/IsaoTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/YoshikoTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/YokoTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/JiroTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/MinoruTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/TextFieldEffects.swift /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/Target\ Support\ Files/TextFieldEffects/TextFieldEffects-umbrella.h /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Build/Intermediates/Pods.build/Debug-iphonesimulator/TextFieldEffects.build/unextended-module.modulemap /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Build/Intermediates/Pods.build/Debug-iphonesimulator/TextFieldEffects.build/Objects-normal/x86_64/HoshiTextField~partial.swiftmodule : /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/MadokaTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/AkiraTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/KaedeTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/HoshiTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/IsaoTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/YoshikoTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/YokoTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/JiroTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/MinoruTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/TextFieldEffects.swift /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/Target\ Support\ Files/TextFieldEffects/TextFieldEffects-umbrella.h /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Build/Intermediates/Pods.build/Debug-iphonesimulator/TextFieldEffects.build/unextended-module.modulemap /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Build/Intermediates/Pods.build/Debug-iphonesimulator/TextFieldEffects.build/Objects-normal/x86_64/HoshiTextField~partial.swiftdoc : /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/MadokaTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/AkiraTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/KaedeTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/HoshiTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/IsaoTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/YoshikoTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/YokoTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/JiroTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/MinoruTextField.swift /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/TextFieldEffects.swift /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Pods/Target\ Support\ Files/TextFieldEffects/TextFieldEffects-umbrella.h /Users/davalcato/Desktop/iOS/Snap(Knock-Off)/Build/Intermediates/Pods.build/Debug-iphonesimulator/TextFieldEffects.build/unextended-module.modulemap /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
D
func void B_CheckDeadMissionNPCs() { if(Hlp_GetInstanceID(Org_844_Lefty) == Hlp_GetInstanceID(self)) { if(Lefty_Mission == LOG_RUNNING) { B_LogEntry(CH1_CarryWater,"После смерти Лефти проблема с водой была решена. Этот тип все равно был невыносим."); Log_SetTopicStatus(CH1_CarryWater,LOG_SUCCESS); LeftyDead = TRUE; }; }; };
D
/* * Licensed under the GNU Lesser General Public License Version 3 * * This library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the license, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see <http://www.gnu.org/licenses/>. */ // generated automatically - do not change module glib.Bytes; private import gi.glib; public import gi.glibtypes; private import glib.ByteArray; private import glib.ConstructionException; /** * A simple refcounted data type representing an immutable sequence of zero or * more bytes from an unspecified origin. * * The purpose of a #GBytes is to keep the memory region that it holds * alive for as long as anyone holds a reference to the bytes. When * the last reference count is dropped, the memory is released. Multiple * unrelated callers can use byte data in the #GBytes without coordinating * their activities, resting assured that the byte data will not change or * move while they hold a reference. * * A #GBytes can come from many different origins that may have * different procedures for freeing the memory region. Examples are * memory from g_malloc(), from memory slices, from a #GMappedFile or * memory from other allocators. * * #GBytes work well as keys in #GHashTable. Use g_bytes_equal() and * g_bytes_hash() as parameters to g_hash_table_new() or g_hash_table_new_full(). * #GBytes can also be used as keys in a #GTree by passing the g_bytes_compare() * function to g_tree_new(). * * The data pointed to by this bytes must not be modified. For a mutable * array of bytes see #GByteArray. Use g_bytes_unref_to_array() to create a * mutable array for a #GBytes sequence. To create an immutable #GBytes from * a mutable #GByteArray, use the g_byte_array_free_to_bytes() function. * * Since: 2.32 */ public class Bytes { /** the main GObject struct */ protected GBytes* gBytes; /** Get the main GObject struct */ public GBytes* getBytesStruct() { return gBytes; } /** the main GObject struct as a void* */ protected void* getStruct() { return cast(void*)gBytes; } /** * Sets our main struct and passes it to the parent class. */ public this (GBytes* gBytes) { this.gBytes = gBytes; } /** * Creates a new #GBytes from @data. * * @data is copied. If @size is 0, @data may be %NULL. * * Params: * data = the data to be used for the bytes * size = the size of @data * * Return: a new #GBytes * * Since: 2.32 * * Throws: ConstructionException Failure to create GObject. */ public this(ubyte[] data) { auto p = g_bytes_new(data.ptr, cast(size_t)data.length); if(p is null) { throw new ConstructionException("null returned by new"); } this(cast(GBytes*) p); } /** * Creates a #GBytes from @data. * * When the last reference is dropped, @free_func will be called with the * @user_data argument. * * @data must not be modified after this call is made until @free_func has * been called to indicate that the bytes is no longer in use. * * @data may be %NULL if @size is 0. * * Params: * data = the data to be used for the bytes * size = the size of @data * freeFunc = the function to call to release the data * userData = data to pass to @free_func * * Return: a new #GBytes * * Since: 2.32 * * Throws: ConstructionException Failure to create GObject. */ public this(void[] data, GDestroyNotify freeFunc, void* userData) { auto p = g_bytes_new_with_free_func(data.ptr, cast(size_t)data.length, freeFunc, userData); if(p is null) { throw new ConstructionException("null returned by new_with_free_func"); } this(cast(GBytes*) p); } /** * Compares the two #GBytes values. * * This function can be used to sort GBytes instances in lexographical order. * * Params: * bytes2 = a pointer to a #GBytes to compare with @bytes1 * * Return: a negative value if bytes2 is lesser, a positive value if bytes2 is * greater, and zero if bytes2 is equal to bytes1 * * Since: 2.32 */ public int compare(Bytes bytes2) { return g_bytes_compare(gBytes, (bytes2 is null) ? null : bytes2.getBytesStruct()); } /** * Compares the two #GBytes values being pointed to and returns * %TRUE if they are equal. * * This function can be passed to g_hash_table_new() as the @key_equal_func * parameter, when using non-%NULL #GBytes pointers as keys in a #GHashTable. * * Params: * bytes2 = a pointer to a #GBytes to compare with @bytes1 * * Return: %TRUE if the two keys match. * * Since: 2.32 */ public bool equal(Bytes bytes2) { return g_bytes_equal(gBytes, (bytes2 is null) ? null : bytes2.getBytesStruct()) != 0; } /** * Get the byte data in the #GBytes. This data should not be modified. * * This function will always return the same pointer for a given #GBytes. * * %NULL may be returned if @size is 0. This is not guaranteed, as the #GBytes * may represent an empty string with @data non-%NULL and @size as 0. %NULL will * not be returned if @size is non-zero. * * Return: a pointer to the * byte data, or %NULL * * Since: 2.32 */ public void[] getData() { size_t size; auto p = g_bytes_get_data(gBytes, &size); return p[0 .. size]; } /** * Get the size of the byte data in the #GBytes. * * This function will always return the same value for a given #GBytes. * * Return: the size * * Since: 2.32 */ public size_t getSize() { return g_bytes_get_size(gBytes); } /** * Creates an integer hash code for the byte data in the #GBytes. * * This function can be passed to g_hash_table_new() as the @key_hash_func * parameter, when using non-%NULL #GBytes pointers as keys in a #GHashTable. * * Return: a hash value corresponding to the key. * * Since: 2.32 */ public uint hash() { return g_bytes_hash(gBytes); } /** * Creates a #GBytes which is a subsection of another #GBytes. The @offset + * @length may not be longer than the size of @bytes. * * A reference to @bytes will be held by the newly created #GBytes until * the byte data is no longer needed. * * Params: * offset = offset which subsection starts at * length = length of subsection * * Return: a new #GBytes * * Since: 2.32 */ public Bytes newFromBytes(size_t offset, size_t length) { auto p = g_bytes_new_from_bytes(gBytes, offset, length); if(p is null) { return null; } return new Bytes(cast(GBytes*) p); } /** * Increase the reference count on @bytes. * * Return: the #GBytes * * Since: 2.32 */ public Bytes doref() { auto p = g_bytes_ref(gBytes); if(p is null) { return null; } return new Bytes(cast(GBytes*) p); } /** * Releases a reference on @bytes. This may result in the bytes being * freed. * * Since: 2.32 */ public void unref() { g_bytes_unref(gBytes); } /** * Unreferences the bytes, and returns a new mutable #GByteArray containing * the same byte data. * * As an optimization, the byte data is transferred to the array without copying * if this was the last reference to bytes and bytes was created with * g_bytes_new(), g_bytes_new_take() or g_byte_array_free_to_bytes(). In all * other cases the data is copied. * * Return: a new mutable #GByteArray containing the same byte data * * Since: 2.32 */ public ByteArray unrefToArray() { auto p = g_bytes_unref_to_array(gBytes); if(p is null) { return null; } return new ByteArray(cast(GByteArray*) p); } /** * Unreferences the bytes, and returns a pointer the same byte data * contents. * * As an optimization, the byte data is returned without copying if this was * the last reference to bytes and bytes was created with g_bytes_new(), * g_bytes_new_take() or g_byte_array_free_to_bytes(). In all other cases the * data is copied. * * Params: * size = location to place the length of the returned data * * Return: a pointer to the same byte data, which should * be freed with g_free() * * Since: 2.32 */ public void* unrefToData(size_t* size) { return g_bytes_unref_to_data(gBytes, size); } }
D
// PERMUTE_ARGS: -g // EXTRA_CPP_SOURCES: cppb.cpp import core.stdc.stdio; import core.stdc.stdarg; import core.stdc.config; extern (C++) int foob(int i, int j, int k); class C { extern (C++) int bar(int i, int j, int k) { printf("this = %p\n", this); printf("i = %d\n", i); printf("j = %d\n", j); printf("k = %d\n", k); return 1; } } extern (C++) int foo(int i, int j, int k) { printf("i = %d\n", i); printf("j = %d\n", j); printf("k = %d\n", k); assert(i == 1); assert(j == 2); assert(k == 3); return 1; } void test1() { foo(1, 2, 3); auto i = foob(1, 2, 3); assert(i == 7); C c = new C(); c.bar(4, 5, 6); } /****************************************/ extern (C++) interface D { int bar(int i, int j, int k); } extern (C++) D getD(); void test2() { D d = getD(); int i = d.bar(9,10,11); assert(i == 8); } /****************************************/ extern (C++) int callE(E); extern (C++) interface E { int bar(int i, int j, int k); } class F : E { extern (C++) int bar(int i, int j, int k) { printf("F.bar: i = %d\n", i); printf("F.bar: j = %d\n", j); printf("F.bar: k = %d\n", k); assert(i == 11); assert(j == 12); assert(k == 13); return 8; } } void test3() { F f = new F(); int i = callE(f); assert(i == 8); } /****************************************/ extern (C++) void foo4(char* p); void test4() { foo4(null); } /****************************************/ extern(C++) { struct foo5 { int i; int j; void* p; } interface bar5{ foo5 getFoo(int i); } bar5 newBar(); } void test5() { bar5 b = newBar(); foo5 f = b.getFoo(4); printf("f.p = %p, b = %p\n", f.p, cast(void*)b); assert(f.p == cast(void*)b); } /****************************************/ extern(C++) { struct S6 { int i; double d; } union S6_2 { int i; double d; } enum S6_3 { A, B } S6 foo6(); S6_2 foo6_2(); S6_3 foo6_3(); } extern (C) int foosize6(); void test6() { S6 f = foo6(); printf("%d %d\n", foosize6(), S6.sizeof); assert(foosize6() == S6.sizeof); version (X86) { assert(f.i == 42); printf("f.d = %g\n", f.d); assert(f.d == 2.5); assert(foo6_2().i == 42); assert(foo6_3() == S6_3.A); } } /****************************************/ extern (C) int foo7(); struct S { int i; long l; } void test7() { printf("%d %d\n", foo7(), S.sizeof); assert(foo7() == S.sizeof); } /****************************************/ extern (C++) void foo8(const(char)*); void test8() { char c; foo8(&c); } /****************************************/ // 4059 struct elem9 { } extern(C++) void foobar9(elem9*, elem9*); void test9() { elem9 *a; foobar9(a, a); } /****************************************/ struct A11802; struct B11802; extern(C++) class C11802 { int x; void fun(A11802*) { x += 2; } void fun(B11802*) { x *= 2; } } extern(C++) class D11802 : C11802 { override void fun(A11802*) { x += 3; } override void fun(B11802*) { x *= 3; } } extern(C++) void test11802x(D11802); void test11802() { auto x = new D11802(); x.x = 0; test11802x(x); assert(x.x == 9); } /****************************************/ struct S13956 { } extern(C++) void func13956(S13956 arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6); extern(C++) void check13956(S13956 arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6) { assert(arg0 == S13956()); assert(arg1 == 1); assert(arg2 == 2); assert(arg3 == 3); assert(arg4 == 4); assert(arg5 == 5); assert(arg6 == 6); } void test13956() { func13956(S13956(), 1, 2, 3, 4, 5, 6); } /****************************************/ // 5148 extern (C++) { void foo10(const(char)*, const(char)*); void foo10(const int, const int); void foo10(const char, const char); void foo10(bool, bool); struct MyStructType { } void foo10(const MyStructType s, const MyStructType t); enum MyEnumType { onemember } void foo10(const MyEnumType s, const MyEnumType t); } void test10() { char* p; foo10(p, p); foo10(1,2); foo10('c','d'); MyStructType s; foo10(s,s); MyEnumType e; foo10(e,e); } /****************************************/ extern (C++, N11.M) { void bar11(); } extern (C++, A11.B) { extern (C++, C) { void bar(); }} void test11() { bar11(); A11.B.C.bar(); } /****************************************/ struct Struct10071 { void *p; c_long_double r; } extern(C++) size_t offset10071(); void test10071() { assert(offset10071() == Struct10071.r.offsetof); } /****************************************/ char[100] valistbuffer; extern(C++) void myvprintfx(const(char)* format, va_list va) { vsprintf(valistbuffer.ptr, format, va); } extern(C++) void myvprintf(const(char)*, va_list); extern(C++) void myprintf(const(char)* format, ...) { va_list ap; va_start(ap, format); myvprintf(format, ap); va_end(ap); } void testvalist() { myprintf("hello %d", 999); assert(valistbuffer[0..9] == "hello 999"); } /****************************************/ // 12825 extern(C++) class C12825 { uint a = 0x12345678; } void test12825() { auto c = new C12825(); } /****************************************/ struct S13955a { float a; double b; } struct S13955b { double a; float b; } struct S13955c { float a; float b; } struct S13955d { double a; double b; } extern(C++) void check13955(S13955a a, S13955b b, S13955c c, S13955d d) { assert(a.a == 2); assert(a.b == 4); assert(b.a == 8); assert(b.b == 16); assert(c.a == 32); assert(c.b == 64); assert(d.a == 128); assert(d.b == 256); } extern(C++) void func13955(S13955a a, S13955b b, S13955c c, S13955d d); void test13955() { func13955(S13955a(2, 4), S13955b(8, 16), S13955c(32, 64), S13955d(128, 256)); } /****************************************/ extern(C++) class C13161 { void dummyfunc() {} long val_5; uint val_9; } extern(C++) class Test : C13161 { uint val_0; long val_1; } extern(C++) size_t getoffset13161(); extern(C++) class C13161a { void dummyfunc() {} c_long_double val_5; uint val_9; } extern(C++) class Testa : C13161a { bool val_0; } extern(C++) size_t getoffset13161a(); void test13161() { assert(getoffset13161() == Test.val_0.offsetof); assert(getoffset13161a() == Testa.val_0.offsetof); } /****************************************/ version (linux) { extern(C++, __gnu_cxx) { struct new_allocator(T) { alias size_type = size_t; static if (is(T : char)) void deallocate(T*, size_type) { } else void deallocate(T*, size_type); } } } extern (C++, std) { struct allocator(T) { version (linux) { alias size_type = size_t; void deallocate(T* p, size_type sz) { (cast(__gnu_cxx.new_allocator!T*)&this).deallocate(p, sz); } } } version (linux) { class vector(T, A = allocator!T) { final void push_back(ref const T); } struct char_traits(T) { } struct basic_string(T, C = char_traits!T, A = allocator!T) { } struct basic_istream(T, C = char_traits!T) { } struct basic_ostream(T, C = char_traits!T) { } struct basic_iostream(T, C = char_traits!T) { } } } extern (C++) { version (linux) { void foo14(std.vector!(int) p); void foo14a(std.basic_string!(char) *p); void foo14b(std.basic_string!(int) *p); void foo14c(std.basic_istream!(char) *p); void foo14d(std.basic_ostream!(char) *p); void foo14e(std.basic_iostream!(char) *p); void foo14f(std.char_traits!char* x, std.basic_string!char* p, std.basic_string!char* q); } } void test14() { version (linux) { std.vector!int p; foo14(p); foo14a(null); foo14b(null); foo14c(null); foo14d(null); foo14e(null); foo14f(null, null, null); } } version (linux) { void test14a(std.allocator!int * pa) { pa.deallocate(null, 0); } void gun(std.vector!int pa) { int x = 42; pa.push_back(x); } } void test13289() { assert(f13289_cpp_wchar_t('a') == 'A'); assert(f13289_cpp_wchar_t('B') == 'B'); assert(f13289_d_wchar('c') == 'C'); assert(f13289_d_wchar('D') == 'D'); assert(f13289_d_dchar('e') == 'E'); assert(f13289_d_dchar('F') == 'F'); assert(f13289_cpp_test()); } extern(C++) { bool f13289_cpp_test(); version(Posix) { dchar f13289_cpp_wchar_t(dchar); } else version(Windows) { wchar f13289_cpp_wchar_t(wchar); } wchar f13289_d_wchar(wchar ch) { if (ch <= 'z' && ch >= 'a') { return cast(wchar)(ch - ('a' - 'A')); } else { return ch; } } dchar f13289_d_dchar(dchar ch) { if (ch <= 'z' && ch >= 'a') { return ch - ('a' - 'A'); } else { return ch; } } } /****************************************/ version (CRuntime_Microsoft) { struct __c_long_double { this(double d) { ld = d; } double ld; alias ld this; } alias __c_long_double myld; } else alias c_long_double myld; extern (C++) myld testld(myld); void test15() { myld ld = 5.0; ld = testld(ld); assert(ld == 6.0); } /****************************************/ version( Windows ) { alias int x_long; alias uint x_ulong; } else { static if( (void*).sizeof > int.sizeof ) { alias long x_long; alias ulong x_ulong; } else { alias int x_long; alias uint x_ulong; } } struct __c_long { this(x_long d) { ld = d; } x_long ld; alias ld this; } struct __c_ulong { this(x_ulong d) { ld = d; } x_ulong ld; alias ld this; } alias __c_long mylong; alias __c_ulong myulong; extern (C++) mylong testl(mylong); extern (C++) myulong testul(myulong); void test16() { { mylong ld = 5; ld = testl(ld); assert(ld == 5 + mylong.sizeof); } { myulong ld = 5; ld = testul(ld); assert(ld == 5 + myulong.sizeof); } } /****************************************/ struct S13707 { void* a; void* b; this(void* a, void* b) { this.a = a; this.b = b; } } extern(C++) S13707 func13707(); void test13707() { auto p = func13707(); assert(p.a == null); assert(p.b == null); } /****************************************/ struct S13932(int x) { int member; } extern(C++) void func13932(S13932!(-1) s); /****************************************/ extern(C++, N13337.M13337) { struct S13337{} void foo13337(S13337 s); } /****************************************/ // 14195 struct Delegate1(T) {} struct Delegate2(T1, T2) {} template Signature(T) { alias Signature = typeof(*(T.init)); } extern(C++) { alias del1_t = Delegate1!(Signature!(void function())); alias del2_t = Delegate2!(Signature!(int function(float, double)), Signature!(int function(float, double))); void test14195a(del1_t); void test14195b(del2_t); } void test14195() { test14195a(del1_t()); test14195b(del2_t()); } /****************************************/ // 14200 template Tuple14200(T...) { alias Tuple14200 = T; } extern(C++) void test14200a(Tuple14200!(int)); extern(C++) void test14200b(float, Tuple14200!(int, double)); void test14200() { test14200a(1); test14200b(1.0f, 1, 1.0); } /****************************************/ // check order of overloads in vtable extern (C++) class Statement {} extern (C++) class ErrorStatement {} extern (C++) class PeelStatement {} extern (C++) class ExpStatement {} extern (C++) class DtorExpStatement {} extern (C++) class Visitor { public: int visit(Statement) { return 1; } int visit(ErrorStatement) { return 2; } int visit(PeelStatement) { return 3; } } extern (C++) class Visitor2 : Visitor { int visit2(ExpStatement) { return 4; } int visit2(DtorExpStatement) { return 5; } } extern(C++) bool testVtableCpp(Visitor2 sv); extern(C++) Visitor2 getVisitor2(); bool testVtableD(Visitor2 sv) { Statement s1; ErrorStatement s2; PeelStatement s3; ExpStatement s4; DtorExpStatement s5; if (sv.visit(s1) != 1) return false; if (sv.visit(s2) != 2) return false; if (sv.visit(s3) != 3) return false; if (sv.visit2(s4) != 4) return false; if (sv.visit2(s5) != 5) return false; return true; } void testVtable() { Visitor2 dinst = new Visitor2; if (!testVtableCpp(dinst)) assert(0); Visitor2 cppinst = getVisitor2(); if (!testVtableD(cppinst)) assert(0); } /****************************************/ void main() { test1(); test2(); test3(); test4(); test13956(); test5(); test6(); test10071(); test7(); test8(); test11802(); test9(); test10(); test13955(); test11(); testvalist(); test12825(); test13161(); test14(); test13289(); test15(); test16(); func13707(); func13932(S13932!(-1)(0)); foo13337(S13337()); test14195(); test14200(); testVtable(); printf("Success\n"); }
D
/////////////////////////////////////////////////////////////////////// // Info EXIT /////////////////////////////////////////////////////////////////////// INSTANCE DIA_Carl_EXIT (C_INFO) { npc = VLK_461_Carl; nr = 999; condition = DIA_Carl_EXIT_Condition; information = DIA_Carl_EXIT_Info; permanent = TRUE; description = DIALOG_ENDE; }; FUNC INT DIA_Carl_EXIT_Condition() { return TRUE; }; FUNC VOID DIA_Carl_EXIT_Info() { AI_StopProcessInfos (self); }; /////////////////////////////////////////////////////////////////////// FUNC VOID B_CarlSayHallo () { AI_Output (self, other, "DIA_Carl_Hallo_05_00"); //Vypadá to, že tu ve męstę máme pár zlodęjů, co okrádají boháče. AI_Output (self, other, "DIA_Carl_Hallo_05_01"); //Męstská stráž nedávno obrátila pâístavní čtvră vzhůru nohama, ale nenašli vůbec nic. }; // ************************************************************ // PICK POCKET // ************************************************************ INSTANCE DIA_Carl_PICKPOCKET (C_INFO) { npc = VLK_461_Carl; nr = 900; condition = DIA_Carl_PICKPOCKET_Condition; information = DIA_Carl_PICKPOCKET_Info; permanent = TRUE; description = Pickpocket_40; }; FUNC INT DIA_Carl_PICKPOCKET_Condition() { C_Beklauen (34, 40); }; FUNC VOID DIA_Carl_PICKPOCKET_Info() { Info_ClearChoices (DIA_Carl_PICKPOCKET); Info_AddChoice (DIA_Carl_PICKPOCKET, DIALOG_BACK ,DIA_Carl_PICKPOCKET_BACK); Info_AddChoice (DIA_Carl_PICKPOCKET, DIALOG_PICKPOCKET ,DIA_Carl_PICKPOCKET_DoIt); }; func void DIA_Carl_PICKPOCKET_DoIt() { B_Beklauen (); Info_ClearChoices (DIA_Carl_PICKPOCKET); }; func void DIA_Carl_PICKPOCKET_BACK() { Info_ClearChoices (DIA_Carl_PICKPOCKET); }; /////////////////////////////////////////////////////////////////////// // Info Hallo /////////////////////////////////////////////////////////////////////// INSTANCE DIA_Carl_Hallo (C_INFO) { npc = VLK_461_Carl; nr = 2; condition = DIA_Carl_Hallo_Condition; information = DIA_Carl_Hallo_Info; permanent = FALSE; Important = TRUE; }; FUNC INT DIA_Carl_Hallo_Condition() { if Npc_IsInState (self, ZS_Talk) { return TRUE; }; }; FUNC VOID DIA_Carl_Hallo_Info() { AI_Output (self, other, "DIA_Carl_Hallo_05_02"); //Co dęláš v týhle ubohý špinavý díâe? Co tady hledáš? Info_ClearChoices (DIA_Carl_Hallo); Info_AddChoice (DIA_Carl_Hallo,"Zabloudil jsem.",DIA_Carl_Hallo_verlaufen); Info_AddChoice (DIA_Carl_Hallo,"Jen se dívám kolem.",DIA_Carl_Hallo_umsehen); }; FUNC VOID DIA_Carl_Hallo_verlaufen() { AI_Output (other, self, "DIA_Carl_Hallo_verlaufen_15_00");//Zabloudil jsem. AI_Output (self, other, "DIA_Carl_Hallo_verlaufen_05_01");//Tak si dávej pozor, aby tę nikdo neokradl. B_CarlSayHallo(); Info_ClearChoices (DIA_Carl_Hallo); }; FUNC VOID DIA_Carl_Hallo_umsehen() { AI_Output (other, self, "DIA_Carl_Hallo_umsehen_15_00");//Jen se dívám kolem. AI_Output (self, other, "DIA_Carl_Hallo_umsehen_05_01");//Aha. Tak si dávej bacha, aă tę nikdo nechytí, jak tu čenicháš. B_CarlSayHallo(); Info_ClearChoices (DIA_Carl_Hallo); }; /////////////////////////////////////////////////////////////////////// // Info Diebe /////////////////////////////////////////////////////////////////////// INSTANCE DIA_Carl_Diebe (C_INFO) { npc = VLK_461_Carl; nr = 3; condition = DIA_Carl_Diebe_Condition; information = DIA_Carl_Diebe_Info; permanent = FALSE; description = "Co víš o tęch zlodęjích?"; }; FUNC INT DIA_Carl_Diebe_Condition() { return TRUE; }; FUNC VOID DIA_Carl_Diebe_Info() { AI_Output (other, self, "DIA_Carl_Diebe_15_00");//Co víš o tęch zlodęjích? AI_Output (self, other, "DIA_Carl_Diebe_05_01");//Nic. Ale všichni męšăané jsou vydęšení a začínají být nedůvęâiví - obzvlášă vůči cizincům. AI_Output (self, other, "DIA_Carl_Diebe_05_02");//Nenech se nachytat v cizím domę - na to se tady nikdo nekouká moc vlídnę. AI_Output (self, other, "DIA_Carl_Diebe_05_03");//Ano, musíš se umęt bránit zlodęjům. Nejlíp na to jít s poâádnę tlustým klackem. }; /////////////////////////////////////////////////////////////////////// // Info Lernen /////////////////////////////////////////////////////////////////////// INSTANCE DIA_Carl_Lernen (C_INFO) { npc = VLK_461_Carl; nr = 3; condition = DIA_Carl_Lernen_Condition; information = DIA_Carl_Lernen_Info; permanent = FALSE; description = "Můžu se u tebe nęčemu pâiučit?"; }; FUNC INT DIA_Carl_Lernen_Condition() { return TRUE; }; FUNC VOID DIA_Carl_Lernen_Info() { AI_Output (other, self, "DIA_Carl_Lernen_15_00");//Můžu se u tebe nęčemu pâiučit? AI_Output (self, other, "DIA_Carl_Lernen_05_01");//No, vyrobil jsem nękolik klik a nęco hâebíků a opravuju kovové součástky. AI_Output (self, other, "DIA_Carl_Lernen_05_02");//Ale o kování zbraní toho nevím tolik, abych tę mohl učit. AI_Output (self, other, "DIA_Carl_Lernen_05_03");//Jestli se chceš nęco naučit, zajdi za Haradem. On určitę ví, jak se vyrábęjí zbranę! AI_Output (self, other, "DIA_Carl_Lernen_05_04");//Ale jestli si chceš trochu vypracovat svaly, tak s tím ti můžu pomoct. Log_CreateTopic (Topic_CityTeacher,LOG_NOTE); B_LogEntry (Topic_CityTeacher,"S pomocí kováâe Carla z pâístavní čtvrti se mohu stát silnęjším."); }; /////////////////////////////////////////////////////////////////////// // Info Für's lernen bezahlen /////////////////////////////////////////////////////////////////////// INSTANCE DIA_Carl_Wieviel (C_INFO) { npc = VLK_461_Carl; nr = 3; condition = DIA_Carl_Wieviel_Condition; information = DIA_Carl_Wieviel_Info; permanent = FALSE; description = "Kolik si necháváš platit za výcvik?"; }; FUNC INT DIA_Carl_Wieviel_Condition() { if Npc_KnowsInfo (other, DIA_Carl_Lernen) { return TRUE; }; }; FUNC VOID DIA_Carl_Wieviel_Info() { AI_Output (other, self, "DIA_Carl_Wieviel_15_00");//Kolik si necháváš platit za výcvik? if Npc_KnowsInfo (other,DIA_Edda_Statue) { AI_Output (self, other, "DIA_Carl_Wieviel_05_01");//Slyšel jsem, žes pracoval pro Eddu. Budu tę cvičit zadarmo. Carl_TeachSTR = TRUE; } else { AI_Output (self, other, "DIA_Carl_Wieviel_05_02");//50 zlatých a já ti dopomůžu k vętší síle. }; }; /////////////////////////////////////////////////////////////////////// // Info Gold zahlen /////////////////////////////////////////////////////////////////////// INSTANCE DIA_Carl_bezahlen (C_INFO) { npc = VLK_461_Carl; nr = 3; condition = DIA_Carl_bezahlen_Condition; information = DIA_Carl_bezahlen_Info; permanent = TRUE; description = "Rád bych se u tebe nechal vycvičit (zaplatit 50 zlaăáků)."; }; FUNC INT DIA_Carl_bezahlen_Condition() { if Npc_KnowsInfo (other, DIA_Carl_Wieviel) && (Carl_TeachSTR == FALSE) { return TRUE; }; }; FUNC VOID DIA_Carl_bezahlen_Info() { AI_Output (other, self, "DIA_Carl_bezahlen_15_00");//Chtęl bych s tebou cvičit. if Npc_KnowsInfo (other,DIA_Edda_Statue) { AI_Output (self, other, "DIA_Carl_bezahlen_05_01");//Slyšel jsem, žes pracoval pro Eddu. Budu tę cvičit zadarmo. Carl_TeachSTR = TRUE; } else { if B_GiveInvItems (other, self, ItMi_Gold, 50) { AI_Output (self, other, "DIA_Carl_bezahlen_05_02");//Dobâe, můžeme začít hned, jak budeš pâipraven. Carl_TeachSTR = TRUE; } else { AI_Output (self, other, "DIA_Carl_bezahlen_05_03");//Dej mi zlato a pak tę budu trénovat. }; }; }; //******************************************* // TechPlayer //******************************************* INSTANCE DIA_Carl_Teach(C_INFO) { npc = VLK_461_Carl; nr = 7; condition = DIA_Carl_Teach_Condition; information = DIA_Carl_Teach_Info; permanent = TRUE; description = "Chtęl bych se stát silnęjším."; }; FUNC INT DIA_Carl_Teach_Condition() { if (Carl_TeachSTR == TRUE) { return TRUE; }; }; FUNC VOID DIA_Carl_Teach_Info() { AI_Output (other,self ,"DIA_Carl_Teach_15_00"); //Chtęl bych se stát silnęjším. Info_ClearChoices (DIA_Carl_Teach); Info_AddChoice (DIA_Carl_Teach, DIALOG_BACK, DIA_Carl_Teach_Back); Info_AddChoice (DIA_Carl_Teach, B_BuildLearnString(PRINT_LearnSTR1 , B_GetLearnCostAttribute(other, ATR_STRENGTH)) ,DIA_Carl_Teach_STR_1); Info_AddChoice (DIA_Carl_Teach, B_BuildLearnString(PRINT_LearnSTR5 , B_GetLearnCostAttribute(other, ATR_STRENGTH)*5) ,DIA_Carl_Teach_STR_5); }; FUNC VOID DIA_Carl_Teach_Back () { Info_ClearChoices (DIA_Carl_Teach); }; FUNC VOID DIA_Carl_Teach_STR_1 () { B_TeachAttributePoints (self, other, ATR_STRENGTH, 1, T_HIGH); Info_ClearChoices (DIA_Carl_Teach); Info_AddChoice (DIA_Carl_Teach, DIALOG_BACK, DIA_Carl_Teach_Back); Info_AddChoice (DIA_Carl_Teach, B_BuildLearnString(PRINT_LearnSTR1 , B_GetLearnCostAttribute(other, ATR_STRENGTH)) ,DIA_Carl_Teach_STR_1); Info_AddChoice (DIA_Carl_Teach, B_BuildLearnString(PRINT_LearnSTR5 , B_GetLearnCostAttribute(other, ATR_STRENGTH)*5) ,DIA_Carl_Teach_STR_5); }; FUNC VOID DIA_Carl_Teach_STR_5 () { B_TeachAttributePoints (self, other, ATR_STRENGTH, 5, T_HIGH); Info_ClearChoices (DIA_Carl_Teach); Info_AddChoice (DIA_Carl_Teach, DIALOG_BACK, DIA_Carl_Teach_Back); Info_AddChoice (DIA_Carl_Teach, B_BuildLearnString(PRINT_LearnSTR1 , B_GetLearnCostAttribute(other, ATR_STRENGTH)) ,DIA_Carl_Teach_STR_1); Info_AddChoice (DIA_Carl_Teach, B_BuildLearnString(PRINT_LearnSTR5 , B_GetLearnCostAttribute(other, ATR_STRENGTH)*5) ,DIA_Carl_Teach_STR_5); };
D
/Users/marvinevins/Library/Autosave\ Information/DetailedViewApp/DerivedData/DetailedViewApp/Build/Intermediates.noindex/DetailedViewApp.build/Debug-iphonesimulator/DetailedViewApp.build/Objects-normal/x86_64/2ndViewController.o : /Users/marvinevins/Library/Autosave\ Information/DetailedViewApp/DetailedViewApp/SceneDelegate.swift /Users/marvinevins/Library/Autosave\ Information/DetailedViewApp/DetailedViewApp/AppDelegate.swift /Users/marvinevins/Library/Autosave\ Information/DetailedViewApp/DetailedViewApp/ViewController.swift /Users/marvinevins/Library/Autosave\ Information/DetailedViewApp/DetailedViewApp/2ndViewController.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/ObjectiveC.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreImage.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/QuartzCore.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Dispatch.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Metal.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Darwin.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Foundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreFoundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreGraphics.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Swift.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/UIKit.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.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.5.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/UserNotifications.framework/Headers/UserNotifications.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes /Users/marvinevins/Library/Autosave\ Information/DetailedViewApp/DerivedData/DetailedViewApp/Build/Intermediates.noindex/DetailedViewApp.build/Debug-iphonesimulator/DetailedViewApp.build/Objects-normal/x86_64/2ndViewController~partial.swiftmodule : /Users/marvinevins/Library/Autosave\ Information/DetailedViewApp/DetailedViewApp/SceneDelegate.swift /Users/marvinevins/Library/Autosave\ Information/DetailedViewApp/DetailedViewApp/AppDelegate.swift /Users/marvinevins/Library/Autosave\ Information/DetailedViewApp/DetailedViewApp/ViewController.swift /Users/marvinevins/Library/Autosave\ Information/DetailedViewApp/DetailedViewApp/2ndViewController.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/ObjectiveC.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreImage.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/QuartzCore.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Dispatch.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Metal.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Darwin.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Foundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreFoundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreGraphics.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Swift.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/UIKit.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.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.5.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/UserNotifications.framework/Headers/UserNotifications.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes /Users/marvinevins/Library/Autosave\ Information/DetailedViewApp/DerivedData/DetailedViewApp/Build/Intermediates.noindex/DetailedViewApp.build/Debug-iphonesimulator/DetailedViewApp.build/Objects-normal/x86_64/2ndViewController~partial.swiftdoc : /Users/marvinevins/Library/Autosave\ Information/DetailedViewApp/DetailedViewApp/SceneDelegate.swift /Users/marvinevins/Library/Autosave\ Information/DetailedViewApp/DetailedViewApp/AppDelegate.swift /Users/marvinevins/Library/Autosave\ Information/DetailedViewApp/DetailedViewApp/ViewController.swift /Users/marvinevins/Library/Autosave\ Information/DetailedViewApp/DetailedViewApp/2ndViewController.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/ObjectiveC.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreImage.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/QuartzCore.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Dispatch.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Metal.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Darwin.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Foundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreFoundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreGraphics.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Swift.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/UIKit.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.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.5.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/UserNotifications.framework/Headers/UserNotifications.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes /Users/marvinevins/Library/Autosave\ Information/DetailedViewApp/DerivedData/DetailedViewApp/Build/Intermediates.noindex/DetailedViewApp.build/Debug-iphonesimulator/DetailedViewApp.build/Objects-normal/x86_64/2ndViewController~partial.swiftsourceinfo : /Users/marvinevins/Library/Autosave\ Information/DetailedViewApp/DetailedViewApp/SceneDelegate.swift /Users/marvinevins/Library/Autosave\ Information/DetailedViewApp/DetailedViewApp/AppDelegate.swift /Users/marvinevins/Library/Autosave\ Information/DetailedViewApp/DetailedViewApp/ViewController.swift /Users/marvinevins/Library/Autosave\ Information/DetailedViewApp/DetailedViewApp/2ndViewController.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/ObjectiveC.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreImage.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/QuartzCore.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Dispatch.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Metal.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Darwin.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Foundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreFoundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreGraphics.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Swift.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/UIKit.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.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.5.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/UserNotifications.framework/Headers/UserNotifications.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
D
/Users/sunchuyue/Documents/test/RX_Product/DerivedData/RX_Product/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RxSwift.build/Objects-normal/x86_64/AnonymousObserver.o : /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Amb.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Deferred.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Deprecated.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Enumerated.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Traits/Maybe.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Sequence.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Traits/ObservableType+PrimitiveSequence.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Debounce.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Reduce.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Range.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Merge.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Take.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Cancelable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Traits/Completable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/GroupedObservable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Traits/Single.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/AsSingle.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Sample.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Throttle.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/ObservableType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/ConnectableObservableType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/SchedulerType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/ObserverType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Subjects/SubjectType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Create.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Generate.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/DataStructures/Queue.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Reactive.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Materialize.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/AddRef.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/DataStructures/Bag.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Using.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Debug.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Catch.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Switch.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/StartWith.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Concurrency/Lock.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/RecursiveLock.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Sink.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Optional.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Scan.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/Platform.Darwin.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Do.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Map.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Zip.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Skip.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Producer.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Buffer.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Timer.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/DeprecationWarner.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Filter.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Never.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/AnyObserver.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Error.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/Disposables.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Errors.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/ElementAt.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Concat.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Repeat.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Subjects/AsyncSubject.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Event.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/SwiftSupport/SwiftSupport.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/TakeLast.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Multicast.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/First.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Just.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Timeout.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Window.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Rx.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/RxMutableBox.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/Platform.Linux.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/GroupBy.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Delay.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/ToArray.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence+Zip+arity.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Empty.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/sunchuyue/Documents/test/RX_Product/Pods/Target\ Support\ Files/RxSwift/RxSwift-umbrella.h /Users/sunchuyue/Documents/test/RX_Product/DerivedData/RX_Product/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RxSwift.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes /Users/sunchuyue/Documents/test/RX_Product/DerivedData/RX_Product/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RxSwift.build/Objects-normal/x86_64/AnonymousObserver~partial.swiftmodule : /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Amb.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Deferred.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Deprecated.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Enumerated.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Traits/Maybe.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Sequence.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Traits/ObservableType+PrimitiveSequence.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Debounce.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Reduce.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Range.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Merge.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Take.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Cancelable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Traits/Completable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/GroupedObservable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Traits/Single.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/AsSingle.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Sample.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Throttle.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/ObservableType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/ConnectableObservableType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/SchedulerType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/ObserverType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Subjects/SubjectType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Create.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Generate.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/DataStructures/Queue.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Reactive.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Materialize.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/AddRef.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/DataStructures/Bag.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Using.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Debug.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Catch.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Switch.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/StartWith.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Concurrency/Lock.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/RecursiveLock.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Sink.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Optional.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Scan.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/Platform.Darwin.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Do.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Map.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Zip.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Skip.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Producer.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Buffer.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Timer.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/DeprecationWarner.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Filter.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Never.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/AnyObserver.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Error.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/Disposables.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Errors.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/ElementAt.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Concat.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Repeat.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Subjects/AsyncSubject.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Event.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/SwiftSupport/SwiftSupport.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/TakeLast.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Multicast.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/First.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Just.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Timeout.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Window.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Rx.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/RxMutableBox.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/Platform.Linux.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/GroupBy.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Delay.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/ToArray.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence+Zip+arity.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Empty.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/sunchuyue/Documents/test/RX_Product/Pods/Target\ Support\ Files/RxSwift/RxSwift-umbrella.h /Users/sunchuyue/Documents/test/RX_Product/DerivedData/RX_Product/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RxSwift.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes /Users/sunchuyue/Documents/test/RX_Product/DerivedData/RX_Product/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RxSwift.build/Objects-normal/x86_64/AnonymousObserver~partial.swiftdoc : /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Amb.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Deferred.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Deprecated.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Enumerated.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Traits/Maybe.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Sequence.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Traits/ObservableType+PrimitiveSequence.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Debounce.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Reduce.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Range.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Merge.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Take.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Cancelable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Traits/Completable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/GroupedObservable.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Traits/Single.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/AsSingle.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Sample.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Throttle.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/ObservableType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/ConnectableObservableType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/SchedulerType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/ObserverType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Subjects/SubjectType.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Create.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Generate.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/DataStructures/Queue.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Reactive.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Materialize.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/AddRef.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/DataStructures/Bag.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Using.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Debug.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Catch.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Switch.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/StartWith.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Concurrency/Lock.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/RecursiveLock.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Sink.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Optional.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Scan.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/Platform.Darwin.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Do.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Map.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Zip.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Skip.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Producer.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Buffer.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Timer.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/DeprecationWarner.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Filter.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Never.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/AnyObserver.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Error.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Disposables/Disposables.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Errors.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/ElementAt.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Concat.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Repeat.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Subjects/AsyncSubject.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Event.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/SwiftSupport/SwiftSupport.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/TakeLast.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Multicast.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/First.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Just.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Timeout.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Window.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Rx.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/RxMutableBox.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/Platform/Platform.Linux.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/GroupBy.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Delay.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/ToArray.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence+Zip+arity.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/Empty.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift /Users/sunchuyue/Documents/test/RX_Product/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/sunchuyue/Documents/test/RX_Product/Pods/Target\ Support\ Files/RxSwift/RxSwift-umbrella.h /Users/sunchuyue/Documents/test/RX_Product/DerivedData/RX_Product/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RxSwift.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
D
$NetBSD$ --- runtime/druntime/src/core/sys/posix/pthread.d.orig 2018-08-23 23:29:55.000000000 +0000 +++ runtime/druntime/src/core/sys/posix/pthread.d @@ -249,6 +249,85 @@ else version( DragonFlyBSD ) enum PTHREAD_COND_INITIALIZER = null; enum PTHREAD_RWLOCK_INITIALIZER = null; } +else version( NetBSD ) +{ + enum PRI_NONE = -1; + enum + { + PTHREAD_INHERIT_SCHED = 0x0, + + PTHREAD_CREATE_DETACHED = 1, + PTHREAD_CREATE_JOINABLE = 0, + PTHREAD_EXPLICIT_SCHED = 1, + } + + enum + { + PTHREAD_PROCESS_PRIVATE = 0, + PTHREAD_PROCESS_SHARED = 1, + } + + enum + { + PTHREAD_CANCEL_ENABLE = 0, + PTHREAD_CANCEL_DISABLE = 1, + PTHREAD_CANCEL_DEFERRED = 0, + PTHREAD_CANCEL_ASYNCHRONOUS = 1, + } + + enum PTHREAD_CANCELED = cast(void*) 1; + + enum PTHREAD_DONE_INIT = 1; + + struct _PTHREAD_MUTEX_INITIALIZER{ + enum f1 = 0x33330003; + enum f2 = 0; + enum f3 = [ 0, 0, 0 ]; + enum f4 = 0; + enum f5 = [0, 0, 0 ]; + enum f6 = null; + enum f7 = null; + enum f8 = 0; + enum f9 = null; + } + enum PTHREAD_MUTEX_INITIALIZER = _PTHREAD_MUTEX_INITIALIZER(); + + struct _PTHREAD_ONCE_INIT{ + enum f1 = PTHREAD_MUTEX_INITIALIZER; + enum f2 = 0; + } + enum PTHREAD_ONCE_INIT = _PTHREAD_ONCE_INIT(); + struct _PTHREAD_COND_INITIALIZER{ + enum f1 = 0x55550005; + enum f2 = 0; + struct __PTHREAD_COND_INITIALIZER_S + { + enum p1 = null; + enum p2 = null; + enum p3 = null; + enum p4 = null; + } + enum f3 = __PTHREAD_COND_INITIALIZER_S(); + } + enum PTHREAD_COND_INITIALIZER = _PTHREAD_COND_INITIALIZER(); + struct _PTHREAD_RWLOCK_INITIALIZER + { + enum f1 = 0x99990009; + enum f2 = 0; + struct __PTHREAD_RWLOCK_INITIALIZER_S + { + enum p1 = null; + enum p2 = null; + } + + enum f3 = __PTHREAD_RWLOCK_INITIALIZER_S(); + enum f4 = __PTHREAD_RWLOCK_INITIALIZER_S(); + enum f5 = 0; + enum f6 = null; + enum f7 = null; + } + enum PTHREAD_RWLOCK_INITIALIZER = _PTHREAD_RWLOCK_INITIALIZER(); +} else version (Solaris) { enum @@ -589,6 +668,18 @@ else version( DragonFlyBSD ) int pthread_barrierattr_init(pthread_barrierattr_t*); int pthread_barrierattr_setpshared(pthread_barrierattr_t*, int); } +else version( NetBSD ) +{ + enum PTHREAD_BARRIER_SERIAL_THREAD = 1234567; + + int pthread_barrier_destroy(pthread_barrier_t*); + int pthread_barrier_init(pthread_barrier_t*, in pthread_barrierattr_t*, uint); + int pthread_barrier_wait(pthread_barrier_t*); + int pthread_barrierattr_destroy(pthread_barrierattr_t*); + int pthread_barrierattr_getpshared(in pthread_barrierattr_t*, int*); + int pthread_barrierattr_init(pthread_barrierattr_t*); + int pthread_barrierattr_setpshared(pthread_barrierattr_t*, int); +} else version (OSX) { } @@ -655,6 +746,14 @@ else version( DragonFlyBSD ) int pthread_spin_trylock(pthread_spinlock_t*); int pthread_spin_unlock(pthread_spinlock_t*); } +else version( NetBSD ) +{ + int pthread_spin_init(pthread_spinlock_t*, int); + int pthread_spin_destroy(pthread_spinlock_t*); + int pthread_spin_lock(pthread_spinlock_t*); + int pthread_spin_trylock(pthread_spinlock_t*); + int pthread_spin_unlock(pthread_spinlock_t*); +} else version (OSX) { } @@ -756,6 +855,24 @@ else version( DragonFlyBSD ) int pthread_mutexattr_settype(pthread_mutexattr_t*, int) @trusted; int pthread_setconcurrency(int); } +else version( NetBSD ) +{ + enum + { + PTHREAD_MUTEX_NORMAL = 0, + PTHREAD_MUTEX_ERRORCHECK = 1, + PTHREAD_MUTEX_RECURSIVE = 2, + PTHREAD_MUTEX_TYPE_MAX + } + enum PTHREAD_MUTEX_DEFAULT = PTHREAD_MUTEX_ERRORCHECK; + + int pthread_attr_getguardsize(in pthread_attr_t*, size_t*); + int pthread_attr_setguardsize(pthread_attr_t*, size_t); + int pthread_getconcurrency(); + int pthread_mutexattr_gettype(pthread_mutexattr_t*, int*); + int pthread_mutexattr_settype(pthread_mutexattr_t*, int) @trusted; + int pthread_setconcurrency(int); +} else version (Solaris) { enum @@ -810,6 +927,10 @@ else version( DragonFlyBSD ) { int pthread_getcpuclockid(pthread_t, clockid_t*); } +else version( NetBSD ) +{ + +} else version (OSX) { } @@ -858,6 +979,12 @@ else version( DragonFlyBSD ) int pthread_rwlock_timedrdlock(pthread_rwlock_t*, in timespec*); int pthread_rwlock_timedwrlock(pthread_rwlock_t*, in timespec*); } +else version( NetBSD ) +{ + int pthread_mutex_timedlock(pthread_mutex_t*, in timespec*); + int pthread_rwlock_timedrdlock(pthread_rwlock_t*, in timespec*); + int pthread_rwlock_timedwrlock(pthread_rwlock_t*, in timespec*); +} else version (Solaris) { int pthread_mutex_timedlock(pthread_mutex_t*, in timespec*); @@ -1097,6 +1224,15 @@ else version( DragonFlyBSD ) int pthread_attr_setstackaddr(pthread_attr_t*, void*); int pthread_attr_setstacksize(pthread_attr_t*, size_t); } +else version( NetBSD ) +{ + int pthread_attr_getstack(in pthread_attr_t*, void**, size_t*); + int pthread_attr_getstackaddr(in pthread_attr_t*, void**); + int pthread_attr_getstacksize(in pthread_attr_t*, size_t*); + int pthread_attr_setstack(pthread_attr_t*, void*, size_t); + int pthread_attr_setstackaddr(pthread_attr_t*, void*); + int pthread_attr_setstacksize(pthread_attr_t*, size_t); +} else version (Solaris) { int pthread_attr_getstack(in pthread_attr_t*, void**, size_t*); @@ -1154,6 +1290,15 @@ else version( DragonFlyBSD ) { int pthread_condattr_getpshared(in pthread_condattr_t*, int*); int pthread_condattr_setpshared(pthread_condattr_t*, int); + int pthread_mutexattr_getpshared(in pthread_mutexattr_t*, int*); + int pthread_mutexattr_setpshared(pthread_mutexattr_t*, int); + int pthread_rwlockattr_getpshared(in pthread_rwlockattr_t*, int*); + int pthread_rwlockattr_setpshared(pthread_rwlockattr_t*, int); +} +else version( NetBSD ) +{ + int pthread_condattr_getpshared(in pthread_condattr_t*, int*); + int pthread_condattr_setpshared(pthread_condattr_t*, int); int pthread_mutexattr_getpshared(in pthread_mutexattr_t*, int*); int pthread_mutexattr_setpshared(pthread_mutexattr_t*, int); int pthread_rwlockattr_getpshared(in pthread_rwlockattr_t*, int*);
D
/// module arsd.color; @safe: // importing phobos explodes the size of this code 10x, so not doing it. private { real toInternal(T)(string s) { real accumulator = 0.0; size_t i = s.length; foreach(idx, c; s) { if(c >= '0' && c <= '9') { accumulator *= 10; accumulator += c - '0'; } else if(c == '.') { i = idx + 1; break; } else throw new Exception("bad char to make real from " ~ s); } real accumulator2 = 0.0; real count = 1; foreach(c; s[i .. $]) { if(c >= '0' && c <= '9') { accumulator2 *= 10; accumulator2 += c - '0'; count *= 10; } else throw new Exception("bad char to make real from " ~ s); } return accumulator + accumulator2 / count; } @trusted string toInternal(T)(int a) { if(a == 0) return "0"; char[] ret; while(a) { ret ~= (a % 10) + '0'; a /= 10; } for(int i = 0; i < ret.length / 2; i++) { char c = ret[i]; ret[i] = ret[$ - i - 1]; ret[$ - i - 1] = c; } return cast(string) ret; } string toInternal(T)(real a) { // a simplifying assumption here is the fact that we only use this in one place: toInternal!string(cast(real) a / 255) // thus we know this will always be between 0.0 and 1.0, inclusive. if(a <= 0.0) return "0.0"; if(a >= 1.0) return "1.0"; string ret = "0."; // I wonder if I can handle round off error any better. Phobos does, but that isn't worth 100 KB of code. int amt = cast(int)(a * 1000); return ret ~ toInternal!string(amt); } nothrow @safe @nogc pure real absInternal(real a) { return a < 0 ? -a : a; } nothrow @safe @nogc pure real minInternal(real a, real b, real c) { auto m = a; if(b < m) m = b; if(c < m) m = c; return m; } nothrow @safe @nogc pure real maxInternal(real a, real b, real c) { auto m = a; if(b > m) m = b; if(c > m) m = c; return m; } nothrow @safe @nogc pure bool startsWithInternal(string a, string b) { return (a.length >= b.length && a[0 .. b.length] == b); } string[] splitInternal(string a, char c) { string[] ret; size_t previous = 0; foreach(i, char ch; a) { if(ch == c) { ret ~= a[previous .. i]; previous = i + 1; } } if(previous != a.length) ret ~= a[previous .. $]; return ret; } nothrow @safe @nogc pure string stripInternal(string s) { foreach(i, char c; s) if(c != ' ' && c != '\t' && c != '\n') { s = s[i .. $]; break; } for(int a = cast(int)(s.length - 1); a > 0; a--) { char c = s[a]; if(c != ' ' && c != '\t' && c != '\n') { s = s[0 .. a + 1]; break; } } return s; } } // done with mini-phobos /// Represents an RGBA color struct Color { @safe: /++ The color components are available as a static array, individual bytes, and a uint inside this union. Since it is anonymous, you can use the inner members' names directly. +/ union { ubyte[4] components; /// [r, g, b, a] /// Holder for rgba individual components. struct { ubyte r; /// red ubyte g; /// green ubyte b; /// blue ubyte a; /// alpha. 255 == opaque } uint asUint; /// The components as a single 32 bit value (beware of endian issues!) } /++ Like the constructor, but this makes sure they are in range before casting. If they are out of range, it saturates: anything less than zero becomes zero and anything greater than 255 becomes 255. +/ nothrow pure static Color fromIntegers(int red, int green, int blue, int alpha = 255) { return Color(clampToByte(red), clampToByte(green), clampToByte(blue), clampToByte(alpha)); } /// Construct a color with the given values. They should be in range 0 <= x <= 255, where 255 is maximum intensity and 0 is minimum intensity. nothrow pure @nogc this(int red, int green, int blue, int alpha = 255) { this.r = cast(ubyte) red; this.g = cast(ubyte) green; this.b = cast(ubyte) blue; this.a = cast(ubyte) alpha; } /// Static convenience functions for common color names nothrow pure @nogc static Color transparent() { return Color(0, 0, 0, 0); } /// Ditto nothrow pure @nogc static Color white() { return Color(255, 255, 255); } /// Ditto nothrow pure @nogc static Color gray() { return Color(128, 128, 128); } /// Ditto nothrow pure @nogc static Color black() { return Color(0, 0, 0); } /// Ditto nothrow pure @nogc static Color red() { return Color(255, 0, 0); } /// Ditto nothrow pure @nogc static Color green() { return Color(0, 255, 0); } /// Ditto nothrow pure @nogc static Color blue() { return Color(0, 0, 255); } /// Ditto nothrow pure @nogc static Color yellow() { return Color(255, 255, 0); } /// Ditto nothrow pure @nogc static Color teal() { return Color(0, 255, 255); } /// Ditto nothrow pure @nogc static Color purple() { return Color(255, 0, 255); } /// Ditto nothrow pure @nogc static Color brown() { return Color(128, 64, 0); } /* ubyte[4] toRgbaArray() { return [r,g,b,a]; } */ /// Return black-and-white color Color toBW() () { int intens = clampToByte(cast(int)(0.2126*r+0.7152*g+0.0722*b)); return Color(intens, intens, intens, a); } /// Makes a string that matches CSS syntax for websites string toCssString() const { if(a == 255) return "#" ~ toHexInternal(r) ~ toHexInternal(g) ~ toHexInternal(b); else { return "rgba("~toInternal!string(r)~", "~toInternal!string(g)~", "~toInternal!string(b)~", "~toInternal!string(cast(real)a / 255.0)~")"; } } /// Makes a hex string RRGGBBAA (aa only present if it is not 255) string toString() const { if(a == 255) return toCssString()[1 .. $]; else return toRgbaHexString(); } /// returns RRGGBBAA, even if a== 255 string toRgbaHexString() const { return toHexInternal(r) ~ toHexInternal(g) ~ toHexInternal(b) ~ toHexInternal(a); } /// Gets a color by name, iff the name is one of the static members listed above static Color fromNameString(string s) { Color c; foreach(member; __traits(allMembers, Color)) { static if(__traits(compiles, c = __traits(getMember, Color, member))) { if(s == member) return __traits(getMember, Color, member); } } throw new Exception("Unknown color " ~ s); } /// Reads a CSS style string to get the color. Understands #rrggbb, rgba(), hsl(), and rrggbbaa static Color fromString(string s) { s = s.stripInternal(); Color c; c.a = 255; // trying named colors via the static no-arg methods here foreach(member; __traits(allMembers, Color)) { static if(__traits(compiles, c = __traits(getMember, Color, member))) { if(s == member) return __traits(getMember, Color, member); } } // try various notations borrowed from CSS (though a little extended) // hsl(h,s,l,a) where h is degrees and s,l,a are 0 >= x <= 1.0 if(s.startsWithInternal("hsl(") || s.startsWithInternal("hsla(")) { assert(s[$-1] == ')'); s = s[s.startsWithInternal("hsl(") ? 4 : 5 .. $ - 1]; // the closing paren real[3] hsl; ubyte a = 255; auto parts = s.splitInternal(','); foreach(i, part; parts) { if(i < 3) hsl[i] = toInternal!real(part.stripInternal); else a = clampToByte(cast(int) (toInternal!real(part.stripInternal) * 255)); } c = .fromHsl(hsl); c.a = a; return c; } // rgb(r,g,b,a) where r,g,b are 0-255 and a is 0-1.0 if(s.startsWithInternal("rgb(") || s.startsWithInternal("rgba(")) { assert(s[$-1] == ')'); s = s[s.startsWithInternal("rgb(") ? 4 : 5 .. $ - 1]; // the closing paren auto parts = s.splitInternal(','); foreach(i, part; parts) { // lol the loop-switch pattern auto v = toInternal!real(part.stripInternal); switch(i) { case 0: // red c.r = clampToByte(cast(int) v); break; case 1: c.g = clampToByte(cast(int) v); break; case 2: c.b = clampToByte(cast(int) v); break; case 3: c.a = clampToByte(cast(int) (v * 255)); break; default: // ignore } } return c; } // otherwise let's try it as a hex string, really loosely if(s.length && s[0] == '#') s = s[1 .. $]; // not a built in... do it as a hex string if(s.length >= 2) { c.r = fromHexInternal(s[0 .. 2]); s = s[2 .. $]; } if(s.length >= 2) { c.g = fromHexInternal(s[0 .. 2]); s = s[2 .. $]; } if(s.length >= 2) { c.b = fromHexInternal(s[0 .. 2]); s = s[2 .. $]; } if(s.length >= 2) { c.a = fromHexInternal(s[0 .. 2]); s = s[2 .. $]; } return c; } /// from hsl static Color fromHsl(real h, real s, real l) { return .fromHsl(h, s, l); } // this is actually branch-less for ints on x86, and even for longs on x86_64 static ubyte clampToByte(T) (T n) pure nothrow @safe @nogc if (__traits(isIntegral, T)) { static if (__VERSION__ > 2067) pragma(inline, true); static if (T.sizeof == 2 || T.sizeof == 4) { static if (__traits(isUnsigned, T)) { return cast(ubyte)(n&0xff|(255-((-cast(int)(n < 256))>>24))); } else { n &= -cast(int)(n >= 0); return cast(ubyte)(n|((255-cast(int)n)>>31)); } } else static if (T.sizeof == 1) { static assert(__traits(isUnsigned, T), "clampToByte: signed byte? no, really?"); return cast(ubyte)n; } else static if (T.sizeof == 8) { static if (__traits(isUnsigned, T)) { return cast(ubyte)(n&0xff|(255-((-cast(long)(n < 256))>>56))); } else { n &= -cast(long)(n >= 0); return cast(ubyte)(n|((255-cast(long)n)>>63)); } } else { static assert(false, "clampToByte: integer too big"); } } /** this mixin can be used to alphablend two `uint` colors; * `colu32name` is variable that holds color to blend, * `destu32name` is variable that holds "current" color (from surface, for example). * alpha value of `destu32name` doesn't matter. * alpha value of `colu32name` means: 255 for replace color, 0 for keep `destu32name`. * * WARNING! This function does blending in RGB space, and RGB space is not linear! */ public enum ColorBlendMixinStr(string colu32name, string destu32name) = "{ immutable uint a_tmp_ = (256-(255-(("~colu32name~")>>24)))&(-(1-(((255-(("~colu32name~")>>24))+1)>>8))); // to not loose bits, but 255 should become 0 immutable uint dc_tmp_ = ("~destu32name~")&0xffffff; immutable uint srb_tmp_ = (("~colu32name~")&0xff00ff); immutable uint sg_tmp_ = (("~colu32name~")&0x00ff00); immutable uint drb_tmp_ = (dc_tmp_&0xff00ff); immutable uint dg_tmp_ = (dc_tmp_&0x00ff00); immutable uint orb_tmp_ = (drb_tmp_+(((srb_tmp_-drb_tmp_)*a_tmp_+0x800080)>>8))&0xff00ff; immutable uint og_tmp_ = (dg_tmp_+(((sg_tmp_-dg_tmp_)*a_tmp_+0x008000)>>8))&0x00ff00; ("~destu32name~") = (orb_tmp_|og_tmp_)|0xff000000; /*&0xffffff;*/ }"; /// Perform alpha-blending of `fore` to this color, return new color. /// WARNING! This function does blending in RGB space, and RGB space is not linear! Color alphaBlend (Color fore) const pure nothrow @trusted @nogc { static if (__VERSION__ > 2067) pragma(inline, true); Color res; res.asUint = asUint; mixin(ColorBlendMixinStr!("fore.asUint", "res.asUint")); return res; } } nothrow @safe private string toHexInternal(ubyte b) { string s; if(b < 16) s ~= '0'; else { ubyte t = (b & 0xf0) >> 4; if(t >= 10) s ~= 'A' + t - 10; else s ~= '0' + t; b &= 0x0f; } if(b >= 10) s ~= 'A' + b - 10; else s ~= '0' + b; return s; } nothrow @safe @nogc pure private ubyte fromHexInternal(string s) { int result = 0; int exp = 1; //foreach(c; retro(s)) { // FIXME: retro doesn't work right in dtojs foreach_reverse(c; s) { if(c >= 'A' && c <= 'F') result += exp * (c - 'A' + 10); else if(c >= 'a' && c <= 'f') result += exp * (c - 'a' + 10); else if(c >= '0' && c <= '9') result += exp * (c - '0'); else // throw new Exception("invalid hex character: " ~ cast(char) c); return 0; exp *= 16; } return cast(ubyte) result; } /// Converts hsl to rgb Color fromHsl(real[3] hsl) { return fromHsl(hsl[0], hsl[1], hsl[2]); } /// Converts hsl to rgb Color fromHsl(real h, real s, real l, real a = 255) { h = h % 360; real C = (1 - absInternal(2 * l - 1)) * s; real hPrime = h / 60; real X = C * (1 - absInternal(hPrime % 2 - 1)); real r, g, b; if(h is real.nan) r = g = b = 0; else if (hPrime >= 0 && hPrime < 1) { r = C; g = X; b = 0; } else if (hPrime >= 1 && hPrime < 2) { r = X; g = C; b = 0; } else if (hPrime >= 2 && hPrime < 3) { r = 0; g = C; b = X; } else if (hPrime >= 3 && hPrime < 4) { r = 0; g = X; b = C; } else if (hPrime >= 4 && hPrime < 5) { r = X; g = 0; b = C; } else if (hPrime >= 5 && hPrime < 6) { r = C; g = 0; b = X; } real m = l - C / 2; r += m; g += m; b += m; return Color( cast(int)(r * 255), cast(int)(g * 255), cast(int)(b * 255), cast(int)(a)); } /// Converts an RGB color into an HSL triplet. useWeightedLightness will try to get a better value for luminosity for the human eye, which is more sensitive to green than red and more to red than blue. If it is false, it just does average of the rgb. real[3] toHsl(Color c, bool useWeightedLightness = false) { real r1 = cast(real) c.r / 255; real g1 = cast(real) c.g / 255; real b1 = cast(real) c.b / 255; real maxColor = maxInternal(r1, g1, b1); real minColor = minInternal(r1, g1, b1); real L = (maxColor + minColor) / 2 ; if(useWeightedLightness) { // the colors don't affect the eye equally // this is a little more accurate than plain HSL numbers L = 0.2126*r1 + 0.7152*g1 + 0.0722*b1; } real S = 0; real H = 0; if(maxColor != minColor) { if(L < 0.5) { S = (maxColor - minColor) / (maxColor + minColor); } else { S = (maxColor - minColor) / (2.0 - maxColor - minColor); } if(r1 == maxColor) { H = (g1-b1) / (maxColor - minColor); } else if(g1 == maxColor) { H = 2.0 + (b1 - r1) / (maxColor - minColor); } else { H = 4.0 + (r1 - g1) / (maxColor - minColor); } } H = H * 60; if(H < 0){ H += 360; } return [H, S, L]; } /// . Color lighten(Color c, real percentage) { auto hsl = toHsl(c); hsl[2] *= (1 + percentage); if(hsl[2] > 1) hsl[2] = 1; return fromHsl(hsl); } /// . Color darken(Color c, real percentage) { auto hsl = toHsl(c); hsl[2] *= (1 - percentage); return fromHsl(hsl); } /// for light colors, call darken. for dark colors, call lighten. /// The goal: get toward center grey. Color moderate(Color c, real percentage) { auto hsl = toHsl(c); if(hsl[2] > 0.5) hsl[2] *= (1 - percentage); else { if(hsl[2] <= 0.01) // if we are given black, moderating it means getting *something* out hsl[2] = percentage; else hsl[2] *= (1 + percentage); } if(hsl[2] > 1) hsl[2] = 1; return fromHsl(hsl); } /// the opposite of moderate. Make darks darker and lights lighter Color extremify(Color c, real percentage) { auto hsl = toHsl(c, true); if(hsl[2] < 0.5) hsl[2] *= (1 - percentage); else hsl[2] *= (1 + percentage); if(hsl[2] > 1) hsl[2] = 1; return fromHsl(hsl); } /// Move around the lightness wheel, trying not to break on moderate things Color oppositeLightness(Color c) { auto hsl = toHsl(c); auto original = hsl[2]; if(original > 0.4 && original < 0.6) hsl[2] = 0.8 - original; // so it isn't quite the same else hsl[2] = 1 - original; return fromHsl(hsl); } /// Try to determine a text color - either white or black - based on the input Color makeTextColor(Color c) { auto hsl = toHsl(c, true); // give green a bonus for contrast if(hsl[2] > 0.71) return Color(0, 0, 0); else return Color(255, 255, 255); } // These provide functional access to hsl manipulation; useful if you need a delegate Color setLightness(Color c, real lightness) { auto hsl = toHsl(c); hsl[2] = lightness; return fromHsl(hsl); } /// Color rotateHue(Color c, real degrees) { auto hsl = toHsl(c); hsl[0] += degrees; return fromHsl(hsl); } /// Color setHue(Color c, real hue) { auto hsl = toHsl(c); hsl[0] = hue; return fromHsl(hsl); } /// Color desaturate(Color c, real percentage) { auto hsl = toHsl(c); hsl[1] *= (1 - percentage); return fromHsl(hsl); } /// Color saturate(Color c, real percentage) { auto hsl = toHsl(c); hsl[1] *= (1 + percentage); if(hsl[1] > 1) hsl[1] = 1; return fromHsl(hsl); } /// Color setSaturation(Color c, real saturation) { auto hsl = toHsl(c); hsl[1] = saturation; return fromHsl(hsl); } /* void main(string[] args) { auto color1 = toHsl(Color(255, 0, 0)); auto color = fromHsl(color1[0] + 60, color1[1], color1[2]); writefln("#%02x%02x%02x", color.r, color.g, color.b); } */ /* Color algebra functions */ /* Alpha putpixel looks like this: void putPixel(Image i, Color c) { Color b; b.r = i.data[(y * i.width + x) * bpp + 0]; b.g = i.data[(y * i.width + x) * bpp + 1]; b.b = i.data[(y * i.width + x) * bpp + 2]; b.a = i.data[(y * i.width + x) * bpp + 3]; float ca = cast(float) c.a / 255; i.data[(y * i.width + x) * bpp + 0] = alpha(c.r, ca, b.r); i.data[(y * i.width + x) * bpp + 1] = alpha(c.g, ca, b.g); i.data[(y * i.width + x) * bpp + 2] = alpha(c.b, ca, b.b); i.data[(y * i.width + x) * bpp + 3] = alpha(c.a, ca, b.a); } ubyte alpha(ubyte c1, float alpha, ubyte onto) { auto got = (1 - alpha) * onto + alpha * c1; if(got > 255) return 255; return cast(ubyte) got; } So, given the background color and the resultant color, what was composited on to it? */ /// ubyte unalpha(ubyte colorYouHave, float alpha, ubyte backgroundColor) { // resultingColor = (1-alpha) * backgroundColor + alpha * answer auto resultingColorf = cast(float) colorYouHave; auto backgroundColorf = cast(float) backgroundColor; auto answer = (resultingColorf - backgroundColorf + alpha * backgroundColorf) / alpha; return Color.clampToByte(cast(int) answer); } /// ubyte makeAlpha(ubyte colorYouHave, ubyte backgroundColor/*, ubyte foreground = 0x00*/) { //auto foregroundf = cast(float) foreground; auto foregroundf = 0.00f; auto colorYouHavef = cast(float) colorYouHave; auto backgroundColorf = cast(float) backgroundColor; // colorYouHave = backgroundColorf - alpha * backgroundColorf + alpha * foregroundf auto alphaf = 1 - colorYouHave / backgroundColorf; alphaf *= 255; return Color.clampToByte(cast(int) alphaf); } int fromHex(string s) { int result = 0; int exp = 1; // foreach(c; retro(s)) { foreach_reverse(c; s) { if(c >= 'A' && c <= 'F') result += exp * (c - 'A' + 10); else if(c >= 'a' && c <= 'f') result += exp * (c - 'a' + 10); else if(c >= '0' && c <= '9') result += exp * (c - '0'); else throw new Exception("invalid hex character: " ~ cast(char) c); exp *= 16; } return result; } /// Color colorFromString(string s) { if(s.length == 0) return Color(0,0,0,255); if(s[0] == '#') s = s[1..$]; assert(s.length == 6 || s.length == 8); Color c; c.r = cast(ubyte) fromHex(s[0..2]); c.g = cast(ubyte) fromHex(s[2..4]); c.b = cast(ubyte) fromHex(s[4..6]); if(s.length == 8) c.a = cast(ubyte) fromHex(s[6..8]); else c.a = 255; return c; } /* import browser.window; import std.conv; void main() { import browser.document; foreach(ele; document.querySelectorAll("input")) { ele.addEventListener("change", { auto h = toInternal!real(document.querySelector("input[name=h]").value); auto s = toInternal!real(document.querySelector("input[name=s]").value); auto l = toInternal!real(document.querySelector("input[name=l]").value); Color c = Color.fromHsl(h, s, l); auto e = document.getElementById("example"); e.style.backgroundColor = c.toCssString(); // JSElement __js_this; // __js_this.style.backgroundColor = c.toCssString(); }, false); } } */ /** This provides two image classes and a bunch of functions that work on them. Why are they separate classes? I think the operations on the two of them are necessarily different. There's a whole bunch of operations that only really work on truecolor (blurs, gradients), and a few that only work on indexed images (palette swaps). Even putpixel is pretty different. On indexed, it is a palette entry's index number. On truecolor, it is the actual color. A greyscale image is the weird thing in the middle. It is truecolor, but fits in the same size as indexed. Still, I'd say it is a specialization of truecolor. There is a subset that works on both */ /// An image in memory interface MemoryImage { //IndexedImage convertToIndexedImage() const; //TrueColorImage convertToTrueColor() const; /// gets it as a TrueColorImage. May return this or may do a conversion and return a new image TrueColorImage getAsTrueColorImage(); /// Image width, in pixels int width() const; /// Image height, in pixels int height() const; /// Get image pixel. Slow, but returns valid RGBA color (completely transparent for off-image pixels). Color getPixel(int x, int y) const; /// Set image pixel. void setPixel(int x, int y, in Color clr); /// Load image from file. This will import arsd.image to do the actual work, and cost nothing if you don't use it. static MemoryImage fromImage(T : const(char)[]) (T filename) @trusted { static if (__traits(compiles, (){import arsd.image;})) { // yay, we have image loader here, try it! import arsd.image; return loadImageFromFile(filename); } else { static assert(0, "please provide 'arsd.image' to load images!"); } } /// Convenient alias for `fromImage` alias fromImageFile = fromImage; } /// An image that consists of indexes into a color palette. Use [getAsTrueColorImage]() if you don't care about palettes class IndexedImage : MemoryImage { bool hasAlpha; /// . Color[] palette; /// the data as indexes into the palette. Stored left to right, top to bottom, no padding. ubyte[] data; /// . override int width() const { return _width; } /// . override int height() const { return _height; } override Color getPixel(int x, int y) const @trusted { if (x >= 0 && y >= 0 && x < _width && y < _height) { uint pos = y*_width+x; if (pos >= data.length) return Color(0, 0, 0, 0); ubyte b = data.ptr[pos]; if (b >= palette.length) return Color(0, 0, 0, 0); return palette.ptr[b]; } else { return Color(0, 0, 0, 0); } } override void setPixel(int x, int y, in Color clr) @trusted { if (x >= 0 && y >= 0 && x < _width && y < _height) { uint pos = y*_width+x; if (pos >= data.length) return; ubyte pidx = findNearestColor(palette, clr); if (palette.length < 255 && (palette.ptr[pidx].r != clr.r || palette.ptr[pidx].g != clr.g || palette.ptr[pidx].b != clr.b || palette.ptr[pidx].a != clr.a)) { // add new color pidx = addColor(clr); } data.ptr[pos] = pidx; } } private int _width; private int _height; /// . this(int w, int h) { _width = w; _height = h; data = new ubyte[w*h]; } /* void resize(int w, int h, bool scale) { } */ /// returns a new image override TrueColorImage getAsTrueColorImage() { return convertToTrueColor(); } /// Creates a new TrueColorImage based on this data TrueColorImage convertToTrueColor() const { auto tci = new TrueColorImage(width, height); foreach(i, b; data) { /* if(b >= palette.length) { string fuckyou; fuckyou ~= b + '0'; fuckyou ~= " "; fuckyou ~= palette.length + '0'; assert(0, fuckyou); } */ tci.imageData.colors[i] = palette[b]; } return tci; } /// Gets an exact match, if possible, adds if not. See also: the findNearestColor free function. ubyte getOrAddColor(Color c) { foreach(i, co; palette) { if(c == co) return cast(ubyte) i; } return addColor(c); } /// Number of colors currently in the palette (note: palette entries are not necessarily used in the image data) int numColors() const { return cast(int) palette.length; } /// Adds an entry to the palette, returning its inded ubyte addColor(Color c) { assert(palette.length < 256); if(c.a != 255) hasAlpha = true; palette ~= c; return cast(ubyte) (palette.length - 1); } } /// An RGBA array of image data. Use the free function quantize() to convert to an IndexedImage class TrueColorImage : MemoryImage { // bool hasAlpha; // bool isGreyscale; //ubyte[] data; // stored as rgba quads, upper left to right to bottom /// . struct Data { ubyte[] bytes; /// the data as rgba bytes. Stored left to right, top to bottom, no padding. // the union is no good because the length of the struct is wrong! /// the same data as Color structs @trusted // the cast here is typically unsafe, but it is ok // here because I guarantee the layout, note the static assert below @property inout(Color)[] colors() inout { return cast(inout(Color)[]) bytes; } static assert(Color.sizeof == 4); } /// . Data imageData; alias imageData.bytes data; int _width; int _height; /// . override int width() const { return _width; } ///. override int height() const { return _height; } override Color getPixel(int x, int y) const @trusted { if (x >= 0 && y >= 0 && x < _width && y < _height) { uint pos = y*_width+x; return imageData.colors.ptr[pos]; } else { return Color(0, 0, 0, 0); } } override void setPixel(int x, int y, in Color clr) @trusted { if (x >= 0 && y >= 0 && x < _width && y < _height) { uint pos = y*_width+x; if (pos < imageData.bytes.length/4) imageData.colors.ptr[pos] = clr; } } /// . this(int w, int h) { _width = w; _height = h; imageData.bytes = new ubyte[w*h*4]; } /// Creates with existing data. The data pointer is stored here. this(int w, int h, ubyte[] data) { _width = w; _height = h; assert(data.length == w * h * 4); imageData.bytes = data; } /// Returns this override TrueColorImage getAsTrueColorImage() { return this; } } /// Converts true color to an indexed image. It uses palette as the starting point, adding entries /// until maxColors as needed. If palette is null, it creates a whole new palette. /// /// After quantizing the image, it applies a dithering algorithm. /// /// This is not written for speed. IndexedImage quantize(in TrueColorImage img, Color[] palette = null, in int maxColors = 256) // this is just because IndexedImage assumes ubyte palette values in { assert(maxColors <= 256); } body { int[Color] uses; foreach(pixel; img.imageData.colors) { if(auto i = pixel in uses) { (*i)++; } else { uses[pixel] = 1; } } struct ColorUse { Color c; int uses; //string toString() { import std.conv; return c.toCssString() ~ " x " ~ to!string(uses); } int opCmp(ref const ColorUse co) const { return co.uses - uses; } } ColorUse[] sorted; foreach(color, count; uses) sorted ~= ColorUse(color, count); uses = null; version(no_phobos) sorted = sorted.sort; else { import std.algorithm : sort; sort(sorted); } ubyte[Color] paletteAssignments; foreach(idx, entry; palette) paletteAssignments[entry] = cast(ubyte) idx; // For the color assignments from the image, I do multiple passes, decreasing the acceptable // distance each time until we're full. // This is probably really slow.... but meh it gives pretty good results. auto ddiff = 32; outer: for(int d1 = 128; d1 >= 0; d1 -= ddiff) { auto minDist = d1*d1; if(d1 <= 64) ddiff = 16; if(d1 <= 32) ddiff = 8; foreach(possibility; sorted) { if(palette.length == maxColors) break; if(palette.length) { auto co = palette[findNearestColor(palette, possibility.c)]; auto pixel = possibility.c; auto dr = cast(int) co.r - pixel.r; auto dg = cast(int) co.g - pixel.g; auto db = cast(int) co.b - pixel.b; auto dist = dr*dr + dg*dg + db*db; // not good enough variety to justify an allocation yet if(dist < minDist) continue; } paletteAssignments[possibility.c] = cast(ubyte) palette.length; palette ~= possibility.c; } } // Final pass: just fill in any remaining space with the leftover common colors while(palette.length < maxColors && sorted.length) { if(sorted[0].c !in paletteAssignments) { paletteAssignments[sorted[0].c] = cast(ubyte) palette.length; palette ~= sorted[0].c; } sorted = sorted[1 .. $]; } bool wasPerfect = true; auto newImage = new IndexedImage(img.width, img.height); newImage.palette = palette; foreach(idx, pixel; img.imageData.colors) { if(auto p = pixel in paletteAssignments) newImage.data[idx] = *p; else { // gotta find the closest one... newImage.data[idx] = findNearestColor(palette, pixel); wasPerfect = false; } } if(!wasPerfect) floydSteinbergDither(newImage, img); return newImage; } /// Finds the best match for pixel in palette (currently by checking for minimum euclidean distance in rgb colorspace) ubyte findNearestColor(in Color[] palette, in Color pixel) { int best = 0; int bestDistance = int.max; foreach(pe, co; palette) { auto dr = cast(int) co.r - pixel.r; auto dg = cast(int) co.g - pixel.g; auto db = cast(int) co.b - pixel.b; int dist = dr*dr + dg*dg + db*db; if(dist < bestDistance) { best = cast(int) pe; bestDistance = dist; } } return cast(ubyte) best; } /+ // Quantizing and dithering test program void main( ){ /* auto img = new TrueColorImage(256, 32); foreach(y; 0 .. img.height) { foreach(x; 0 .. img.width) { img.imageData.colors[x + y * img.width] = Color(x, y * (255 / img.height), 0); } } */ TrueColorImage img; { import arsd.png; struct P { ubyte[] range; void put(ubyte[] a) { range ~= a; } } P range; import std.algorithm; import std.stdio; writePngLazy(range, pngFromBytes(File("/home/me/nyesha.png").byChunk(4096)).byRgbaScanline.map!((line) { foreach(ref pixel; line.pixels) { continue; auto sum = cast(int) pixel.r + pixel.g + pixel.b; ubyte a = cast(ubyte)(sum / 3); pixel.r = a; pixel.g = a; pixel.b = a; } return line; })); img = imageFromPng(readPng(range.range)).getAsTrueColorImage; } auto qimg = quantize(img, null, 2); import arsd.simpledisplay; auto win = new SimpleWindow(img.width, img.height * 3); auto painter = win.draw(); painter.drawImage(Point(0, 0), Image.fromMemoryImage(img)); painter.drawImage(Point(0, img.height), Image.fromMemoryImage(qimg)); floydSteinbergDither(qimg, img); painter.drawImage(Point(0, img.height * 2), Image.fromMemoryImage(qimg)); win.eventLoop(0); } +/ /+ /// If the background is transparent, it simply erases the alpha channel. void removeTransparency(IndexedImage img, Color background) +/ /// Perform alpha-blending of `fore` to this color, return new color. /// WARNING! This function does blending in RGB space, and RGB space is not linear! Color alphaBlend(Color foreground, Color background) pure nothrow @safe @nogc { static if (__VERSION__ > 2067) pragma(inline, true); return background.alphaBlend(foreground); } /* /// Reduces the number of colors in a palette. void reducePaletteSize(IndexedImage img, int maxColors = 16) { } */ // I think I did this wrong... but the results aren't too bad so the bug can't be awful. /// Dithers img in place to look more like original. void floydSteinbergDither(IndexedImage img, in TrueColorImage original) { assert(img.width == original.width); assert(img.height == original.height); auto buffer = new Color[](original.imageData.colors.length); int x, y; foreach(idx, c; original.imageData.colors) { auto n = img.palette[img.data[idx]]; int errorR = cast(int) c.r - n.r; int errorG = cast(int) c.g - n.g; int errorB = cast(int) c.b - n.b; void doit(int idxOffset, int multiplier) { // if(idx + idxOffset < buffer.length) buffer[idx + idxOffset] = Color.fromIntegers( c.r + multiplier * errorR / 16, c.g + multiplier * errorG / 16, c.b + multiplier * errorB / 16, c.a ); } if((x+1) != original.width) doit(1, 7); if((y+1) != original.height) { if(x != 0) doit(-1 + img.width, 3); doit(img.width, 5); if(x+1 != original.width) doit(1 + img.width, 1); } img.data[idx] = findNearestColor(img.palette, buffer[idx]); x++; if(x == original.width) { x = 0; y++; } } } // these are just really useful in a lot of places where the color/image functions are used, // so I want them available with Color /// struct Point { int x; /// int y; /// pure const nothrow @safe: Point opBinary(string op)(in Point rhs) { return Point(mixin("x" ~ op ~ "rhs.x"), mixin("y" ~ op ~ "rhs.y")); } Point opBinary(string op)(int rhs) { return Point(mixin("x" ~ op ~ "rhs"), mixin("y" ~ op ~ "rhs")); } } /// struct Size { int width; /// int height; /// } /// struct Rectangle { int left; /// int top; /// int right; /// int bottom; /// pure const nothrow @safe: /// this(int left, int top, int right, int bottom) { this.left = left; this.top = top; this.right = right; this.bottom = bottom; } /// this(in Point upperLeft, in Point lowerRight) { this(upperLeft.x, upperLeft.y, lowerRight.x, lowerRight.y); } /// this(in Point upperLeft, in Size size) { this(upperLeft.x, upperLeft.y, upperLeft.x + size.width, upperLeft.y + size.height); } /// @property Point upperLeft() { return Point(left, top); } /// @property Point lowerRight() { return Point(right, bottom); } /// @property Size size() { return Size(width, height); } /// @property int width() { return right - left; } /// @property int height() { return bottom - top; } /// Returns true if this rectangle entirely contains the other bool contains(in Rectangle r) { return contains(r.upperLeft) && contains(r.lowerRight); } /// ditto bool contains(in Point p) { return (p.x >= left && p.y < right && p.y >= top && p.y < bottom); } /// Returns true of the two rectangles at any point overlap bool overlaps(in Rectangle r) { // the -1 in here are because right and top are exclusive return !((right-1) < r.left || (r.right-1) < left || (bottom-1) < r.top || (r.bottom-1) < top); } } /++ Implements a flood fill algorithm, like the bucket tool in MS Paint. Params: what = the canvas to work with, arranged as top to bottom, left to right elements width = the width of the canvas height = the height of the canvas target = the type to replace. You may pass the existing value if you want to do what Paint does replacement = the replacement value x = the x-coordinate to start the fill (think of where the user clicked in Paint) y = the y-coordinate to start the fill additionalCheck = A custom additional check to perform on each square before continuing. Returning true means keep flooding, returning false means stop. +/ void floodFill(T)( T[] what, int width, int height, // the canvas to inspect T target, T replacement, // fill params int x, int y, bool delegate(int x, int y) @safe additionalCheck) // the node { T node = what[y * width + x]; if(target == replacement) return; if(node != target) return; if(additionalCheck is null) additionalCheck = (int, int) => true; if(!additionalCheck(x, y)) return; what[y * width + x] = replacement; if(x) floodFill(what, width, height, target, replacement, x - 1, y, additionalCheck); if(x != width - 1) floodFill(what, width, height, target, replacement, x + 1, y, additionalCheck); if(y) floodFill(what, width, height, target, replacement, x, y - 1, additionalCheck); if(y != height - 1) floodFill(what, width, height, target, replacement, x, y + 1, additionalCheck); } // for scripting, so you can tag it without strictly needing to import arsd.jsvar enum arsd_jsvar_compatible = "arsd_jsvar_compatible";
D
module imports.a8392; import ice8392; class B { this(B); } void foob(A a, B b) { a.fooa!((arg){ return new B(b); }); }
D
module dsdl.core.error; import std.traits; import derelict.sdl2.sdl; import derelict.sdl2.image; /** * Abstract superclass for SDL and satellite library exceptions. * It stores an int error code in addition to a message. */ abstract class AbstractSDLException : Exception { private int _code; public this(string msg, int code, string file = __FILE__, size_t line = cast(size_t)__LINE__) { super(msg, file, line); this._code = code; } @property int code() { return _code; } } /** * A convenient mixin template for creating constructors for subclasses of * AbstractSDLException. See SDLCoreException for a usage example. * * @param ErrorTextFunction the name of the function to call to get the last * error string (e.g. SDL_GetError). The function must take no arguments and * return a char* or const(char)* */ mixin template SDLExceptionSubclassThis(alias ErrorTextFunction) if (isSomeFunction!ErrorTextFunction && arity!ErrorTextFunction == 0 && (is(ReturnType!ErrorTextFunction == const(char)*) || is(ReturnType!ErrorTextFunction == char*))) { /** * Construct the exception with a custom int code and a custom message. */ public this(string msg, int code, string file = __FILE__, size_t line = cast(size_t)__LINE__) { super(msg, code, file, line); } /** * Construct the exception with a custom int code and a message derived * from the error string function given as a template parameter. */ public this(int code, string file = __FILE__, size_t line = cast(size_t)__LINE__) { // keep this import here so client files do not have to import it import std.string : fromStringz; super(fromStringz(ErrorTextFunction()).idup, code, file, line); } } /** * Thrown to signify an error in the core SDL library. */ class SDLCoreException : AbstractSDLException { // use SDL_GetError to get the last error string mixin SDLExceptionSubclassThis!(SDL_GetError); } /** * Thrown to signify an error in the IMG satellite library. */ class SDLIMGException : AbstractSDLException { mixin SDLExceptionSubclassThis!(IMG_GetError); } /** * If code is not zero, throw an AbstractSDLException-derived exception of the * given type with that code. */ int sdlEnforceZero(ExceptionType) (int code, string file = __FILE__, size_t line = cast(size_t)__LINE__) if (is(ExceptionType : AbstractSDLException)) { if (code != 0) { throw new ExceptionType(code, file, line); } return code; } /** * Same as sdlEnforceZero, but throw only when the code is negative. */ int sdlEnforceNatural(ExceptionType) (int code, string file = __FILE__, size_t line = cast(size_t)__LINE__) if (is(ExceptionType : AbstractSDLException)) { if (code < 0) { throw new ExceptionType(code, file, line); } return code; } PointedType* sdlEnforcePtr(ExceptionType, PointedType) (PointedType* ptr, string file = __FILE__, size_t line = cast(size_t)__LINE__) if (is(ExceptionType : AbstractSDLException)) { if (ptr is null) { throw new ExceptionType(0, file, line); } return ptr; }
D
module main; import org.serviio.MediaServer; int main(string[] argv) { MediaServer.main(argv); return 0; }
D
/Users/Zhongli/Desktop/NewsDemo/DerivedData/NewsDemo/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/SnapKit.build/Objects-normal/x86_64/ConstraintLayoutSupport.o : /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintLayoutGuideDSL.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintDSL.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintLayoutSupportDSL.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintViewDSL.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintLayoutGuide.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintMakerExtendable.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintMakerRelatable.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintMakerEditable.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintMakerFinalizable.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintMakerPriortizable.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintConfig.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/Debugging.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintItem.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/LayoutConstraintItem.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintRelation.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintDescription.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintMaker.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/Typealiases.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintAttributes.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintLayoutGuide+Extensions.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/UILayoutSupport+Extensions.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintView+Extensions.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintInsets.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintRelatableTarget.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintMultiplierTarget.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintOffsetTarget.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintInsetTarget.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintConstantTarget.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintPriorityTarget.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/Constraint.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/LayoutConstraint.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintLayoutSupport.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintView.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintPriority.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/Zhongli/Desktop/NewsDemo/Pods/Target\ Support\ Files/SnapKit/SnapKit-umbrella.h /Users/Zhongli/Desktop/NewsDemo/DerivedData/NewsDemo/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/SnapKit.build/unextended-module.modulemap /Users/Zhongli/Desktop/NewsDemo/DerivedData/NewsDemo/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/SnapKit.build/Objects-normal/x86_64/ConstraintLayoutSupport~partial.swiftmodule : /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintLayoutGuideDSL.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintDSL.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintLayoutSupportDSL.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintViewDSL.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintLayoutGuide.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintMakerExtendable.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintMakerRelatable.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintMakerEditable.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintMakerFinalizable.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintMakerPriortizable.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintConfig.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/Debugging.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintItem.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/LayoutConstraintItem.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintRelation.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintDescription.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintMaker.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/Typealiases.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintAttributes.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintLayoutGuide+Extensions.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/UILayoutSupport+Extensions.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintView+Extensions.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintInsets.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintRelatableTarget.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintMultiplierTarget.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintOffsetTarget.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintInsetTarget.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintConstantTarget.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintPriorityTarget.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/Constraint.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/LayoutConstraint.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintLayoutSupport.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintView.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintPriority.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/Zhongli/Desktop/NewsDemo/Pods/Target\ Support\ Files/SnapKit/SnapKit-umbrella.h /Users/Zhongli/Desktop/NewsDemo/DerivedData/NewsDemo/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/SnapKit.build/unextended-module.modulemap /Users/Zhongli/Desktop/NewsDemo/DerivedData/NewsDemo/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/SnapKit.build/Objects-normal/x86_64/ConstraintLayoutSupport~partial.swiftdoc : /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintLayoutGuideDSL.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintDSL.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintLayoutSupportDSL.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintViewDSL.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintLayoutGuide.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintMakerExtendable.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintMakerRelatable.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintMakerEditable.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintMakerFinalizable.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintMakerPriortizable.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintConfig.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/Debugging.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintItem.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/LayoutConstraintItem.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintRelation.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintDescription.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintMaker.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/Typealiases.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintAttributes.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintLayoutGuide+Extensions.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/UILayoutSupport+Extensions.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintView+Extensions.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintInsets.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintRelatableTarget.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintMultiplierTarget.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintOffsetTarget.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintInsetTarget.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintConstantTarget.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintPriorityTarget.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/Constraint.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/LayoutConstraint.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintLayoutSupport.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintView.swift /Users/Zhongli/Desktop/NewsDemo/Pods/SnapKit/Source/ConstraintPriority.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/Zhongli/Desktop/NewsDemo/Pods/Target\ Support\ Files/SnapKit/SnapKit-umbrella.h /Users/Zhongli/Desktop/NewsDemo/DerivedData/NewsDemo/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/SnapKit.build/unextended-module.modulemap
D
/++ This is a port of the C code from https://www.nayuki.io/page/qr-code-generator-library History: Originally written in C by Project Nayuki. Ported to D by me on July 26, 2021 +/ /* * QR Code generator library (C) * * Copyright (c) Project Nayuki. (MIT License) * https://www.nayuki.io/page/qr-code-generator-library * * 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 arsd.qrcode; /// unittest { import arsd.qrcode; void main() { import arsd.simpledisplay; QrCode code = QrCode("http://arsdnet.net/"); enum drawsize = 4; // you have to have some border around it auto window = new SimpleWindow(code.size * drawsize + 80, code.size * drawsize + 80); { auto painter = window.draw; painter.clear(Color.white); foreach(y; 0 .. code.size) foreach(x; 0 .. code.size) { if(code[x, y]) { painter.outlineColor = Color.black; painter.fillColor = Color.black; } else { painter.outlineColor = Color.white; painter.fillColor = Color.white; } painter.drawRectangle(Point(x * drawsize + 40, y * drawsize + 40), Size(drawsize, drawsize)); } } window.eventLoop(0); } main; // exclude from docs } import core.stdc.stddef; import core.stdc.stdint; import core.stdc.string; import core.stdc.config; import core.stdc.stdlib; import core.stdc.math; /* * This library creates QR Code symbols, which is a type of two-dimension barcode. * Invented by Denso Wave and described in the ISO/IEC 18004 standard. * A QR Code structure is an immutable square grid of black and white cells. * The library provides functions to create a QR Code from text or binary data. * The library covers the QR Code Model 2 specification, supporting all versions (sizes) * from 1 to 40, all 4 error correction levels, and 4 character encoding modes. * * Ways to create a QR Code object: * - High level: Take the payload data and call qrcodegen_encodeText() or qrcodegen_encodeBinary(). * - Low level: Custom-make the list of segments and call * qrcodegen_encodeSegments() or qrcodegen_encodeSegmentsAdvanced(). * (Note that all ways require supplying the desired error correction level and various byte buffers.) */ /*---- Enum and struct types----*/ /* * The error correction level in a QR Code symbol. */ alias qrcodegen_Ecc = int; enum /*qrcodegen_Ecc*/ { // Must be declared in ascending order of error protection // so that an internal qrcodegen function works properly qrcodegen_Ecc_LOW = 0 , // The QR Code can tolerate about 7% erroneous codewords qrcodegen_Ecc_MEDIUM , // The QR Code can tolerate about 15% erroneous codewords qrcodegen_Ecc_QUARTILE, // The QR Code can tolerate about 25% erroneous codewords qrcodegen_Ecc_HIGH , // The QR Code can tolerate about 30% erroneous codewords } /* * The mask pattern used in a QR Code symbol. */ alias qrcodegen_Mask = int; enum /* qrcodegen_Mask */ { // A special value to tell the QR Code encoder to // automatically select an appropriate mask pattern qrcodegen_Mask_AUTO = -1, // The eight actual mask patterns qrcodegen_Mask_0 = 0, qrcodegen_Mask_1, qrcodegen_Mask_2, qrcodegen_Mask_3, qrcodegen_Mask_4, qrcodegen_Mask_5, qrcodegen_Mask_6, qrcodegen_Mask_7, } /* * Describes how a segment's data bits are interpreted. */ alias qrcodegen_Mode = int; enum /*qrcodegen_Mode*/ { qrcodegen_Mode_NUMERIC = 0x1, qrcodegen_Mode_ALPHANUMERIC = 0x2, qrcodegen_Mode_BYTE = 0x4, qrcodegen_Mode_KANJI = 0x8, qrcodegen_Mode_ECI = 0x7, } /* * A segment of character/binary/control data in a QR Code symbol. * The mid-level way to create a segment is to take the payload data * and call a factory function such as qrcodegen_makeNumeric(). * The low-level way to create a segment is to custom-make the bit buffer * and initialize a qrcodegen_Segment struct with appropriate values. * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data. * Any segment longer than this is meaningless for the purpose of generating QR Codes. * Moreover, the maximum allowed bit length is 32767 because * the largest QR Code (version 40) has 31329 modules. */ struct qrcodegen_Segment { // The mode indicator of this segment. qrcodegen_Mode mode; // The length of this segment's unencoded data. Measured in characters for // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode. // Always zero or positive. Not the same as the data's bit length. int numChars; // The data bits of this segment, packed in bitwise big endian. // Can be null if the bit length is zero. uint8_t *data; // The number of valid data bits used in the buffer. Requires // 0 <= bitLength <= 32767, and bitLength <= (capacity of data array) * 8. // The character count (numChars) must agree with the mode and the bit buffer length. int bitLength; }; /*---- Macro constants and functions ----*/ enum qrcodegen_VERSION_MIN = 1; // The minimum version number supported in the QR Code Model 2 standard enum qrcodegen_VERSION_MAX = 40; // The maximum version number supported in the QR Code Model 2 standard // Calculates the number of bytes needed to store any QR Code up to and including the given version number, // as a compile-time constant. For example, 'uint8_t buffer[qrcodegen_BUFFER_LEN_FOR_VERSION(25)];' // can store any single QR Code from version 1 to 25 (inclusive). The result fits in an int (or int16). // Requires qrcodegen_VERSION_MIN <= n <= qrcodegen_VERSION_MAX. auto qrcodegen_BUFFER_LEN_FOR_VERSION(int n) { return ((((n) * 4 + 17) * ((n) * 4 + 17) + 7) / 8 + 1); } // The worst-case number of bytes needed to store one QR Code, up to and including // version 40. This value equals 3918, which is just under 4 kilobytes. // Use this more convenient value to avoid calculating tighter memory bounds for buffers. auto qrcodegen_BUFFER_LEN_MAX() { return qrcodegen_BUFFER_LEN_FOR_VERSION(qrcodegen_VERSION_MAX); } /*---- Functions (high level) to generate QR Codes ----*/ /* * Encodes the given text string to a QR Code, returning true if encoding succeeded. * If the data is too long to fit in any version in the given range * at the given ECC level, then false is returned. * - The input text must be encoded in UTF-8 and contain no NULs. * - The variables ecl and mask must correspond to enum constant values. * - Requires 1 <= minVersion <= maxVersion <= 40. * - The arrays tempBuffer and qrcode must each have a length * of at least qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion). * - After the function returns, tempBuffer contains no useful data. * - If successful, the resulting QR Code may use numeric, * alphanumeric, or byte mode to encode the text. * - In the most optimistic case, a QR Code at version 40 with low ECC * can hold any UTF-8 string up to 2953 bytes, or any alphanumeric string * up to 4296 characters, or any digit string up to 7089 characters. * These numbers represent the hard upper limit of the QR Code standard. * - Please consult the QR Code specification for information on * data capacities per version, ECC level, and text encoding mode. */ bool qrcodegen_encodeText(const char *text, uint8_t* tempBuffer, uint8_t* qrcode, qrcodegen_Ecc ecl, int minVersion, int maxVersion, qrcodegen_Mask mask, bool boostEcl); /* * Encodes the given binary data to a QR Code, returning true if encoding succeeded. * If the data is too long to fit in any version in the given range * at the given ECC level, then false is returned. * - The input array range dataAndTemp[0 : dataLen] should normally be * valid UTF-8 text, but is not required by the QR Code standard. * - The variables ecl and mask must correspond to enum constant values. * - Requires 1 <= minVersion <= maxVersion <= 40. * - The arrays dataAndTemp and qrcode must each have a length * of at least qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion). * - After the function returns, the contents of dataAndTemp may have changed, * and does not represent useful data anymore. * - If successful, the resulting QR Code will use byte mode to encode the data. * - In the most optimistic case, a QR Code at version 40 with low ECC can hold any byte * sequence up to length 2953. This is the hard upper limit of the QR Code standard. * - Please consult the QR Code specification for information on * data capacities per version, ECC level, and text encoding mode. */ bool qrcodegen_encodeBinary(uint8_t* dataAndTemp, size_t dataLen, uint8_t* qrcode, qrcodegen_Ecc ecl, int minVersion, int maxVersion, qrcodegen_Mask mask, bool boostEcl); /*---- Functions to extract raw data from QR Codes ----*/ /* * QR Code generator library (C) * * Copyright (c) Project Nayuki. (MIT License) * https://www.nayuki.io/page/qr-code-generator-library * * 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. */ /*---- Forward declarations for private functions ----*/ // Regarding all public and private functions defined in this source file: // - They require all pointer/array arguments to be not null unless the array length is zero. // - They only read input scalar/array arguments, write to output pointer/array // arguments, and return scalar values; they are "pure" functions. // - They don't read mutable global variables or write to any global variables. // - They don't perform I/O, read the clock, print to console, etc. // - They allocate a small and constant amount of stack memory. // - They don't allocate or free any memory on the heap. // - They don't recurse or mutually recurse. All the code // could be inlined into the top-level public functions. // - They run in at most quadratic time with respect to input arguments. // Most functions run in linear time, and some in constant time. // There are no unbounded loops or non-obvious termination conditions. // - They are completely thread-safe if the caller does not give the // same writable buffer to concurrent calls to these functions. /*---- Private tables of constants ----*/ // The set of all legal characters in alphanumeric mode, where each character // value maps to the index in the string. For checking text and encoding segments. static const char *ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; // For generating error correction codes. private const int8_t[41][4] ECC_CODEWORDS_PER_BLOCK = [ // Version: (note that index 0 is for padding, and is set to an illegal value) //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level [-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // Low [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28], // Medium [-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // Quartile [-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // High ]; enum qrcodegen_REED_SOLOMON_DEGREE_MAX = 30; // Based on the table above // For generating error correction codes. private const int8_t[41][4] NUM_ERROR_CORRECTION_BLOCKS = [ // Version: (note that index 0 is for padding, and is set to an illegal value) //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level [-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25], // Low [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49], // Medium [-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68], // Quartile [-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81], // High ]; // For automatic mask pattern selection. static const int PENALTY_N1 = 3; static const int PENALTY_N2 = 3; static const int PENALTY_N3 = 40; static const int PENALTY_N4 = 10; /*---- High-level QR Code encoding functions ----*/ // Public function - see documentation comment in header file. bool qrcodegen_encodeText(const char *text, uint8_t* tempBuffer, uint8_t* qrcode, qrcodegen_Ecc ecl, int minVersion, int maxVersion, qrcodegen_Mask mask, bool boostEcl) { size_t textLen = strlen(text); if (textLen == 0) return qrcodegen_encodeSegmentsAdvanced(null, 0, ecl, minVersion, maxVersion, mask, boostEcl, tempBuffer, qrcode); size_t bufLen = qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion); qrcodegen_Segment seg; if (qrcodegen_isNumeric(text)) { if (qrcodegen_calcSegmentBufferSize(qrcodegen_Mode_NUMERIC, textLen) > bufLen) goto fail; seg = qrcodegen_makeNumeric(text, tempBuffer); } else if (qrcodegen_isAlphanumeric(text)) { if (qrcodegen_calcSegmentBufferSize(qrcodegen_Mode_ALPHANUMERIC, textLen) > bufLen) goto fail; seg = qrcodegen_makeAlphanumeric(text, tempBuffer); } else { if (textLen > bufLen) goto fail; for (size_t i = 0; i < textLen; i++) tempBuffer[i] = cast(uint8_t)text[i]; seg.mode = qrcodegen_Mode_BYTE; seg.bitLength = calcSegmentBitLength(seg.mode, textLen); if (seg.bitLength == -1) goto fail; seg.numChars = cast(int)textLen; seg.data = tempBuffer; } return qrcodegen_encodeSegmentsAdvanced(&seg, 1, ecl, minVersion, maxVersion, mask, boostEcl, tempBuffer, qrcode); fail: qrcode[0] = 0; // Set size to invalid value for safety return false; } // Public function - see documentation comment in header file. bool qrcodegen_encodeBinary(uint8_t* dataAndTemp, size_t dataLen, uint8_t* qrcode, qrcodegen_Ecc ecl, int minVersion, int maxVersion, qrcodegen_Mask mask, bool boostEcl) { qrcodegen_Segment seg; seg.mode = qrcodegen_Mode_BYTE; seg.bitLength = calcSegmentBitLength(seg.mode, dataLen); if (seg.bitLength == -1) { qrcode[0] = 0; // Set size to invalid value for safety return false; } seg.numChars = cast(int)dataLen; seg.data = dataAndTemp; return qrcodegen_encodeSegmentsAdvanced(&seg, 1, ecl, minVersion, maxVersion, mask, boostEcl, dataAndTemp, qrcode); } // Appends the given number of low-order bits of the given value to the given byte-based // bit buffer, increasing the bit length. Requires 0 <= numBits <= 16 and val < 2^numBits. private void appendBitsToBuffer(uint val, int numBits, uint8_t* buffer, int *bitLen) { assert(0 <= numBits && numBits <= 16 && cast(c_ulong)val >> numBits == 0); for (int i = numBits - 1; i >= 0; i--, (*bitLen)++) buffer[*bitLen >> 3] |= ((val >> i) & 1) << (7 - (*bitLen & 7)); } /*---- Low-level QR Code encoding functions ----*/ // Public function - see documentation comment in header file. /* * Renders a QR Code representing the given segments at the given error correction level. * The smallest possible QR Code version is automatically chosen for the output. Returns true if * QR Code creation succeeded, or false if the data is too long to fit in any version. The ECC level * of the result may be higher than the ecl argument if it can be done without increasing the version. * This function allows the user to create a custom sequence of segments that switches * between modes (such as alphanumeric and byte) to encode text in less space. * This is a low-level API; the high-level API is qrcodegen_encodeText() and qrcodegen_encodeBinary(). * To save memory, the segments' data buffers can alias/overlap tempBuffer, and will * result in them being clobbered, but the QR Code output will still be correct. * But the qrcode array must not overlap tempBuffer or any segment's data buffer. */ bool qrcodegen_encodeSegments(const qrcodegen_Segment* segs, size_t len, qrcodegen_Ecc ecl, uint8_t* tempBuffer, uint8_t* qrcode) { return qrcodegen_encodeSegmentsAdvanced(segs, len, ecl, qrcodegen_VERSION_MIN, qrcodegen_VERSION_MAX, qrcodegen_Mask_AUTO, true, tempBuffer, qrcode); } // Public function - see documentation comment in header file. /* * Renders a QR Code representing the given segments with the given encoding parameters. * Returns true if QR Code creation succeeded, or false if the data is too long to fit in the range of versions. * The smallest possible QR Code version within the given range is automatically * chosen for the output. Iff boostEcl is true, then the ECC level of the result * may be higher than the ecl argument if it can be done without increasing the * version. The mask is either between qrcodegen_Mask_0 to 7 to force that mask, or * qrcodegen_Mask_AUTO to automatically choose an appropriate mask (which may be slow). * This function allows the user to create a custom sequence of segments that switches * between modes (such as alphanumeric and byte) to encode text in less space. * This is a low-level API; the high-level API is qrcodegen_encodeText() and qrcodegen_encodeBinary(). * To save memory, the segments' data buffers can alias/overlap tempBuffer, and will * result in them being clobbered, but the QR Code output will still be correct. * But the qrcode array must not overlap tempBuffer or any segment's data buffer. */ bool qrcodegen_encodeSegmentsAdvanced(const qrcodegen_Segment* segs, size_t len, qrcodegen_Ecc ecl, int minVersion, int maxVersion, qrcodegen_Mask mask, bool boostEcl, uint8_t* tempBuffer, uint8_t* qrcode) { assert(segs != null || len == 0); assert(qrcodegen_VERSION_MIN <= minVersion && minVersion <= maxVersion && maxVersion <= qrcodegen_VERSION_MAX); assert(0 <= cast(int)ecl && cast(int)ecl <= 3 && -1 <= cast(int)mask && cast(int)mask <= 7); // Find the minimal version_ number to use int version_, dataUsedBits; for (version_ = minVersion; ; version_++) { int dataCapacityBits = getNumDataCodewords(version_, ecl) * 8; // Number of data bits available dataUsedBits = getTotalBits(segs, len, version_); if (dataUsedBits != -1 && dataUsedBits <= dataCapacityBits) break; // This version_ number is found to be suitable if (version_ >= maxVersion) { // All version_s in the range could not fit the given data qrcode[0] = 0; // Set size to invalid value for safety return false; } } assert(dataUsedBits != -1); // Increase the error correction level while the data still fits in the current version_ number for (int i = cast(int)qrcodegen_Ecc_MEDIUM; i <= cast(int)qrcodegen_Ecc_HIGH; i++) { // From low to high if (boostEcl && dataUsedBits <= getNumDataCodewords(version_, cast(qrcodegen_Ecc)i) * 8) ecl = cast(qrcodegen_Ecc)i; } // Concatenate all segments to create the data bit string memset(qrcode, 0, cast(size_t)qrcodegen_BUFFER_LEN_FOR_VERSION(version_) * (qrcode[0]).sizeof); int bitLen = 0; for (size_t i = 0; i < len; i++) { const qrcodegen_Segment *seg = &segs[i]; appendBitsToBuffer(cast(uint)seg.mode, 4, qrcode, &bitLen); appendBitsToBuffer(cast(uint)seg.numChars, numCharCountBits(seg.mode, version_), qrcode, &bitLen); for (int j = 0; j < seg.bitLength; j++) { int bit = (seg.data[j >> 3] >> (7 - (j & 7))) & 1; appendBitsToBuffer(cast(uint)bit, 1, qrcode, &bitLen); } } assert(bitLen == dataUsedBits); // Add terminator and pad up to a byte if applicable int dataCapacityBits = getNumDataCodewords(version_, ecl) * 8; assert(bitLen <= dataCapacityBits); int terminatorBits = dataCapacityBits - bitLen; if (terminatorBits > 4) terminatorBits = 4; appendBitsToBuffer(0, terminatorBits, qrcode, &bitLen); appendBitsToBuffer(0, (8 - bitLen % 8) % 8, qrcode, &bitLen); assert(bitLen % 8 == 0); // Pad with alternating bytes until data capacity is reached for (uint8_t padByte = 0xEC; bitLen < dataCapacityBits; padByte ^= 0xEC ^ 0x11) appendBitsToBuffer(padByte, 8, qrcode, &bitLen); // Draw function and data codeword modules addEccAndInterleave(qrcode, version_, ecl, tempBuffer); initializeFunctionModules(version_, qrcode); drawCodewords(tempBuffer, getNumRawDataModules(version_) / 8, qrcode); drawWhiteFunctionModules(qrcode, version_); initializeFunctionModules(version_, tempBuffer); // Handle masking if (mask == qrcodegen_Mask_AUTO) { // Automatically choose best mask long minPenalty = long.max; for (int i = 0; i < 8; i++) { qrcodegen_Mask msk = cast(qrcodegen_Mask)i; applyMask(tempBuffer, qrcode, msk); drawFormatBits(ecl, msk, qrcode); long penalty = getPenaltyScore(qrcode); if (penalty < minPenalty) { mask = msk; minPenalty = penalty; } applyMask(tempBuffer, qrcode, msk); // Undoes the mask due to XOR } } assert(0 <= cast(int)mask && cast(int)mask <= 7); applyMask(tempBuffer, qrcode, mask); drawFormatBits(ecl, mask, qrcode); return true; } /*---- Error correction code generation functions ----*/ // Appends error correction bytes to each block of the given data array, then interleaves // bytes from the blocks and stores them in the result array. data[0 : dataLen] contains // the input data. data[dataLen : rawCodewords] is used as a temporary work area and will // be clobbered by this function. The final answer is stored in result[0 : rawCodewords]. private void addEccAndInterleave(uint8_t* data, int version_, qrcodegen_Ecc ecl, uint8_t* result) { // Calculate parameter numbers assert(0 <= cast(int)ecl && cast(int)ecl < 4 && qrcodegen_VERSION_MIN <= version_ && version_ <= qrcodegen_VERSION_MAX); int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[cast(int)ecl][version_]; int blockEccLen = ECC_CODEWORDS_PER_BLOCK [cast(int)ecl][version_]; int rawCodewords = getNumRawDataModules(version_) / 8; int dataLen = getNumDataCodewords(version_, ecl); int numShortBlocks = numBlocks - rawCodewords % numBlocks; int shortBlockDataLen = rawCodewords / numBlocks - blockEccLen; // Split data into blocks, calculate ECC, and interleave // (not concatenate) the bytes into a single sequence uint8_t[qrcodegen_REED_SOLOMON_DEGREE_MAX] rsdiv; reedSolomonComputeDivisor(blockEccLen, rsdiv.ptr); const(uint8_t)* dat = data; for (int i = 0; i < numBlocks; i++) { int datLen = shortBlockDataLen + (i < numShortBlocks ? 0 : 1); uint8_t *ecc = &data[dataLen]; // Temporary storage reedSolomonComputeRemainder(dat, datLen, rsdiv.ptr, blockEccLen, ecc); for (int j = 0, k = i; j < datLen; j++, k += numBlocks) { // Copy data if (j == shortBlockDataLen) k -= numShortBlocks; result[k] = dat[j]; } for (int j = 0, k = dataLen + i; j < blockEccLen; j++, k += numBlocks) // Copy ECC result[k] = ecc[j]; dat += datLen; } } // Returns the number of 8-bit codewords that can be used for storing data (not ECC), // for the given version_ number and error correction level. The result is in the range [9, 2956]. private int getNumDataCodewords(int version_, qrcodegen_Ecc ecl) { int v = version_, e = cast(int)ecl; assert(0 <= e && e < 4); return getNumRawDataModules(v) / 8 - ECC_CODEWORDS_PER_BLOCK [e][v] * NUM_ERROR_CORRECTION_BLOCKS[e][v]; } // Returns the number of data bits that can be stored in a QR Code of the given version_ number, after // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8. // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table. private int getNumRawDataModules(int ver) { assert(qrcodegen_VERSION_MIN <= ver && ver <= qrcodegen_VERSION_MAX); int result = (16 * ver + 128) * ver + 64; if (ver >= 2) { int numAlign = ver / 7 + 2; result -= (25 * numAlign - 10) * numAlign - 55; if (ver >= 7) result -= 36; } assert(208 <= result && result <= 29648); return result; } /*---- Reed-Solomon ECC generator functions ----*/ // Computes a Reed-Solomon ECC generator polynomial for the given degree, storing in result[0 : degree]. // This could be implemented as a lookup table over all possible parameter values, instead of as an algorithm. private void reedSolomonComputeDivisor(int degree, uint8_t* result) { assert(1 <= degree && degree <= qrcodegen_REED_SOLOMON_DEGREE_MAX); // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1. // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array {255, 8, 93}. memset(result, 0, cast(size_t)degree * (result[0]).sizeof); result[degree - 1] = 1; // Start off with the monomial x^0 // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}), // drop the highest monomial term which is always 1x^degree. // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D). uint8_t root = 1; for (int i = 0; i < degree; i++) { // Multiply the current product by (x - r^i) for (int j = 0; j < degree; j++) { result[j] = reedSolomonMultiply(result[j], root); if (j + 1 < degree) result[j] ^= result[j + 1]; } root = reedSolomonMultiply(root, 0x02); } } // Computes the Reed-Solomon error correction codeword for the given data and divisor polynomials. // The remainder when data[0 : dataLen] is divided by divisor[0 : degree] is stored in result[0 : degree]. // All polynomials are in big endian, and the generator has an implicit leading 1 term. private void reedSolomonComputeRemainder(const uint8_t* data, int dataLen, const uint8_t* generator, int degree, uint8_t* result) { assert(1 <= degree && degree <= qrcodegen_REED_SOLOMON_DEGREE_MAX); memset(result, 0, cast(size_t)degree * (result[0]).sizeof); for (int i = 0; i < dataLen; i++) { // Polynomial division uint8_t factor = data[i] ^ result[0]; memmove(&result[0], &result[1], cast(size_t)(degree - 1) * (result[0]).sizeof); result[degree - 1] = 0; for (int j = 0; j < degree; j++) result[j] ^= reedSolomonMultiply(generator[j], factor); } } // Returns the product of the two given field elements modulo GF(2^8/0x11D). // All inputs are valid. This could be implemented as a 256*256 lookup table. private uint8_t reedSolomonMultiply(uint8_t x, uint8_t y) { // Russian peasant multiplication uint8_t z = 0; for (int i = 7; i >= 0; i--) { z = cast(uint8_t)((z << 1) ^ ((z >> 7) * 0x11D)); z ^= ((y >> i) & 1) * x; } return z; } /*---- Drawing function modules ----*/ // Clears the given QR Code grid with white modules for the given // version_'s size, then marks every function module as black. private void initializeFunctionModules(int version_, uint8_t* qrcode) { // Initialize QR Code int qrsize = version_ * 4 + 17; memset(qrcode, 0, cast(size_t)((qrsize * qrsize + 7) / 8 + 1) * (qrcode[0]).sizeof); qrcode[0] = cast(uint8_t)qrsize; // Fill horizontal and vertical timing patterns fillRectangle(6, 0, 1, qrsize, qrcode); fillRectangle(0, 6, qrsize, 1, qrcode); // Fill 3 finder patterns (all corners except bottom right) and format bits fillRectangle(0, 0, 9, 9, qrcode); fillRectangle(qrsize - 8, 0, 8, 9, qrcode); fillRectangle(0, qrsize - 8, 9, 8, qrcode); // Fill numerous alignment patterns uint8_t[7] alignPatPos; int numAlign = getAlignmentPatternPositions(version_, alignPatPos); for (int i = 0; i < numAlign; i++) { for (int j = 0; j < numAlign; j++) { // Don't draw on the three finder corners if (!((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0))) fillRectangle(alignPatPos[i] - 2, alignPatPos[j] - 2, 5, 5, qrcode); } } // Fill version_ blocks if (version_ >= 7) { fillRectangle(qrsize - 11, 0, 3, 6, qrcode); fillRectangle(0, qrsize - 11, 6, 3, qrcode); } } // Draws white function modules and possibly some black modules onto the given QR Code, without changing // non-function modules. This does not draw the format bits. This requires all function modules to be previously // marked black (namely by initializeFunctionModules()), because this may skip redrawing black function modules. static void drawWhiteFunctionModules(uint8_t* qrcode, int version_) { // Draw horizontal and vertical timing patterns int qrsize = qrcodegen_getSize(qrcode); for (int i = 7; i < qrsize - 7; i += 2) { setModule(qrcode, 6, i, false); setModule(qrcode, i, 6, false); } // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules) for (int dy = -4; dy <= 4; dy++) { for (int dx = -4; dx <= 4; dx++) { int dist = abs(dx); if (abs(dy) > dist) dist = abs(dy); if (dist == 2 || dist == 4) { setModuleBounded(qrcode, 3 + dx, 3 + dy, false); setModuleBounded(qrcode, qrsize - 4 + dx, 3 + dy, false); setModuleBounded(qrcode, 3 + dx, qrsize - 4 + dy, false); } } } // Draw numerous alignment patterns uint8_t[7] alignPatPos; int numAlign = getAlignmentPatternPositions(version_, alignPatPos); for (int i = 0; i < numAlign; i++) { for (int j = 0; j < numAlign; j++) { if ((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0)) continue; // Don't draw on the three finder corners for (int dy = -1; dy <= 1; dy++) { for (int dx = -1; dx <= 1; dx++) setModule(qrcode, alignPatPos[i] + dx, alignPatPos[j] + dy, dx == 0 && dy == 0); } } } // Draw version_ blocks if (version_ >= 7) { // Calculate error correction code and pack bits int rem = version_; // version_ is uint6, in the range [7, 40] for (int i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >> 11) * 0x1F25); c_long bits = cast(c_long)version_ << 12 | rem; // uint18 assert(bits >> 18 == 0); // Draw two copies for (int i = 0; i < 6; i++) { for (int j = 0; j < 3; j++) { int k = qrsize - 11 + j; setModule(qrcode, k, i, (bits & 1) != 0); setModule(qrcode, i, k, (bits & 1) != 0); bits >>= 1; } } } } // Draws two copies of the format bits (with its own error correction code) based // on the given mask and error correction level. This always draws all modules of // the format bits, unlike drawWhiteFunctionModules() which might skip black modules. static void drawFormatBits(qrcodegen_Ecc ecl, qrcodegen_Mask mask, uint8_t* qrcode) { // Calculate error correction code and pack bits assert(0 <= cast(int)mask && cast(int)mask <= 7); static const int[] table = [1, 0, 3, 2]; int data = table[cast(int)ecl] << 3 | cast(int)mask; // errCorrLvl is uint2, mask is uint3 int rem = data; for (int i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >> 9) * 0x537); int bits = (data << 10 | rem) ^ 0x5412; // uint15 assert(bits >> 15 == 0); // Draw first copy for (int i = 0; i <= 5; i++) setModule(qrcode, 8, i, getBit(bits, i)); setModule(qrcode, 8, 7, getBit(bits, 6)); setModule(qrcode, 8, 8, getBit(bits, 7)); setModule(qrcode, 7, 8, getBit(bits, 8)); for (int i = 9; i < 15; i++) setModule(qrcode, 14 - i, 8, getBit(bits, i)); // Draw second copy int qrsize = qrcodegen_getSize(qrcode); for (int i = 0; i < 8; i++) setModule(qrcode, qrsize - 1 - i, 8, getBit(bits, i)); for (int i = 8; i < 15; i++) setModule(qrcode, 8, qrsize - 15 + i, getBit(bits, i)); setModule(qrcode, 8, qrsize - 8, true); // Always black } // Calculates and stores an ascending list of positions of alignment patterns // for this version_ number, returning the length of the list (in the range [0,7]). // Each position is in the range [0,177), and are used on both the x and y axes. // This could be implemented as lookup table of 40 variable-length lists of unsigned bytes. private int getAlignmentPatternPositions(int version_, ref uint8_t[7] result) { if (version_ == 1) return 0; int numAlign = version_ / 7 + 2; int step = (version_ == 32) ? 26 : (version_*4 + numAlign*2 + 1) / (numAlign*2 - 2) * 2; for (int i = numAlign - 1, pos = version_ * 4 + 10; i >= 1; i--, pos -= step) result[i] = cast(uint8_t)pos; result[0] = 6; return numAlign; } // Sets every pixel in the range [left : left + width] * [top : top + height] to black. static void fillRectangle(int left, int top, int width, int height, uint8_t* qrcode) { for (int dy = 0; dy < height; dy++) { for (int dx = 0; dx < width; dx++) setModule(qrcode, left + dx, top + dy, true); } } /*---- Drawing data modules and masking ----*/ // Draws the raw codewords (including data and ECC) onto the given QR Code. This requires the initial state of // the QR Code to be black at function modules and white at codeword modules (including unused remainder bits). static void drawCodewords(const uint8_t* data, int dataLen, uint8_t* qrcode) { int qrsize = qrcodegen_getSize(qrcode); int i = 0; // Bit index into the data // Do the funny zigzag scan for (int right = qrsize - 1; right >= 1; right -= 2) { // Index of right column in each column pair if (right == 6) right = 5; for (int vert = 0; vert < qrsize; vert++) { // Vertical counter for (int j = 0; j < 2; j++) { int x = right - j; // Actual x coordinate bool upward = ((right + 1) & 2) == 0; int y = upward ? qrsize - 1 - vert : vert; // Actual y coordinate if (!getModule(qrcode, x, y) && i < dataLen * 8) { bool black = getBit(data[i >> 3], 7 - (i & 7)); setModule(qrcode, x, y, black); i++; } // If this QR Code has any remainder bits (0 to 7), they were assigned as // 0/false/white by the constructor and are left unchanged by this method } } } assert(i == dataLen * 8); } // XORs the codeword modules in this QR Code with the given mask pattern. // The function modules must be marked and the codeword bits must be drawn // before masking. Due to the arithmetic of XOR, calling applyMask() with // the same mask value a second time will undo the mask. A final well-formed // QR Code needs exactly one (not zero, two, etc.) mask applied. static void applyMask(const uint8_t* functionModules, uint8_t* qrcode, qrcodegen_Mask mask) { assert(0 <= cast(int)mask && cast(int)mask <= 7); // Disallows qrcodegen_Mask_AUTO int qrsize = qrcodegen_getSize(qrcode); for (int y = 0; y < qrsize; y++) { for (int x = 0; x < qrsize; x++) { if (getModule(functionModules, x, y)) continue; bool invert; switch (cast(int)mask) { case 0: invert = (x + y) % 2 == 0; break; case 1: invert = y % 2 == 0; break; case 2: invert = x % 3 == 0; break; case 3: invert = (x + y) % 3 == 0; break; case 4: invert = (x / 3 + y / 2) % 2 == 0; break; case 5: invert = x * y % 2 + x * y % 3 == 0; break; case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break; case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break; default: assert(false); } bool val = getModule(qrcode, x, y); setModule(qrcode, x, y, val ^ invert); } } } // Calculates and returns the penalty score based on state of the given QR Code's current modules. // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. static long getPenaltyScore(const uint8_t* qrcode) { int qrsize = qrcodegen_getSize(qrcode); long result = 0; // Adjacent modules in row having same color, and finder-like patterns for (int y = 0; y < qrsize; y++) { bool runColor = false; int runX = 0; int[7] runHistory = 0; for (int x = 0; x < qrsize; x++) { if (getModule(qrcode, x, y) == runColor) { runX++; if (runX == 5) result += PENALTY_N1; else if (runX > 5) result++; } else { finderPenaltyAddHistory(runX, runHistory, qrsize); if (!runColor) result += finderPenaltyCountPatterns(runHistory, qrsize) * PENALTY_N3; runColor = getModule(qrcode, x, y); runX = 1; } } result += finderPenaltyTerminateAndCount(runColor, runX, runHistory, qrsize) * PENALTY_N3; } // Adjacent modules in column having same color, and finder-like patterns for (int x = 0; x < qrsize; x++) { bool runColor = false; int runY = 0; int[7] runHistory = 0; for (int y = 0; y < qrsize; y++) { if (getModule(qrcode, x, y) == runColor) { runY++; if (runY == 5) result += PENALTY_N1; else if (runY > 5) result++; } else { finderPenaltyAddHistory(runY, runHistory, qrsize); if (!runColor) result += finderPenaltyCountPatterns(runHistory, qrsize) * PENALTY_N3; runColor = getModule(qrcode, x, y); runY = 1; } } result += finderPenaltyTerminateAndCount(runColor, runY, runHistory, qrsize) * PENALTY_N3; } // 2*2 blocks of modules having same color for (int y = 0; y < qrsize - 1; y++) { for (int x = 0; x < qrsize - 1; x++) { bool color = getModule(qrcode, x, y); if ( color == getModule(qrcode, x + 1, y) && color == getModule(qrcode, x, y + 1) && color == getModule(qrcode, x + 1, y + 1)) result += PENALTY_N2; } } // Balance of black and white modules int black = 0; for (int y = 0; y < qrsize; y++) { for (int x = 0; x < qrsize; x++) { if (getModule(qrcode, x, y)) black++; } } int total = qrsize * qrsize; // Note that size is odd, so black/total != 1/2 // Compute the smallest integer k >= 0 such that (45-5k)% <= black/total <= (55+5k)% int k = cast(int)((labs(black * 20 - total * 10) + total - 1) / total) - 1; result += k * PENALTY_N4; return result; } // Can only be called immediately after a white run is added, and // returns either 0, 1, or 2. A helper function for getPenaltyScore(). static int finderPenaltyCountPatterns(const int[7] runHistory, int qrsize) { int n = runHistory[1]; assert(n <= qrsize * 3); bool core = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n; // The maximum QR Code size is 177, hence the black run length n <= 177. // Arithmetic is promoted to int, so n*4 will not overflow. return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0) + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0); } // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore(). static int finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, ref int[7] runHistory, int qrsize) { if (currentRunColor) { // Terminate black run finderPenaltyAddHistory(currentRunLength, runHistory, qrsize); currentRunLength = 0; } currentRunLength += qrsize; // Add white border to final run finderPenaltyAddHistory(currentRunLength, runHistory, qrsize); return finderPenaltyCountPatterns(runHistory, qrsize); } // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore(). static void finderPenaltyAddHistory(int currentRunLength, ref int[7] runHistory, int qrsize) { if (runHistory[0] == 0) currentRunLength += qrsize; // Add white border to initial run memmove(&runHistory[1], &runHistory[0], 6 * (runHistory[0]).sizeof); runHistory[0] = currentRunLength; } /*---- Basic QR Code information ----*/ // Public function - see documentation comment in header file. /* * Returns the side length of the given QR Code, assuming that encoding succeeded. * The result is in the range [21, 177]. Note that the length of the array buffer * is related to the side length - every 'uint8_t qrcode[]' must have length at least * qrcodegen_BUFFER_LEN_FOR_VERSION(version), which equals ceil(size^2 / 8 + 1). */ int qrcodegen_getSize(const uint8_t* qrcode) { assert(qrcode != null); int result = qrcode[0]; assert((qrcodegen_VERSION_MIN * 4 + 17) <= result && result <= (qrcodegen_VERSION_MAX * 4 + 17)); return result; } // Public function - see documentation comment in header file. /* * Returns the color of the module (pixel) at the given coordinates, which is false * for white or true for black. The top left corner has the coordinates (x=0, y=0). * If the given coordinates are out of bounds, then false (white) is returned. */ bool qrcodegen_getModule(const uint8_t* qrcode, int x, int y) { assert(qrcode != null); int qrsize = qrcode[0]; return (0 <= x && x < qrsize && 0 <= y && y < qrsize) && getModule(qrcode, x, y); } // Gets the module at the given coordinates, which must be in bounds. private bool getModule(const uint8_t* qrcode, int x, int y) { int qrsize = qrcode[0]; assert(21 <= qrsize && qrsize <= 177 && 0 <= x && x < qrsize && 0 <= y && y < qrsize); int index = y * qrsize + x; return getBit(qrcode[(index >> 3) + 1], index & 7); } // Sets the module at the given coordinates, which must be in bounds. private void setModule(uint8_t* qrcode, int x, int y, bool isBlack) { int qrsize = qrcode[0]; assert(21 <= qrsize && qrsize <= 177 && 0 <= x && x < qrsize && 0 <= y && y < qrsize); int index = y * qrsize + x; int bitIndex = index & 7; int byteIndex = (index >> 3) + 1; if (isBlack) qrcode[byteIndex] |= 1 << bitIndex; else qrcode[byteIndex] &= (1 << bitIndex) ^ 0xFF; } // Sets the module at the given coordinates, doing nothing if out of bounds. private void setModuleBounded(uint8_t* qrcode, int x, int y, bool isBlack) { int qrsize = qrcode[0]; if (0 <= x && x < qrsize && 0 <= y && y < qrsize) setModule(qrcode, x, y, isBlack); } // Returns true iff the i'th bit of x is set to 1. Requires x >= 0 and 0 <= i <= 14. static bool getBit(int x, int i) { return ((x >> i) & 1) != 0; } /*---- Segment handling ----*/ // Public function - see documentation comment in header file. /* * Tests whether the given string can be encoded as a segment in alphanumeric mode. * A string is encodable iff each character is in the following set: 0 to 9, A to Z * (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon. */ bool qrcodegen_isAlphanumeric(const(char)* text) { assert(text != null); for (; *text != '\0'; text++) { if (strchr(ALPHANUMERIC_CHARSET, *text) == null) return false; } return true; } // Public function - see documentation comment in header file. /* * Tests whether the given string can be encoded as a segment in numeric mode. * A string is encodable iff each character is in the range 0 to 9. */ bool qrcodegen_isNumeric(const(char)* text) { assert(text != null); for (; *text != '\0'; text++) { if (*text < '0' || *text > '9') return false; } return true; } // Public function - see documentation comment in header file. /* * Returns the number of bytes (uint8_t) needed for the data buffer of a segment * containing the given number of characters using the given mode. Notes: * - Returns SIZE_MAX on failure, i.e. numChars > INT16_MAX or * the number of needed bits exceeds INT16_MAX (i.e. 32767). * - Otherwise, all valid results are in the range [0, ceil(INT16_MAX / 8)], i.e. at most 4096. * - It is okay for the user to allocate more bytes for the buffer than needed. * - For byte mode, numChars measures the number of bytes, not Unicode code points. * - For ECI mode, numChars must be 0, and the worst-case number of bytes is returned. * An actual ECI segment can have shorter data. For non-ECI modes, the result is exact. */ size_t qrcodegen_calcSegmentBufferSize(qrcodegen_Mode mode, size_t numChars) { int temp = calcSegmentBitLength(mode, numChars); if (temp == -1) return SIZE_MAX; assert(0 <= temp && temp <= INT16_MAX); return (cast(size_t)temp + 7) / 8; } // Returns the number of data bits needed to represent a segment // containing the given number of characters using the given mode. Notes: // - Returns -1 on failure, i.e. numChars > INT16_MAX or // the number of needed bits exceeds INT16_MAX (i.e. 32767). // - Otherwise, all valid results are in the range [0, INT16_MAX]. // - For byte mode, numChars measures the number of bytes, not Unicode code points. // - For ECI mode, numChars must be 0, and the worst-case number of bits is returned. // An actual ECI segment can have shorter data. For non-ECI modes, the result is exact. private int calcSegmentBitLength(qrcodegen_Mode mode, size_t numChars) { // All calculations are designed to avoid overflow on all platforms if (numChars > cast(uint)INT16_MAX) return -1; c_long result = cast(c_long)numChars; if (mode == qrcodegen_Mode_NUMERIC) result = (result * 10 + 2) / 3; // ceil(10/3 * n) else if (mode == qrcodegen_Mode_ALPHANUMERIC) result = (result * 11 + 1) / 2; // ceil(11/2 * n) else if (mode == qrcodegen_Mode_BYTE) result *= 8; else if (mode == qrcodegen_Mode_KANJI) result *= 13; else if (mode == qrcodegen_Mode_ECI && numChars == 0) result = 3 * 8; else { // Invalid argument assert(false); } assert(result >= 0); if (result > INT16_MAX) return -1; return cast(int)result; } // Public function - see documentation comment in header file. /* * Returns a segment representing the given binary data encoded in * byte mode. All input byte arrays are acceptable. Any text string * can be converted to UTF-8 bytes and encoded as a byte mode segment. */ qrcodegen_Segment qrcodegen_makeBytes(const uint8_t* data, size_t len, uint8_t* buf) { assert(data != null || len == 0); qrcodegen_Segment result; result.mode = qrcodegen_Mode_BYTE; result.bitLength = calcSegmentBitLength(result.mode, len); assert(result.bitLength != -1); result.numChars = cast(int)len; if (len > 0) memcpy(buf, data, len * (buf[0]).sizeof); result.data = buf; return result; } // Public function - see documentation comment in header file. /* * Returns a segment representing the given string of decimal digits encoded in numeric mode. */ qrcodegen_Segment qrcodegen_makeNumeric(const(char)* digits, uint8_t* buf) { assert(digits != null); qrcodegen_Segment result; size_t len = strlen(digits); result.mode = qrcodegen_Mode_NUMERIC; int bitLen = calcSegmentBitLength(result.mode, len); assert(bitLen != -1); result.numChars = cast(int)len; if (bitLen > 0) memset(buf, 0, (cast(size_t)bitLen + 7) / 8 * (buf[0]).sizeof); result.bitLength = 0; uint accumData = 0; int accumCount = 0; for (; *digits != '\0'; digits++) { char c = *digits; assert('0' <= c && c <= '9'); accumData = accumData * 10 + cast(uint)(c - '0'); accumCount++; if (accumCount == 3) { appendBitsToBuffer(accumData, 10, buf, &result.bitLength); accumData = 0; accumCount = 0; } } if (accumCount > 0) // 1 or 2 digits remaining appendBitsToBuffer(accumData, accumCount * 3 + 1, buf, &result.bitLength); assert(result.bitLength == bitLen); result.data = buf; return result; } // Public function - see documentation comment in header file. /* * Returns a segment representing the given text string encoded in alphanumeric mode. * The characters allowed are: 0 to 9, A to Z (uppercase only), space, * dollar, percent, asterisk, plus, hyphen, period, slash, colon. */ qrcodegen_Segment qrcodegen_makeAlphanumeric(const(char)* text, uint8_t* buf) { assert(text != null); qrcodegen_Segment result; size_t len = strlen(text); result.mode = qrcodegen_Mode_ALPHANUMERIC; int bitLen = calcSegmentBitLength(result.mode, len); assert(bitLen != -1); result.numChars = cast(int)len; if (bitLen > 0) memset(buf, 0, (cast(size_t)bitLen + 7) / 8 * (buf[0]).sizeof); result.bitLength = 0; uint accumData = 0; int accumCount = 0; for (; *text != '\0'; text++) { const char *temp = strchr(ALPHANUMERIC_CHARSET, *text); assert(temp != null); accumData = accumData * 45 + cast(uint)(temp - ALPHANUMERIC_CHARSET); accumCount++; if (accumCount == 2) { appendBitsToBuffer(accumData, 11, buf, &result.bitLength); accumData = 0; accumCount = 0; } } if (accumCount > 0) // 1 character remaining appendBitsToBuffer(accumData, 6, buf, &result.bitLength); assert(result.bitLength == bitLen); result.data = buf; return result; } // Public function - see documentation comment in header file. /* * Returns a segment representing an Extended Channel Interpretation * (ECI) designator with the given assignment value. */ qrcodegen_Segment qrcodegen_makeEci(c_long assignVal, uint8_t* buf) { qrcodegen_Segment result; result.mode = qrcodegen_Mode_ECI; result.numChars = 0; result.bitLength = 0; if (assignVal < 0) assert(false); else if (assignVal < (1 << 7)) { memset(buf, 0, 1 * (buf[0]).sizeof); appendBitsToBuffer(cast(uint)assignVal, 8, buf, &result.bitLength); } else if (assignVal < (1 << 14)) { memset(buf, 0, 2 * (buf[0]).sizeof); appendBitsToBuffer(2, 2, buf, &result.bitLength); appendBitsToBuffer(cast(uint)assignVal, 14, buf, &result.bitLength); } else if (assignVal < 1000000L) { memset(buf, 0, 3 * (buf[0]).sizeof); appendBitsToBuffer(6, 3, buf, &result.bitLength); appendBitsToBuffer(cast(uint)(assignVal >> 10), 11, buf, &result.bitLength); appendBitsToBuffer(cast(uint)(assignVal & 0x3FF), 10, buf, &result.bitLength); } else assert(false); result.data = buf; return result; } // Calculates the number of bits needed to encode the given segments at the given version_. // Returns a non-negative number if successful. Otherwise returns -1 if a segment has too // many characters to fit its length field, or the total bits exceeds INT16_MAX. private int getTotalBits(const qrcodegen_Segment* segs, size_t len, int version_) { assert(segs != null || len == 0); long result = 0; for (size_t i = 0; i < len; i++) { int numChars = segs[i].numChars; int bitLength = segs[i].bitLength; assert(0 <= numChars && numChars <= INT16_MAX); assert(0 <= bitLength && bitLength <= INT16_MAX); int ccbits = numCharCountBits(segs[i].mode, version_); assert(0 <= ccbits && ccbits <= 16); if (numChars >= (1L << ccbits)) return -1; // The segment's length doesn't fit the field's bit width result += 4L + ccbits + bitLength; if (result > INT16_MAX) return -1; // The sum might overflow an int type } assert(0 <= result && result <= INT16_MAX); return cast(int)result; } // Returns the bit width of the character count field for a segment in the given mode // in a QR Code at the given version_ number. The result is in the range [0, 16]. static int numCharCountBits(qrcodegen_Mode mode, int version_) { assert(qrcodegen_VERSION_MIN <= version_ && version_ <= qrcodegen_VERSION_MAX); int i = (version_ + 7) / 17; switch (mode) { case qrcodegen_Mode_NUMERIC : { static immutable int[] temp1 = [10, 12, 14]; return temp1[i]; } case qrcodegen_Mode_ALPHANUMERIC: { static immutable int[] temp2 = [ 9, 11, 13]; return temp2[i]; } case qrcodegen_Mode_BYTE : { static immutable int[] temp3 = [ 8, 16, 16]; return temp3[i]; } case qrcodegen_Mode_KANJI : { static immutable int[] temp4 = [ 8, 10, 12]; return temp4[i]; } case qrcodegen_Mode_ECI : return 0; default: assert(false); // Dummy value } } /++ +/ struct QrCode { ubyte[qrcodegen_BUFFER_LEN_MAX] qrcode; this(string text) { ubyte[qrcodegen_BUFFER_LEN_MAX] tempBuffer; bool ok = qrcodegen_encodeText((text ~ "\0").ptr, tempBuffer.ptr, qrcode.ptr, qrcodegen_Ecc_MEDIUM, qrcodegen_VERSION_MIN, qrcodegen_VERSION_MAX, qrcodegen_Mask_AUTO, true); if(!ok) throw new Exception("qr code generation failed"); } /++ The size of the square of the code. It is size x size. +/ int size() { return qrcodegen_getSize(qrcode.ptr); } /++ Returns true if it is a dark square, false if it is a light one. +/ bool opIndex(int x, int y) { return qrcodegen_getModule(qrcode.ptr, x, y); } }
D
module android.java.java.io.ObjectStreamClass_d_interface; import arsd.jni : IJavaObjectImplementation, JavaPackageId, JavaName, IJavaObject, ImportExportImpl, JavaInterfaceMembers; static import arsd.jni; import import1 = android.java.java.lang.Class_d_interface; import import2 = android.java.java.io.ObjectStreamField_d_interface; import import0 = android.java.java.io.ObjectStreamClass_d_interface; final class ObjectStreamClass : IJavaObject { static immutable string[] _d_canCastTo = [ "java/io/Serializable", ]; @Import static import0.ObjectStreamClass lookup(import1.Class); @Import static import0.ObjectStreamClass lookupAny(import1.Class); @Import string getName(); @Import long getSerialVersionUID(); @Import import1.Class forClass(); @Import import2.ObjectStreamField[] getFields(); @Import import2.ObjectStreamField getField(string); @Import @JavaName("toString") string toString_(); override string toString() { return arsd.jni.javaObjectToString(this); } @Import import1.Class getClass(); @Import int hashCode(); @Import bool equals(IJavaObject); @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 = "Ljava/io/ObjectStreamClass;"; }
D
/Users/imutayuji/programming/rust_practice/templates/target/debug/deps/fnv-c2f60708f70b5b57.rmeta: /Users/imutayuji/.cargo/registry/src/github.com-1ecc6299db9ec823/fnv-1.0.7/lib.rs /Users/imutayuji/programming/rust_practice/templates/target/debug/deps/libfnv-c2f60708f70b5b57.rlib: /Users/imutayuji/.cargo/registry/src/github.com-1ecc6299db9ec823/fnv-1.0.7/lib.rs /Users/imutayuji/programming/rust_practice/templates/target/debug/deps/fnv-c2f60708f70b5b57.d: /Users/imutayuji/.cargo/registry/src/github.com-1ecc6299db9ec823/fnv-1.0.7/lib.rs /Users/imutayuji/.cargo/registry/src/github.com-1ecc6299db9ec823/fnv-1.0.7/lib.rs:
D
auto f(T)(T x) pure { return x; } auto g(T)(T x) pure { return f(x); } @safe pure unittest { const _ = g(42); }
D
/* * PS3 Media Server, for streaming any medias to your PS3. * Copyright (C) 2012 I. Sokolov * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; version 2 * of the License only. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ module net.pms.formats.v2.AudioUtils; import net.pms.dlna.DLNAMediaAudio; public class AudioUtils { /** * Due to mencoder/ffmpeg bug we need to manually remap audio channels for LPCM * output. This function generates argument for channels/pan audio filters * * @param audioTrack DLNAMediaAudio resource * @return argument for -af option or null if we can't remap to desired numberOfOutputChannels */ public static String getLPCMChannelMappingForMencoder(DLNAMediaAudio audioTrack) { // for reference // Channel Arrangement for Multi Channel Audio Formats // http://avisynth.org/mediawiki/GetChannel // http://flac.sourceforge.net/format.html#frame_header // http://msdn.microsoft.com/en-us/windows/hardware/gg463006.aspx#E6C // http://labs.divx.com/node/44 // http://lists.mplayerhq.hu/pipermail/mplayer-users/2006-October/063511.html // // Format Chan 0 Chan 1 Chan 2 Chan 3 Chan 4 Chan 5 // 1.0 WAV/FLAC/MP3/WMA FC // 2.0 WAV/FLAC/MP3/WMA FL FR // 4.0 WAV/FLAC/MP3/WMA FL FR SL SR // 5.0 WAV/FLAC/MP3/WMA FL FR FC SL SR // 5.1 WAV/FLAC/MP3/WMA FL FR FC LFE SL SR // 5.1 PCM (mencoder) FL FR SR FC SL LFE // 7.1 PCM (mencoder) FL SL RR SR FR LFE RL FC // 5.1 AC3 FL FC FR SL SR LFE // 5.1 DTS/AAC FC FL FR SL SR LFE // 5.1 AIFF FL SL FC FR SR LFE // // FL : Front Left // FC : Front Center // FR : Front Right // SL : Surround Left // SR : Surround Right // LFE : Low Frequency Effects (Sub) String mixer = null; int numberOfInputChannels = audioTrack.getAudioProperties().getNumberOfChannels(); if (numberOfInputChannels == 6) { // 5.1 // we are using PCM output and have to manually remap channels because of MEncoder's incorrect PCM mappings // (as of r34814 / SB28) // as of MEncoder r34814 '-af pan' do nothing (LFE is missing from right channel) // same thing for AC3 transcoding. Thats why we should always use 5.1 output on PS3MS configuration // and leave stereo downmixing to PS3! // mixer for 5.1 => 2.0 mixer = "pan=2:1:0:0:1:0:1:0.707:0.707:1:0:1:1"; mixer = "channels=6:6:0:0:1:1:2:5:3:2:4:4:5:3"; } else if (numberOfInputChannels == 8) { // 7.1 // remap and leave 7.1 // inputs to PCM encoder are FL:0 FR:1 RL:2 RR:3 FC:4 LFE:5 SL:6 SR:7 mixer = "channels=8:8:0:0:1:4:2:7:3:5:4:1:5:3:6:6:7:2"; } else if (numberOfInputChannels == 2) { // 2.0 // do nothing for stereo tracks } return mixer; } }
D
module arsd.web; // FIXME: if a method has a default value of a non-primitive type, // it's still liable to screw everything else. /* Reasonably easy CSRF plan: A csrf token can be associated with the entire session, and saved in the session file. Each form outputs the token, and it is added as a parameter to the script thingy somewhere. It need only be sent on POST items. Your app should handle proper get and post separation. */ /* Future directions for web stuff: an improved css: add definition nesting add importing things from another definition Implemented: see html.d All css improvements are done via simple text rewriting. Aside from the nesting, it'd just be a simple macro system. Struct input functions: static typeof(this) fromWebString(string fromUrl) {} Automatic form functions: static Element makeFormElement(Document document) {} javascript: I'd like to add functions and do static analysis actually. I can't believe I just said that though. But the stuff I'd analyze is checking it against the D functions, recognizing that JS is loosely typed. So basically it can do a grep for simple stuff: CoolApi.xxxxxxx if xxxxxxx isn't a function in CoolApi (the name it knows from the server), it can flag a compile error. Might not be able to catch usage all the time but could catch typo names. */ /* FIXME: in params on the wrapped functions generally don't work (can't modify const) Running from the command line: ./myapp function positional args.... ./myapp --format=json function ./myapp --make-nested-call Formatting data: CoolApi.myFunc().getFormat('Element', [...same as get...]); You should also be able to ask for json, but with a particular format available as toString format("json", "html") -- gets json, but each object has it's own toString. Actually, the object adds a member called formattedSecondarily that is the other thing. Note: the array itself cannot be changed in format, only it's members. Note: the literal string of the formatted object is often returned. This may more than double the bandwidth of the call Note: BUG: it only works with built in formats right now when doing secondary // formats are: text, html, json, table, and xml // except json, they are all represented as strings in json values string toString -> formatting as text Element makeHtmlElement -> making it html (same as fragment) JSONValue makeJsonValue -> formatting to json Table makeHtmlTable -> making a table (not implemented) toXml -> making it into an xml document Arrays can be handled too: static (converts to) string makeHtmlArray(typeof(this)[] arr); Envelope format: document (default), json, none */ import std.exception; public import arsd.dom; public import arsd.cgi; // you have to import this in the actual usage file or else it won't link; surely a compiler bug import arsd.sha; public import std.string; public import std.array; public import std.stdio : writefln; public import std.conv; import std.random; import std.typetuple; import std.datetime; public import std.range; public import std.traits; import std.json; /// This gets your site's base link. note it's really only good if you are using FancyMain. string getSiteLink(Cgi cgi) { return cgi.requestUri[0.. cgi.requestUri.indexOf(cgi.scriptName) + cgi.scriptName.length + 1 /* for the slash at the end */]; } /// use this in a function parameter if you want the automatic form to render /// it as a textarea /// FIXME: this should really be an annotation on the parameter... somehow struct Text { string content; alias content this; } /// This is the JSON envelope format struct Envelope { bool success; /// did the call succeed? false if it threw an exception string type; /// static type of the return value string errorMessage; /// if !success, this is exception.msg string userData; /// null unless the user request included passedThroughUserData // use result.str if the format was anything other than json JSONValue result; /// the return value of the function debug string dFullString; /// exception.toString - includes stack trace, etc. Only available in debug mode for privacy reasons. } /// Info about the current request - more specialized than the cgi object directly struct RequestInfo { string mainSitePath; /// the bottom-most ApiProvider's path in this request string objectBasePath; /// the top-most resolved path in the current request FunctionInfo currentFunction; /// what function is being called according to the url? string requestedFormat; /// the format the returned data was requested to be sent string requestedEnvelopeFormat; /// the format the data is to be wrapped in } /+ string linkTo(alias func, T...)(T args) { auto reflection = __traits(parent, func).reflection; assert(reflection !is null); auto name = func.stringof; auto idx = name.indexOf("("); if(idx != -1) name = name[0 .. idx]; auto funinfo = reflection.functions[name]; return funinfo.originalName; } +/ /// this is there so there's a common runtime type for all callables class WebDotDBaseType { Cgi cgi; /// lower level access to the request /// Override this if you want to do something special to the document /// You should probably call super._postProcess at some point since I /// might add some default transformations here. /// By default, it forwards the document root to _postProcess(Element). void _postProcess(Document document) { if(document !is null && document.root !is null) _postProcessElement(document.root); } /// Override this to do something special to returned HTML Elements. /// This is ONLY run if the return type is(: Element). It is NOT run /// if the return type is(: Document). void _postProcessElement(Element element) {} // why the fuck doesn't overloading actually work? /// convenience function to enforce that the current method is POST. /// You should use this if you are going to commit to the database or something. void ensurePost() { assert(cgi !is null); enforce(cgi.requestMethod == Cgi.RequestMethod.POST); } } /// This is meant to beautify and check links and javascripts to call web.d functions. /// FIXME: this function sucks. string linkCall(alias Func, Args...)(Args args) { static if(!__traits(compiles, Func(args))) { static assert(0, "Your function call doesn't compile. If you need client side dynamic data, try building the call as a string."); } // FIXME: this link won't work from other parts of the site... //string script = __traits(parent, Func).stringof; auto href = __traits(identifier, Func) ~ "?"; bool outputted = false; foreach(i, arg; args) { if(outputted) { href ~= "&"; } else outputted = true; href ~= std.uri.encodeComponent("positional-arg-" ~ to!string(i)); href ~= "="; href ~= to!string(arg); // FIXME: this is wrong for all but the simplest types } return href; } /// This is meant to beautify and check links and javascripts to call web.d functions. /// This function works pretty ok. You're going to want to append a string to the return /// value to actually call .get() or whatever; it only does the name and arglist. string jsCall(alias Func, Args...)(Args args) /*if(is(__traits(parent, Func) : WebDotDBaseType))*/ { static if(!__traits(compiles, Func(args))) { static assert(0, "Your function call doesn't compile. If you need client side dynamic data, try building the call as a string."); } string script = __traits(parent, Func).stringof; script ~= "." ~ __traits(identifier, Func) ~ "("; bool outputted = false; foreach(arg; args) { if(outputted) { script ~= ","; } else outputted = true; script ~= toJson(arg); } script ~= ")"; return script; } /// Everything should derive from this instead of the old struct namespace used before /// Your class must provide a default constructor. class ApiProvider : WebDotDBaseType { private ApiProvider builtInFunctions; Session session; // note: may be null /// override this to change cross-site request forgery checks. /// /// To perform a csrf check, call ensureGoodPost(); in your code. /// /// It throws a PermissionDeniedException if the check fails. /// This might change later to make catching it easier. /// /// If there is no session object, the test always succeeds. This lets you opt /// out of the system. /// /// If the session is null, it does nothing. FancyMain makes a session for you. /// If you are doing manual run(), it is your responsibility to create a session /// and attach it to each primary object. /// /// NOTE: it is important for you use ensureGoodPost() on any data changing things! /// This function alone is a no-op on non-POST methods, so there's no real protection /// without ensuring POST when making changes. /// // FIXME: if someone is OAuth authorized, a csrf token should not really be necessary. // This check is done automatically right now, and doesn't account for that. I guess // people could override it in a subclass though. (Which they might have to since there's // no oauth integration at this level right now anyway. Nor may there ever be; it's kinda // high level. Perhaps I'll provide an oauth based subclass later on.) protected void checkCsrfToken() { assert(cgi !is null); if(cgi.requestMethod == Cgi.RequestMethod.POST) { auto tokenInfo = _getCsrfInfo(); if(tokenInfo is null) return; // not doing checks void fail() { throw new PermissionDeniedException("CSRF token test failed"); } // expiration is handled by the session itself expiring (in the Session class) if(tokenInfo["key"] !in cgi.post) fail(); if(cgi.post[tokenInfo["key"]] != tokenInfo["token"]) fail(); } } protected bool isCsrfTokenCorrect() { auto tokenInfo = _getCsrfInfo(); if(tokenInfo is null) return false; // this means we aren't doing checks (probably because there is no session), but it is a failure nonetheless auto token = tokenInfo["key"] ~ "=" ~ tokenInfo["token"]; if("x-arsd-csrf-pair" in cgi.requestHeaders) return cgi.requestHeaders["x-arsd-csrf-pair"] == token; if(tokenInfo["key"] in cgi.post) return cgi.post[tokenInfo["key"]] == tokenInfo["token"]; if(tokenInfo["key"] in cgi.get) return cgi.get[tokenInfo["key"]] == tokenInfo["token"]; return false; } /// Shorthand for ensurePost and checkCsrfToken. You should use this on non-indempotent /// functions. Override it if doing some custom checking. void ensureGoodPost() { ensurePost(); checkCsrfToken(); } // gotta make sure this isn't callable externally! Oh lol that'd defeat the point... /// Gets the CSRF info (an associative array with key and token inside at least) from the session. /// Note that the actual token is generated by the Session class. protected string[string] _getCsrfInfo() { if(session is null) return null; return decodeVariablesSingle(session.csrfToken); } /// Adds CSRF tokens to the document for use by script (required by the Javascript API) /// and then calls addCsrfTokens(document.root) to add them to all POST forms as well. protected void addCsrfTokens(Document document) { if(document is null) return; auto bod = document.mainBody; if(!bod.hasAttribute("data-csrf-key")) { auto tokenInfo = _getCsrfInfo(); if(tokenInfo is null) return; if(bod !is null) { bod.setAttribute("data-csrf-key", tokenInfo["key"]); bod.setAttribute("data-csrf-token", tokenInfo["token"]); } addCsrfTokens(document.root); } } /// we have to add these things to the document... override void _postProcess(Document document) { foreach(pp; documentPostProcessors) pp(document); addCsrfTokens(document); super._postProcess(document); } /// This adds CSRF tokens to all forms in the tree protected void addCsrfTokens(Element element) { if(element is null) return; auto tokenInfo = _getCsrfInfo(); if(tokenInfo is null) return; foreach(formElement; element.getElementsByTagName("form")) { if(formElement.method != "POST" && formElement.method != "post") continue; auto form = cast(Form) formElement; assert(form !is null); form.setValue(tokenInfo["key"], tokenInfo["token"]); } } // and added to ajax forms.. override void _postProcessElement(Element element) { foreach(pp; elementPostProcessors) pp(element); addCsrfTokens(element); super._postProcessElement(element); } // FIXME: the static is meant to be a performance improvement, but it breaks child modules' reflection! /*static */immutable(ReflectionInfo)* reflection; string _baseUrl; // filled based on where this is called from on this request RequestInfo currentRequest; // FIXME: actually fill this in /// Override this if you have initialization work that must be done *after* cgi and reflection is ready. /// It should be used instead of the constructor for most work. void _initialize() {} /// On each call, you can register another post processor for the generated html. If your delegate takes a Document, it will only run on document envelopes (full pages generated). If you take an Element, it will apply on almost any generated html. /// /// Note: if you override _postProcess or _postProcessElement, be sure to call the superclass version for these registered functions to run. void _registerPostProcessor(void delegate(Document) pp) { documentPostProcessors ~= pp; } /// ditto void _registerPostProcessor(void delegate(Element) pp) { elementPostProcessors ~= pp; } /// ditto void _registerPostProcessor(void function(Document) pp) { documentPostProcessors ~= delegate void(Document d) { pp(d); }; } /// ditto void _registerPostProcessor(void function(Element) pp) { elementPostProcessors ~= delegate void(Element d) { pp(d); }; } // these only work for one particular call private void delegate(Document d)[] documentPostProcessors; private void delegate(Element d)[] elementPostProcessors; private void _initializePerCallInternal() { documentPostProcessors = null; elementPostProcessors = null; _initializePerCall(); } /// This one is called at least once per call. (_initialize is only called once per process) void _initializePerCall() {} /// Returns the stylesheet for this module. Use it to encapsulate the needed info for your output so the module is more easily reusable /// Override this to provide your own stylesheet. (of course, you can always provide it via _catchAll or any standard css file/style element too.) string _style() const { return null; } /// Returns the combined stylesheet of all child modules and this module string stylesheet() const { string ret; foreach(i; reflection.objects) { if(i.instantiation !is null) ret ~= i.instantiation.stylesheet(); } ret ~= _style(); return ret; } /// This tentatively redirects the user - depends on the envelope fomat void redirect(string location, bool important = false) { auto f = cgi.request("envelopeFormat", "document"); if(f == "document" || f == "redirect") cgi.setResponseLocation(location, important); } /// Returns a list of links to all functions in this class or sub-classes /// You can expose it publicly with alias: "alias _sitemap sitemap;" for example. Element _sitemap() { auto container = _getGenericContainer(); void writeFunctions(Element list, in ReflectionInfo* reflection, string base) { string[string] handled; foreach(key, func; reflection.functions) { if(func.originalName in handled) continue; handled[func.originalName] = func.originalName; // skip these since the root is what this is there for if(func.originalName == "GET" || func.originalName == "POST") continue; // the builtins aren't interesting either if(key.startsWith("builtin.")) continue; if(func.originalName.length) list.addChild("li", new Link(base ~ func.name, beautify(func.originalName))); } handled = null; foreach(obj; reflection.objects) { if(obj.name in handled) continue; handled[obj.name] = obj.name; auto li = list.addChild("li", new Link(base ~ obj.name, obj.name)); auto ul = li.addChild("ul"); writeFunctions(ul, obj, base ~ obj.name ~ "/"); } } auto list = container.addChild("ul"); auto starting = _baseUrl; if(starting is null) starting = cgi.scriptName ~ cgi.pathInfo; // FIXME writeFunctions(list, reflection, starting ~ "/"); return list.parentNode.removeChild(list); } /// If the user goes to your program without specifying a path, this function is called. // FIXME: should it return document? That's kinda a pain in the butt. Document _defaultPage() { throw new Exception("no default"); } /// When the html document envelope is used, this function is used to get a html element /// where the return value is appended. /// It's the main function to override to provide custom HTML templates. /// /// The default document provides a default stylesheet, our default javascript, and some timezone cookie handling (which you must handle on the server. Eventually I'll open source my date-time helpers that do this, but the basic idea is it sends an hour offset, and you can add that to any UTC time you have to get a local time). Element _getGenericContainer() out(ret) { assert(ret !is null); } body { auto document = new TemplatedDocument( "<!DOCTYPE html> <html> <head> <title></title> <link rel=\"stylesheet\" href=\"styles.css\" /> <script> var delayedExecutionQueue = []; </script> <!-- FIXME do some better separation --> <script> if(document.cookie.indexOf(\"timezone=\") == -1) { var d = new Date(); var tz = -d.getTimezoneOffset() / 60; document.cookie = \"timezone=\" + tz + \"; path=/\"; } </script> <style>.format-row { display: none; }</style> </head> <body> <div id=\"body\"></div> <script src=\"functions.js\"></script> </body> </html>"); if(this.reflection !is null) document.title = this.reflection.name; auto container = document.requireElementById("body"); return container; } // FIXME: set a generic container for a particular call /// If the given url path didn't match a function, it is passed to this function /// for further handling. By default, it throws a NoSuchFunctionException. /// Overriding it might be useful if you want to serve generic filenames or an opDispatch kind of thing. /// (opDispatch itself won't work because it's name argument needs to be known at compile time!) /// /// Note that you can return Documents here as they implement /// the FileResource interface too. FileResource _catchAll(string path) { throw new NoSuchFunctionException(_errorMessageForCatchAll); } private string _errorMessageForCatchAll; private FileResource _catchallEntry(string path, string funName, string errorMessage) { if(!errorMessage.length) { /* string allFuncs, allObjs; foreach(n, f; reflection.functions) allFuncs ~= n ~ "\n"; foreach(n, f; reflection.objects) allObjs ~= n ~ "\n"; errorMessage = "no such function " ~ funName ~ "\n functions are:\n" ~ allFuncs ~ "\n\nObjects are:\n" ~ allObjs; */ errorMessage = "No such page: " ~ funName; } _errorMessageForCatchAll = errorMessage; return _catchAll(path); } /// When in website mode, you can use this to beautify the error message Document delegate(Throwable) _errorFunction; } /// Implement subclasses of this inside your main provider class to do a more object /// oriented site. class ApiObject : WebDotDBaseType { /* abstract this(ApiProvider parent, string identifier) */ /// Override this to make json out of this object JSONValue makeJsonValue() { return toJsonValue(null); } } class DataFile : FileResource { this(string contentType, immutable(void)[] contents) { _contentType = contentType; _content = contents; } private string _contentType; private immutable(void)[] _content; string contentType() const { return _contentType; } immutable(ubyte)[] getData() const { return cast(immutable(ubyte)[]) _content; } } /// Describes the info collected about your class struct ReflectionInfo { immutable(FunctionInfo)*[string] functions; /// the methods EnumInfo[string] enums; /// . StructInfo[string] structs; ///. const(ReflectionInfo)*[string] objects; /// ApiObjects and ApiProviders bool needsInstantiation; // internal - does the object exist or should it be new'd before referenced? ApiProvider instantiation; // internal (for now) - reference to the actual object being described WebDotDBaseType delegate(string) instantiate; // the overall namespace string name; /// this is also used as the object name in the JS api // these might go away. string defaultOutputFormat = "html"; int versionOfOutputFormat = 2; // change this in your constructor if you still need the (deprecated) old behavior // bool apiMode = false; // no longer used - if format is json, apiMode behavior is assumed. if format is html, it is not. // FIXME: what if you want the data formatted server side, but still in a json envelope? // should add format-payload: } /// describes an enum, iff based on int as the underlying type struct EnumInfo { string name; ///. int[] values; ///. string[] names; ///. } /// describes a plain data struct struct StructInfo { string name; ///. // a struct is sort of like a function constructor... StructMemberInfo[] members; ///. } ///. struct StructMemberInfo { string name; ///. string staticType; ///. string defaultValue; ///. } ///. struct FunctionInfo { WrapperFunction dispatcher; /// this is the actual function called when a request comes to it - it turns a string[][string] into the actual args and formats the return value const(ReflectionInfo)* parentObject; // should I also offer dispatchers for other formats like Variant[]? string name; /// the URL friendly name string originalName; /// the original name in code //string uriPath; Parameter[] parameters; ///. string returnType; ///. static type to string bool returnTypeIsDocument; // internal used when wrapping bool returnTypeIsElement; // internal used when wrapping Document delegate(in string[string] args) createForm; /// This is used if you want a custom form - normally, on insufficient parameters, an automatic form is created. But if there's a functionName_Form method, it is used instead. FIXME: this used to work but not sure if it still does } /// Function parameter struct Parameter { string name; /// name (not always accurate) string value; // ??? string type; /// type of HTML element to create when asking string staticType; /// original type string validator; /// FIXME bool hasDefault; /// if there was a default defined in the function string defaultValue; /// the default value defined in D, but as a string, if present // for radio and select boxes string[] options; /// possible options for selects string[] optionValues; ///. Element function(Document, string) makeFormElement; } // these are all filthy hacks template isEnum(alias T) if(is(T)) { static if (is(T == enum)) enum bool isEnum = true; else enum bool isEnum = false; } // WTF, shouldn't is(T == xxx) already do this? template isEnum(T) if(!is(T)) { enum bool isEnum = false; } template isStruct(alias T) if(is(T)) { static if (is(T == struct)) enum bool isStruct = true; else enum bool isStruct = false; } // WTF template isStruct(T) if(!is(T)) { enum bool isStruct = false; } template isApiObject(alias T) if(is(T)) { static if (is(T : ApiObject)) enum bool isApiObject = true; else enum bool isApiObject = false; } // WTF template isApiObject(T) if(!is(T)) { enum bool isApiObject = false; } template isApiProvider(alias T) if(is(T)) { static if (is(T : ApiProvider)) enum bool isApiProvider = true; else enum bool isApiProvider = false; } // WTF template isApiProvider(T) if(!is(T)) { enum bool isApiProvider = false; } template Passthrough(T) { T Passthrough; } template PassthroughType(T) { alias T PassthroughType; } // sets up the reflection object. now called automatically so you probably don't have to mess with it immutable(ReflectionInfo*) prepareReflection(alias PM)(PM instantiation) if(is(PM : ApiProvider) || is(PM: ApiObject) ) { return prepareReflectionImpl!(PM, PM)(instantiation); } // FIXME: this doubles the compile time and can add megabytes to the executable. immutable(ReflectionInfo*) prepareReflectionImpl(alias PM, alias Parent)(Parent instantiation) if(is(PM : WebDotDBaseType) && is(Parent : ApiProvider)) { assert(instantiation !is null); ReflectionInfo* reflection = new ReflectionInfo; reflection.name = PM.stringof; static if(is(PM: ApiObject)) { reflection.needsInstantiation = true; reflection.instantiate = delegate WebDotDBaseType(string i) { auto n = new PM(instantiation, i); return n; }; } else { reflection.instantiation = instantiation; static if(!is(PM : BuiltInFunctions)) { auto builtins = new BuiltInFunctions(instantiation, reflection); instantiation.builtInFunctions = builtins; foreach(k, v; builtins.reflection.functions) reflection.functions["builtin." ~ k] = v; } } static if(is(PM : ApiProvider)) {{ // double because I want a new scope auto f = new FunctionInfo; f.parentObject = reflection; f.dispatcher = generateWrapper!(PM, "_defaultPage", PM._defaultPage)(reflection, instantiation); f.returnTypeIsDocument = true; reflection.functions["/"] = cast(immutable) f; /+ // catchAll here too f = new FunctionInfo; f.parentObject = reflection; f.dispatcher = generateWrapper!(PM, "_catchAll", PM._catchAll)(reflection, instantiation); f.returnTypeIsDocument = true; reflection.functions["/_catchAll"] = cast(immutable) f; +/ }} // derivedMembers is changed from allMembers // FIXME: this seems to do the right thing with inheritance.... but I don't really understand why. Isn't the override done first, and thus overwritten by the base class version? you know maybe it is all because it still does a vtable lookup on the real object. eh idk, just confirm what it does eventually foreach(Class; TypeTuple!(PM, BaseClassesTuple!(PM))) static if(is(Class : ApiProvider) && !is(Class == ApiProvider)) foreach(member; __traits(derivedMembers, Class)) { // we do derived on a base class loop because we don't want interfaces (OR DO WE? seriously idk) and we definitely don't want stuff from Object, ApiProvider itself is out too but that might change. static if(member[0] != '_') { // FIXME: the filthiest of all hacks... static if(!__traits(compiles, !is(typeof(__traits(getMember, Class, member)) == function) && isEnum!(__traits(getMember, Class, member)))) continue; // must be a data member or something... else // DONE WITH FILTHIEST OF ALL HACKS //if(member.length == 0) // continue; static if( !is(typeof(__traits(getMember, Class, member)) == function) && isEnum!(__traits(getMember, Class, member)) ) { EnumInfo i; i.name = member; foreach(m; __traits(allMembers, __traits(getMember, Class, member))) { i.names ~= m; i.values ~= cast(int) __traits(getMember, __traits(getMember, Class, member), m); } reflection.enums[member] = i; } else static if( !is(typeof(__traits(getMember, Class, member)) == function) && isStruct!(__traits(getMember, Class, member)) ) { StructInfo i; i.name = member; typeof(Passthrough!(__traits(getMember, Class, member))) s; foreach(idx, m; s.tupleof) { StructMemberInfo mem; mem.name = s.tupleof[idx].stringof[2..$]; mem.staticType = typeof(m).stringof; mem.defaultValue = null; // FIXME i.members ~= mem; } reflection.structs[member] = i; } else static if( is(typeof(__traits(getMember, Class, member)) == function) && ( member.length < 5 || ( member[$ - 5 .. $] != "_Page" && member[$ - 5 .. $] != "_Form") && !(member.length > 16 && member[$ - 16 .. $] == "_PermissionCheck") )) { FunctionInfo* f = new FunctionInfo; ParameterTypeTuple!(__traits(getMember, Class, member)) fargs; f.returnType = ReturnType!(__traits(getMember, Class, member)).stringof; f.returnTypeIsDocument = is(ReturnType!(__traits(getMember, Class, member)) : Document); f.returnTypeIsElement = is(ReturnType!(__traits(getMember, Class, member)) : Element); f.parentObject = reflection; f.name = toUrlName(member); f.originalName = member; assert(instantiation !is null); f.dispatcher = generateWrapper!(Class, member, __traits(getMember, Class, member))(reflection, instantiation); //f.uriPath = f.originalName; auto namesAndDefaults = parameterInfoImpl!(__traits(getMember, Class, member)); auto names = namesAndDefaults[0]; auto defaults = namesAndDefaults[1]; assert(names.length == defaults.length); foreach(idx, param; fargs) { if(idx >= names.length) assert(0, to!string(idx) ~ " " ~ to!string(names)); Parameter p = reflectParam!(typeof(param))(); p.name = names[idx]; auto d = defaults[idx]; p.defaultValue = d == "null" ? "" : d; p.hasDefault = d.length > 0; f.parameters ~= p; } static if(__traits(hasMember, Class, member ~ "_Form")) { f.createForm = &__traits(getMember, instantiation, member ~ "_Form"); } reflection.functions[f.name] = cast(immutable) (f); // also offer the original name if it doesn't // conflict //if(f.originalName !in reflection.functions) reflection.functions[f.originalName] = cast(immutable) (f); } else static if( !is(typeof(__traits(getMember, Class, member)) == function) && isApiObject!(__traits(getMember, Class, member)) ) { reflection.objects[member] = prepareReflectionImpl!( __traits(getMember, Class, member), Parent) (instantiation); } else static if( // child ApiProviders are like child modules !is(typeof(__traits(getMember, Class, member)) == function) && isApiProvider!(__traits(getMember, Class, member)) ) { PassthroughType!(__traits(getMember, Class, member)) i; static if(__traits(compiles, i = new typeof(i)(instantiation))) i = new typeof(i)(instantiation); else i = new typeof(i)(); auto r = prepareReflectionImpl!(__traits(getMember, Class, member), typeof(i))(i); i.reflection = cast(immutable) r; reflection.objects[member] = r; if(toLower(member) !in reflection.objects) // web filenames are often lowercase too reflection.objects[member.toLower] = r; } } } return cast(immutable) reflection; } Parameter reflectParam(param)() { Parameter p; p.staticType = param.stringof; static if( __traits(compiles, p.makeFormElement = &(param.makeFormElement))) { p.makeFormElement = &(param.makeFormElement); } else static if( __traits(compiles, PM.makeFormElement!(param)(null, null))) { alias PM.makeFormElement!(param) LOL; p.makeFormElement = &LOL; } else static if( is( param == enum )) { p.type = "select"; foreach(opt; __traits(allMembers, param)) { p.options ~= opt; p.optionValues ~= to!string(__traits(getMember, param, opt)); } } else static if (is(param == bool)) { p.type = "checkbox"; } else static if (is(Unqual!(param) == Cgi.UploadedFile)) { p.type = "file"; } else static if(is(Unqual!(param) == Text)) { p.type = "textarea"; } else { p.type = "text"; } return p; } struct CallInfo { string objectIdentifier; immutable(FunctionInfo)* func; void delegate(Document)[] postProcessors; } class NonCanonicalUrlException : Exception { this(CanonicalUrlOption option, string properUrl = null) { this.howToFix = option; this.properUrl = properUrl; super("The given URL needs this fix: " ~ to!string(option) ~ " " ~ properUrl); } CanonicalUrlOption howToFix; string properUrl; } enum CanonicalUrlOption { cutTrailingSlash, addTrailingSlash } CallInfo parseUrl(in ReflectionInfo* reflection, string url, string defaultFunction, in bool hasTrailingSlash) { CallInfo info; if(url.length && url[0] == '/') url = url[1 .. $]; if(reflection.needsInstantiation) { // FIXME: support object identifiers that span more than one slash... maybe auto idx = url.indexOf("/"); if(idx != -1) { info.objectIdentifier = url[0 .. idx]; url = url[idx + 1 .. $]; } else { info.objectIdentifier = url; url = null; } } string name; auto idx = url.indexOf("/"); if(idx != -1) { name = url[0 .. idx]; url = url[idx + 1 .. $]; } else { name = url; url = null; } bool usingDefault = false; if(name.length == 0) { name = defaultFunction; usingDefault = true; if(name !in reflection.functions) name = "/"; // should call _defaultPage } if(reflection.instantiation !is null) info.postProcessors ~= &(reflection.instantiation._postProcess); if(name in reflection.functions) { info.func = reflection.functions[name]; // if we're using a default thing, we need as slash on the end so relative links work if(usingDefault) { if(!hasTrailingSlash) throw new NonCanonicalUrlException(CanonicalUrlOption.addTrailingSlash); } else { if(hasTrailingSlash) throw new NonCanonicalUrlException(CanonicalUrlOption.cutTrailingSlash); } } if(name in reflection.objects) { info = parseUrl(reflection.objects[name], url, defaultFunction, hasTrailingSlash); } return info; } /// If you're not using FancyMain, this is the go-to function to do most the work. /// instantiation should be an object of your ApiProvider type. /// pathInfoStartingPoint is used to make a slice of it, incase you already consumed part of the path info before you called this. void run(Provider)(Cgi cgi, Provider instantiation, size_t pathInfoStartingPoint = 0, bool handleAllExceptions = true) if(is(Provider : ApiProvider)) { assert(instantiation !is null); if(instantiation.reflection is null) { instantiation.reflection = prepareReflection!(Provider)(instantiation); instantiation.cgi = cgi; instantiation._initialize(); // FIXME: what about initializing child objects? } auto reflection = instantiation.reflection; instantiation._baseUrl = cgi.scriptName ~ cgi.pathInfo[0 .. pathInfoStartingPoint]; // everything assumes the url isn't empty... if(cgi.pathInfo.length < pathInfoStartingPoint + 1) { cgi.setResponseLocation(cgi.scriptName ~ cgi.pathInfo ~ "/" ~ (cgi.queryString.length ? "?" ~ cgi.queryString : "")); return; } // kinda a hack, but this kind of thing should be available anyway string funName = cgi.pathInfo[pathInfoStartingPoint + 1..$]; if(funName == "functions.js") { cgi.gzipResponse = true; cgi.setResponseContentType("text/javascript"); cgi.write(makeJavascriptApi(reflection, replace(cast(string) cgi.requestUri, "functions.js", "")), true); cgi.close(); return; } if(funName == "styles.css") { cgi.gzipResponse = true; cgi.setResponseContentType("text/css"); cgi.write(instantiation.stylesheet(), true); cgi.close(); return; } CallInfo info; try info = parseUrl(reflection, cgi.pathInfo[pathInfoStartingPoint + 1 .. $], to!string(cgi.requestMethod), cgi.pathInfo[$-1] == '/'); catch(NonCanonicalUrlException e) { final switch(e.howToFix) { case CanonicalUrlOption.cutTrailingSlash: cgi.setResponseLocation(cgi.scriptName ~ cgi.pathInfo[0 .. $ - 1] ~ (cgi.queryString.length ? ("?" ~ cgi.queryString) : "")); break; case CanonicalUrlOption.addTrailingSlash: cgi.setResponseLocation(cgi.scriptName ~ cgi.pathInfo ~ "/" ~ (cgi.queryString.length ? ("?" ~ cgi.queryString) : "")); break; } return; } auto fun = info.func; auto instantiator = info.objectIdentifier; Envelope result; result.userData = cgi.request("passedThroughUserData"); auto envelopeFormat = cgi.request("envelopeFormat", "document"); WebDotDBaseType base = instantiation; WebDotDBaseType realObject = instantiation; if(instantiator.length == 0) if(fun !is null && fun.parentObject !is null && fun.parentObject.instantiation !is null) realObject = cast() fun.parentObject.instantiation; // casting away transitive immutable... // FIXME if(cgi.pathInfo.indexOf("builtin.") != -1 && instantiation.builtInFunctions !is null) base = instantiation.builtInFunctions; if(base !is realObject) { auto hack1 = cast(ApiProvider) base; auto hack2 = cast(ApiProvider) realObject; if(hack1 !is null && hack2 !is null && hack2.session is null) hack2.session = hack1.session; } try { if(fun is null) { auto d = instantiation._catchallEntry( cgi.pathInfo[pathInfoStartingPoint + 1..$], funName, ""); result.success = true; if(d !is null) { auto doc = cast(Document) d; if(doc) instantiation._postProcess(doc); cgi.setResponseContentType(d.contentType()); cgi.write(d.getData(), true); } // we did everything we need above... envelopeFormat = "no-processing"; goto do_nothing_else; } assert(fun !is null); assert(fun.dispatcher !is null); assert(cgi !is null); if(instantiator.length) { assert(fun !is null); assert(fun.parentObject !is null); assert(fun.parentObject.instantiate !is null); realObject = fun.parentObject.instantiate(instantiator); } result.type = fun.returnType; string format = cgi.request("format", reflection.defaultOutputFormat); string secondaryFormat = cgi.request("secondaryFormat", ""); if(secondaryFormat.length == 0) secondaryFormat = null; JSONValue res; // FIXME: hackalicious garbage. kill. string[][string] want = cast(string[][string]) (cgi.requestMethod == Cgi.RequestMethod.POST ? cgi.postArray : cgi.getArray); version(fb_inside_hack) { if(cgi.referrer.indexOf("apps.facebook.com") != -1) { auto idx = cgi.referrer.indexOf("?"); if(idx != -1 && cgi.referrer[idx + 1 .. $] != cgi.queryString) { // so fucking broken cgi.setResponseLocation(cgi.scriptName ~ cgi.pathInfo ~ cgi.referrer[idx .. $]); return; } } if(cgi.requestMethod == Cgi.RequestMethod.POST) { foreach(k, v; cgi.getArray) want[k] = cast(string[]) v; foreach(k, v; cgi.postArray) want[k] = cast(string[]) v; } } realObject.cgi = cgi; res = fun.dispatcher(cgi, realObject, want, format, secondaryFormat); //if(cgi) // cgi.setResponseContentType("application/json"); result.success = true; result.result = res; do_nothing_else: {} } catch (Throwable e) { result.success = false; result.errorMessage = e.msg; result.type = e.classinfo.name; debug result.dFullString = e.toString(); if(envelopeFormat == "document" || envelopeFormat == "html") { auto ipe = cast(InsufficientParametersException) e; if(ipe !is null) { assert(fun !is null); Form form; if(fun.createForm !is null) { // go ahead and use it to make the form page auto doc = fun.createForm(cgi.requestMethod == Cgi.RequestMethod.POST ? cgi.post : cgi.get); form = doc.requireSelector!Form("form.created-by-create-form, form.automatic-form, form"); } else { Parameter[] params = (cast(Parameter[])fun.parameters).dup; foreach(i, p; fun.parameters) { string value = ""; if(p.name in cgi.get) value = cgi.get[p.name]; if(p.name in cgi.post) value = cgi.post[p.name]; params[i].value = value; } form = createAutomaticForm(new Document("<html></html>", true, true), fun);// params, beautify(fun.originalName)); foreach(k, v; cgi.get) form.setValue(k, v); instantiation.addCsrfTokens(form); form.setValue("envelopeFormat", envelopeFormat); auto n = form.getElementById("function-name"); if(n) n.innerText = beautify(fun.originalName); // FIXME: I like having something, but it needs to not // show it on the first user load. // form.prependChild(Element.make("p", ipe.msg)); } assert(form !is null); foreach(k, v; cgi.get) form.setValue(k, v); // carry what we have for params over result.result.str = form.toString(); } else { auto fourOhFour = cast(NoSuchPageException) e; if(fourOhFour !is null) cgi.setResponseStatus("404 File Not Found"); if(instantiation._errorFunction !is null) { auto document = instantiation._errorFunction(e); if(document is null) goto gotnull; result.result.str = (document.toString()); } else { gotnull: if(!handleAllExceptions) { envelopeFormat = "internal"; throw e; // pass it up the chain } auto code = Element.make("div"); code.addClass("exception-error-message"); code.addChild("p", e.msg); debug code.addChild("pre", e.toString()); result.result.str = (code.toString()); } } } } finally { // the function must have done its own thing; we need to quit or else it will trigger an assert down here if(!cgi.isClosed()) switch(envelopeFormat) { case "no-processing": case "internal": break; case "redirect": auto redirect = cgi.request("_arsd_redirect_location", cgi.referrer); // FIXME: is this safe? it'd make XSS super easy // add result to url if(!result.success) goto case "none"; cgi.setResponseLocation(redirect, false); break; case "json": // this makes firefox ugly //cgi.setResponseContentType("application/json"); auto json = toJsonValue(result); cgi.write(toJSON(&json), true); break; case "script": case "jsonp": bool securityPass = false; version(web_d_unrestricted_jsonp) { // unrestricted is opt-in because i worry about fetching user info from across sites securityPass = true; } else { // we check this on both get and post to ensure they can't fetch user private data cross domain. auto hack1 = cast(ApiProvider) base; if(hack1) securityPass = hack1.isCsrfTokenCorrect(); } if(securityPass) { if(envelopeFormat == "script") cgi.setResponseContentType("text/html"); else cgi.setResponseContentType("application/javascript"); auto json = cgi.request("jsonp", "throw new Error") ~ "(" ~ toJson(result) ~ ");"; if(envelopeFormat == "script") json = "<script type=\"text/javascript\">" ~ json ~ "</script>"; cgi.write(json, true); } else { // if the security check fails, you just don't get anything at all data wise... cgi.setResponseStatus("403 Forbidden"); } break; case "none": cgi.setResponseContentType("text/plain"); if(result.success) { if(result.result.type == JSON_TYPE.STRING) { cgi.write(result.result.str, true); } else { cgi.write(toJSON(&result.result), true); } } else { cgi.write(result.errorMessage, true); } break; case "document": case "html": default: cgi.setResponseContentType("text/html; charset=utf-8"); if(result.result.type == JSON_TYPE.STRING) { auto returned = result.result.str; if(envelopeFormat != "html") { Document document; if(result.success && fun !is null && fun.returnTypeIsDocument && returned.length) { // probably not super efficient... document = new TemplatedDocument(returned); } else { // auto e = instantiation._getGenericContainer(); Element e; auto hack = cast(ApiProvider) realObject; if(hack !is null) e = hack._getGenericContainer(); else e = instantiation._getGenericContainer(); document = e.parentDocument; // FIXME: a wee bit slow, esp if func return element e.innerHTML = returned; if(fun !is null) e.setAttribute("data-from-function", fun.originalName); } if(document !is null) { if(envelopeFormat == "document") { // forming a nice chain here... // FIXME: this isn't actually a nice chain! bool[void delegate(Document)] run; auto postProcessors = info.postProcessors; if(base !is instantiation) postProcessors ~= &(instantiation._postProcess); if(realObject !is null) postProcessors ~= &(realObject._postProcess); postProcessors ~= &(base._postProcess); foreach(pp; postProcessors) { if(pp in run) continue; run[pp] = true; pp(document); } } returned = document.toString; } } cgi.write(returned, true); } else cgi.write(htmlEntitiesEncode(toJSON(&result.result)), true); break; } if(envelopeFormat != "internal") cgi.close(); } } class BuiltInFunctions : ApiProvider { const(ReflectionInfo)* workingFor; ApiProvider basedOn; this(ApiProvider basedOn, in ReflectionInfo* other) { this.basedOn = basedOn; workingFor = other; if(this.reflection is null) this.reflection = prepareReflection!(BuiltInFunctions)(this); assert(this.reflection !is null); } Form getAutomaticForm(string method) { if(method !in workingFor.functions) throw new Exception("no such method " ~ method); auto f = workingFor.functions[method]; Form form; if(f.createForm !is null) { form = f.createForm(null).requireSelector!Form("form"); } else form = createAutomaticForm(new Document("<html></html>", true, true), f); auto idx = basedOn.cgi.requestUri.indexOf("builtin.getAutomaticForm"); if(idx == -1) idx = basedOn.cgi.requestUri.indexOf("builtin.get-automatic-form"); assert(idx != -1); form.action = basedOn.cgi.requestUri[0 .. idx] ~ form.action; // make sure it works across the site return form; } } // what about some built in functions? /+ // Built-ins // Basic integer operations builtin.opAdd builtin.opSub builtin.opMul builtin.opDiv // Basic array operations builtin.opConcat // use to combine calls easily builtin.opIndex builtin.opSlice builtin.length // Basic floating point operations builtin.round builtin.floor builtin.ceil // Basic object operations builtin.getMember // Basic functional operations builtin.filter // use to slice down on stuff to transfer builtin.map // call a server function on a whole array builtin.reduce // Access to the html items builtin.getAutomaticForm(method) +/ /// fancier wrapper to cgi.d's GenericMain - does most the work for you, so you can just write your class and be done with it /// Note it creates a session for you too, and will write to the disk - a csrf token. Compile with -version=no_automatic_session /// to disable this. mixin template FancyMain(T, Args...) { mixin CustomCgiFancyMain!(Cgi, T, Args); } /// Like FancyMain, but you can pass a custom subclass of Cgi mixin template CustomCgiFancyMain(CustomCgi, T, Args...) if(is(CustomCgi : Cgi)) { void fancyMainFunction(Cgi cgi) { //string[] args) { // auto cgi = new Cgi; // there must be a trailing slash for relative links.. if(cgi.pathInfo.length == 0) { cgi.setResponseLocation(cgi.requestUri ~ "/"); cgi.close(); return; } // FIXME: won't work for multiple objects T instantiation = new T(); auto reflection = prepareReflection!(T)(instantiation); version(no_automatic_session) {} else { auto session = new Session(cgi); scope(exit) session.commit(); instantiation.session = session; } run(cgi, instantiation); /+ if(args.length > 1) { string[string][] namedArgs; foreach(arg; args[2..$]) { auto lol = arg.indexOf("="); if(lol == -1) throw new Exception("use named args for all params"); //namedArgs[arg[0..lol]] = arg[lol+1..$]; // FIXME } if(!(args[1] in reflection.functions)) { throw new Exception("No such function"); } //writefln("%s", reflection.functions[args[1]].dispatcher(null, namedArgs, "string")); } else { +/ // } } mixin CustomCgiMain!(CustomCgi, fancyMainFunction, Args); } /// Given a function from reflection, build a form to ask for it's params Form createAutomaticForm(Document document, in FunctionInfo* func, string[string] fieldTypes = null) { return createAutomaticForm(document, func.name, func.parameters, beautify(func.originalName), "POST", fieldTypes); } /// ditto // FIXME: should there be something to prevent the pre-filled options from url? It's convenient but // someone might use it to trick people into submitting badness too. I'm leaning toward meh. Form createAutomaticForm(Document document, string action, in Parameter[] parameters, string submitText = "Submit", string method = "POST", string[string] fieldTypes = null) { auto form = cast(Form) Element.make("form"); form.parentDocument = document; form.addClass("automatic-form"); form.action = action; assert(form !is null); form.method = method; auto fieldset = form.addChild("fieldset"); auto legend = fieldset.addChild("legend", submitText); auto table = cast(Table) fieldset.addChild("table"); assert(table !is null); table.addChild("tbody"); static int count = 0; foreach(param; parameters) { Element input; if(param.makeFormElement !is null) { input = param.makeFormElement(document, param.name); goto gotelement; } string type = param.type; if(param.name in fieldTypes) type = fieldTypes[param.name]; if(type == "select") { input = Element.make("select"); foreach(idx, opt; param.options) { auto option = Element.make("option"); option.name = opt; option.value = param.optionValues[idx]; option.innerText = beautify(opt); if(option.value == param.value) option.selected = "selected"; input.appendChild(option); } input.name = param.name; } else if (type == "radio") { assert(0, "FIXME"); } else { if(type.startsWith("textarea")) { input = Element.make("textarea"); input.name = param.name; input.innerText = param.value; input.rows = "7"; auto idx = type.indexOf("-"); if(idx != -1) { idx++; input.rows = type[idx .. $]; } } else { input = Element.make("input"); // hack to support common naming convention if(type == "text" && param.name.toLower.indexOf("password") != -1) input.type = "password"; else input.type = type; input.name = param.name; input.value = param.value; if(type == "file") { form.method = "POST"; form.enctype = "multipart/form-data"; } } } gotelement: string n = param.name ~ "_auto-form-" ~ to!string(count); input.id = n; if(type == "hidden") { form.appendChild(input); } else { auto th = Element.make("th"); auto label = Element.make("label"); label.setAttribute("for", n); label.innerText = beautify(param.name) ~ ": "; th.appendChild(label); table.appendRow(th, input); } count++; } auto fmt = Element.make("select"); fmt.name = "format"; fmt.addChild("option", "html").setAttribute("value", "html"); fmt.addChild("option", "table").setAttribute("value", "table"); fmt.addChild("option", "json").setAttribute("value", "json"); fmt.addChild("option", "string").setAttribute("value", "string"); auto th = table.th(""); th.addChild("label", "Format:"); table.appendRow(th, fmt).className = "format-row"; auto submit = Element.make("input"); submit.value = submitText; submit.type = "submit"; table.appendRow(Html("&nbsp;"), submit); // form.setValue("format", reflection.defaultOutputFormat); return form; } /* * * Returns the parameter names of the given function * * Params: * func = the function alias to get the parameter names of * * Returns: an array of strings containing the parameter names */ /+ string parameterNamesOf( alias fn )( ) { string fullName = typeof(&fn).stringof; int pos = fullName.lastIndexOf( ')' ); int end = pos; int count = 0; do { if ( fullName[pos] == ')' ) { count++; } else if ( fullName[pos] == '(' ) { count--; } pos--; } while ( count > 0 ); return fullName[pos+2..end]; } +/ template parameterNamesOf (alias func) { const parameterNamesOf = parameterInfoImpl!(func)[0]; } // FIXME: I lost about a second on compile time after adding support for defaults :-( template parameterDefaultsOf (alias func) { const parameterDefaultsOf = parameterInfoImpl!(func)[1]; } bool parameterHasDefault(alias func)(int p) { auto a = parameterDefaultsOf!(func); if(a.length == 0) return false; return a[p].length > 0; } string parameterDefaultOf (alias func)(int paramNum) { auto a = parameterDefaultsOf!(func); return a[paramNum]; } sizediff_t indexOfNew(string s, char a) { foreach(i, c; s) if(c == a) return i; return -1; } sizediff_t lastIndexOfNew(string s, char a) { for(sizediff_t i = s.length; i > 0; i--) if(s[i - 1] == a) return i - 1; return -1; } // FIXME: a problem here is the compiler only keeps one stringof // for a particular type // // so if you have void a(string a, string b); and void b(string b, string c), // both a() and b() will show up as params == ["a", "b"]! // // private string[][2] parameterInfoImpl (alias func) () { string funcStr = typeof(func).stringof; // this might fix the fixme above... // it used to be typeof(&func).stringof auto start = funcStr.indexOfNew('('); auto end = funcStr.lastIndexOfNew(')'); assert(start != -1); assert(end != -1); const firstPattern = ' '; const secondPattern = ','; funcStr = funcStr[start + 1 .. end]; if (funcStr == "") // no parameters return [null, null]; funcStr ~= secondPattern; string token; string[] arr; foreach (c ; funcStr) { if (c != firstPattern && c != secondPattern) token ~= c; else { if (token) arr ~= token; token = null; } } if (arr.length == 1) return [arr, [""]]; string[] result; string[] defaults; bool skip = false; bool gettingDefault = false; string currentName = ""; string currentDefault = ""; foreach (str ; arr) { if(str == "=") { gettingDefault = true; continue; } if(gettingDefault) { assert(str.length); currentDefault = str; gettingDefault = false; continue; } skip = !skip; if (skip) { if(currentName.length) { result ~= currentName; defaults ~= currentDefault; currentName = null; } continue; } currentName = str; } if(currentName !is null) { result ~= currentName; defaults ~= currentDefault; } assert(result.length == defaults.length); return [result, defaults]; } ///////////////////////////////// /// Formats any given type as HTML. In custom types, you can write Element makeHtmlElement(Document document = null); to provide /// custom html. (the default arg is important - it won't necessarily pass a Document in at all, and since it's silently duck typed, /// not having that means your function won't be called and you can be left wondering WTF is going on.) /// Alternatively, static Element makeHtmlArray(T[]) if you want to make a whole list of them. By default, it will just concat a bunch of individual /// elements though. string toHtml(T)(T a) { string ret; static if(is(T == typeof(null))) ret = null; else static if(is(T : Document)) { if(a is null) ret = null; else ret = a.toString(); } else static if(isArray!(T) && !isSomeString!(T)) { static if(__traits(compiles, typeof(T[0]).makeHtmlArray(a))) ret = to!string(typeof(T[0]).makeHtmlArray(a)); else foreach(v; a) ret ~= toHtml(v); } else static if(is(T : Element)) ret = a.toString(); else static if(__traits(compiles, a.makeHtmlElement().toString())) ret = a.makeHtmlElement().toString(); else static if(is(T == Html)) ret = a.source; else { auto str = to!string(a); if(str.indexOf("\t") == -1) ret = std.array.replace(htmlEntitiesEncode(str), "\n", "<br />\n"); else // if there's tabs in it, output it as code or something; the tabs are probably there for a reason. ret = "<pre>" ~ htmlEntitiesEncode(str) ~ "</pre>"; } return ret; } /// Translates a given type to a JSON string. /// TIP: if you're building a Javascript function call by strings, toJson("your string"); will build a nicely escaped string for you of any type. string toJson(T)(T a) { auto v = toJsonValue(a); return toJSON(&v); } // FIXME: are the explicit instantiations of this necessary? /// like toHtml - it makes a json value of any given type. /// It can be used generically, or it can be passed an ApiProvider so you can do a secondary custom /// format. (it calls api.formatAs!(type)(typeRequestString)). Why would you want that? Maybe /// your javascript wants to do work with a proper object,but wants to append it to the document too. /// Asking for json with secondary format = html means the server will provide both to you. /// Implement JSONValue makeJsonValue() in your struct or class to provide 100% custom Json. /// Elements from DOM are turned into JSON strings of the element's html. JSONValue toJsonValue(T, R = ApiProvider)(T a, string formatToStringAs = null, R api = null) if(is(R : ApiProvider)) { JSONValue val; static if(is(T == typeof(null)) || is(T == void*)) { /* void* goes here too because we don't know how to make it work... */ val.type = JSON_TYPE.NULL; } else static if(is(T == JSONValue)) { val = a; } else static if(__traits(compiles, val = a.makeJsonValue())) { val = a.makeJsonValue(); // FIXME: free function to emulate UFCS? // FIXME: should we special case something like struct Html? } else static if(is(T : Element)) { if(a is null) { val.type = JSON_TYPE.NULL; } else { val.type = JSON_TYPE.STRING; val.str = a.toString(); } } else static if(isIntegral!(T)) { val.type = JSON_TYPE.INTEGER; val.integer = to!long(a); } else static if(isFloatingPoint!(T)) { val.type = JSON_TYPE.FLOAT; val.floating = to!real(a); } else static if(isPointer!(T)) { if(a is null) { val.type = JSON_TYPE.NULL; } else { val = toJsonValue!(typeof(*a), R)(*a, formatToStringAs, api); } } else static if(is(T == bool)) { if(a == true) val.type = JSON_TYPE.TRUE; if(a == false) val.type = JSON_TYPE.FALSE; } else static if(isSomeString!(T)) { val.type = JSON_TYPE.STRING; val.str = to!string(a); } else static if(isAssociativeArray!(T)) { val.type = JSON_TYPE.OBJECT; foreach(k, v; a) { val.object[to!string(k)] = toJsonValue!(typeof(v), R)(v, formatToStringAs, api); } } else static if(isArray!(T)) { val.type = JSON_TYPE.ARRAY; val.array.length = a.length; foreach(i, v; a) { val.array[i] = toJsonValue!(typeof(v), R)(v, formatToStringAs, api); } } else static if(is(T == struct)) { // also can do all members of a struct... val.type = JSON_TYPE.OBJECT; foreach(i, member; a.tupleof) { string name = a.tupleof[i].stringof[2..$]; static if(a.tupleof[i].stringof[2] != '_') val.object[name] = toJsonValue!(typeof(member), R)(member, formatToStringAs, api); } // HACK: bug in dmd can give debug members in a non-debug build //static if(__traits(compiles, __traits(getMember, a, member))) } else { /* our catch all is to just do strings */ val.type = JSON_TYPE.STRING; val.str = to!string(a); // FIXME: handle enums } // don't want json because it could recurse if(val.type == JSON_TYPE.OBJECT && formatToStringAs !is null && formatToStringAs != "json") { JSONValue formatted; formatted.type = JSON_TYPE.STRING; formatAs!(T, R)(a, formatToStringAs, api, &formatted, null /* only doing one level of special formatting */); assert(formatted.type == JSON_TYPE.STRING); val.object["formattedSecondarily"] = formatted; } return val; } /+ Document toXml(T)(T t) { auto xml = new Document; xml.parse(emptyTag(T.stringof), true, true); xml.prolog = `<?xml version="1.0" encoding="UTF-8" ?>` ~ "\n"; xml.root = toXmlElement(xml, t); return xml; } Element toXmlElement(T)(Document document, T t) { Element val; static if(is(T == Document)) { val = t.root; //} else static if(__traits(compiles, a.makeJsonValue())) { // val = a.makeJsonValue(); } else static if(is(T : Element)) { if(t is null) { val = document.createElement("value"); val.innerText = "null"; val.setAttribute("isNull", "true"); } else val = t; } else static if(is(T == void*)) { val = document.createElement("value"); val.innerText = "null"; val.setAttribute("isNull", "true"); } else static if(isPointer!(T)) { if(t is null) { val = document.createElement("value"); val.innerText = "null"; val.setAttribute("isNull", "true"); } else { val = toXmlElement(document, *t); } } else static if(isAssociativeArray!(T)) { val = document.createElement("value"); foreach(k, v; t) { auto e = document.createElement(to!string(k)); e.appendChild(toXmlElement(document, v)); val.appendChild(e); } } else static if(isSomeString!(T)) { val = document.createTextNode(to!string(t)); } else static if(isArray!(T)) { val = document.createElement("array"); foreach(i, v; t) { auto e = document.createElement("item"); e.appendChild(toXmlElement(document, v)); val.appendChild(e); } } else static if(is(T == struct)) { // also can do all members of a struct... val = document.createElement(T.stringof); foreach(member; __traits(allMembers, T)) { if(member[0] == '_') continue; // FIXME: skip member functions auto e = document.createElement(member); e.appendChild(toXmlElement(document, __traits(getMember, t, member))); val.appendChild(e); } } else { /* our catch all is to just do strings */ val = document.createTextNode(to!string(t)); // FIXME: handle enums } return val; } +/ /// throw this if your function needs something that is missing. /// Done automatically by the wrapper function class InsufficientParametersException : Exception { this(string functionName, string msg) { super(functionName ~ ": " ~ msg); } } /// throw this if a paramater is invalid. Automatic forms may present this to the user in a new form. (FIXME: implement that) class InvalidParameterException : Exception { this(string param, string value, string expected) { super("bad param: " ~ param ~ ". got: " ~ value ~ ". Expected: " ~expected); } } /// convenience for throwing InvalidParameterExceptions void badParameter(alias T)(string expected = "") { throw new InvalidParameterException(T.stringof, T, expected); } /// throw this if the user's access is denied class PermissionDeniedException : Exception { this(string msg, string file = __FILE__, int line = __LINE__) { super(msg, file, line); } } /// throw if the request path is not found. Done automatically by the default catch all handler. class NoSuchPageException : Exception { this(string msg, string file = __FILE__, int line = __LINE__) { super(msg, file, line); } } class NoSuchFunctionException : NoSuchPageException { this(string msg, string file = __FILE__, int line = __LINE__) { super(msg, file, line); } } type fromUrlParam(type)(string ofInterest) { type ret; static if(isArray!(type) && !isSomeString!(type)) { // how do we get an array out of a simple string? // FIXME static assert(0); } else static if(__traits(compiles, ret = type.fromWebString(ofInterest))) { // for custom object handling... ret = type.fromWebString(ofInterest); } else static if(is(type : Element)) { auto doc = new Document(ofInterest, true, true); ret = doc.root; } else static if(is(type : Text)) { ret = ofInterest; } else static if(is(type : DateTime)) { ret = DateTime.fromISOString(ofInterest); } /* else static if(is(type : struct)) { static assert(0, "struct not supported yet"); } */ else { // enum should be handled by this too ret = to!type(ofInterest); } // FIXME: can we support classes? return ret; } /// turns a string array from the URL into a proper D type type fromUrlParam(type)(string[] ofInterest) { type ret; // Arrays in a query string are sent as the name repeating... static if(isArray!(type) && !isSomeString!type) { foreach(a; ofInterest) { ret ~= fromUrlParam!(ElementType!(type))(a); } } else static if(isArray!(type) && isSomeString!(ElementType!type)) { foreach(a; ofInterest) { ret ~= fromUrlParam!(ElementType!(type))(a); } } else ret = fromUrlParam!type(ofInterest[$-1]); return ret; } auto getMemberDelegate(alias ObjectType, string member)(ObjectType object) if(is(ObjectType : WebDotDBaseType)) { if(object is null) throw new NoSuchFunctionException("no such object " ~ ObjectType.stringof); return &__traits(getMember, object, member); } /// generates the massive wrapper function for each of your class' methods. /// it is responsible for turning strings to params and return values back to strings. WrapperFunction generateWrapper(alias ObjectType, string funName, alias f, R)(ReflectionInfo* reflection, R api) if(is(R: ApiProvider) && (is(ObjectType : WebDotDBaseType)) ) { JSONValue wrapper(Cgi cgi, WebDotDBaseType object, in string[][string] sargs, in string format, in string secondaryFormat = null) { JSONValue returnValue; returnValue.type = JSON_TYPE.STRING; auto instantiation = getMemberDelegate!(ObjectType, funName)(cast(ObjectType) object); api._initializePerCallInternal(); ParameterTypeTuple!(f) args; // Actually calling the function // FIXME: default parameters foreach(i, type; ParameterTypeTuple!(f)) { string name = parameterNamesOf!(f)[i]; // We want to check the named argument first. If it's not there, // try the positional arguments string using = name; if(name !in sargs) using = "positional-arg-" ~ to!string(i); // FIXME: if it's a struct, we should do it's pieces independently here static if(is(type == bool)) { // bool is special cased because HTML checkboxes don't send anything if it isn't checked if(using in sargs) { if( sargs[using][$-1] != "false" && sargs[using][$-1] != "False" && sargs[using][$-1] != "FALSE" && sargs[using][$-1] != "0" ) args[i] = true; // FIXME: should try looking at the value } else args[i] = false; // FIXME: what if the default is true? } else static if(is(Unqual!(type) == Cgi.UploadedFile)) { if(using !in cgi.files) throw new InsufficientParametersException(funName, "file " ~ using ~ " is not present"); args[i] = cast() cgi.files[using]; // casting away const for the assignment to compile FIXME: shouldn't be needed } else { if(using !in sargs) { static if(parameterHasDefault!(f)(i)) { args[i] = mixin(parameterDefaultOf!(f)(i)); } else { throw new InsufficientParametersException(funName, "arg " ~ name ~ " is not present"); } } else { // We now check the type reported by the client, if there is one // Right now, only one type is supported: ServerResult, which means // it's actually a nested function call string[] ofInterest = cast(string[]) sargs[using]; // I'm changing the reference, but not the underlying stuff, so this cast is ok if(using ~ "-type" in sargs) { string reportedType = sargs[using ~ "-type"][$-1]; if(reportedType == "ServerResult") { // FIXME: doesn't handle functions that return // compound types (structs, arrays, etc) ofInterest = null; string str = sargs[using][$-1]; auto idx = str.indexOf("?"); string callingName, callingArguments; if(idx == -1) { callingName = str; } else { callingName = str[0..idx]; callingArguments = str[idx + 1 .. $]; } // find it in reflection ofInterest ~= reflection.functions[callingName]. dispatcher(cgi, null, decodeVariables(callingArguments), "string", null).str; } } args[i] = fromUrlParam!type(ofInterest); } } } static if(!is(ReturnType!f == void)) ReturnType!(f) ret; else void* ret; static if(!is(ReturnType!f == void)) ret = instantiation(args); else instantiation(args); static if(is(ReturnType!f : Element)) { if(ret is null) return returnValue; // HACK to handle null returns // we need to make sure that it's not called again when _postProcess(Document) is called! // FIXME: is this right? if(cgi.request("envelopeFormat", "document") != "document") api._postProcessElement(ret); // need to post process the element here so it works in ajax modes. } formatAs(ret, format, api, &returnValue, secondaryFormat); return returnValue; } return &wrapper; } /// This is the function called to turn return values into strings. /// Implement a template called _customFormat in your apiprovider class to make special formats. /// Otherwise, this provides the defaults of html, table, json, etc. /// call it like so: JSONValue returnValue; formatAs(value, this, returnValue, "type"); // FIXME: it's awkward to call manually due to the JSONValue ref thing. Returning a string would be mega nice. string formatAs(T, R)(T ret, string format, R api = null, JSONValue* returnValue = null, string formatJsonToStringAs = null) if(is(R : ApiProvider)) { string retstr; if(api !is null) { static if(__traits(compiles, api._customFormat(ret, format))) { auto customFormatted = api._customFormat(ret, format); if(customFormatted !is null) { if(returnValue !is null) returnValue.str = customFormatted; return customFormatted; } } } switch(format) { case "html": retstr = toHtml(ret); if(returnValue !is null) returnValue.str = retstr; break; case "string": // FIXME: this is the most expensive part of the compile! Two seconds in one of my apps. /+ static if(__traits(compiles, to!string(ret))) { retstr = to!string(ret); if(returnValue !is null) returnValue.str = retstr; } else goto badType; +/ goto badType; // FIXME case "json": assert(returnValue !is null); *returnValue = toJsonValue!(typeof(ret), R)(ret, formatJsonToStringAs, api); break; case "table": auto document = new Document("<root></root>"); static if(__traits(compiles, structToTable(document, ret))) { retstr = structToTable(document, ret).toString(); if(returnValue !is null) returnValue.str = retstr; break; } else goto badType; default: badType: throw new Exception("Couldn't get result as " ~ format); } return retstr; } private string emptyTag(string rootName) { return ("<" ~ rootName ~ "></" ~ rootName ~ ">"); } /// The definition of the beastly wrapper function alias JSONValue delegate(Cgi cgi, WebDotDBaseType, in string[][string] args, in string format, in string secondaryFormat = null) WrapperFunction; /// tries to take a URL name and turn it into a human natural name. so get rid of slashes, capitalize, etc. string urlToBeauty(string url) { string u = url.replace("/", ""); string ret; bool capitalize = true; foreach(c; u) { if(capitalize) { ret ~= ("" ~ c).toUpper; capitalize = false; } else { if(c == '-') { ret ~= " "; capitalize = true; } else ret ~= c; } } return ret; } /// turns camelCase into dash-separated string toUrlName(string name) { string res; foreach(c; name) { if(c >= 'a' && c <= 'z') res ~= c; else { res ~= '-'; if(c >= 'A' && c <= 'Z') res ~= c + 0x20; else res ~= c; } } return res; } /// turns camelCase into human presentable capitalized words with spaces string beautify(string name) { string n; // all caps names shouldn't get spaces if(name.length == 0 || name.toUpper() == name) return name; n ~= toUpper(name[0..1]); dchar last; foreach(dchar c; name[1..$]) { if((c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) { if(last != ' ') n ~= " "; } if(c == '_') n ~= " "; else n ~= c; last = c; } return n; } import std.md5; import core.stdc.stdlib; import core.stdc.time; import std.file; /// meant to give a generic useful hook for sessions. kinda sucks at this point. /// use the Session class instead. If you just construct it, the sessionId property /// works fine. Don't set any data and it won't save any file. deprecated string getSessionId(Cgi cgi) { string token; // FIXME: should this actually be static? it seems wrong if(token is null) { if("_sess_id" in cgi.cookies) token = cgi.cookies["_sess_id"]; else { auto tmp = uniform(0, int.max); token = to!string(tmp); cgi.setCookie("_sess_id", token, /*60 * 8 * 1000*/ 0, "/", null, true); } } return getDigestString(cgi.remoteAddress ~ "\r\n" ~ cgi.userAgent ~ "\r\n" ~ token); } version(Posix) { static import linux = std.c.linux.linux; } /// This is cookie parameters for the Session class. The default initializers provide some simple default /// values for a site-wide session cookie. struct CookieParams { string name = "_sess_id"; string host = null; string path = "/"; long expiresIn = 0; bool httpsOnly = false; } /// Provides some persistent storage, kinda like PHP /// But, you have to manually commit() the data back to a file. /// You might want to put this in a scope(exit) block or something like that. class Session { /// Loads the session if available, and creates one if not. /// May write a session id cookie to the passed cgi object. this(Cgi cgi, CookieParams cookieParams = CookieParams(), bool useFile = true) { // uncomment these two to render session useless (it has no backing) // but can be good for benchmarking the rest of your app //useFile = false; //_readOnly = true; // assert(cgi.https); // you want this for best security, but I won't be an ass and require it. this.cookieParams = cookieParams; this.cgi = cgi; bool isNew = false; string token; if(cookieParams.name in cgi.cookies && cgi.cookies[cookieParams.name].length) token = cgi.cookies[cookieParams.name]; else { if("x-arsd-session-override" in cgi.requestHeaders) { loadSpecialSession(cgi); return; } else { // there is no session; make a new one. token = makeNewCookie(); isNew = true; } } makeSessionId(token); if(useFile) reload(); if(isNew) addDefaults(); } /// This loads a session that the user requests, without the normal /// checks. The idea is to allow debugging or local request sharing. /// /// It is private because you never have to call it yourself, but read on /// to understand how it works and some potential security concerns. /// /// It loads the requested session read-only (it does not commit), /// if and only if the request asked for the correct hash and id. /// /// If they have enough info to build the correct hash, they must /// already know the contents of the file, so there should be no /// risk of data contamination here. (A traditional session hijack /// is surely much easier.) /// /// It is possible for them to forge a request as a particular user /// if they can read the file, but otherwise not write. For that reason, /// especially with this functionality here, it is very important for you /// to lock down your session files. If on a shared host, be sure each user's /// processes run as separate operating system users, so the file permissions /// set in commit() actually help you. /// /// If you can't reasonably protect the session file, compile this out with /// -version=no_session_override and only access unauthenticated functions /// from other languages. They can still read your sessions, and potentially /// hijack it, but it will at least be a little harder. /// /// Also, don't use this over the open internet at all. It's supposed /// to be local only. If someone sniffs the request, hijacking it /// becomes very easy; even easier than a normal session id since they just reply it. /// (you should really ssl encrypt all sessions for any real protection btw) private void loadSpecialSession(Cgi cgi) { version(no_session_override) throw new Exception("You cannot access sessions this way."); else { // the header goes full-session-id;file-contents-hash auto info = split(cgi.requestHeaders["x-arsd-session-override"], ";"); _sessionId = info[0]; auto hash = info[1]; if(_sessionId.length == 0 || !std.file.exists(getFilePath())) { // there is no session _readOnly = true; return; } // FIXME: race condition if the session changes? auto file = getFilePath(); auto contents = readText(file); auto ourhash = hashToString(SHA256(contents)); enforce(ourhash == hash);//, ourhash); _readOnly = true; reload(); } } /// Call this periodically to clean up old session files. The finalizer param can cancel the deletion /// of a file by returning false. public static void garbageCollect(bool delegate(string[string] data) finalizer = null, Duration maxAge = dur!"hours"(4)) { auto ctime = Clock.currTime(); foreach(DirEntry e; dirEntries(getTempDirectory(), "arsd_session_file_*", SpanMode.shallow)) { try { if(ctime - e.timeLastAccessed() > maxAge) { auto data = Session.loadData(e.name); if(finalizer is null || !finalizer(data)) std.file.remove(e.name); } } catch(Exception except) { // if it is bad, kill it if(std.file.exists(e.name)) std.file.remove(e.name); } } } private void addDefaults() { set("csrfToken", generateCsrfToken()); set("creationTime", Clock.currTime().toISOExtString()); // this is there to help control access to someone requesting a specific session id (helpful for debugging or local access from other languages) // the idea is if there's some random stuff in there that you can only know if you have access to the file, it doesn't hurt to load that // session, since they have to be able to read it to know this value anyway, so you aren't giving them anything they don't already have. set("randomRandomness", to!string(uniform(0, ulong.max))); } private string makeSessionId(string cookieToken) { _sessionId = hashToString(SHA256(cgi.remoteAddress ~ "\r\n" ~ cgi.userAgent ~ "\r\n" ~ cookieToken)); return _sessionId; } private string generateCsrfToken() { string[string] csrf; csrf["key"] = to!string(uniform(0, ulong.max)); csrf["token"] = to!string(uniform(0, ulong.max)); return encodeVariables(csrf); } private CookieParams cookieParams; // don't forget to make the new session id and set a new csrfToken after this too. private string makeNewCookie() { auto tmp = uniform(0, ulong.max); auto token = to!string(tmp); setOurCookie(token); return token; } private void setOurCookie(string data) { cgi.setCookie(cookieParams.name, data, cookieParams.expiresIn, cookieParams.path, cookieParams.host, true, cookieParams.httpsOnly); } /// Kill the current session. It wipes out the disk file and memory, and /// changes the session ID. /// /// You should do this if the user's authentication info changes /// at all. void invalidate() { setOurCookie(""); clear(); regenerateId(); } /// Creates a new cookie, session id, and csrf token, deleting the old disk data. /// If you call commit() after doing this, it will save your existing data back to disk. /// (If you don't commit, the data will be lost when this object is deleted.) void regenerateId() { // we want to clean up the old file, but keep the data we have in memory. if(std.file.exists(getFilePath())) std.file.remove(getFilePath()); // and new cookie -> new session id -> new csrf token makeSessionId(makeNewCookie()); addDefaults(); if(hasData) changed = true; } /// Clears the session data from both memory and disk. /// The session id is not changed by this function. To change it, /// use invalidate() if you want to clear data and change the ID /// or regenerateId() if you want to change the session ID, but not change the data. /// /// Odds are, invalidate() is what you really want. void clear() { if(std.file.exists(getFilePath())) std.file.remove(getFilePath()); data = null; _hasData = false; changed = false; } // FIXME: what about expiring a session id and perhaps issuing a new // one? They should automatically invalidate at some point. // Both an idle timeout and a forced reauth timeout is good to offer. // perhaps a helper function to do it in js too? // I also want some way to attach to a session if you have root // on the server, for convenience of debugging... string sessionId() const { return _sessionId; } bool hasData() const { return _hasData; } /// like opIn bool hasKey(string key) const { auto ptr = key in data; if(ptr is null) return false; else return true; } /// get/set for strings @property string opDispatch(string name)(string v = null) if(name != "popFront") { if(v !is null) set(name, v); if(hasKey(name)) return get(name); return null; } string opIndex(string key) const { return get(key); } string opIndexAssign(string value, string field) { set(field, value); return value; } // FIXME: doesn't seem to work string* opBinary(string op)(string key) if(op == "in") { return key in fields; } void set(string key, string value) { data[key] = value; _hasData = true; changed = true; } string get(string key) const { if(key !in data) throw new Exception("No such key in session: " ~ key); return data[key]; } private string getFilePath() const { string path = getTempDirectory(); path ~= "arsd_session_file_" ~ sessionId; return path; } private static string[string] loadData(string path) { string[string] data = null; auto json = std.file.readText(path); auto obj = parseJSON(json); enforce(obj.type == JSON_TYPE.OBJECT); foreach(k, v; obj.object) { string ret; final switch(v.type) { case JSON_TYPE.STRING: ret = v.str; break; case JSON_TYPE.UINTEGER: ret = to!string(v.integer); break; case JSON_TYPE.INTEGER: ret = to!string(v.integer); break; case JSON_TYPE.FLOAT: ret = to!string(v.floating); break; case JSON_TYPE.OBJECT: case JSON_TYPE.ARRAY: enforce(0, "invalid session data"); break; case JSON_TYPE.TRUE: ret = "true"; break; case JSON_TYPE.FALSE: ret = "false"; break; case JSON_TYPE.NULL: ret = null; break; } data[k] = ret; } return data; } // FIXME: there's a race condition here - if the user is using the session // from two windows, one might write to it as we're executing, and we won't // see the difference.... meaning we'll write the old data back. /// Discards your changes, reloading the session data from the disk file. void reload() { data = null; auto path = getFilePath(); try { data = Session.loadData(path); _hasData = true; } catch(Exception e) { // it's a bad session... _hasData = false; data = null; if(std.file.exists(path)) std.file.remove(path); } } // FIXME: there's a race condition here - if the user is using the session // from two windows, one might write to it as we're executing, and we won't // see the difference.... meaning we'll write the old data back. /// Commits your changes back to disk. void commit(bool force = false) { if(_readOnly) return; if(force || changed) { std.file.write(getFilePath(), toJson(data)); changed = false; // We have to make sure that only we can read this file, // since otherwise, on shared hosts, our session data might be // easily stolen. Note: if your shared host doesn't have different // users on the operating system for each user, it's still possible // for them to access this file and hijack your session! version(Posix) enforce(linux.chmod(toStringz(getFilePath()), octal!600) == 0, "chmod failed"); // FIXME: ensure the file's read permissions are locked down // on Windows too. } } private string[string] data; private bool _hasData; private bool changed; private bool _readOnly; private string _sessionId; private Cgi cgi; // used to regenerate cookies, etc. //private Variant[string] data; /* Variant* opBinary(string op)(string key) if(op == "in") { return key in data; } T get(T)(string key) { if(key !in data) throw new Exception(key ~ " not in session data"); return data[key].coerce!T; } void set(T)(string key, T t) { Variant v; v = t; data[key] = t; } */ } /// sets a site-wide cookie, meant to simplify login code. Note: you often might not want a side wide cookie, but I usually do since my projects need single sessions across multiple thingies, hence, this. void setLoginCookie(Cgi cgi, string name, string value) { cgi.setCookie(name, value, 0, "/", null, true); } immutable(string[]) monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; immutable(string[]) weekdayNames = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]; // this might be temporary struct TemplateFilters { string date(string replacement, string[], in Element, string) { auto dateTicks = to!time_t(replacement); auto date = SysTime( unixTimeToStdTime(dateTicks/1_000) ); auto day = date.day; auto year = date.year; auto month = monthNames[date.month]; replacement = format("%s %d, %d", month, day, year); return replacement; } string uri(string replacement, string[], in Element, string) { return std.uri.encodeComponent(replacement); } string js(string replacement, string[], in Element, string) { return toJson(replacement); } static auto defaultThings() { string delegate(string, string[], in Element, string)[string] pipeFunctions; TemplateFilters filters; if("date" !in pipeFunctions) pipeFunctions["date"] = &filters.date; if("uri" !in pipeFunctions) pipeFunctions["uri"] = &filters.uri; if("js" !in pipeFunctions) pipeFunctions["js"] = &filters.js; return pipeFunctions; } } void applyTemplateToElement( Element e, in string[string] vars, in string delegate(string, string[], in Element, string)[string] pipeFunctions = TemplateFilters.defaultThings()) { foreach(ele; e.tree) { auto tc = cast(TextNode) ele; if(tc !is null) { // text nodes have no attributes, but they do have text we might replace. tc.contents = htmlTemplateWithData(tc.contents, vars, pipeFunctions, false); } else { auto rs = cast(RawSource) ele; if(rs !is null) { bool isSpecial; if(ele.parentNode) isSpecial = ele.parentNode.tagName == "script" || ele.parentNode.tagName == "style"; rs.source = htmlTemplateWithData(rs.source, vars, pipeFunctions, !isSpecial); /* FIXME: might be wrong... */ } // if it is not a text node, it has no text where templating is valid, except the attributes // note: text nodes have no attributes, which is why this is in the separate branch. foreach(k, v; ele.attributes) { if(k == "href" || k == "src") { // FIXME: HACK this should be properly context sensitive.. v = v.replace("%7B%24", "{$"); v = v.replace("%7D", "}"); } ele.attributes[k] = htmlTemplateWithData(v, vars, pipeFunctions, false); } } } } // this thing sucks a little less now. // set useHtml to false if you're working on internal data (such as TextNode.contents, or attribute); // it should only be set to true if you're doing input that has already been ran through toString or something. // NOTE: I'm probably going to change the pipe function thing a bit more, but I'm basically happy with it now. string htmlTemplateWithData(in string text, in string[string] vars, in string delegate(string, string[], in Element, string)[string] pipeFunctions, bool useHtml) { if(text is null) return null; int state = 0; string newText = null; size_t nameStart; size_t replacementStart; size_t lastAppend = 0; string name = null; bool replacementPresent = false; string replacement = null; string currentPipe = null; foreach(i, c; text) { void stepHandler() { if(name is null) name = text[nameStart .. i]; else if(nameStart != i) currentPipe = text[nameStart .. i]; nameStart = i + 1; auto it = name in vars; if(it !is null) { replacement = *it; replacementPresent = true; } } void pipeHandler() { if(currentPipe is null || replacement is null) return; if(currentPipe in pipeFunctions) { replacement = pipeFunctions[currentPipe](replacement, null, null, null); // FIXME context // string, string[], in Element, string } currentPipe = null; } switch(state) { default: assert(0); case 0: if(c == '{') { replacementStart = i; state++; replacementPresent = false; } break; case 1: if(c == '$') state++; else state--; // not a variable break; case 2: // just started seeing a name if(c == '}') { state = 0; // empty names aren't allowed; ignore it } else { nameStart = i; name = null; state++; } break; case 3: // reading a name // the pipe operator lets us filter the text if(c == '|') { pipeHandler(); stepHandler(); } else if(c == '}') { // just finished reading it, let's do our replacement. pipeHandler(); // anything that was there stepHandler(); // might make a new pipe if the first... pipeHandler(); // new names/pipes since this is the last go if(name !is null && replacementPresent /*&& replacement !is null*/) { newText ~= text[lastAppend .. replacementStart]; if(useHtml) replacement = htmlEntitiesEncode(replacement).replace("\n", "<br />"); newText ~= replacement; lastAppend = i + 1; replacement = null; } state = 0; } break; } } if(newText is null) newText = text; // nothing was found, so no need to risk allocating anything... else newText ~= text[lastAppend .. $]; // make sure we have everything here return newText; } /// a specialization of Document that: a) is always in strict mode and b) provides some template variable text replacement, in addition to DOM manips. The variable text is valid in text nodes and attribute values. It takes the format of {$variable}, where variable is a key into the vars member. class TemplatedDocument : Document { override string toString() const { if(this.root !is null) applyTemplateToElement(cast() this.root, vars, viewFunctions); /* FIXME: I shouldn't cast away const, since it's rude to modify an object in any toString.... but that's what I'm doing for now */ return super.toString(); } public: string[string] vars; /// use this to set up the string replacements. document.vars["name"] = "adam"; then in doc, <p>hellp, {$name}.</p>. Note the vars are converted lazily at toString time and are always HTML escaped. /// In the html templates, you can write {$varname} or {$varname|func} (or {$varname|func arg arg|func} and so on). This holds the functions available these. The TemplatedDocument constructor puts in a handful of generic ones. string delegate(string, string[], in Element, string)[string] viewFunctions; this(string src) { super(); viewFunctions = TemplateFilters.defaultThings(); parse(src, true, true); } this() { viewFunctions = TemplateFilters.defaultThings(); } void delegate(TemplatedDocument)[] preToStringFilters; void delegate(ref string)[] postToStringFilters; } /// a convenience function to do filters on your doc and write it out. kinda useless still at this point. void writeDocument(Cgi cgi, TemplatedDocument document) { foreach(f; document.preToStringFilters) f(document); auto s = document.toString(); foreach(f; document.postToStringFilters) f(s); cgi.write(s); } /* Password helpers */ /// These added a dependency on arsd.sha, but hashing passwords is somewhat useful in a lot of apps so I figured it was worth it. /// use this to make the hash to put in the database... string makeSaltedPasswordHash(string userSuppliedPassword, string salt = null) { if(salt is null) salt = to!string(uniform(0, int.max)); // FIXME: sha256 is actually not ideal for this, but meh it's what i have. return hashToString(SHA256(salt ~ userSuppliedPassword)) ~ ":" ~ salt; } /// and use this to check it. bool checkPassword(string saltedPasswordHash, string userSuppliedPassword) { auto parts = saltedPasswordHash.split(":"); return makeSaltedPasswordHash(userSuppliedPassword, parts[1]) == saltedPasswordHash; } /// implements the "table" format option. Works on structs and associative arrays (string[string][]) Table structToTable(T)(Document document, T arr, string[] fieldsToSkip = null) if(isArray!(T) && !isAssociativeArray!(T)) { auto t = cast(Table) document.createElement("table"); t.border = "1"; static if(is(T == string[string][])) { string[string] allKeys; foreach(row; arr) { foreach(k; row.keys) allKeys[k] = k; } auto sortedKeys = allKeys.keys.sort; Element tr; auto thead = t.addChild("thead"); auto tbody = t.addChild("tbody"); tr = thead.addChild("tr"); foreach(key; sortedKeys) tr.addChild("th", key); bool odd = true; foreach(row; arr) { tr = tbody.addChild("tr"); foreach(k; sortedKeys) { tr.addChild("td", k in row ? row[k] : ""); } if(odd) tr.addClass("odd"); odd = !odd; } } else static if(is(typeof(T[0]) == struct)) { { auto thead = t.addChild("thead"); auto tr = thead.addChild("tr"); auto s = arr[0]; foreach(idx, member; s.tupleof) tr.addChild("th", s.tupleof[idx].stringof[2..$]); } bool odd = true; auto tbody = t.addChild("tbody"); foreach(s; arr) { auto tr = tbody.addChild("tr"); foreach(member; s.tupleof) { tr.addChild("td", to!string(member)); } if(odd) tr.addClass("odd"); odd = !odd; } } else static assert(0); return t; } // this one handles horizontal tables showing just one item /// does a name/field table for just a singular object Table structToTable(T)(Document document, T s, string[] fieldsToSkip = null) if(!isArray!(T) || isAssociativeArray!(T)) { static if(__traits(compiles, s.makeHtmlTable(document))) return s.makeHtmlTable(document); else { auto t = cast(Table) document.createElement("table"); static if(is(T == struct)) { main: foreach(i, member; s.tupleof) { string name = s.tupleof[i].stringof[2..$]; foreach(f; fieldsToSkip) if(name == f) continue main; string nameS = name.idup; name = ""; foreach(idx, c; nameS) { if(c >= 'A' && c <= 'Z') name ~= " " ~ c; else if(c == '_') name ~= " "; else name ~= c; } t.appendRow(t.th(name.capitalize), to!string(member)); } } else static if(is(T == string[string])) { foreach(k, v; s){ t.appendRow(t.th(k), v); } } else static assert(0); return t; } } /// This adds a custom attribute to links in the document called qsa which modifies the values on the query string void translateQsa(Document document, Cgi cgi, string logicalScriptName = null) { if(logicalScriptName is null) logicalScriptName = cgi.scriptName; foreach(a; document.querySelectorAll("a[qsa]")) { string href = logicalScriptName ~ cgi.pathInfo ~ "?"; int matches, possibilities; string[][string] vars; foreach(k, v; cgi.getArray) vars[k] = cast(string[]) v; foreach(k, v; decodeVariablesSingle(a.qsa)) { if(k in cgi.get && cgi.get[k] == v) matches++; possibilities++; if(k !in vars || vars[k].length <= 1) vars[k] = [v]; else assert(0, "qsa doesn't work here"); } string[] clear = a.getAttribute("qsa-clear").split("&"); clear ~= "ajaxLoading"; if(a.parentNode !is null) clear ~= a.parentNode.getAttribute("qsa-clear").split("&"); bool outputted = false; varskip: foreach(k, varr; vars) { foreach(item; clear) if(k == item) continue varskip; foreach(v; varr) { if(outputted) href ~= "&"; else outputted = true; href ~= std.uri.encodeComponent(k) ~ "=" ~ std.uri.encodeComponent(v); } } a.href = href; a.removeAttribute("qsa"); if(matches == possibilities) a.addClass("current"); } } /// This uses reflection info to generate Javascript that can call the server with some ease. /// Also includes javascript base (see bottom of this file) string makeJavascriptApi(const ReflectionInfo* mod, string base, bool isNested = false) { assert(mod !is null); string script; if(0 && isNested) script = `'`~mod.name~`': { "_apiBase":'`~base~`',`; else script = `var `~mod.name~` = { "_apiBase":'`~base~`',`; script ~= javascriptBase; script ~= "\n\t"; bool[string] alreadyDone; bool outp = false; foreach(s; mod.enums) { if(outp) script ~= ",\n\t"; else outp = true; script ~= "'"~s.name~"': {\n"; bool outp2 = false; foreach(i, n; s.names) { if(outp2) script ~= ",\n"; else outp2 = true; // auto v = s.values[i]; auto v = "'" ~ n ~ "'"; // we actually want to use the name here because to!enum() uses member name. script ~= "\t\t'"~n~"':" ~ to!string(v); } script ~= "\n\t}"; } foreach(s; mod.structs) { if(outp) script ~= ",\n\t"; else outp = true; script ~= "'"~s.name~"': function("; bool outp2 = false; foreach(n; s.members) { if(outp2) script ~= ", "; else outp2 = true; script ~= n.name; } script ~= ") { return {\n"; outp2 = false; script ~= "\t\t'_arsdTypeOf':'"~s.name~"'"; if(s.members.length) script ~= ","; script ~= " // metadata, ought to be read only\n"; // outp2 is still false because I put the comma above foreach(n; s.members) { if(outp2) script ~= ",\n"; else outp2 = true; auto v = n.defaultValue; script ~= "\t\t'"~n.name~"': (typeof "~n.name~" == 'undefined') ? "~n.name~" : '" ~ to!string(v) ~ "'"; } script ~= "\n\t}; }"; } foreach(key, func; mod.functions) { if(func.originalName in alreadyDone) continue; // there's url friendly and code friendly, only need one alreadyDone[func.originalName] = true; if(outp) script ~= ",\n\t"; else outp = true; string args; string obj; bool outputted = false; /+ foreach(i, arg; func.parameters) { if(outputted) { args ~= ","; obj ~= ","; } else outputted = true; args ~= arg.name; // FIXME: we could probably do better checks here too like on type obj ~= `'`~arg.name~`':(typeof `~arg.name ~ ` == "undefined" ? this._raiseError('InsufficientParametersException', '`~func.originalName~`: argument `~to!string(i) ~ " (" ~ arg.staticType~` `~arg.name~`) is not present') : `~arg.name~`)`; } +/ /* if(outputted) args ~= ","; args ~= "callback"; */ script ~= `'` ~ func.originalName ~ `'`; script ~= ":"; script ~= `function(`~args~`) {`; if(obj.length) script ~= ` var argumentsObject = { `~obj~` }; return this._serverCall('`~key~`', argumentsObject, '`~func.returnType~`');`; else script ~= ` return this._serverCall('`~key~`', arguments, '`~func.returnType~`');`; script ~= ` }`; } script ~= "\n}"; // some global stuff to put in if(!isNested) script ~= ` if(typeof arsdGlobalStuffLoadedForWebDotD == "undefined") { arsdGlobalStuffLoadedForWebDotD = true; var oldObjectDotPrototypeDotToString = Object.prototype.toString; Object.prototype.toString = function() { if(this.formattedSecondarily) return this.formattedSecondarily; return oldObjectDotPrototypeDotToString.call(this); } } `; // FIXME: it should output the classes too // FIXME: hax hax hax foreach(n, obj; mod.objects) { script ~= ";"; //if(outp) // script ~= ",\n\t"; //else // outp = true; script ~= makeJavascriptApi(obj, base ~ n ~ "/", true); } return script; } debug string javascriptBase = ` // change this in your script to get fewer error popups "_debugMode":true,` ~ javascriptBaseImpl; else string javascriptBase = ` // change this in your script to get more details in errors "_debugMode":false,` ~ javascriptBaseImpl; /// The Javascript code used in the generated JS API. /** It provides the foundation to calling the server via background requests and handling the response in callbacks. (ajax style stuffs). The names with a leading underscore are meant to be private. Generally: YourClassName.yourMethodName(args...).operation(args); CoolApi.getABox("red").useToReplace(document.getElementById("playground")); for example. When you call a method, it doesn't make the server request. Instead, it returns an object describing the call. This means you can manipulate it (such as requesting a custom format), pass it as an argument to other functions (thus saving http requests) and finally call it at the end. The operations are: get(callback, args to callback...); See below. useToReplace(element) // pass an element reference. Example: useToReplace(document.querySelector(".name")); useToReplace(element ID : string) // you pass a string, it calls document.getElementById for you useToReplace sets the given element's innerHTML to the return value. The return value is automatically requested to be formatted as HTML. appendTo(element) appendTo(element ID : String) Adds the return value, as HTML, to the given element's inner html. useToReplaceElement(element) Replaces the given element entirely with the return value. (basically element.outerHTML = returnValue;) useToFillForm(form) Takes an object. Loop through the members, setting the form.elements[key].value = value. Does not work if the return value is not a javascript object (so use it if your function returns a struct or string[string]) getSync() Does a synchronous get and returns the server response. Not recommended. get() : The generic get() function is the most generic operation to get a response. It's arguments implement partial application for you, so you can pass just about any callback to it. Despite the name, the underlying operation may be HTTP GET or HTTP POST. This is determined from the function's server side attributes. (FIXME: implement smarter thing. Currently it actually does it by name - if the function name starts with get, do get. Else, do POST.) Usage: CoolApi.getABox('red').get(alert); // calls alert(returnedValue); so pops up the returned value CoolApi.getABox('red').get(fadeOut, this); // calls fadeOut(this, returnedValue); Since JS functions generally ignore extra params, this lets you call just about anything: CoolApi.getABox('red').get(alert, "Success"); // pops a box saying "Success", ignoring the actual return value Passing arguments to the functions let you reuse a lot of things that might not have been designed with this in mind. If you use arsd.js, there's other little functions that let you turn properties into callbacks too. Passing "this" to a callback via get is useful too since inside the callback, this probably won't refer to what you wanted. As an argument though, it all remains sane. Error Handling: D exceptions are translated into Javascript exceptions by the serverCall function. They are thrown, but since it's async, catching them is painful. It will probably show up in your browser's error console, or you can set the returned object's onerror function to something to handle it callback style. FIXME: not sure if this actually works right! */ // FIXME: this should probably be rewritten to make a constructable prototype object instead of a literal. enum string javascriptBaseImpl = q{ "_doRequest": function(url, args, callback, method, async) { var xmlHttp; try { xmlHttp=new XMLHttpRequest(); } catch (e) { try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } if(async) xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { // either if the function is nor available or if it returns a good result, we're set. // it might get to this point without the headers if the request was aborted if(callback && (!xmlHttp.getAllResponseHeaders || xmlHttp.getAllResponseHeaders())) { callback(xmlHttp.responseText, xmlHttp.responseXML); } } } var argString = this._getArgString(args); if(method == "GET" && url.indexOf("?") == -1) url = url + "?" + argString; xmlHttp.open(method, url, async); var a = ""; var csrfKey = document.body.getAttribute("data-csrf-key"); var csrfToken = document.body.getAttribute("data-csrf-token"); var csrfPair = ""; if(csrfKey && csrfKey.length > 0 && csrfToken && csrfToken.length > 0) { csrfPair = encodeURIComponent(csrfKey) + "=" + encodeURIComponent(csrfToken); // we send this so it can be easily verified for things like restricted jsonp xmlHttp.setRequestHeader("X-Arsd-Csrf-Pair", csrfPair); } if(method == "POST") { xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); a = argString; // adding the CSRF stuff, if necessary if(csrfPair.length) { if(a.length > 0) a += "&"; a += csrfPair; } } else { xmlHttp.setRequestHeader("Content-type", "text/plain"); } xmlHttp.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xmlHttp.send(a); if(!async && callback) { xmlHttp.timeout = 500; return callback(xmlHttp.responseText, xmlHttp.responseXML); } return xmlHttp; }, "_raiseError":function(type, message) { var error = new Error(message); error.name = type; throw error; }, "_getUriRelativeToBase":function(name, args) { var str = name; var argsStr = this._getArgString(args); if(argsStr.length) str += "?" + argsStr; return str; }, "_getArgString":function(args) { var a = ""; var outputted = false; var i; // wow Javascript sucks! god damned global loop variables for(i in args) { if(outputted) { a += "&"; } else outputted = true; var arg = args[i]; var argType = ""; // Make sure the types are all sane if(arg && arg._arsdTypeOf && arg._arsdTypeOf == "ServerResult") { argType = arg._arsdTypeOf; arg = this._getUriRelativeToBase(arg._serverFunction, arg._serverArguments); // this arg is a nested server call a += encodeURIComponent(i) + "="; a += encodeURIComponent(arg); } else if(arg && arg.length && typeof arg != "string") { // FIXME: are we sure this is actually an array? It might be an object with a length property... var outputtedHere = false; for(var idx = 0; idx < arg.length; idx++) { if(outputtedHere) { a += "&"; } else outputtedHere = true; // FIXME: ought to be recursive a += encodeURIComponent(i) + "="; a += encodeURIComponent(arg[idx]); } } else { // a regular argument a += encodeURIComponent(i) + "="; a += encodeURIComponent(arg); } // else if: handle arrays and objects too if(argType.length > 0) { a += "&"; a += encodeURIComponent(i + "-type") + "="; a += encodeURIComponent(argType); } } return a; }, "_onError":function(error) { throw error; }, /// returns an object that can be used to get the actual response from the server "_serverCall": function (name, passedArgs, returnType) { var me = this; // this is the Api object var args; // FIXME: is there some way to tell arguments apart from other objects? dynamic languages suck. if(!passedArgs.length) args = passedArgs; else { args = new Object(); for(var a = 0; a < passedArgs.length; a++) args["positional-arg-" + a] = passedArgs[a]; } return { // type info metadata "_arsdTypeOf":"ServerResult", "_staticType":(typeof returnType == "undefined" ? null : returnType), // Info about the thing "_serverFunction":name, "_serverArguments":args, // lower level implementation "_get":function(callback, onError, async) { var resObj = this; // the request/response object. var me is the ApiObject. if(args == null) args = {}; if(!args.format) args.format = "json"; args.envelopeFormat = "json"; return me._doRequest(me._apiBase + name, args, function(t, xml) { /* if(me._debugMode) { try { var obj = eval("(" + t + ")"); } catch(e) { alert("Bad server json: " + e + "\nOn page: " + (me._apiBase + name) + "\nGot:\n" + t); } } else { */ var obj; if(JSON && JSON.parse) obj = JSON.parse(t); else obj = eval("(" + t + ")"); //} var returnValue; if(obj.success) { if(typeof callback == "function") callback(obj.result); else if(typeof resObj.onSuccess == "function") { resObj.onSuccess(obj.result); } else if(typeof me.onSuccess == "function") { // do we really want this? me.onSuccess(obj.result); } else { // can we automatically handle it? // If it's an element, we should replace innerHTML by ID if possible // if a callback is given and it's a string, that's an id. Return type of element // should replace that id. return type of string should be appended // FIXME: meh just do something here. } returnValue = obj.result; } else { // how should we handle the error? I guess throwing is better than nothing // but should there be an error callback too? var error = new Error(obj.errorMessage); error.name = obj.type; error.functionUrl = me._apiBase + name; error.functionArgs = args; error.errorMessage = obj.errorMessage; // myFunction.caller should be available and checked too // btw arguments.callee is like this for functions if(me._debugMode) { var ourMessage = obj.type + ": " + obj.errorMessage + "\nOn: " + me._apiBase + name; if(args.toSource) ourMessage += args.toSource(); if(args.stack) ourMessage += "\n" + args.stack; error.message = ourMessage; // alert(ourMessage); } if(onError) // local override first... returnValue = onError(error); else if(resObj.onError) // then this object returnValue = resObj.onError(error); else if(me._onError) // then the global object returnValue = me._onError(error); else throw error; // if all else fails... } if(typeof resObj.onComplete == "function") { resObj.onComplete(); } if(typeof me._onComplete == "function") { me._onComplete(resObj); } return returnValue; // assert(0); // not reached }, (name.indexOf("get") == 0) ? "GET" : "POST", async); // FIXME: hack: naming convention used to figure out method to use }, // should pop open the thing in HTML format // "popup":null, // FIXME not implemented "onError":null, // null means call the global one "onSuccess":null, // a generic callback. generally pass something to get instead. "formatSet":false, // is the format overridden? // gets the result. Works automatically if you don't pass a callback. // You can also curry arguments to your callback by listing them here. The // result is put on the end of the arg list to the callback "get":function(callbackObj) { var callback = null; var errorCb = null; var callbackThis = null; if(callbackObj) { if(typeof callbackObj == "function") callback = callbackObj; else { if(callbackObj.length) { // array callback = callbackObj[0]; if(callbackObj.length >= 2) errorCb = callbackObj[1]; } else { if(callbackObj.onSuccess) callback = callbackObj.onSuccess; if(callbackObj.onError) errorCb = callbackObj.onError; if(callbackObj.self) callbackThis = callbackObj.self; else callbackThis = callbackObj; } } } if(arguments.length > 1) { var ourArguments = []; for(var a = 1; a < arguments.length; a++) ourArguments.push(arguments[a]); function cb(obj, xml) { ourArguments.push(obj); ourArguments.push(xml); // that null is the this object inside the function... can // we make that work? return callback.apply(callbackThis, ourArguments); } function cberr(err) { ourArguments.unshift(err); // that null is the this object inside the function... can // we make that work? return errorCb.apply(callbackThis, ourArguments); } this._get(cb, errorCb ? cberr : null, true); } else { this._get(callback, errorCb, true); } }, // If you need a particular format, use this. "getFormat":function(format /* , same args as get... */) { this.format(format); var forwardedArgs = []; for(var a = 1; a < arguments.length; a++) forwardedArgs.push(arguments[a]); this.get.apply(this, forwardedArgs); }, // sets the format of the request so normal get uses it // myapi.someFunction().format('table').get(...); // see also: getFormat and getHtml // the secondaryFormat only makes sense if format is json. It // sets the format returned by object.toString() in the returned objects. "format":function(format, secondaryFormat) { if(args == null) args = {}; args.format = format; if(typeof secondaryFormat == "string" && secondaryFormat) { if(format != "json") me._raiseError("AssertError", "secondaryFormat only works if format == json"); args.secondaryFormat = secondaryFormat; } this.formatSet = true; return this; }, "getHtml":function(/* args to get... */) { this.format("html"); this.get.apply(this, arguments); }, // FIXME: add post aliases // don't use unless you're deploying to localhost or something "getSync":function() { function cb(obj) { // no nothing, we're returning the value below } return this._get(cb, null, false); }, // takes the result and appends it as html to the given element // FIXME: have a type override "appendTo":function(what) { if(!this.formatSet) this.format("html"); this.get(me._appendContent(what)); }, // use it to replace the content of the given element "useToReplace":function(what) { if(!this.formatSet) this.format("html"); this.get(me._replaceContent(what)); }, // use to replace the given element altogether "useToReplaceElement":function(what) { if(!this.formatSet) this.format("html"); this.get(me._replaceElement(what)); }, "useToFillForm":function(what) { this.get(me._fillForm(what)); } // runAsScript has been removed, use get(eval) instead // FIXME: might be nice to have an automatic popin function too }; }, "_fillForm": function(what) { var e = this._getElement(what); if(this._isListOfNodes(e)) alert("FIXME: list of forms not implemented"); else return function(obj) { if(e.elements && typeof obj == "object") { for(i in obj) if(e.elements[i]) e.elements[i].value = obj[i]; // FIXME: what about checkboxes, selects, etc? } else throw new Error("unsupported response"); }; }, "_getElement": function(what) { // FIXME: what about jQuery users? If they do useToReplace($("whatever")), we ought to do what we can with it for the most seamless experience even if I loathe that bloat. // though I guess they should be ok in doing $("whatever")[0] or maybe $("whatever").get() so not too awful really. var e; if(typeof what == "string") e = document.getElementById(what); else e = what; return e; }, "_isListOfNodes": function(what) { // length is on both arrays and lists, but some elements // have it too. We disambiguate with getAttribute return (what && (what.length && !what.getAttribute)) }, // These are some convenience functions to use as callbacks "_replaceContent": function(what) { var e = this._getElement(what); var me = this; if(this._isListOfNodes(e)) return function(obj) { // I do not want scripts accidentally running here... for(var a = 0; a < e.length; a++) { if( (e[a].tagName.toLowerCase() == "input" && e[a].getAttribute("type") == "text") || e[a].tagName.toLowerCase() == "textarea") { e[a].value = obj; } else e[a].innerHTML = obj; } } else return function(obj) { var data = me._extractHtmlScript(obj); if( (e.tagName.toLowerCase() == "input" && e.getAttribute("type") == "text") || e.tagName.toLowerCase() == "textarea") { e.value = obj; // might want script looking thing as a value } else e.innerHTML = data[0]; if(me._wantScriptExecution && data[1].length) eval(data[1]); } }, // note: what must be only a single element, FIXME: could check the static type "_replaceElement": function(what) { var e = this._getElement(what); if(this._isListOfNodes(e)) throw new Error("Can only replace individual elements since removal from a list may be unstable."); var me = this; return function(obj) { var data = me._extractHtmlScript(obj); var n = document.createElement("div"); n.innerHTML = data[0]; if(n.firstChild) { e.parentNode.replaceChild(n.firstChild, e); } else { e.parentNode.removeChild(e); } if(me._wantScriptExecution && data[1].length) eval(data[1]); } }, "_appendContent": function(what) { var e = this._getElement(what); var me = this; if(this._isListOfNodes(e)) // FIXME: repeating myself... return function(obj) { var data = me._extractHtmlScript(obj); for(var a = 0; a < e.length; a++) e[a].innerHTML += data[0]; if(me._wantScriptExecution && data[1].length) eval(data[1]); } else return function(obj) { var data = me._extractHtmlScript(obj); e.innerHTML += data[0]; if(me._wantScriptExecution && data[1].length) eval(data[1]); } }, "_extractHtmlScript": function(response) { var scriptRegex = new RegExp("<script>([\\s\\S]*?)<\\/script>", "g"); var scripts = ""; var match; while(match = scriptRegex.exec(response)) { scripts += match[1]; } var html = response.replace(scriptRegex, ""); return [html, scripts]; }, // we say yes by default because these always come from your own domain anyway; // it should be safe (as long as your app is sane). You can turn it off though if you want // by setting this to false somewhere in your code. "_wantScriptExecution" : true, }; /* Copyright: Adam D. Ruppe, 2010 - 2012 License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>. Authors: Adam D. Ruppe, with contributions by Nick Sabalausky Copyright Adam D. Ruppe 2010-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) */
D
module armos.graphics.font; import derelict.freetype.ft; import armos.graphics; import armos.math; import armos.types; /++ 読み込まれる文字を表します. +/ struct Character{ int index; int glyph; int height; int width; int bearingX, bearingY; int xmin, xmax, ymin, ymax; int advance; float tW,tH; float t1,t2,v1,v2; void setupInfo(in int index, in int glyph, in FT_Face face){ this.index = index; this.glyph = glyph; height = cast(int)face.glyph.metrics.height >>6; width = cast(int)face.glyph.metrics.width >>6; bearingX = cast(int)face.glyph.metrics.horiBearingX >>6; bearingY = cast(int)face.glyph.metrics.horiBearingY >>6; xmin = face.glyph.bitmap_left; xmax = xmin + width; ymin = -face.glyph.bitmap_top; ymax = ymin + height; advance = cast(int)face.glyph.metrics.horiAdvance >>6; tW = width; tH = height; } } /++ Fontを読み込み,描画を行います. Deprecated: 現在動作しません. +/ class Font{ public{ this(){ DerelictFT.load(); if(!_librariesInitialized){ FT_Error error = FT_Init_FreeType( &_library ); if(!error){ _librariesInitialized = true; } } } /++ +/ void load( string fontName, int fontSize, bool isAntiAliased=false, bool isFullCharacterSet=false, bool makeContours=false, float simplifyAmt=0.3f, int dpi=0 ){ int fontId = 0; // string filePath = toDataPath( fontName ); string filePath = ""; FT_Error error = FT_New_Face( _library, filePath.ptr, fontId, &_face ); if(dpi!=0){ _dpi = dpi; } FT_Set_Char_Size( _face, fontSize << 6, fontSize << 6, _dpi, _dpi); float fontUnitScale = (cast(float)fontSize * _dpi) / (72 * _face.units_per_EM); _lineHeight = _face.height * fontUnitScale; _ascenderHeight = _face.ascender * fontUnitScale; _descenderHeight = _face.descender * fontUnitScale; _glyphBBox.set( _face.bbox.xMin * fontUnitScale, _face.bbox.yMin * fontUnitScale, (_face.bbox.xMax - _face.bbox.xMin) * fontUnitScale, (_face.bbox.yMax - _face.bbox.yMin) * fontUnitScale ); _useKerning = FT_HAS_KERNING( _face ); _numCharacters = (isFullCharacterSet ? 256 : 128) - NUM_CHARACTER_TO_START; loadEachCharacters(isAntiAliased); } /++ +/ void drawString(string drawnString, int x, int y)const{} /++ +/ void drawStringAsShapes(string drawnString, int x, int y)const{} }//public private{ static immutable NUM_CHARACTER_TO_START = 32; static FT_Library _library; static bool _librariesInitialized = false; static int _dpi = 96; Character[] _characters; FT_Face _face; float _lineHeight = 0.0; float _ascenderHeight = 0.0; float _descenderHeight = 0.0; bool _useKerning; int _numCharacters = 0; Rectangle _glyphBBox; Texture _textureAtlas; /++ +/ void loadEachCharacters(bool isAntiAliased){ int border = 1; long areaSum=0; _characters = new Character[](_numCharacters); Bitmap!(char)[] expandedData = new Bitmap!(char)[](_numCharacters); foreach (int i, ref character; _characters) { int glyph = cast(char)(i+NUM_CHARACTER_TO_START); if (glyph == 0xA4) glyph = 0x20AC; // hack to load the euro sign, all codes in 8859-15 match with utf-32 except for this one FT_Error error = FT_Load_Glyph( _face, FT_Get_Char_Index( _face, glyph ), isAntiAliased ? FT_LOAD_FORCE_AUTOHINT : FT_LOAD_DEFAULT ); if (isAntiAliased == true){ FT_Render_Glyph(_face.glyph, FT_RENDER_MODE_NORMAL); }else{ FT_Render_Glyph(_face.glyph, FT_RENDER_MODE_MONO); } FT_Bitmap* bitmap= &_face.glyph.bitmap; auto width = bitmap.width; auto height = bitmap.rows; character.setupInfo(i, glyph, _face); areaSum += cast(long)( (character.tW+border*2)*(character.tH+border*2) ); if(width==0 || height==0) continue; expandedData[i].allocate(width, height, ColorFormat.GrayAlpha); expandedData[i].setAllPixels(0, 255); expandedData[i].setAllPixels(1, 0); if (isAntiAliased){ } else { auto src = bitmap.buffer; for(typeof(height) j=0; j < height; j++) { char b=0; auto bptr = src; for(typeof(width) k=0; k < width; k++){ expandedData[i].pixel(k, j, 0, 255); if (k%8==0){ b = (*bptr++); } expandedData[i].pixel(k, j, 1, b&0x80 ? 255 : 0); b <<= 1; } src += bitmap.pitch; } } } } /++ +/ bool packInTexture(in long areaSum, in int border, Bitmap!(char)[] expandedData){ import std.algorithm; bool compareCharacters(in Character c1, in Character c2){ if(c1.tH == c2.tH) return c1.tW > c2.tW; else return c1.tH > c2.tH; } auto sortedCharacter = _characters; sort!(compareCharacters)(sortedCharacter); Vector2i atlasSize = calcAtlasSize(areaSum, sortedCharacter, border); Bitmap!char atlasPixelsLuminanceAlpha; atlasPixelsLuminanceAlpha.allocate(atlasSize[0], atlasSize[1], ColorFormat.GrayAlpha); atlasPixelsLuminanceAlpha.setAllPixels(0,255); atlasPixelsLuminanceAlpha.setAllPixels(1,0); int x=0; int y=0; int maxRowHeight = cast(int)sortedCharacter[0].tH + border*2; for(int i = 0; i < cast(int)sortedCharacter.length; i++){ Bitmap!(char)* charBitmap = &expandedData[cast(int)sortedCharacter[i].index]; if(x+cast(int)sortedCharacter[i].tW + border*2 > atlasSize[0]){ x = 0; y += maxRowHeight; maxRowHeight = cast(int)sortedCharacter[i].tH + border*2; } _characters[sortedCharacter[i].index].t1 = cast( float )(x + border)/cast( float )(atlasSize[0]); _characters[sortedCharacter[i].index].v1 = cast( float )(y + border)/cast( float )(atlasSize[1]); _characters[sortedCharacter[i].index].t2 = float(_characters[sortedCharacter[i].index].tW + x + border)/float(atlasSize[0]); _characters[sortedCharacter[i].index].v2 = float(_characters[sortedCharacter[i].index].tH + y + border)/float(atlasSize[1]); charBitmap.pasteInto(atlasPixelsLuminanceAlpha,x+border,y+border); x+= cast(int)sortedCharacter[i].tW + border*2; } _textureAtlas.allocate(atlasPixelsLuminanceAlpha); // if(bAntiAliased && fontSize>20){ // _textureAtlas.setTextureMinMagFilter(GL_LINEAR,GL_LINEAR); // }else{ // _textureAtlas.setTextureMinMagFilter(GL_NEAREST,GL_NEAREST); // } // _textureAtlas.loadData(atlasPixelsLuminanceAlpha); return true; } /++ +/ Vector2i calcAtlasSize(long areaSum, in Character[] sortedCharacter, int border){ import std.math; bool packed = false; float alpha = log(cast(float)areaSum)*1.44269; int w; int h; while(!packed){ w = cast(int)pow(2,floor((alpha/2.0) + 0.5)); h = w; int x=0; int y=0; int maxRowHeight = cast(int)sortedCharacter[0].tH + border*2; for(int i=0; i<cast(int)sortedCharacter.length; i++){ if(x+sortedCharacter[i].tW + border*2>w){ x = 0; y += maxRowHeight; maxRowHeight = cast(int)sortedCharacter[i].tH + border*2; if(y + maxRowHeight > h){ alpha++; break; } } x+= cast(int)sortedCharacter[i].tW + border*2; if(i==cast(int)sortedCharacter.length-1){ packed = true; } } } return Vector2i(w, h); } /++ +/ // string fontPathByName(string fontName){ // version(linux){ // import std.string; // string fileName; // FcPattern* pattern = FcNameParse(cast(const FcChar8*)fontname.toStringz); // return fileName; // } // version(Windows){ // return ""; // } // }; }//private } /++ Fontを読み込みます Deprecated: 現在動作しません. +/ class FontLoader{ public{ /++ +/ void loadFont( string fontName, int fontSize, bool isAntiAliased=false, bool isFullCharacterSet=false, bool makeContours=false, float simplifyAmt=0.3f, int dpi=0 ){} }//public private{}//private }
D
import std.stdio; void main(){ int i = 0; do { foo(i); } while (++i < 10); }
D
/Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/DerivedData/CryptoLive/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Charts.build/Objects-normal/x86_64/CandleStickChartView.o : /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Filters/DataApproximator+N.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/CombinedChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarLineScatterCandleBubbleChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/ScatterChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Jobs/ViewPortJob.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Jobs/AnimatedViewPortJob.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Jobs/MoveViewJob.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Jobs/AnimatedMoveViewJob.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Jobs/ZoomViewJob.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Jobs/AnimatedZoomViewJob.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/Legend.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/MarkerImage.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/Range.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/ChartLimitLine.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/ChartDataRendererBase.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/AxisRendererBase.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/AxisBase.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/ComponentBase.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/ChartViewBase.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/BarLineChartViewBase.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/PieRadarChartViewBase.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataEntryBase.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Animation/ChartAnimationEasing.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Utils/Fill.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Utils/Platform.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/Description.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Interfaces/ChartDataProvider.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Interfaces/CombinedChartDataProvider.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Interfaces/BubbleChartDataProvider.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Interfaces/BarLineScatterCandleBubbleChartDataProvider.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Interfaces/CandleChartDataProvider.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Interfaces/LineChartDataProvider.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Interfaces/BarChartDataProvider.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Interfaces/ScatterChartDataProvider.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/IMarker.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Utils/ViewPortHandler.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Utils/Transformer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Renderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/LegendRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/BarLineScatterCandleBubbleRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Scatter/IShapeRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Scatter/XShapeRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Scatter/CircleShapeRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Scatter/TriangleShapeRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Scatter/SquareShapeRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Scatter/ChevronDownShapeRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Scatter/ChevronUpShapeRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Scatter/CrossShapeRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/LineScatterCandleRadarRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/LineRadarRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/XAxisRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/YAxisRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/CombinedChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/PieChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/BubbleChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/LineChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/CandleStickChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/BarChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/HorizontalBarChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/RadarChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/ScatterChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/IHighlighter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/CombinedHighlighter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/PieHighlighter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/BarHighlighter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/HorizontalBarHighlighter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/RadarHighlighter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/PieRadarHighlighter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/ChartHighlighter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Formatters/IValueFormatter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Formatters/IAxisValueFormatter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Formatters/DefaultAxisValueFormatter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Formatters/IndexAxisValueFormatter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Formatters/DefaultValueFormatter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Formatters/IFillFormatter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Formatters/DefaultFillFormatter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Animation/Animator.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Filters/DataApproximator.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Utils/ChartColorTemplates.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/XAxis.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/YAxis.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Utils/ChartUtils.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/ChartBaseDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/IChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/IPieChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/IBubbleChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarLineScatterCandleBubbleChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/IBarLineScatterCandleBubbleChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/ICandleChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/ILineChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/IBarChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/IRadarChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineScatterCandleRadarChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/ILineScatterCandleRadarChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineRadarChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/ILineRadarChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/ScatterChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/IScatterChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/Highlight.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Utils/TransformerHorizontalBarChart.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/XAxisRendererHorizontalBarChart.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/YAxisRendererHorizontalBarChart.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/XAxisRendererRadarChart.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/YAxisRendererRadarChart.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/MarkerView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/CombinedChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/PieChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/BubbleChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/LineChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/CandleStickChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/BarChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/HorizontalBarChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/RadarChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/ScatterChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataEntry.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartDataEntry.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartDataEntry.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartDataEntry.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartDataEntry.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartDataEntry.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/LegendEntry.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Target\ Support\ Files/Charts/Charts-umbrella.h /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/DerivedData/CryptoLive/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Charts.build/unextended-module.modulemap /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/DerivedData/CryptoLive/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Charts.build/Objects-normal/x86_64/CandleStickChartView~partial.swiftmodule : /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Filters/DataApproximator+N.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/CombinedChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarLineScatterCandleBubbleChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/ScatterChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Jobs/ViewPortJob.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Jobs/AnimatedViewPortJob.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Jobs/MoveViewJob.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Jobs/AnimatedMoveViewJob.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Jobs/ZoomViewJob.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Jobs/AnimatedZoomViewJob.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/Legend.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/MarkerImage.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/Range.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/ChartLimitLine.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/ChartDataRendererBase.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/AxisRendererBase.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/AxisBase.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/ComponentBase.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/ChartViewBase.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/BarLineChartViewBase.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/PieRadarChartViewBase.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataEntryBase.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Animation/ChartAnimationEasing.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Utils/Fill.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Utils/Platform.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/Description.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Interfaces/ChartDataProvider.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Interfaces/CombinedChartDataProvider.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Interfaces/BubbleChartDataProvider.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Interfaces/BarLineScatterCandleBubbleChartDataProvider.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Interfaces/CandleChartDataProvider.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Interfaces/LineChartDataProvider.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Interfaces/BarChartDataProvider.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Interfaces/ScatterChartDataProvider.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/IMarker.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Utils/ViewPortHandler.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Utils/Transformer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Renderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/LegendRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/BarLineScatterCandleBubbleRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Scatter/IShapeRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Scatter/XShapeRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Scatter/CircleShapeRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Scatter/TriangleShapeRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Scatter/SquareShapeRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Scatter/ChevronDownShapeRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Scatter/ChevronUpShapeRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Scatter/CrossShapeRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/LineScatterCandleRadarRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/LineRadarRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/XAxisRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/YAxisRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/CombinedChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/PieChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/BubbleChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/LineChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/CandleStickChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/BarChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/HorizontalBarChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/RadarChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/ScatterChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/IHighlighter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/CombinedHighlighter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/PieHighlighter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/BarHighlighter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/HorizontalBarHighlighter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/RadarHighlighter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/PieRadarHighlighter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/ChartHighlighter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Formatters/IValueFormatter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Formatters/IAxisValueFormatter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Formatters/DefaultAxisValueFormatter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Formatters/IndexAxisValueFormatter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Formatters/DefaultValueFormatter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Formatters/IFillFormatter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Formatters/DefaultFillFormatter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Animation/Animator.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Filters/DataApproximator.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Utils/ChartColorTemplates.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/XAxis.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/YAxis.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Utils/ChartUtils.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/ChartBaseDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/IChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/IPieChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/IBubbleChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarLineScatterCandleBubbleChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/IBarLineScatterCandleBubbleChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/ICandleChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/ILineChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/IBarChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/IRadarChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineScatterCandleRadarChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/ILineScatterCandleRadarChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineRadarChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/ILineRadarChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/ScatterChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/IScatterChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/Highlight.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Utils/TransformerHorizontalBarChart.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/XAxisRendererHorizontalBarChart.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/YAxisRendererHorizontalBarChart.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/XAxisRendererRadarChart.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/YAxisRendererRadarChart.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/MarkerView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/CombinedChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/PieChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/BubbleChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/LineChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/CandleStickChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/BarChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/HorizontalBarChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/RadarChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/ScatterChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataEntry.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartDataEntry.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartDataEntry.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartDataEntry.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartDataEntry.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartDataEntry.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/LegendEntry.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Target\ Support\ Files/Charts/Charts-umbrella.h /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/DerivedData/CryptoLive/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Charts.build/unextended-module.modulemap /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/DerivedData/CryptoLive/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Charts.build/Objects-normal/x86_64/CandleStickChartView~partial.swiftdoc : /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Filters/DataApproximator+N.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/CombinedChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarLineScatterCandleBubbleChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/ScatterChartData.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Jobs/ViewPortJob.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Jobs/AnimatedViewPortJob.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Jobs/MoveViewJob.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Jobs/AnimatedMoveViewJob.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Jobs/ZoomViewJob.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Jobs/AnimatedZoomViewJob.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/Legend.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/MarkerImage.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/Range.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/ChartLimitLine.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/ChartDataRendererBase.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/AxisRendererBase.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/AxisBase.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/ComponentBase.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/ChartViewBase.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/BarLineChartViewBase.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/PieRadarChartViewBase.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataEntryBase.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Animation/ChartAnimationEasing.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Utils/Fill.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Utils/Platform.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/Description.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Interfaces/ChartDataProvider.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Interfaces/CombinedChartDataProvider.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Interfaces/BubbleChartDataProvider.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Interfaces/BarLineScatterCandleBubbleChartDataProvider.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Interfaces/CandleChartDataProvider.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Interfaces/LineChartDataProvider.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Interfaces/BarChartDataProvider.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Interfaces/ScatterChartDataProvider.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/IMarker.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Utils/ViewPortHandler.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Utils/Transformer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Renderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/LegendRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/BarLineScatterCandleBubbleRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Scatter/IShapeRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Scatter/XShapeRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Scatter/CircleShapeRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Scatter/TriangleShapeRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Scatter/SquareShapeRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Scatter/ChevronDownShapeRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Scatter/ChevronUpShapeRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/Scatter/CrossShapeRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/LineScatterCandleRadarRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/LineRadarRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/XAxisRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/YAxisRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/CombinedChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/PieChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/BubbleChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/LineChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/CandleStickChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/BarChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/HorizontalBarChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/RadarChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/ScatterChartRenderer.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/IHighlighter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/CombinedHighlighter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/PieHighlighter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/BarHighlighter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/HorizontalBarHighlighter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/RadarHighlighter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/PieRadarHighlighter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/ChartHighlighter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Formatters/IValueFormatter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Formatters/IAxisValueFormatter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Formatters/DefaultAxisValueFormatter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Formatters/IndexAxisValueFormatter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Formatters/DefaultValueFormatter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Formatters/IFillFormatter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Formatters/DefaultFillFormatter.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Animation/Animator.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Filters/DataApproximator.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Utils/ChartColorTemplates.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/XAxis.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/YAxis.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Utils/ChartUtils.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/ChartBaseDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/IChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/IPieChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/IBubbleChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarLineScatterCandleBubbleChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/IBarLineScatterCandleBubbleChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/ICandleChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/ILineChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/IBarChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/IRadarChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineScatterCandleRadarChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/ILineScatterCandleRadarChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineRadarChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/ILineRadarChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/ScatterChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Interfaces/IScatterChartDataSet.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Highlight/Highlight.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Utils/TransformerHorizontalBarChart.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/XAxisRendererHorizontalBarChart.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/YAxisRendererHorizontalBarChart.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/XAxisRendererRadarChart.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Renderers/YAxisRendererRadarChart.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/MarkerView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/CombinedChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/PieChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/BubbleChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/LineChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/CandleStickChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/BarChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/HorizontalBarChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/RadarChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Charts/ScatterChartView.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataEntry.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartDataEntry.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartDataEntry.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartDataEntry.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartDataEntry.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartDataEntry.swift /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Charts/Source/Charts/Components/LegendEntry.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/Pods/Target\ Support\ Files/Charts/Charts-umbrella.h /Users/Jaskeerat/Desktop/CryptoLive/CryptoLive/DerivedData/CryptoLive/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Charts.build/unextended-module.modulemap
D
module d.context; struct Name { private: uint id; this(uint id) { this.id = id; } public: string toString(Context c) const { return c.names[id]; } @property bool isEmpty() const { return this == BuiltinName!""; } @property bool isReserved() const { return id < (Names.length - Prefill.length); } @property bool isDefined() const { return id != 0; } } final class Context { private: string[] names; uint[string] lookups; public: this() { names = Names; lookups = Lookups; } auto getName(string s) { if (auto id = s in lookups) { return Name(*id); } // Do not keep around slice of potentially large input. s = s.idup; auto id = lookups[s] = cast(uint) names.length; names ~= s; return Name(id); } } template BuiltinName(string name) { private enum id = Lookups.get(name, uint.max); static assert(id < uint.max, name ~ " is not a builtin name."); enum BuiltinName = Name(id); } private: enum Reserved = ["__ctor", "__dtor", "__vtbl"]; enum Prefill = [ // Linkages "C", "D", "C++", "Windows", "System", "Pascal", "Java", // Version "SDC", "D_LP64", "X86_64", "linux", "OSX", // Generated "init", "length", "max", "min", "ptr", "sizeof", // Scope "exit", "success", "failure", // Main "main", "_Dmain", // Defined in object "object", "size_t", "ptrdiff_t", "string", "Object", "TypeInfo", "ClassInfo", "Throwable", "Exception", "Error", // Attribute "property", "safe", "trusted", "system", "nogc", // Runtime "__sd_class_downcast", "__sd_eh_throw", "__sd_eh_personality", // Generated symbols "__dg", "__lambda", "__ctx", ]; auto getNames() { import d.lexer; auto identifiers = [""]; foreach(k, _; getOperatorsMap()) { identifiers ~= k; } foreach(k, _; getKeywordsMap()) { identifiers ~= k; } return identifiers ~ Reserved ~ Prefill; } enum Names = getNames(); static assert(Names[0] == ""); auto getLookups() { uint[string] lookups; foreach(uint i, id; Names) { lookups[id] = i; } return lookups; } enum Lookups = getLookups();
D
class C : Exception { this() { super(""); } } version (DLL) { version (Windows) { import core.sys.windows.dll; mixin SimpleDllMain; } pragma(mangle, "foo") export Object foo(Object o) { assert(cast(C) o); return new C; } pragma(mangle, "bar") export void bar(void function() f) { import core.stdc.stdio : fopen, fclose; bool caught; try f(); catch (C e) caught = true; assert(caught); // verify we've actually got to the end, because for some reason we can // end up exiting with code 0 when throwing an exception fclose(fopen("dynamiccast_endbar", "w")); throw new C; } } else { T getFunc(T)(const(char)* sym) { import core.runtime : Runtime; version (Windows) { import core.sys.windows.winbase : GetProcAddress; return cast(T) Runtime.loadLibrary("dynamiccast.dll") .GetProcAddress(sym); } else version (Posix) { import core.sys.posix.dlfcn : dlsym; return cast(T) Runtime.loadLibrary("./dynamiccast.so") .dlsym(sym); } else static assert(0); } // Returns the path to the executable's directory (null-terminated). string getThisExeDir(string arg0) { char[] buffer = arg0.dup; assert(buffer.length); for (size_t i = buffer.length - 1; i > 0; --i) { if (buffer[i] == '/' || buffer[i] == '\\') { buffer[i] = 0; return cast(string) buffer[0 .. i]; } } return null; } version (DigitalMars) version (Win64) version = DMD_Win64; void main(string[] args) { import core.stdc.stdio : fopen, fclose, remove; const exeDir = getThisExeDir(args[0]); if (exeDir.length) { version (Windows) { import core.sys.windows.winbase : SetCurrentDirectoryA; SetCurrentDirectoryA(exeDir.ptr); } else { import core.sys.posix.unistd : chdir; chdir(exeDir.ptr); } } remove("dynamiccast_endmain"); remove("dynamiccast_endbar"); C c = new C; auto o = getFunc!(Object function(Object))("foo")(c); assert(cast(C) o); version (DMD_Win64) { // FIXME: apparent crash & needs more work, see https://github.com/dlang/druntime/pull/2874 fclose(fopen("dynamiccast_endbar", "w")); } else { bool caught; try getFunc!(void function(void function()))("bar")( { throw new C; }); catch (C e) caught = true; assert(caught); } // verify we've actually got to the end, because for some reason we can // end up exiting with code 0 when throwing an exception fclose(fopen("dynamiccast_endmain", "w")); } }
D
/** * Semantic analysis for cast-expressions. * * Copyright: Copyright (C) 1999-2021 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/dcast.d, _dcast.d) * Documentation: https://dlang.org/phobos/dmd_dcast.html * Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/dcast.d */ module dmd.dcast; import core.stdc.stdio; import core.stdc.string; import dmd.aggregate; import dmd.aliasthis; import dmd.arrayop; import dmd.arraytypes; import dmd.astenums; import dmd.dclass; import dmd.declaration; import dmd.dscope; import dmd.dstruct; import dmd.dsymbol; import dmd.errors; import dmd.escape; import dmd.expression; import dmd.expressionsem; import dmd.func; import dmd.globals; import dmd.hdrgen; import dmd.impcnvtab; import dmd.id; import dmd.importc; import dmd.init; import dmd.intrange; import dmd.mtype; import dmd.opover; import dmd.root.ctfloat; import dmd.common.outbuffer; import dmd.root.rmem; import dmd.tokens; import dmd.typesem; import dmd.utf; import dmd.visitor; enum LOG = false; /** * Attempt to implicitly cast the expression into type `t`. * * This routine will change `e`. To check the matching level, * use `implicitConvTo`. * * Params: * e = Expression that is to be casted * sc = Current scope * t = Expected resulting type * * Returns: * The resulting casted expression (mutating `e`), or `ErrorExp` * if such an implicit conversion is not possible. */ Expression implicitCastTo(Expression e, Scope* sc, Type t) { extern (C++) final class ImplicitCastTo : Visitor { alias visit = Visitor.visit; public: Type t; Scope* sc; Expression result; extern (D) this(Scope* sc, Type t) { this.sc = sc; this.t = t; } override void visit(Expression e) { //printf("Expression.implicitCastTo(%s of type %s) => %s\n", e.toChars(), e.type.toChars(), t.toChars()); if (const match = (sc && sc.flags & SCOPE.Cfile) ? e.cimplicitConvTo(t) : e.implicitConvTo(t)) { if (match == MATCH.constant && (e.type.constConv(t) || !e.isLvalue() && e.type.equivalent(t))) { /* Do not emit CastExp for const conversions and * unique conversions on rvalue. */ result = e.copy(); result.type = t; return; } auto ad = isAggregate(e.type); if (ad && ad.aliasthis) { auto ts = ad.type.isTypeStruct(); const adMatch = ts ? ts.implicitConvToWithoutAliasThis(t) : ad.type.isTypeClass().implicitConvToWithoutAliasThis(t); if (!adMatch) { Type tob = t.toBasetype(); Type t1b = e.type.toBasetype(); if (ad != isAggregate(tob)) { if (t1b.ty == Tclass && tob.ty == Tclass) { ClassDeclaration t1cd = t1b.isClassHandle(); ClassDeclaration tocd = tob.isClassHandle(); int offset; if (tocd.isBaseOf(t1cd, &offset)) { result = new CastExp(e.loc, e, t); result.type = t; return; } } /* Forward the cast to our alias this member, rewrite to: * cast(to)e1.aliasthis */ result = resolveAliasThis(sc, e); result = result.castTo(sc, t); return; } } } result = e.castTo(sc, t); return; } result = e.optimize(WANTvalue); if (result != e) { result.accept(this); return; } if (t.ty != Terror && e.type.ty != Terror) { if (!t.deco) { e.error("forward reference to type `%s`", t.toChars()); } else { //printf("type %p ty %d deco %p\n", type, type.ty, type.deco); //type = type.typeSemantic(loc, sc); //printf("type %s t %s\n", type.deco, t.deco); auto ts = toAutoQualChars(e.type, t); e.error("cannot implicitly convert expression `%s` of type `%s` to `%s`", e.toChars(), ts[0], ts[1]); } } result = ErrorExp.get(); } override void visit(StringExp e) { //printf("StringExp::implicitCastTo(%s of type %s) => %s\n", e.toChars(), e.type.toChars(), t.toChars()); visit(cast(Expression)e); if (auto se = result.isStringExp()) { // Retain polysemous nature if it started out that way se.committed = e.committed; } } override void visit(ErrorExp e) { result = e; } override void visit(FuncExp e) { //printf("FuncExp::implicitCastTo type = %p %s, t = %s\n", e.type, e.type ? e.type.toChars() : NULL, t.toChars()); FuncExp fe; if (e.matchType(t, sc, &fe) > MATCH.nomatch) { result = fe; return; } visit(cast(Expression)e); } override void visit(ArrayLiteralExp e) { visit(cast(Expression)e); Type tb = result.type.toBasetype(); if (auto ta = tb.isTypeDArray()) if (global.params.useTypeInfo && Type.dtypeinfo) semanticTypeInfo(sc, ta.next); } override void visit(SliceExp e) { visit(cast(Expression)e); if (auto se = result.isSliceExp()) if (auto ale = se.e1.isArrayLiteralExp()) { Type tb = t.toBasetype(); Type tx = (tb.ty == Tsarray) ? tb.nextOf().sarrayOf(ale.elements ? ale.elements.dim : 0) : tb.nextOf().arrayOf(); se.e1 = ale.implicitCastTo(sc, tx); } } } scope ImplicitCastTo v = new ImplicitCastTo(sc, t); e.accept(v); return v.result; } /** * Checks whether or not an expression can be implicitly converted * to type `t`. * * Unlike `implicitCastTo`, this routine does not perform the actual cast, * but only checks up to what `MATCH` level the conversion would be possible. * * Params: * e = Expression that is to be casted * t = Expected resulting type * * Returns: * The `MATCH` level between `e.type` and `t`. */ MATCH implicitConvTo(Expression e, Type t) { extern (C++) final class ImplicitConvTo : Visitor { alias visit = Visitor.visit; public: Type t; MATCH result; extern (D) this(Type t) { this.t = t; result = MATCH.nomatch; } override void visit(Expression e) { version (none) { printf("Expression::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars()); } //static int nest; if (++nest == 10) assert(0); if (t == Type.terror) return; if (!e.type) { e.error("`%s` is not an expression", e.toChars()); e.type = Type.terror; } Expression ex = e.optimize(WANTvalue); if (ex.type.equals(t)) { result = MATCH.exact; return; } if (ex != e) { //printf("\toptimized to %s of type %s\n", e.toChars(), e.type.toChars()); result = ex.implicitConvTo(t); return; } MATCH match = e.type.implicitConvTo(t); if (match != MATCH.nomatch) { result = match; return; } /* See if we can do integral narrowing conversions */ if (e.type.isintegral() && t.isintegral() && e.type.isTypeBasic() && t.isTypeBasic()) { IntRange src = getIntRange(e); IntRange target = IntRange.fromType(t); if (target.contains(src)) { result = MATCH.convert; return; } } } /****** * Given expression e of type t, see if we can implicitly convert e * to type tprime, where tprime is type t with mod bits added. * Returns: * match level */ static MATCH implicitMod(Expression e, Type t, MOD mod) { Type tprime; if (t.ty == Tpointer) tprime = t.nextOf().castMod(mod).pointerTo(); else if (t.ty == Tarray) tprime = t.nextOf().castMod(mod).arrayOf(); else if (t.ty == Tsarray) tprime = t.nextOf().castMod(mod).sarrayOf(t.size() / t.nextOf().size()); else tprime = t.castMod(mod); return e.implicitConvTo(tprime); } static MATCH implicitConvToAddMin(BinExp e, Type t) { /* Is this (ptr +- offset)? If so, then ask ptr * if the conversion can be done. * This is to support doing things like implicitly converting a mutable unique * pointer to an immutable pointer. */ Type tb = t.toBasetype(); Type typeb = e.type.toBasetype(); if (typeb.ty != Tpointer || tb.ty != Tpointer) return MATCH.nomatch; Type t1b = e.e1.type.toBasetype(); Type t2b = e.e2.type.toBasetype(); if (t1b.ty == Tpointer && t2b.isintegral() && t1b.equivalent(tb)) { // ptr + offset // ptr - offset MATCH m = e.e1.implicitConvTo(t); return (m > MATCH.constant) ? MATCH.constant : m; } if (t2b.ty == Tpointer && t1b.isintegral() && t2b.equivalent(tb)) { // offset + ptr MATCH m = e.e2.implicitConvTo(t); return (m > MATCH.constant) ? MATCH.constant : m; } return MATCH.nomatch; } override void visit(AddExp e) { version (none) { printf("AddExp::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars()); } visit(cast(Expression)e); if (result == MATCH.nomatch) result = implicitConvToAddMin(e, t); } override void visit(MinExp e) { version (none) { printf("MinExp::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars()); } visit(cast(Expression)e); if (result == MATCH.nomatch) result = implicitConvToAddMin(e, t); } override void visit(IntegerExp e) { version (none) { printf("IntegerExp::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars()); } MATCH m = e.type.implicitConvTo(t); if (m >= MATCH.constant) { result = m; return; } TY ty = e.type.toBasetype().ty; TY toty = t.toBasetype().ty; TY oldty = ty; if (m == MATCH.nomatch && t.ty == Tenum) return; if (auto tv = t.isTypeVector()) { TypeBasic tb = tv.elementType(); if (tb.ty == Tvoid) return; toty = tb.ty; } switch (ty) { case Tbool: case Tint8: case Tchar: case Tuns8: case Tint16: case Tuns16: case Twchar: ty = Tint32; break; case Tdchar: ty = Tuns32; break; default: break; } // Only allow conversion if no change in value immutable dinteger_t value = e.toInteger(); bool isLosslesslyConvertibleToFP(T)() { if (e.type.isunsigned()) { const f = cast(T) value; return cast(dinteger_t) f == value; } const f = cast(T) cast(sinteger_t) value; return cast(sinteger_t) f == cast(sinteger_t) value; } switch (toty) { case Tbool: if ((value & 1) != value) return; break; case Tint8: if (ty == Tuns64 && value & ~0x7FU) return; else if (cast(byte)value != value) return; break; case Tchar: if ((oldty == Twchar || oldty == Tdchar) && value > 0x7F) return; goto case Tuns8; case Tuns8: //printf("value = %llu %llu\n", (dinteger_t)(unsigned char)value, value); if (cast(ubyte)value != value) return; break; case Tint16: if (ty == Tuns64 && value & ~0x7FFFU) return; else if (cast(short)value != value) return; break; case Twchar: if (oldty == Tdchar && value > 0xD7FF && value < 0xE000) return; goto case Tuns16; case Tuns16: if (cast(ushort)value != value) return; break; case Tint32: if (ty == Tuns32) { } else if (ty == Tuns64 && value & ~0x7FFFFFFFU) return; else if (cast(int)value != value) return; break; case Tuns32: if (ty == Tint32) { } else if (cast(uint)value != value) return; break; case Tdchar: if (value > 0x10FFFFU) return; break; case Tfloat32: if (!isLosslesslyConvertibleToFP!float) return; break; case Tfloat64: if (!isLosslesslyConvertibleToFP!double) return; break; case Tfloat80: if (!isLosslesslyConvertibleToFP!real_t) return; break; case Tpointer: //printf("type = %s\n", type.toBasetype()->toChars()); //printf("t = %s\n", t.toBasetype()->toChars()); if (ty == Tpointer && e.type.toBasetype().nextOf().ty == t.toBasetype().nextOf().ty) { /* Allow things like: * const char* P = cast(char *)3; * char* q = P; */ break; } goto default; default: visit(cast(Expression)e); return; } //printf("MATCH.convert\n"); result = MATCH.convert; } override void visit(ErrorExp e) { // no match } override void visit(NullExp e) { version (none) { printf("NullExp::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars()); } if (e.type.equals(t)) { result = MATCH.exact; return; } /* Allow implicit conversions from immutable to mutable|const, * and mutable to immutable. It works because, after all, a null * doesn't actually point to anything. */ if (t.equivalent(e.type)) { result = MATCH.constant; return; } visit(cast(Expression)e); } override void visit(StructLiteralExp e) { version (none) { printf("StructLiteralExp::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars()); } visit(cast(Expression)e); if (result != MATCH.nomatch) return; if (e.type.ty == t.ty && e.type.isTypeStruct() && e.type.isTypeStruct().sym == t.isTypeStruct().sym) { result = MATCH.constant; foreach (i, el; (*e.elements)[]) { if (!el) continue; Type te = e.sd.fields[i].type.addMod(t.mod); MATCH m2 = el.implicitConvTo(te); //printf("\t%s => %s, match = %d\n", el.toChars(), te.toChars(), m2); if (m2 < result) result = m2; } } } override void visit(StringExp e) { version (none) { printf("StringExp::implicitConvTo(this=%s, committed=%d, type=%s, t=%s)\n", e.toChars(), e.committed, e.type.toChars(), t.toChars()); } if (!e.committed && t.ty == Tpointer && t.nextOf().ty == Tvoid) return; if (!(e.type.ty == Tsarray || e.type.ty == Tarray || e.type.ty == Tpointer)) return visit(cast(Expression)e); TY tyn = e.type.nextOf().ty; if (!tyn.isSomeChar) return visit(cast(Expression)e); switch (t.ty) { case Tsarray: if (e.type.ty == Tsarray) { TY tynto = t.nextOf().ty; if (tynto == tyn) { if (e.type.isTypeSArray().dim.toInteger() == t.isTypeSArray().dim.toInteger()) { result = MATCH.exact; } return; } if (tynto.isSomeChar) { if (e.committed && tynto != tyn) return; size_t fromlen = e.numberOfCodeUnits(tynto); size_t tolen = cast(size_t)t.isTypeSArray().dim.toInteger(); if (tolen < fromlen) return; if (tolen != fromlen) { // implicit length extending result = MATCH.convert; return; } } if (!e.committed && tynto.isSomeChar) { result = MATCH.exact; return; } } else if (e.type.ty == Tarray) { TY tynto = t.nextOf().ty; if (tynto.isSomeChar) { if (e.committed && tynto != tyn) return; size_t fromlen = e.numberOfCodeUnits(tynto); size_t tolen = cast(size_t)t.isTypeSArray().dim.toInteger(); if (tolen < fromlen) return; if (tolen != fromlen) { // implicit length extending result = MATCH.convert; return; } } if (tynto == tyn) { result = MATCH.exact; return; } if (!e.committed && tynto.isSomeChar) { result = MATCH.exact; return; } } goto case; /+ fall through +/ case Tarray: case Tpointer: Type tn = t.nextOf(); MATCH m = MATCH.exact; if (e.type.nextOf().mod != tn.mod) { // https://issues.dlang.org/show_bug.cgi?id=16183 if (!tn.isConst() && !tn.isImmutable()) return; m = MATCH.constant; } if (!e.committed) { switch (tn.ty) { case Tchar: if (e.postfix == 'w' || e.postfix == 'd') m = MATCH.convert; result = m; return; case Twchar: if (e.postfix != 'w') m = MATCH.convert; result = m; return; case Tdchar: if (e.postfix != 'd') m = MATCH.convert; result = m; return; case Tenum: if (tn.isTypeEnum().sym.isSpecial()) { /* Allow string literal -> const(wchar_t)[] */ if (TypeBasic tob = tn.toBasetype().isTypeBasic()) result = tn.implicitConvTo(tob); return; } break; default: break; } } break; default: break; } visit(cast(Expression)e); } override void visit(ArrayLiteralExp e) { version (none) { printf("ArrayLiteralExp::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars()); } Type tb = t.toBasetype(); Type typeb = e.type.toBasetype(); if ((tb.ty == Tarray || tb.ty == Tsarray) && (typeb.ty == Tarray || typeb.ty == Tsarray)) { result = MATCH.exact; Type typen = typeb.nextOf().toBasetype(); if (auto tsa = tb.isTypeSArray()) { if (e.elements.dim != tsa.dim.toInteger()) result = MATCH.nomatch; } Type telement = tb.nextOf(); if (!e.elements.dim) { if (typen.ty != Tvoid) result = typen.implicitConvTo(telement); } else { if (e.basis) { MATCH m = e.basis.implicitConvTo(telement); if (m < result) result = m; } for (size_t i = 0; i < e.elements.dim; i++) { Expression el = (*e.elements)[i]; if (result == MATCH.nomatch) break; if (!el) continue; MATCH m = el.implicitConvTo(telement); if (m < result) result = m; // remember worst match } } if (!result) result = e.type.implicitConvTo(t); return; } else if (tb.ty == Tvector && (typeb.ty == Tarray || typeb.ty == Tsarray)) { result = MATCH.exact; // Convert array literal to vector type TypeVector tv = tb.isTypeVector(); TypeSArray tbase = tv.basetype.isTypeSArray(); assert(tbase); const edim = e.elements.dim; const tbasedim = tbase.dim.toInteger(); if (edim > tbasedim) { result = MATCH.nomatch; return; } Type telement = tv.elementType(); if (edim < tbasedim) { Expression el = typeb.nextOf.defaultInitLiteral(e.loc); MATCH m = el.implicitConvTo(telement); if (m < result) result = m; // remember worst match } foreach (el; (*e.elements)[]) { MATCH m = el.implicitConvTo(telement); if (m < result) result = m; // remember worst match if (result == MATCH.nomatch) break; // no need to check for worse } return; } visit(cast(Expression)e); } override void visit(AssocArrayLiteralExp e) { auto taa = t.toBasetype().isTypeAArray(); Type typeb = e.type.toBasetype(); if (!(taa && typeb.ty == Taarray)) return visit(cast(Expression)e); result = MATCH.exact; foreach (i, el; (*e.keys)[]) { MATCH m = el.implicitConvTo(taa.index); if (m < result) result = m; // remember worst match if (result == MATCH.nomatch) break; // no need to check for worse el = (*e.values)[i]; m = el.implicitConvTo(taa.nextOf()); if (m < result) result = m; // remember worst match if (result == MATCH.nomatch) break; // no need to check for worse } } override void visit(CallExp e) { enum LOG = false; static if (LOG) { printf("CallExp::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars()); } visit(cast(Expression)e); if (result != MATCH.nomatch) return; /* Allow the result of strongly pure functions to * convert to immutable */ if (e.f && (global.params.useDIP1000 != FeatureState.enabled || // lots of legacy code breaks with the following purity check e.f.isPure() >= PURE.strong || // Special case exemption for Object.dup() which we assume is implemented correctly e.f.ident == Id.dup && e.f.toParent2() == ClassDeclaration.object.toParent()) && e.f.isReturnIsolated() // check isReturnIsolated last, because it is potentially expensive. ) { result = e.type.immutableOf().implicitConvTo(t); if (result > MATCH.constant) // Match level is MATCH.constant at best. result = MATCH.constant; return; } /* Conversion is 'const' conversion if: * 1. function is pure (weakly pure is ok) * 2. implicit conversion only fails because of mod bits * 3. each function parameter can be implicitly converted to the mod bits */ auto tf = (e.f ? e.f.type : e.e1.type).toBasetype().isTypeFunction(); if (!tf) return; if (tf.purity == PURE.impure) return; if (e.f && e.f.isNested()) return; /* See if fail only because of mod bits. * * https://issues.dlang.org/show_bug.cgi?id=14155 * All pure functions can access global immutable data. * So the returned pointer may refer an immutable global data, * and then the returned pointer that points non-mutable object * cannot be unique pointer. * * Example: * immutable g; * static this() { g = 1; } * const(int*) foo() pure { return &g; } * void test() { * immutable(int*) ip = foo(); // OK * int* mp = foo(); // should be disallowed * } */ if (e.type.immutableOf().implicitConvTo(t) < MATCH.constant && e.type.addMod(MODFlags.shared_).implicitConvTo(t) < MATCH.constant && e.type.implicitConvTo(t.addMod(MODFlags.shared_)) < MATCH.constant) { return; } // Allow a conversion to immutable type, or // conversions of mutable types between thread-local and shared. /* Get mod bits of what we're converting to */ Type tb = t.toBasetype(); MOD mod = tb.mod; if (tf.isref) { } else { if (Type ti = getIndirection(t)) mod = ti.mod; } static if (LOG) { printf("mod = x%x\n", mod); } if (mod & MODFlags.wild) return; // not sure what to do with this /* Apply mod bits to each function parameter, * and see if we can convert the function argument to the modded type */ size_t nparams = tf.parameterList.length; size_t j = tf.isDstyleVariadic(); // if TypeInfoArray was prepended if (auto dve = e.e1.isDotVarExp()) { /* Treat 'this' as just another function argument */ Type targ = dve.e1.type; if (targ.constConv(targ.castMod(mod)) == MATCH.nomatch) return; } foreach (const i; j .. e.arguments.dim) { Expression earg = (*e.arguments)[i]; Type targ = earg.type.toBasetype(); static if (LOG) { printf("[%d] earg: %s, targ: %s\n", cast(int)i, earg.toChars(), targ.toChars()); } if (i - j < nparams) { Parameter fparam = tf.parameterList[i - j]; if (fparam.storageClass & STC.lazy_) return; // not sure what to do with this Type tparam = fparam.type; if (!tparam) continue; if (fparam.isReference()) { if (targ.constConv(tparam.castMod(mod)) == MATCH.nomatch) return; continue; } } static if (LOG) { printf("[%d] earg: %s, targm: %s\n", cast(int)i, earg.toChars(), targ.addMod(mod).toChars()); } if (implicitMod(earg, targ, mod) == MATCH.nomatch) return; } /* Success */ result = MATCH.constant; } override void visit(AddrExp e) { version (none) { printf("AddrExp::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars()); } result = e.type.implicitConvTo(t); //printf("\tresult = %d\n", result); if (result != MATCH.nomatch) return; Type tb = t.toBasetype(); Type typeb = e.type.toBasetype(); // Look for pointers to functions where the functions are overloaded. if (e.e1.op == EXP.overloadSet && (tb.ty == Tpointer || tb.ty == Tdelegate) && tb.nextOf().ty == Tfunction) { OverExp eo = e.e1.isOverExp(); FuncDeclaration f = null; foreach (s; eo.vars.a[]) { FuncDeclaration f2 = s.isFuncDeclaration(); assert(f2); if (f2.overloadExactMatch(tb.nextOf())) { if (f) { /* Error if match in more than one overload set, * even if one is a 'better' match than the other. */ ScopeDsymbol.multiplyDefined(e.loc, f, f2); } else f = f2; result = MATCH.exact; } } } if (e.e1.op == EXP.variable && typeb.ty == Tpointer && typeb.nextOf().ty == Tfunction && tb.ty == Tpointer && tb.nextOf().ty == Tfunction) { /* I don't think this can ever happen - * it should have been * converted to a SymOffExp. */ assert(0); } //printf("\tresult = %d\n", result); } override void visit(SymOffExp e) { version (none) { printf("SymOffExp::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars()); } result = e.type.implicitConvTo(t); //printf("\tresult = %d\n", result); if (result != MATCH.nomatch) return; Type tb = t.toBasetype(); Type typeb = e.type.toBasetype(); // Look for pointers to functions where the functions are overloaded. if (typeb.ty == Tpointer && typeb.nextOf().ty == Tfunction && (tb.ty == Tpointer || tb.ty == Tdelegate) && tb.nextOf().ty == Tfunction) { if (FuncDeclaration f = e.var.isFuncDeclaration()) { f = f.overloadExactMatch(tb.nextOf()); if (f) { if ((tb.ty == Tdelegate && (f.needThis() || f.isNested())) || (tb.ty == Tpointer && !(f.needThis() || f.isNested()))) { result = MATCH.exact; } } } } //printf("\tresult = %d\n", result); } override void visit(DelegateExp e) { version (none) { printf("DelegateExp::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars()); } result = e.type.implicitConvTo(t); if (result != MATCH.nomatch) return; Type tb = t.toBasetype(); Type typeb = e.type.toBasetype(); // Look for pointers to functions where the functions are overloaded. if (typeb.ty == Tdelegate && tb.ty == Tdelegate) { if (e.func && e.func.overloadExactMatch(tb.nextOf())) result = MATCH.exact; } } override void visit(FuncExp e) { //printf("FuncExp::implicitConvTo type = %p %s, t = %s\n", e.type, e.type ? e.type.toChars() : NULL, t.toChars()); MATCH m = e.matchType(t, null, null, 1); if (m > MATCH.nomatch) { result = m; return; } visit(cast(Expression)e); } override void visit(AndExp e) { visit(cast(Expression)e); if (result != MATCH.nomatch) return; MATCH m1 = e.e1.implicitConvTo(t); MATCH m2 = e.e2.implicitConvTo(t); // Pick the worst match result = (m1 < m2) ? m1 : m2; } override void visit(OrExp e) { visit(cast(Expression)e); if (result != MATCH.nomatch) return; MATCH m1 = e.e1.implicitConvTo(t); MATCH m2 = e.e2.implicitConvTo(t); // Pick the worst match result = (m1 < m2) ? m1 : m2; } override void visit(XorExp e) { visit(cast(Expression)e); if (result != MATCH.nomatch) return; MATCH m1 = e.e1.implicitConvTo(t); MATCH m2 = e.e2.implicitConvTo(t); // Pick the worst match result = (m1 < m2) ? m1 : m2; } override void visit(CondExp e) { MATCH m1 = e.e1.implicitConvTo(t); MATCH m2 = e.e2.implicitConvTo(t); //printf("CondExp: m1 %d m2 %d\n", m1, m2); // Pick the worst match result = (m1 < m2) ? m1 : m2; } override void visit(CommaExp e) { e.e2.accept(this); } override void visit(CastExp e) { version (none) { printf("CastExp::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars()); } result = e.type.implicitConvTo(t); if (result != MATCH.nomatch) return; if (t.isintegral() && e.e1.type.isintegral() && e.e1.implicitConvTo(t) != MATCH.nomatch) result = MATCH.convert; else visit(cast(Expression)e); } override void visit(NewExp e) { version (none) { printf("NewExp::implicitConvTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars()); } visit(cast(Expression)e); if (result != MATCH.nomatch) return; /* Calling new() is like calling a pure function. We can implicitly convert the * return from new() to t using the same algorithm as in CallExp, with the function * 'arguments' being: * thisexp * newargs * arguments * .init * 'member' need to be pure. */ /* See if fail only because of mod bits */ if (e.type.immutableOf().implicitConvTo(t.immutableOf()) == MATCH.nomatch) return; /* Get mod bits of what we're converting to */ Type tb = t.toBasetype(); MOD mod = tb.mod; if (Type ti = getIndirection(t)) mod = ti.mod; static if (LOG) { printf("mod = x%x\n", mod); } if (mod & MODFlags.wild) return; // not sure what to do with this /* Apply mod bits to each argument, * and see if we can convert the argument to the modded type */ if (e.thisexp) { /* Treat 'this' as just another function argument */ Type targ = e.thisexp.type; if (targ.constConv(targ.castMod(mod)) == MATCH.nomatch) return; } /* Check call to 'member' */ if (e.member) { FuncDeclaration fd = e.member; if (fd.errors || fd.type.ty != Tfunction) return; // error TypeFunction tf = fd.type.isTypeFunction(); if (tf.purity == PURE.impure) return; // impure if (e.type.immutableOf().implicitConvTo(t) < MATCH.constant && e.type.addMod(MODFlags.shared_).implicitConvTo(t) < MATCH.constant && e.type.implicitConvTo(t.addMod(MODFlags.shared_)) < MATCH.constant) { return; } // Allow a conversion to immutable type, or // conversions of mutable types between thread-local and shared. Expressions* args = e.arguments; size_t nparams = tf.parameterList.length; // if TypeInfoArray was prepended size_t j = tf.isDstyleVariadic(); for (size_t i = j; i < e.arguments.dim; ++i) { Expression earg = (*args)[i]; Type targ = earg.type.toBasetype(); static if (LOG) { printf("[%d] earg: %s, targ: %s\n", cast(int)i, earg.toChars(), targ.toChars()); } if (i - j < nparams) { Parameter fparam = tf.parameterList[i - j]; if (fparam.storageClass & STC.lazy_) return; // not sure what to do with this Type tparam = fparam.type; if (!tparam) continue; if (fparam.isReference()) { if (targ.constConv(tparam.castMod(mod)) == MATCH.nomatch) return; continue; } } static if (LOG) { printf("[%d] earg: %s, targm: %s\n", cast(int)i, earg.toChars(), targ.addMod(mod).toChars()); } if (implicitMod(earg, targ, mod) == MATCH.nomatch) return; } } /* If no 'member', then construction is by simple assignment, * and just straight check 'arguments' */ if (!e.member && e.arguments) { for (size_t i = 0; i < e.arguments.dim; ++i) { Expression earg = (*e.arguments)[i]; if (!earg) // https://issues.dlang.org/show_bug.cgi?id=14853 // if it's on overlapped field continue; Type targ = earg.type.toBasetype(); static if (LOG) { printf("[%d] earg: %s, targ: %s\n", cast(int)i, earg.toChars(), targ.toChars()); printf("[%d] earg: %s, targm: %s\n", cast(int)i, earg.toChars(), targ.addMod(mod).toChars()); } if (implicitMod(earg, targ, mod) == MATCH.nomatch) return; } } /* Consider the .init expression as an argument */ Type ntb = e.newtype.toBasetype(); if (ntb.ty == Tarray) ntb = ntb.nextOf().toBasetype(); if (auto ts = ntb.isTypeStruct()) { // Don't allow nested structs - uplevel reference may not be convertible StructDeclaration sd = ts.sym; sd.size(e.loc); // resolve any forward references if (sd.isNested()) return; } if (ntb.isZeroInit(e.loc)) { /* Zeros are implicitly convertible, except for special cases. */ if (auto tc = ntb.isTypeClass()) { /* With new() must look at the class instance initializer. */ ClassDeclaration cd = tc.sym; cd.size(e.loc); // resolve any forward references if (cd.isNested()) return; // uplevel reference may not be convertible assert(!cd.isInterfaceDeclaration()); struct ClassCheck { extern (C++) static bool convertible(Expression e, ClassDeclaration cd, MOD mod) { for (size_t i = 0; i < cd.fields.dim; i++) { VarDeclaration v = cd.fields[i]; Initializer _init = v._init; if (_init) { if (_init.isVoidInitializer()) { } else if (ExpInitializer ei = _init.isExpInitializer()) { // https://issues.dlang.org/show_bug.cgi?id=21319 // This is to prevent re-analyzing the same expression // over and over again. if (ei.exp == e) return false; Type tb = v.type.toBasetype(); if (implicitMod(ei.exp, tb, mod) == MATCH.nomatch) return false; } else { /* Enhancement: handle StructInitializer and ArrayInitializer */ return false; } } else if (!v.type.isZeroInit(e.loc)) return false; } return cd.baseClass ? convertible(e, cd.baseClass, mod) : true; } } if (!ClassCheck.convertible(e, cd, mod)) return; } } else { Expression earg = e.newtype.defaultInitLiteral(e.loc); Type targ = e.newtype.toBasetype(); if (implicitMod(earg, targ, mod) == MATCH.nomatch) return; } /* Success */ result = MATCH.constant; } override void visit(SliceExp e) { //printf("SliceExp::implicitConvTo e = %s, type = %s\n", e.toChars(), e.type.toChars()); visit(cast(Expression)e); if (result != MATCH.nomatch) return; Type tb = t.toBasetype(); Type typeb = e.type.toBasetype(); if (tb.ty == Tsarray && typeb.ty == Tarray) { typeb = toStaticArrayType(e); if (typeb) { // Try: T[] -> T[dim] // (Slice with compile-time known boundaries to static array) result = typeb.implicitConvTo(t); if (result > MATCH.convert) result = MATCH.convert; // match with implicit conversion at most } return; } /* If the only reason it won't convert is because of the mod bits, * then test for conversion by seeing if e1 can be converted with those * same mod bits. */ Type t1b = e.e1.type.toBasetype(); if (tb.ty == Tarray && typeb.equivalent(tb)) { Type tbn = tb.nextOf(); Type tx = null; /* If e.e1 is dynamic array or pointer, the uniqueness of e.e1 * is equivalent with the uniqueness of the referred data. And in here * we can have arbitrary typed reference for that. */ if (t1b.ty == Tarray) tx = tbn.arrayOf(); if (t1b.ty == Tpointer) tx = tbn.pointerTo(); /* If e.e1 is static array, at least it should be an rvalue. * If not, e.e1 is a reference, and its uniqueness does not link * to the uniqueness of the referred data. */ if (t1b.ty == Tsarray && !e.e1.isLvalue()) tx = tbn.sarrayOf(t1b.size() / tbn.size()); if (tx) { result = e.e1.implicitConvTo(tx); if (result > MATCH.constant) // Match level is MATCH.constant at best. result = MATCH.constant; } } // Enhancement 10724 if (tb.ty == Tpointer && e.e1.op == EXP.string_) e.e1.accept(this); } override void visit(TupleExp e) { result = e.type.implicitConvTo(t); if (result != MATCH.nomatch) return; /* If target type is a tuple of same length, test conversion of * each expression to the corresponding type in the tuple. */ TypeTuple totuple = t.isTypeTuple(); if (totuple && e.exps.length == totuple.arguments.length) { result = MATCH.exact; foreach (i, ex; *e.exps) { auto to = (*totuple.arguments)[i].type; MATCH mi = ex.implicitConvTo(to); if (mi < result) result = mi; } } } } scope ImplicitConvTo v = new ImplicitConvTo(t); e.accept(v); return v.result; } /** * Same as implicitConvTo(); except follow C11 rules, which are quite a bit * more permissive than D. * C11 6.3 and 6.5.16.1 * Params: * e = Expression that is to be casted * t = Expected resulting type * Returns: * The `MATCH` level between `e.type` and `t`. */ MATCH cimplicitConvTo(Expression e, Type t) { Type tb = t.toBasetype(); Type typeb = e.type.toBasetype(); if (tb.equals(typeb)) return MATCH.exact; if ((typeb.isintegral() || typeb.isfloating()) && (tb.isintegral() || tb.isfloating())) return MATCH.convert; if (tb.ty == Tpointer && typeb.isintegral()) // C11 6.3.2.3-5 return MATCH.convert; if (tb.isintegral() && typeb.ty == Tpointer) // C11 6.3.2.3-6 return MATCH.convert; if (tb.ty == Tpointer && typeb.ty == Tpointer) // C11 6.3.2.3-7 return MATCH.convert; return implicitConvTo(e, t); } /***************************************** */ Type toStaticArrayType(SliceExp e) { if (e.lwr && e.upr) { // For the following code to work, e should be optimized beforehand. // (eg. $ in lwr and upr should be already resolved, if possible) Expression lwr = e.lwr.optimize(WANTvalue); Expression upr = e.upr.optimize(WANTvalue); if (lwr.isConst() && upr.isConst()) { size_t len = cast(size_t)(upr.toUInteger() - lwr.toUInteger()); return e.type.toBasetype().nextOf().sarrayOf(len); } } else { Type t1b = e.e1.type.toBasetype(); if (t1b.ty == Tsarray) return t1b; } return null; } /************************************** * Do an explicit cast. * Assume that the expression `e` does not have any indirections. * (Parameter 'att' is used to stop 'alias this' recursion) */ Expression castTo(Expression e, Scope* sc, Type t, Type att = null) { extern (C++) final class CastTo : Visitor { alias visit = Visitor.visit; public: Type t; Scope* sc; Expression result; extern (D) this(Scope* sc, Type t) { this.sc = sc; this.t = t; } override void visit(Expression e) { //printf("Expression::castTo(this=%s, t=%s)\n", e.toChars(), t.toChars()); version (none) { printf("Expression::castTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars()); } if (e.type.equals(t)) { result = e; return; } if (auto ve = e.isVarExp()) { VarDeclaration v = ve.var.isVarDeclaration(); if (v && v.storage_class & STC.manifest) { result = e.ctfeInterpret(); /* https://issues.dlang.org/show_bug.cgi?id=18236 * * The expression returned by ctfeInterpret points * to the line where the manifest constant was declared * so we need to update the location before trying to cast */ result.loc = e.loc; result = result.castTo(sc, t); return; } } Type tob = t.toBasetype(); Type t1b = e.type.toBasetype(); if (tob.equals(t1b)) { result = e.copy(); // because of COW for assignment to e.type result.type = t; return; } /* Make semantic error against invalid cast between concrete types. * Assume that 'e' is never be any placeholder expressions. * The result of these checks should be consistent with CastExp::toElem(). */ // Fat Value types const(bool) tob_isFV = (tob.ty == Tstruct || tob.ty == Tsarray || tob.ty == Tvector); const(bool) t1b_isFV = (t1b.ty == Tstruct || t1b.ty == Tsarray || t1b.ty == Tvector); // Fat Reference types const(bool) tob_isFR = (tob.ty == Tarray || tob.ty == Tdelegate); const(bool) t1b_isFR = (t1b.ty == Tarray || t1b.ty == Tdelegate); // Reference types const(bool) tob_isR = (tob_isFR || tob.ty == Tpointer || tob.ty == Taarray || tob.ty == Tclass); const(bool) t1b_isR = (t1b_isFR || t1b.ty == Tpointer || t1b.ty == Taarray || t1b.ty == Tclass); // Arithmetic types (== valueable basic types) const(bool) tob_isA = ((tob.isintegral() || tob.isfloating()) && tob.ty != Tvector); const(bool) t1b_isA = ((t1b.isintegral() || t1b.isfloating()) && t1b.ty != Tvector); // Try casting the alias this member. // Return the expression if it succeeds, null otherwise. Expression tryAliasThisCast() { if (isRecursiveAliasThis(att, t1b)) return null; /* Forward the cast to our alias this member, rewrite to: * cast(to)e1.aliasthis */ auto exp = resolveAliasThis(sc, e); const errors = global.startGagging(); exp = castTo(exp, sc, t, att); return global.endGagging(errors) ? null : exp; } bool hasAliasThis; if (AggregateDeclaration t1ad = isAggregate(t1b)) { AggregateDeclaration toad = isAggregate(tob); if (t1ad != toad && t1ad.aliasthis) { if (t1b.ty == Tclass && tob.ty == Tclass) { ClassDeclaration t1cd = t1b.isClassHandle(); ClassDeclaration tocd = tob.isClassHandle(); int offset; if (tocd.isBaseOf(t1cd, &offset)) goto Lok; } hasAliasThis = true; } } else if (tob.ty == Tvector && t1b.ty != Tvector) { //printf("test1 e = %s, e.type = %s, tob = %s\n", e.toChars(), e.type.toChars(), tob.toChars()); TypeVector tv = tob.isTypeVector(); result = new CastExp(e.loc, e, tv.elementType()); result = new VectorExp(e.loc, result, tob); result = result.expressionSemantic(sc); return; } else if (tob.ty != Tvector && t1b.ty == Tvector) { // T[n] <-- __vector(U[m]) if (tob.ty == Tsarray) { if (t1b.size(e.loc) == tob.size(e.loc)) goto Lok; } goto Lfail; } else if (t1b.implicitConvTo(tob) == MATCH.constant && t.equals(e.type.constOf())) { result = e.copy(); result.type = t; return; } // arithmetic values vs. other arithmetic values // arithmetic values vs. T* if (tob_isA && (t1b_isA || t1b.ty == Tpointer) || t1b_isA && (tob_isA || tob.ty == Tpointer)) { goto Lok; } // arithmetic values vs. references or fat values if (tob_isA && (t1b_isR || t1b_isFV) || t1b_isA && (tob_isR || tob_isFV)) { goto Lfail; } // Bugzlla 3133: A cast between fat values is possible only when the sizes match. if (tob_isFV && t1b_isFV) { if (hasAliasThis) { result = tryAliasThisCast(); if (result) return; } if (t1b.size(e.loc) == tob.size(e.loc)) goto Lok; auto ts = toAutoQualChars(e.type, t); e.error("cannot cast expression `%s` of type `%s` to `%s` because of different sizes", e.toChars(), ts[0], ts[1]); result = ErrorExp.get(); return; } // Fat values vs. null or references if (tob_isFV && (t1b.ty == Tnull || t1b_isR) || t1b_isFV && (tob.ty == Tnull || tob_isR)) { if (tob.ty == Tpointer && t1b.ty == Tsarray) { // T[n] sa; // cast(U*)sa; // ==> cast(U*)sa.ptr; result = new AddrExp(e.loc, e, t); return; } if (tob.ty == Tarray && t1b.ty == Tsarray) { // T[n] sa; // cast(U[])sa; // ==> cast(U[])sa[]; if (global.params.useDIP1000 == FeatureState.enabled) { if (auto v = expToVariable(e)) { if (e.type.hasPointers() && !checkAddressVar(sc, e, v)) goto Lfail; } } const fsize = t1b.nextOf().size(); const tsize = tob.nextOf().size(); if (fsize == SIZE_INVALID || tsize == SIZE_INVALID) { result = ErrorExp.get(); return; } if (fsize != tsize) { const dim = t1b.isTypeSArray().dim.toInteger(); if (tsize == 0 || (dim * fsize) % tsize != 0) { e.error("cannot cast expression `%s` of type `%s` to `%s` since sizes don't line up", e.toChars(), e.type.toChars(), t.toChars()); result = ErrorExp.get(); return; } } goto Lok; } goto Lfail; } /* For references, any reinterpret casts are allowed to same 'ty' type. * T* to U* * R1 function(P1) to R2 function(P2) * R1 delegate(P1) to R2 delegate(P2) * T[] to U[] * V1[K1] to V2[K2] * class/interface A to B (will be a dynamic cast if possible) */ if (tob.ty == t1b.ty && tob_isR && t1b_isR) goto Lok; // typeof(null) <-- non-null references or values if (tob.ty == Tnull && t1b.ty != Tnull) goto Lfail; // https://issues.dlang.org/show_bug.cgi?id=14629 // typeof(null) --> non-null references or arithmetic values if (t1b.ty == Tnull && tob.ty != Tnull) goto Lok; // Check size mismatch of references. // Tarray and Tdelegate are (void*).sizeof*2, but others have (void*).sizeof. if (tob_isFR && t1b_isR || t1b_isFR && tob_isR) { if (tob.ty == Tpointer && t1b.ty == Tarray) { // T[] da; // cast(U*)da; // ==> cast(U*)da.ptr; goto Lok; } if (tob.ty == Tpointer && t1b.ty == Tdelegate) { // void delegate() dg; // cast(U*)dg; // ==> cast(U*)dg.ptr; // Note that it happens even when U is a Tfunction! e.deprecation("casting from %s to %s is deprecated", e.type.toChars(), t.toChars()); goto Lok; } goto Lfail; } if (t1b.ty == Tvoid && tob.ty != Tvoid) { Lfail: /* if the cast cannot be performed, maybe there is an alias * this that can be used for casting. */ if (hasAliasThis) { result = tryAliasThisCast(); if (result) return; } e.error("cannot cast expression `%s` of type `%s` to `%s`", e.toChars(), e.type.toChars(), t.toChars()); result = ErrorExp.get(); return; } Lok: result = new CastExp(e.loc, e, t); result.type = t; // Don't call semantic() //printf("Returning: %s\n", result.toChars()); } override void visit(ErrorExp e) { result = e; } override void visit(RealExp e) { if (!e.type.equals(t)) { if ((e.type.isreal() && t.isreal()) || (e.type.isimaginary() && t.isimaginary())) { result = e.copy(); result.type = t; } else visit(cast(Expression)e); return; } result = e; } override void visit(ComplexExp e) { if (!e.type.equals(t)) { if (e.type.iscomplex() && t.iscomplex()) { result = e.copy(); result.type = t; } else visit(cast(Expression)e); return; } result = e; } override void visit(StructLiteralExp e) { visit(cast(Expression)e); if (auto sle = result.isStructLiteralExp()) sle.stype = t; // commit type } override void visit(StringExp e) { /* This follows copy-on-write; any changes to 'this' * will result in a copy. * The this.string member is considered immutable. */ int copied = 0; //printf("StringExp::castTo(t = %s), '%s' committed = %d\n", t.toChars(), e.toChars(), e.committed); if (!e.committed && t.ty == Tpointer && t.nextOf().ty == Tvoid && (!sc || !(sc.flags & SCOPE.Cfile))) { e.error("cannot convert string literal to `void*`"); result = ErrorExp.get(); return; } StringExp se = e; void lcast() { result = new CastExp(e.loc, se, t); result.type = t; // so semantic() won't be run on e } if (!e.committed) { se = e.copy().isStringExp(); se.committed = 1; copied = 1; } if (e.type.equals(t)) { result = se; return; } Type tb = t.toBasetype(); Type typeb = e.type.toBasetype(); //printf("\ttype = %s\n", e.type.toChars()); if (tb.ty == Tdelegate && typeb.ty != Tdelegate) { visit(cast(Expression)e); return; } if (typeb.equals(tb)) { if (!copied) { se = e.copy().isStringExp(); copied = 1; } se.type = t; result = se; return; } /* Handle reinterpret casts: * cast(wchar[3])"abcd"c --> [\u6261, \u6463, \u0000] * cast(wchar[2])"abcd"c --> [\u6261, \u6463] * cast(wchar[1])"abcd"c --> [\u6261] * cast(char[4])"a" --> ['a', 0, 0, 0] */ if (e.committed && tb.ty == Tsarray && typeb.ty == Tarray) { se = e.copy().isStringExp(); d_uns64 szx = tb.nextOf().size(); assert(szx <= 255); se.sz = cast(ubyte)szx; se.len = cast(size_t)tb.isTypeSArray().dim.toInteger(); se.committed = 1; se.type = t; /* If larger than source, pad with zeros. */ const fullSize = (se.len + 1) * se.sz; // incl. terminating 0 if (fullSize > (e.len + 1) * e.sz) { void* s = mem.xmalloc(fullSize); const srcSize = e.len * e.sz; const data = se.peekData(); memcpy(s, data.ptr, srcSize); memset(s + srcSize, 0, fullSize - srcSize); se.setData(s, se.len, se.sz); } result = se; return; } if (tb.ty != Tsarray && tb.ty != Tarray && tb.ty != Tpointer) { if (!copied) { se = e.copy().isStringExp(); copied = 1; } return lcast(); } if (typeb.ty != Tsarray && typeb.ty != Tarray && typeb.ty != Tpointer) { if (!copied) { se = e.copy().isStringExp(); copied = 1; } return lcast(); } const nextSz = typeb.nextOf().size(); if (nextSz == SIZE_INVALID) { result = ErrorExp.get(); return; } if (nextSz == tb.nextOf().size()) { if (!copied) { se = e.copy().isStringExp(); copied = 1; } if (tb.ty == Tsarray) goto L2; // handle possible change in static array dimension se.type = t; result = se; return; } if (e.committed) goto Lcast; auto X(T, U)(T tf, U tt) { return (cast(int)tf * 256 + cast(int)tt); } { OutBuffer buffer; size_t newlen = 0; int tfty = typeb.nextOf().toBasetype().ty; int ttty = tb.nextOf().toBasetype().ty; switch (X(tfty, ttty)) { case X(Tchar, Tchar): case X(Twchar, Twchar): case X(Tdchar, Tdchar): break; case X(Tchar, Twchar): for (size_t u = 0; u < e.len;) { dchar c; if (const s = utf_decodeChar(se.peekString(), u, c)) e.error("%.*s", cast(int)s.length, s.ptr); else buffer.writeUTF16(c); } newlen = buffer.length / 2; buffer.writeUTF16(0); goto L1; case X(Tchar, Tdchar): for (size_t u = 0; u < e.len;) { dchar c; if (const s = utf_decodeChar(se.peekString(), u, c)) e.error("%.*s", cast(int)s.length, s.ptr); buffer.write4(c); newlen++; } buffer.write4(0); goto L1; case X(Twchar, Tchar): for (size_t u = 0; u < e.len;) { dchar c; if (const s = utf_decodeWchar(se.peekWstring(), u, c)) e.error("%.*s", cast(int)s.length, s.ptr); else buffer.writeUTF8(c); } newlen = buffer.length; buffer.writeUTF8(0); goto L1; case X(Twchar, Tdchar): for (size_t u = 0; u < e.len;) { dchar c; if (const s = utf_decodeWchar(se.peekWstring(), u, c)) e.error("%.*s", cast(int)s.length, s.ptr); buffer.write4(c); newlen++; } buffer.write4(0); goto L1; case X(Tdchar, Tchar): for (size_t u = 0; u < e.len; u++) { uint c = se.peekDstring()[u]; if (!utf_isValidDchar(c)) e.error("invalid UCS-32 char \\U%08x", c); else buffer.writeUTF8(c); newlen++; } newlen = buffer.length; buffer.writeUTF8(0); goto L1; case X(Tdchar, Twchar): for (size_t u = 0; u < e.len; u++) { uint c = se.peekDstring()[u]; if (!utf_isValidDchar(c)) e.error("invalid UCS-32 char \\U%08x", c); else buffer.writeUTF16(c); newlen++; } newlen = buffer.length / 2; buffer.writeUTF16(0); goto L1; L1: if (!copied) { se = e.copy().isStringExp(); copied = 1; } { d_uns64 szx = tb.nextOf().size(); assert(szx <= 255); se.setData(buffer.extractSlice().ptr, newlen, cast(ubyte)szx); } break; default: assert(typeb.nextOf().size() != tb.nextOf().size()); goto Lcast; } } L2: assert(copied); // See if need to truncate or extend the literal if (auto tsa = tb.isTypeSArray()) { size_t dim2 = cast(size_t)tsa.dim.toInteger(); //printf("dim from = %d, to = %d\n", (int)se.len, (int)dim2); // Changing dimensions if (dim2 != se.len) { // Copy when changing the string literal const newsz = se.sz; const d = (dim2 < se.len) ? dim2 : se.len; void* s = mem.xmalloc((dim2 + 1) * newsz); memcpy(s, se.peekData().ptr, d * newsz); // Extend with 0, add terminating 0 memset(s + d * newsz, 0, (dim2 + 1 - d) * newsz); se.setData(s, dim2, newsz); } } se.type = t; result = se; return; Lcast: result = new CastExp(e.loc, se, t); result.type = t; // so semantic() won't be run on e } override void visit(AddrExp e) { version (none) { printf("AddrExp::castTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars()); } result = e; Type tb = t.toBasetype(); Type typeb = e.type.toBasetype(); if (tb.equals(typeb)) { result = e.copy(); result.type = t; return; } // Look for pointers to functions where the functions are overloaded. if (e.e1.isOverExp() && (tb.ty == Tpointer || tb.ty == Tdelegate) && tb.nextOf().ty == Tfunction) { OverExp eo = e.e1.isOverExp(); FuncDeclaration f = null; for (size_t i = 0; i < eo.vars.a.dim; i++) { auto s = eo.vars.a[i]; auto f2 = s.isFuncDeclaration(); assert(f2); if (f2.overloadExactMatch(tb.nextOf())) { if (f) { /* Error if match in more than one overload set, * even if one is a 'better' match than the other. */ ScopeDsymbol.multiplyDefined(e.loc, f, f2); } else f = f2; } } if (f) { f.tookAddressOf++; auto se = new SymOffExp(e.loc, f, 0, false); auto se2 = se.expressionSemantic(sc); // Let SymOffExp::castTo() do the heavy lifting visit(se2); return; } } if (e.e1.isVarExp() && typeb.ty == Tpointer && typeb.nextOf().ty == Tfunction && tb.ty == Tpointer && tb.nextOf().ty == Tfunction) { auto ve = e.e1.isVarExp(); auto f = ve.var.isFuncDeclaration(); if (f) { assert(f.isImportedSymbol()); f = f.overloadExactMatch(tb.nextOf()); if (f) { result = new VarExp(e.loc, f, false); result.type = f.type; result = new AddrExp(e.loc, result, t); return; } } } if (auto f = isFuncAddress(e)) { if (f.checkForwardRef(e.loc)) { result = ErrorExp.get(); return; } } visit(cast(Expression)e); } override void visit(TupleExp e) { if (e.type.equals(t)) { result = e; return; } /* If target type is a tuple of same length, cast each expression to * the corresponding type in the tuple. */ TypeTuple totuple; if (auto tt = t.isTypeTuple()) totuple = e.exps.length == tt.arguments.length ? tt : null; TupleExp te = e.copy().isTupleExp(); te.e0 = e.e0 ? e.e0.copy() : null; te.exps = e.exps.copy(); for (size_t i = 0; i < te.exps.dim; i++) { Expression ex = (*te.exps)[i]; ex = ex.castTo(sc, totuple ? (*totuple.arguments)[i].type : t); (*te.exps)[i] = ex; } result = te; /* Questionable behavior: In here, result.type is not set to t. * Therefoe: * TypeTuple!(int, int) values; * auto values2 = cast(long)values; * // typeof(values2) == TypeTuple!(int, int) !! * * Only when the casted tuple is immediately expanded, it would work. * auto arr = [cast(long)values]; * // typeof(arr) == long[] */ } override void visit(ArrayLiteralExp e) { version (none) { printf("ArrayLiteralExp::castTo(this=%s, type=%s, => %s)\n", e.toChars(), e.type.toChars(), t.toChars()); } ArrayLiteralExp ae = e; Type tb = t.toBasetype(); if (tb.ty == Tarray && global.params.useDIP1000 == FeatureState.enabled) { if (checkArrayLiteralEscape(sc, ae, false)) { result = ErrorExp.get(); return; } } if (e.type == t) { result = e; return; } Type typeb = e.type.toBasetype(); if ((tb.ty == Tarray || tb.ty == Tsarray) && (typeb.ty == Tarray || typeb.ty == Tsarray)) { if (tb.nextOf().toBasetype().ty == Tvoid && typeb.nextOf().toBasetype().ty != Tvoid) { // Don't do anything to cast non-void[] to void[] } else if (typeb.ty == Tsarray && typeb.nextOf().toBasetype().ty == Tvoid) { // Don't do anything for casting void[n] to others } else { if (auto tsa = tb.isTypeSArray()) { if (e.elements.dim != tsa.dim.toInteger()) goto L1; } ae = e.copy().isArrayLiteralExp(); if (e.basis) ae.basis = e.basis.castTo(sc, tb.nextOf()); ae.elements = e.elements.copy(); for (size_t i = 0; i < e.elements.dim; i++) { Expression ex = (*e.elements)[i]; if (!ex) continue; ex = ex.castTo(sc, tb.nextOf()); (*ae.elements)[i] = ex; } ae.type = t; result = ae; return; } } else if (tb.ty == Tpointer && typeb.ty == Tsarray) { Type tp = typeb.nextOf().pointerTo(); if (!tp.equals(ae.type)) { ae = e.copy().isArrayLiteralExp(); ae.type = tp; } } else if (tb.ty == Tvector && (typeb.ty == Tarray || typeb.ty == Tsarray)) { // Convert array literal to vector type TypeVector tv = tb.isTypeVector(); TypeSArray tbase = tv.basetype.isTypeSArray(); assert(tbase.ty == Tsarray); const edim = e.elements.dim; const tbasedim = tbase.dim.toInteger(); if (edim > tbasedim) goto L1; ae = e.copy().isArrayLiteralExp(); ae.type = tbase; // https://issues.dlang.org/show_bug.cgi?id=12642 ae.elements = e.elements.copy(); Type telement = tv.elementType(); foreach (i; 0 .. edim) { Expression ex = (*e.elements)[i]; ex = ex.castTo(sc, telement); (*ae.elements)[i] = ex; } // Fill in the rest with the default initializer ae.elements.setDim(cast(size_t)tbasedim); foreach (i; edim .. cast(size_t)tbasedim) { Expression ex = typeb.nextOf.defaultInitLiteral(e.loc); ex = ex.castTo(sc, telement); (*ae.elements)[i] = ex; } Expression ev = new VectorExp(e.loc, ae, tb); ev = ev.expressionSemantic(sc); result = ev; return; } L1: visit(cast(Expression)ae); } override void visit(AssocArrayLiteralExp e) { //printf("AssocArrayLiteralExp::castTo(this=%s, type=%s, => %s)\n", e.toChars(), e.type.toChars(), t.toChars()); if (e.type == t) { result = e; return; } Type tb = t.toBasetype(); Type typeb = e.type.toBasetype(); if (tb.ty == Taarray && typeb.ty == Taarray && tb.nextOf().toBasetype().ty != Tvoid) { AssocArrayLiteralExp ae = e.copy().isAssocArrayLiteralExp(); ae.keys = e.keys.copy(); ae.values = e.values.copy(); assert(e.keys.dim == e.values.dim); for (size_t i = 0; i < e.keys.dim; i++) { Expression ex = (*e.values)[i]; ex = ex.castTo(sc, tb.nextOf()); (*ae.values)[i] = ex; ex = (*e.keys)[i]; ex = ex.castTo(sc, tb.isTypeAArray().index); (*ae.keys)[i] = ex; } ae.type = t; result = ae; return; } visit(cast(Expression)e); } override void visit(SymOffExp e) { version (none) { printf("SymOffExp::castTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars()); } if (e.type == t && !e.hasOverloads) { result = e; return; } Type tb = t.toBasetype(); Type typeb = e.type.toBasetype(); if (tb.equals(typeb)) { result = e.copy(); result.type = t; result.isSymOffExp().hasOverloads = false; return; } // Look for pointers to functions where the functions are overloaded. if (e.hasOverloads && typeb.ty == Tpointer && typeb.nextOf().ty == Tfunction && (tb.ty == Tpointer || tb.ty == Tdelegate) && tb.nextOf().ty == Tfunction) { FuncDeclaration f = e.var.isFuncDeclaration(); f = f ? f.overloadExactMatch(tb.nextOf()) : null; if (f) { if (tb.ty == Tdelegate) { if (f.needThis() && hasThis(sc)) { result = new DelegateExp(e.loc, new ThisExp(e.loc), f, false); result = result.expressionSemantic(sc); } else if (f.needThis()) { e.error("no `this` to create delegate for `%s`", f.toChars()); result = ErrorExp.get(); return; } else if (f.isNested()) { result = new DelegateExp(e.loc, IntegerExp.literal!0, f, false); result = result.expressionSemantic(sc); } else { e.error("cannot cast from function pointer to delegate"); result = ErrorExp.get(); return; } } else { result = new SymOffExp(e.loc, f, 0, false); result.type = t; } f.tookAddressOf++; return; } } if (auto f = isFuncAddress(e)) { if (f.checkForwardRef(e.loc)) { result = ErrorExp.get(); return; } } visit(cast(Expression)e); } override void visit(DelegateExp e) { version (none) { printf("DelegateExp::castTo(this=%s, type=%s, t=%s)\n", e.toChars(), e.type.toChars(), t.toChars()); } __gshared const(char)* msg = "cannot form delegate due to covariant return type"; Type tb = t.toBasetype(); Type typeb = e.type.toBasetype(); if (tb.equals(typeb) && !e.hasOverloads) { int offset; e.func.tookAddressOf++; if (e.func.tintro && e.func.tintro.nextOf().isBaseOf(e.func.type.nextOf(), &offset) && offset) e.error("%s", msg); result = e.copy(); result.type = t; return; } // Look for delegates to functions where the functions are overloaded. if (typeb.ty == Tdelegate && tb.ty == Tdelegate) { if (e.func) { auto f = e.func.overloadExactMatch(tb.nextOf()); if (f) { int offset; if (f.tintro && f.tintro.nextOf().isBaseOf(f.type.nextOf(), &offset) && offset) e.error("%s", msg); if (f != e.func) // if address not already marked as taken f.tookAddressOf++; result = new DelegateExp(e.loc, e.e1, f, false, e.vthis2); result.type = t; return; } if (e.func.tintro) e.error("%s", msg); } } if (auto f = isFuncAddress(e)) { if (f.checkForwardRef(e.loc)) { result = ErrorExp.get(); return; } } visit(cast(Expression)e); } override void visit(FuncExp e) { //printf("FuncExp::castTo type = %s, t = %s\n", e.type.toChars(), t.toChars()); FuncExp fe; if (e.matchType(t, sc, &fe, 1) > MATCH.nomatch) { result = fe; return; } visit(cast(Expression)e); } override void visit(CondExp e) { if (!e.type.equals(t)) { result = new CondExp(e.loc, e.econd, e.e1.castTo(sc, t), e.e2.castTo(sc, t)); result.type = t; return; } result = e; } override void visit(CommaExp e) { Expression e2c = e.e2.castTo(sc, t); if (e2c != e.e2) { result = new CommaExp(e.loc, e.e1, e2c); result.type = e2c.type; } else { result = e; result.type = e.e2.type; } } override void visit(SliceExp e) { //printf("SliceExp::castTo e = %s, type = %s, t = %s\n", e.toChars(), e.type.toChars(), t.toChars()); Type tb = t.toBasetype(); Type typeb = e.type.toBasetype(); if (e.type.equals(t) || typeb.ty != Tarray || (tb.ty != Tarray && tb.ty != Tsarray)) { visit(cast(Expression)e); return; } if (tb.ty == Tarray) { if (typeb.nextOf().equivalent(tb.nextOf())) { // T[] to const(T)[] result = e.copy(); result.type = t; } else { visit(cast(Expression)e); } return; } // Handle the cast from Tarray to Tsarray with CT-known slicing TypeSArray tsa = toStaticArrayType(e).isTypeSArray(); if (tsa && tsa.size(e.loc) == tb.size(e.loc)) { /* Match if the sarray sizes are equal: * T[a .. b] to const(T)[b-a] * T[a .. b] to U[dim] if (T.sizeof*(b-a) == U.sizeof*dim) * * If a SliceExp has Tsarray, it will become lvalue. * That's handled in SliceExp::isLvalue and toLvalue */ result = e.copy(); result.type = t; return; } if (tsa && tsa.dim.equals(tb.isTypeSArray().dim)) { /* Match if the dimensions are equal * with the implicit conversion of e.e1: * cast(float[2]) [2.0, 1.0, 0.0][0..2]; */ Type t1b = e.e1.type.toBasetype(); if (t1b.ty == Tsarray) t1b = tb.nextOf().sarrayOf(t1b.isTypeSArray().dim.toInteger()); else if (t1b.ty == Tarray) t1b = tb.nextOf().arrayOf(); else if (t1b.ty == Tpointer) t1b = tb.nextOf().pointerTo(); else assert(0); if (e.e1.implicitConvTo(t1b) > MATCH.nomatch) { Expression e1x = e.e1.implicitCastTo(sc, t1b); assert(e1x.op != EXP.error); e = e.copy().isSliceExp(); e.e1 = e1x; e.type = t; result = e; return; } } auto ts = toAutoQualChars(tsa ? tsa : e.type, t); e.error("cannot cast expression `%s` of type `%s` to `%s`", e.toChars(), ts[0], ts[1]); result = ErrorExp.get(); } } // Casting to noreturn isn't an actual cast // Rewrite cast(<qual> noreturn) <exp> // as <exp>, assert(false) if (t.isTypeNoreturn()) { // Don't generate an unreachable assert(false) if e will abort if (e.type.isTypeNoreturn()) { // Paint e to accomodate for different type qualifiers e.type = t; return e; } auto ini = t.defaultInitLiteral(e.loc); return Expression.combine(e, ini); } scope CastTo v = new CastTo(sc, t); e.accept(v); return v.result; } /**************************************** * Set type inference target * t Target type * flag 1: don't put an error when inference fails */ Expression inferType(Expression e, Type t, int flag = 0) { Expression visitAle(ArrayLiteralExp ale) { Type tb = t.toBasetype(); if (tb.ty == Tarray || tb.ty == Tsarray) { Type tn = tb.nextOf(); if (ale.basis) ale.basis = inferType(ale.basis, tn, flag); for (size_t i = 0; i < ale.elements.dim; i++) { if (Expression e = (*ale.elements)[i]) { e = inferType(e, tn, flag); (*ale.elements)[i] = e; } } } return ale; } Expression visitAar(AssocArrayLiteralExp aale) { Type tb = t.toBasetype(); if (auto taa = tb.isTypeAArray()) { Type ti = taa.index; Type tv = taa.nextOf(); for (size_t i = 0; i < aale.keys.dim; i++) { if (Expression e = (*aale.keys)[i]) { e = inferType(e, ti, flag); (*aale.keys)[i] = e; } } for (size_t i = 0; i < aale.values.dim; i++) { if (Expression e = (*aale.values)[i]) { e = inferType(e, tv, flag); (*aale.values)[i] = e; } } } return aale; } Expression visitFun(FuncExp fe) { //printf("FuncExp::inferType('%s'), to=%s\n", fe.type ? fe.type.toChars() : "null", t.toChars()); if (t.ty == Tdelegate || t.ty == Tpointer && t.nextOf().ty == Tfunction) { fe.fd.treq = t; } return fe; } Expression visitTer(CondExp ce) { Type tb = t.toBasetype(); ce.e1 = inferType(ce.e1, tb, flag); ce.e2 = inferType(ce.e2, tb, flag); return ce; } if (t) switch (e.op) { case EXP.arrayLiteral: return visitAle(e.isArrayLiteralExp()); case EXP.assocArrayLiteral: return visitAar(e.isAssocArrayLiteralExp()); case EXP.function_: return visitFun(e.isFuncExp()); case EXP.question: return visitTer(e.isCondExp()); default: } return e; } /**************************************** * Scale addition/subtraction to/from pointer. */ Expression scaleFactor(BinExp be, Scope* sc) { Type t1b = be.e1.type.toBasetype(); Type t2b = be.e2.type.toBasetype(); Expression eoff; if (t1b.ty == Tpointer && t2b.isintegral()) { // Need to adjust operator by the stride // Replace (ptr + int) with (ptr + (int * stride)) Type t = Type.tptrdiff_t; d_uns64 stride = t1b.nextOf().size(be.loc); if (!t.equals(t2b)) be.e2 = be.e2.castTo(sc, t); eoff = be.e2; be.e2 = new MulExp(be.loc, be.e2, new IntegerExp(Loc.initial, stride, t)); be.e2.type = t; be.type = be.e1.type; } else if (t2b.ty == Tpointer && t1b.isintegral()) { // Need to adjust operator by the stride // Replace (int + ptr) with (ptr + (int * stride)) Type t = Type.tptrdiff_t; Expression e; d_uns64 stride = t2b.nextOf().size(be.loc); if (!t.equals(t1b)) e = be.e1.castTo(sc, t); else e = be.e1; eoff = e; e = new MulExp(be.loc, e, new IntegerExp(Loc.initial, stride, t)); e.type = t; be.type = be.e2.type; be.e1 = be.e2; be.e2 = e; } else assert(0); if (sc.func && !sc.intypeof) { eoff = eoff.optimize(WANTvalue); if (eoff.op == EXP.int64 && eoff.toInteger() == 0) { } else if (sc.func.setUnsafe()) { be.error("pointer arithmetic not allowed in @safe functions"); return ErrorExp.get(); } } return be; } /************************************** * Return true if e is an empty array literal with dimensionality * equal to or less than type of other array. * [], [[]], [[[]]], etc. * I.e., make sure that [1,2] is compatible with [], * [[1,2]] is compatible with [[]], etc. */ private bool isVoidArrayLiteral(Expression e, Type other) { while (e.op == EXP.arrayLiteral && e.type.ty == Tarray && (e.isArrayLiteralExp().elements.dim == 1)) { auto ale = e.isArrayLiteralExp(); e = ale[0]; if (other.ty == Tsarray || other.ty == Tarray) other = other.nextOf(); else return false; } if (other.ty != Tsarray && other.ty != Tarray) return false; Type t = e.type; return (e.op == EXP.arrayLiteral && t.ty == Tarray && t.nextOf().ty == Tvoid && e.isArrayLiteralExp().elements.dim == 0); } /** * Merge types of `e1` and `e2` into a common subset * * Parameters `e1` and `e2` will be rewritten in place as needed. * * Params: * sc = Current scope * op = Operator such as `e1 op e2`. In practice, either EXP.question * or one of the binary operator. * pe1 = The LHS of the operation, will be rewritten * pe2 = The RHS of the operation, will be rewritten * * Returns: * The resulting type in case of success, `null` in case of error */ Type typeMerge(Scope* sc, EXP op, ref Expression pe1, ref Expression pe2) { //printf("typeMerge() %s op %s\n", e1.toChars(), e2.toChars()); Expression e1 = pe1; Expression e2 = pe2; // ImportC: do array/function conversions if (sc) { e1 = e1.arrayFuncConv(sc); e2 = e2.arrayFuncConv(sc); } Type Lret(Type result) { pe1 = e1; pe2 = e2; version (none) { printf("-typeMerge() %s op %s\n", e1.toChars(), e2.toChars()); if (e1.type) printf("\tt1 = %s\n", e1.type.toChars()); if (e2.type) printf("\tt2 = %s\n", e2.type.toChars()); printf("\ttype = %s\n", result.toChars()); } return result; } /// Converts one of the expression to the other Type convert(ref Expression from, Type to) { from = from.castTo(sc, to); return Lret(to); } /// Converts both expression to a third type Type coerce(Type towards) { e1 = e1.castTo(sc, towards); e2 = e2.castTo(sc, towards); return Lret(towards); } Type t1b = e1.type.toBasetype(); Type t2b = e2.type.toBasetype(); if (sc && sc.flags & SCOPE.Cfile) { // Integral types can be implicitly converted to pointers if ((t1b.ty == Tpointer) != (t2b.ty == Tpointer)) { if (t1b.isintegral()) { return convert(e1, t2b); } else if (t2b.isintegral()) { return convert(e2, t1b); } } } if (op != EXP.question || t1b.ty != t2b.ty && (t1b.isTypeBasic() && t2b.isTypeBasic())) { if (op == EXP.question && t1b.ty.isSomeChar() && t2b.ty.isSomeChar()) { e1 = e1.castTo(sc, Type.tdchar); e2 = e2.castTo(sc, Type.tdchar); } else { e1 = integralPromotions(e1, sc); e2 = integralPromotions(e2, sc); } } MATCH m; Type t1 = e1.type; Type t2 = e2.type; assert(t1); Type t = t1; /* The start type of alias this type recursion. * In following case, we should save A, and stop recursion * if it appears again. * X -> Y -> [A] -> B -> A -> B -> ... */ Type att1 = null; Type att2 = null; if (t1.mod != t2.mod && t1.ty == Tenum && t2.ty == Tenum && t1.isTypeEnum().sym == t2.isTypeEnum().sym) { ubyte mod = MODmerge(t1.mod, t2.mod); t1 = t1.castMod(mod); t2 = t2.castMod(mod); } Lagain: t1b = t1.toBasetype(); t2b = t2.toBasetype(); const ty = implicitConvCommonTy(t1b.ty, t2b.ty); if (ty != Terror) { const ty1 = implicitConvTy1(t1b.ty, t2b.ty); const ty2 = implicitConvTy1(t2b.ty, t1b.ty); if (t1b.ty == ty1) // if no promotions { if (t1.equals(t2)) return Lret(t1); if (t1b.equals(t2b)) return Lret(t1b); } t1 = Type.basic[ty1]; t2 = Type.basic[ty2]; e1 = e1.castTo(sc, t1); e2 = e2.castTo(sc, t2); return Lret(Type.basic[ty]); } t1 = t1b; t2 = t2b; if (t1.ty == Ttuple || t2.ty == Ttuple) return null; if (t1.equals(t2)) { // merging can not result in new enum type if (t.ty == Tenum) return Lret(t1b); return Lret(t); } if ((t1.ty == Tpointer && t2.ty == Tpointer) || (t1.ty == Tdelegate && t2.ty == Tdelegate)) { // Bring pointers to compatible type Type t1n = t1.nextOf(); Type t2n = t2.nextOf(); if (t1n.equals(t2n)) return Lret(t); if (t1n.ty == Tvoid) // pointers to void are always compatible return Lret(t2); if (t2n.ty == Tvoid) return Lret(t); if (t1.implicitConvTo(t2)) return convert(e1, t2); if (t2.implicitConvTo(t1)) return convert(e2, t1); if (t1n.ty == Tfunction && t2n.ty == Tfunction) { TypeFunction tf1 = t1n.isTypeFunction(); TypeFunction tf2 = t2n.isTypeFunction(); tf1.purityLevel(); tf2.purityLevel(); TypeFunction d = tf1.syntaxCopy(); if (tf1.purity != tf2.purity) d.purity = PURE.impure; assert(d.purity != PURE.fwdref); d.isnothrow = (tf1.isnothrow && tf2.isnothrow); d.isnogc = (tf1.isnogc && tf2.isnogc); if (tf1.trust == tf2.trust) d.trust = tf1.trust; else if (tf1.trust <= TRUST.system || tf2.trust <= TRUST.system) d.trust = TRUST.system; else d.trust = TRUST.trusted; Type tx = (t1.ty == Tdelegate) ? new TypeDelegate(d) : d.pointerTo(); tx = tx.typeSemantic(e1.loc, sc); if (t1.implicitConvTo(tx) && t2.implicitConvTo(tx)) return coerce(tx); return null; } if (t1n.mod != t2n.mod) { if (!t1n.isImmutable() && !t2n.isImmutable() && t1n.isShared() != t2n.isShared()) return null; ubyte mod = MODmerge(t1n.mod, t2n.mod); t1 = t1n.castMod(mod).pointerTo(); t2 = t2n.castMod(mod).pointerTo(); t = t1; goto Lagain; } if (t1n.ty == Tclass && t2n.ty == Tclass) { ClassDeclaration cd1 = t1n.isClassHandle(); ClassDeclaration cd2 = t2n.isClassHandle(); int offset; if (cd1.isBaseOf(cd2, &offset)) { if (offset) e2 = e2.castTo(sc, t); return Lret(t); } if (cd2.isBaseOf(cd1, &offset)) { if (offset) e1 = e1.castTo(sc, t2); return Lret(t2); } return null; } t1 = t1n.constOf().pointerTo(); t2 = t2n.constOf().pointerTo(); if (t1.implicitConvTo(t2)) return convert(e1, t2); if (t2.implicitConvTo(t1)) return convert(e2, t1); return null; } if ((t1.ty == Tsarray || t1.ty == Tarray) && (e2.op == EXP.null_ && t2.ty == Tpointer && t2.nextOf().ty == Tvoid || e2.op == EXP.arrayLiteral && t2.ty == Tsarray && t2.nextOf().ty == Tvoid && t2.isTypeSArray().dim.toInteger() == 0 || isVoidArrayLiteral(e2, t1))) { /* (T[n] op void*) => T[] * (T[] op void*) => T[] * (T[n] op void[0]) => T[] * (T[] op void[0]) => T[] * (T[n] op void[]) => T[] * (T[] op void[]) => T[] */ return coerce(t1.nextOf().arrayOf()); } if ((t2.ty == Tsarray || t2.ty == Tarray) && (e1.op == EXP.null_ && t1.ty == Tpointer && t1.nextOf().ty == Tvoid || e1.op == EXP.arrayLiteral && t1.ty == Tsarray && t1.nextOf().ty == Tvoid && t1.isTypeSArray().dim.toInteger() == 0 || isVoidArrayLiteral(e1, t2))) { /* (void* op T[n]) => T[] * (void* op T[]) => T[] * (void[0] op T[n]) => T[] * (void[0] op T[]) => T[] * (void[] op T[n]) => T[] * (void[] op T[]) => T[] */ return coerce(t2.nextOf().arrayOf()); } if ((t1.ty == Tsarray || t1.ty == Tarray) && (m = t1.implicitConvTo(t2)) != MATCH.nomatch) { // https://issues.dlang.org/show_bug.cgi?id=7285 // Tsarray op [x, y, ...] should to be Tsarray // https://issues.dlang.org/show_bug.cgi?id=14737 // Tsarray ~ [x, y, ...] should to be Tarray if (t1.ty == Tsarray && e2.op == EXP.arrayLiteral && op != EXP.concatenate) return convert(e2, t1); if (m == MATCH.constant && (op == EXP.addAssign || op == EXP.minAssign || op == EXP.mulAssign || op == EXP.divAssign || op == EXP.modAssign || op == EXP.powAssign || op == EXP.andAssign || op == EXP.orAssign || op == EXP.xorAssign)) { // Don't make the lvalue const return Lret(t2); } return convert(e1, t2); } if ((t2.ty == Tsarray || t2.ty == Tarray) && t2.implicitConvTo(t1)) { // https://issues.dlang.org/show_bug.cgi?id=7285 // https://issues.dlang.org/show_bug.cgi?id=14737 if (t2.ty == Tsarray && e1.op == EXP.arrayLiteral && op != EXP.concatenate) return convert(e1, t2); return convert(e2, t1); } if ((t1.ty == Tsarray || t1.ty == Tarray || t1.ty == Tpointer) && (t2.ty == Tsarray || t2.ty == Tarray || t2.ty == Tpointer) && t1.nextOf().mod != t2.nextOf().mod) { /* If one is mutable and the other immutable, then retry * with both of them as const */ Type t1n = t1.nextOf(); Type t2n = t2.nextOf(); ubyte mod; if (e1.op == EXP.null_ && e2.op != EXP.null_) mod = t2n.mod; else if (e1.op != EXP.null_ && e2.op == EXP.null_) mod = t1n.mod; else if (!t1n.isImmutable() && !t2n.isImmutable() && t1n.isShared() != t2n.isShared()) return null; else mod = MODmerge(t1n.mod, t2n.mod); if (t1.ty == Tpointer) t1 = t1n.castMod(mod).pointerTo(); else t1 = t1n.castMod(mod).arrayOf(); if (t2.ty == Tpointer) t2 = t2n.castMod(mod).pointerTo(); else t2 = t2n.castMod(mod).arrayOf(); t = t1; goto Lagain; } if (t1.ty == Tclass && t2.ty == Tclass) { if (t1.mod != t2.mod) { ubyte mod; if (e1.op == EXP.null_ && e2.op != EXP.null_) mod = t2.mod; else if (e1.op != EXP.null_ && e2.op == EXP.null_) mod = t1.mod; else if (!t1.isImmutable() && !t2.isImmutable() && t1.isShared() != t2.isShared()) return null; else mod = MODmerge(t1.mod, t2.mod); t1 = t1.castMod(mod); t2 = t2.castMod(mod); t = t1; goto Lagain; } goto Lcc; } if (t1.ty == Tclass || t2.ty == Tclass) { Lcc: while (1) { MATCH i1woat = MATCH.exact; MATCH i2woat = MATCH.exact; if (auto t2c = t2.isTypeClass()) i1woat = t2c.implicitConvToWithoutAliasThis(t1); if (auto t1c = t1.isTypeClass()) i2woat = t1c.implicitConvToWithoutAliasThis(t2); MATCH i1 = e2.implicitConvTo(t1); MATCH i2 = e1.implicitConvTo(t2); if (i1 && i2) { // We have the case of class vs. void*, so pick class if (t1.ty == Tpointer) i1 = MATCH.nomatch; else if (t2.ty == Tpointer) i2 = MATCH.nomatch; } // Match but without 'alias this' on classes if (i2 && i2woat) return coerce(t2); if (i1 && i1woat) return coerce(t1); // Here use implicitCastTo() instead of castTo() to try 'alias this' on classes Type coerceImplicit(Type towards) { e1 = e1.implicitCastTo(sc, towards); e2 = e2.implicitCastTo(sc, towards); return Lret(towards); } // Implicit conversion with 'alias this' if (i2) return coerceImplicit(t2); if (i1) return coerceImplicit(t1); if (t1.ty == Tclass && t2.ty == Tclass) { TypeClass tc1 = t1.isTypeClass(); TypeClass tc2 = t2.isTypeClass(); /* Pick 'tightest' type */ ClassDeclaration cd1 = tc1.sym.baseClass; ClassDeclaration cd2 = tc2.sym.baseClass; if (cd1 && cd2) { t1 = cd1.type.castMod(t1.mod); t2 = cd2.type.castMod(t2.mod); } else if (cd1) t1 = cd1.type; else if (cd2) t2 = cd2.type; else return null; } else if (t1.ty == Tstruct && t1.isTypeStruct().sym.aliasthis) { if (isRecursiveAliasThis(att1, e1.type)) return null; //printf("att tmerge(c || c) e1 = %s\n", e1.type.toChars()); e1 = resolveAliasThis(sc, e1); t1 = e1.type; continue; } else if (t2.ty == Tstruct && t2.isTypeStruct().sym.aliasthis) { if (isRecursiveAliasThis(att2, e2.type)) return null; //printf("att tmerge(c || c) e2 = %s\n", e2.type.toChars()); e2 = resolveAliasThis(sc, e2); t2 = e2.type; continue; } else return null; } } if (t1.ty == Tstruct && t2.ty == Tstruct) { if (t1.mod != t2.mod) { if (!t1.isImmutable() && !t2.isImmutable() && t1.isShared() != t2.isShared()) return null; ubyte mod = MODmerge(t1.mod, t2.mod); t1 = t1.castMod(mod); t2 = t2.castMod(mod); t = t1; goto Lagain; } TypeStruct ts1 = t1.isTypeStruct(); TypeStruct ts2 = t2.isTypeStruct(); if (ts1.sym != ts2.sym) { if (!ts1.sym.aliasthis && !ts2.sym.aliasthis) return null; MATCH i1 = MATCH.nomatch; MATCH i2 = MATCH.nomatch; Expression e1b = null; Expression e2b = null; if (ts2.sym.aliasthis) { if (isRecursiveAliasThis(att2, e2.type)) return null; //printf("att tmerge(s && s) e2 = %s\n", e2.type.toChars()); e2b = resolveAliasThis(sc, e2); i1 = e2b.implicitConvTo(t1); } if (ts1.sym.aliasthis) { if (isRecursiveAliasThis(att1, e1.type)) return null; //printf("att tmerge(s && s) e1 = %s\n", e1.type.toChars()); e1b = resolveAliasThis(sc, e1); i2 = e1b.implicitConvTo(t2); } if (i1 && i2) return null; if (i1) return convert(e2, t1); if (i2) return convert(e1, t2); if (e1b) { e1 = e1b; t1 = e1b.type.toBasetype(); } if (e2b) { e2 = e2b; t2 = e2b.type.toBasetype(); } t = t1; goto Lagain; } } if (t1.ty == Tstruct && t1.isTypeStruct().sym.aliasthis) { if (isRecursiveAliasThis(att1, e1.type)) return null; //printf("att tmerge(s || s) e1 = %s\n", e1.type.toChars()); e1 = resolveAliasThis(sc, e1); t1 = e1.type; t = t1; goto Lagain; } if (t2.ty == Tstruct && t2.isTypeStruct().sym.aliasthis) { if (isRecursiveAliasThis(att2, e2.type)) return null; //printf("att tmerge(s || s) e2 = %s\n", e2.type.toChars()); e2 = resolveAliasThis(sc, e2); t2 = e2.type; t = t2; goto Lagain; } if ((e1.op == EXP.string_ || e1.op == EXP.null_) && e1.implicitConvTo(t2)) return convert(e1, t2); if ((e2.op == EXP.string_ || e2.op == EXP.null_) && e2.implicitConvTo(t1)) return convert(e2, t1); if (t1.ty == Tsarray && t2.ty == Tsarray && e2.implicitConvTo(t1.nextOf().arrayOf())) return coerce(t1.nextOf().arrayOf()); if (t1.ty == Tsarray && t2.ty == Tsarray && e1.implicitConvTo(t2.nextOf().arrayOf())) return coerce(t2.nextOf().arrayOf()); if (t1.ty == Tvector && t2.ty == Tvector) { // https://issues.dlang.org/show_bug.cgi?id=13841 // all vector types should have no common types between // different vectors, even though their sizes are same. auto tv1 = t1.isTypeVector(); auto tv2 = t2.isTypeVector(); if (!tv1.basetype.equals(tv2.basetype)) return null; goto LmodCompare; } if (t1.ty == Tvector && t2.ty != Tvector && e2.implicitConvTo(t1)) { e2 = e2.castTo(sc, t1); t2 = t1; t = t1; goto Lagain; } if (t2.ty == Tvector && t1.ty != Tvector && e1.implicitConvTo(t2)) { e1 = e1.castTo(sc, t2); t1 = t2; t = t1; goto Lagain; } if (t1.isintegral() && t2.isintegral()) { if (t1.ty != t2.ty) { if (t1.ty == Tvector || t2.ty == Tvector) return null; e1 = integralPromotions(e1, sc); e2 = integralPromotions(e2, sc); t1 = e1.type; t2 = e2.type; goto Lagain; } assert(t1.ty == t2.ty); LmodCompare: if (!t1.isImmutable() && !t2.isImmutable() && t1.isShared() != t2.isShared()) return null; ubyte mod = MODmerge(t1.mod, t2.mod); t1 = t1.castMod(mod); t2 = t2.castMod(mod); t = t1; e1 = e1.castTo(sc, t); e2 = e2.castTo(sc, t); goto Lagain; } if (t1.ty == Tnull && t2.ty == Tnull) { ubyte mod = MODmerge(t1.mod, t2.mod); return coerce(t1.castMod(mod)); } if (t2.ty == Tnull && (t1.ty == Tpointer || t1.ty == Taarray || t1.ty == Tarray)) return convert(e2, t1); if (t1.ty == Tnull && (t2.ty == Tpointer || t2.ty == Taarray || t2.ty == Tarray)) return convert(e1, t2); /// Covers array operations for user-defined types Type checkArrayOpType(Expression e1, Expression e2, EXP op, Scope *sc) { // scalar op scalar - we shouldn't be here if (e1.type.ty != Tarray && e1.type.ty != Tsarray && e2.type.ty != Tarray && e2.type.ty != Tsarray) return null; // only supporting slices and array literals if (!e1.isSliceExp() && !e1.isArrayLiteralExp() && !e2.isSliceExp() && !e2.isArrayLiteralExp()) return null; // start with e1 op e2 and if either one of e1 or e2 is a slice or array literal, // replace it with the first element of the array Expression lhs = e1; Expression rhs = e2; // T[x .. y] op ? if (auto se1 = e1.isSliceExp()) lhs = new IndexExp(Loc.initial, se1.e1, IntegerExp.literal!0); // [t1, t2, .. t3] op ? if (auto ale1 = e1.isArrayLiteralExp()) lhs = ale1.opIndex(0); // ? op U[z .. t] if (auto se2 = e2.isSliceExp()) rhs = new IndexExp(Loc.initial, se2.e1, IntegerExp.literal!0); // ? op [u1, u2, .. u3] if (auto ale2 = e2.isArrayLiteralExp()) rhs = ale2.opIndex(0); // create a new binary expression with the new lhs and rhs (at this stage, at least // one of lhs/rhs has been replaced with the 0'th element of the array it was before) Expression exp; switch (op) { case EXP.add: exp = new AddExp(Loc.initial, lhs, rhs); break; case EXP.min: exp = new MinExp(Loc.initial, lhs, rhs); break; case EXP.mul: exp = new MulExp(Loc.initial, lhs, rhs); break; case EXP.div: exp = new DivExp(Loc.initial, lhs, rhs); break; case EXP.pow: exp = new PowExp(Loc.initial, lhs, rhs); break; default: exp = null; } if (exp) { // if T op U is valid and has type V // then T[] op U and T op U[] should be valid and have type V[] Expression e = exp.trySemantic(sc); if (e && e.type) return e.type.arrayOf; } return null; } if (t1.ty == Tarray && isBinArrayOp(op) && isArrayOpOperand(e1)) { if (e2.implicitConvTo(t1.nextOf())) { // T[] op T // T[] op cast(T)U e2 = e2.castTo(sc, t1.nextOf()); return Lret(t1.nextOf().arrayOf()); } if (t1.nextOf().implicitConvTo(e2.type)) { // (cast(T)U)[] op T (https://issues.dlang.org/show_bug.cgi?id=12780) // e1 is left as U[], it will be handled in arrayOp() later. return Lret(e2.type.arrayOf()); } if (t2.ty == Tarray && isArrayOpOperand(e2)) { if (t1.nextOf().implicitConvTo(t2.nextOf())) { // (cast(T)U)[] op T[] (https://issues.dlang.org/show_bug.cgi?id=12780) t = t2.nextOf().arrayOf(); // if cast won't be handled in arrayOp() later if (!isArrayOpImplicitCast(t1.isTypeDArray(), t2.isTypeDArray())) e1 = e1.castTo(sc, t); return Lret(t); } if (t2.nextOf().implicitConvTo(t1.nextOf())) { // T[] op (cast(T)U)[] (https://issues.dlang.org/show_bug.cgi?id=12780) // e2 is left as U[], it will be handled in arrayOp() later. t = t1.nextOf().arrayOf(); // if cast won't be handled in arrayOp() later if (!isArrayOpImplicitCast(t2.isTypeDArray(), t1.isTypeDArray())) e2 = e2.castTo(sc, t); return Lret(t); } } t = checkArrayOpType(e1, e2, op, sc); if (t !is null) return Lret(t); return null; } else if (t2.ty == Tarray && isBinArrayOp(op) && isArrayOpOperand(e2)) { if (e1.implicitConvTo(t2.nextOf())) { // T op T[] // cast(T)U op T[] e1 = e1.castTo(sc, t2.nextOf()); t = t2.nextOf().arrayOf(); } else if (t2.nextOf().implicitConvTo(e1.type)) { // T op (cast(T)U)[] (https://issues.dlang.org/show_bug.cgi?id=12780) // e2 is left as U[], it will be handled in arrayOp() later. t = e1.type.arrayOf(); } else { t = checkArrayOpType(e1, e2, op, sc); if (t is null) return null; } //printf("test %s\n", EXPtoString(op).ptr); e1 = e1.optimize(WANTvalue); if (isCommutative(op) && e1.isConst()) { /* Swap operands to minimize number of functions generated */ //printf("swap %s\n", EXPtoString(op).ptr); Expression tmp = e1; e1 = e2; e2 = tmp; } return Lret(t); } return null; } /************************************ * Bring leaves to common type. * Returns: * null on success, ErrorExp if error occurs */ Expression typeCombine(BinExp be, Scope* sc) { Expression errorReturn() { Expression ex = be.incompatibleTypes(); if (ex.op == EXP.error) return ex; return ErrorExp.get(); } Type t1 = be.e1.type.toBasetype(); Type t2 = be.e2.type.toBasetype(); if (be.op == EXP.min || be.op == EXP.add) { // struct+struct, and class+class are errors if (t1.ty == Tstruct && t2.ty == Tstruct) return errorReturn(); else if (t1.ty == Tclass && t2.ty == Tclass) return errorReturn(); else if (t1.ty == Taarray && t2.ty == Taarray) return errorReturn(); } if (auto result = typeMerge(sc, be.op, be.e1, be.e2)) { if (be.type is null) be.type = result; } else return errorReturn(); // If the types have no value, return an error if (be.e1.op == EXP.error) return be.e1; if (be.e2.op == EXP.error) return be.e2; return null; } /*********************************** * Do integral promotions (convertchk). * Don't convert <array of> to <pointer to> */ Expression integralPromotions(Expression e, Scope* sc) { //printf("integralPromotions %s %s\n", e.toChars(), e.type.toChars()); switch (e.type.toBasetype().ty) { case Tvoid: e.error("void has no value"); return ErrorExp.get(); case Tint8: case Tuns8: case Tint16: case Tuns16: case Tbool: case Tchar: case Twchar: e = e.castTo(sc, Type.tint32); break; case Tdchar: e = e.castTo(sc, Type.tuns32); break; default: break; } return e; } /****************************************************** * This provides a transition from the non-promoting behavior * of unary + - ~ to the C-like integral promotion behavior. * Params: * sc = context * ue = NegExp, UAddExp, or ComExp which is revised per rules * References: * https://issues.dlang.org/show_bug.cgi?id=16997 */ void fix16997(Scope* sc, UnaExp ue) { if (global.params.fix16997 || sc.flags & SCOPE.Cfile) ue.e1 = integralPromotions(ue.e1, sc); // desired C-like behavor else { switch (ue.e1.type.toBasetype.ty) { case Tint8: case Tuns8: case Tint16: case Tuns16: //case Tbool: // these operations aren't allowed on bool anyway case Tchar: case Twchar: case Tdchar: ue.deprecation("integral promotion not done for `%s`, remove '-revert=intpromote' switch or `%scast(int)(%s)`", ue.toChars(), EXPtoString(ue.op).ptr, ue.e1.toChars()); break; default: break; } } } /*********************************** * See if both types are arrays that can be compared * for equality without any casting. Return true if so. * This is to enable comparing things like an immutable * array with a mutable one. */ extern (C++) bool arrayTypeCompatibleWithoutCasting(Type t1, Type t2) { t1 = t1.toBasetype(); t2 = t2.toBasetype(); if ((t1.ty == Tarray || t1.ty == Tsarray || t1.ty == Tpointer) && t2.ty == t1.ty) { if (t1.nextOf().implicitConvTo(t2.nextOf()) >= MATCH.constant || t2.nextOf().implicitConvTo(t1.nextOf()) >= MATCH.constant) return true; } return false; } /******************************************************************/ /* Determine the integral ranges of an expression. * This is used to determine if implicit narrowing conversions will * be allowed. */ IntRange getIntRange(Expression e) { extern (C++) final class IntRangeVisitor : Visitor { alias visit = Visitor.visit; public: IntRange range; override void visit(Expression e) { range = IntRange.fromType(e.type); } override void visit(IntegerExp e) { range = IntRange(SignExtendedNumber(e.getInteger()))._cast(e.type); } override void visit(CastExp e) { range = getIntRange(e.e1)._cast(e.type); } override void visit(AddExp e) { IntRange ir1 = getIntRange(e.e1); IntRange ir2 = getIntRange(e.e2); range = (ir1 + ir2)._cast(e.type); } override void visit(MinExp e) { IntRange ir1 = getIntRange(e.e1); IntRange ir2 = getIntRange(e.e2); range = (ir1 - ir2)._cast(e.type); } override void visit(DivExp e) { IntRange ir1 = getIntRange(e.e1); IntRange ir2 = getIntRange(e.e2); range = (ir1 / ir2)._cast(e.type); } override void visit(MulExp e) { IntRange ir1 = getIntRange(e.e1); IntRange ir2 = getIntRange(e.e2); range = (ir1 * ir2)._cast(e.type); } override void visit(ModExp e) { IntRange ir1 = getIntRange(e.e1); IntRange ir2 = getIntRange(e.e2); // Modding on 0 is invalid anyway. if (!ir2.absNeg().imin.negative) { visit(cast(Expression)e); return; } range = (ir1 % ir2)._cast(e.type); } override void visit(AndExp e) { IntRange result; bool hasResult = false; result.unionOrAssign(getIntRange(e.e1) & getIntRange(e.e2), hasResult); assert(hasResult); range = result._cast(e.type); } override void visit(OrExp e) { IntRange result; bool hasResult = false; result.unionOrAssign(getIntRange(e.e1) | getIntRange(e.e2), hasResult); assert(hasResult); range = result._cast(e.type); } override void visit(XorExp e) { IntRange result; bool hasResult = false; result.unionOrAssign(getIntRange(e.e1) ^ getIntRange(e.e2), hasResult); assert(hasResult); range = result._cast(e.type); } override void visit(ShlExp e) { IntRange ir1 = getIntRange(e.e1); IntRange ir2 = getIntRange(e.e2); range = (ir1 << ir2)._cast(e.type); } override void visit(ShrExp e) { IntRange ir1 = getIntRange(e.e1); IntRange ir2 = getIntRange(e.e2); range = (ir1 >> ir2)._cast(e.type); } override void visit(UshrExp e) { IntRange ir1 = getIntRange(e.e1).castUnsigned(e.e1.type); IntRange ir2 = getIntRange(e.e2); range = (ir1 >>> ir2)._cast(e.type); } override void visit(AssignExp e) { range = getIntRange(e.e2)._cast(e.type); } override void visit(CondExp e) { // No need to check e.econd; assume caller has called optimize() IntRange ir1 = getIntRange(e.e1); IntRange ir2 = getIntRange(e.e2); range = ir1.unionWith(ir2)._cast(e.type); } override void visit(VarExp e) { Expression ie; VarDeclaration vd = e.var.isVarDeclaration(); if (vd && vd.range) range = vd.range._cast(e.type); else if (vd && vd._init && !vd.type.isMutable() && (ie = vd.getConstInitializer()) !is null) ie.accept(this); else visit(cast(Expression)e); } override void visit(CommaExp e) { e.e2.accept(this); } override void visit(ComExp e) { IntRange ir = getIntRange(e.e1); range = IntRange(SignExtendedNumber(~ir.imax.value, !ir.imax.negative), SignExtendedNumber(~ir.imin.value, !ir.imin.negative))._cast(e.type); } override void visit(NegExp e) { IntRange ir = getIntRange(e.e1); range = (-ir)._cast(e.type); } } scope IntRangeVisitor v = new IntRangeVisitor(); e.accept(v); return v.range; }
D
/** Author: Logan Freesh Date: 2017.1.18 */ module and.learning.backprop_mod_reinforcement; private import and.learning.model.ilearning; private import and.learning.backprop; private import and.network.neuralnetwork; private import and.network.layer; private import and.network.neuron; private import and.platform; private import and.util; private import and.cost.model.icostfunction; /** This is a learning function that preforms a modfied version of Reinforcement Learning. This version has multiple output neurons, each representing the projected reward some time in the future after making the choice corresponding to that output neuron. We train the network ex-post-facto, so we don't have to use Temporal Difference learning to guess at the actual reward. We train only the output neuron that was selected (as that action was actually taken and we have the real value to compare to our projection). */ class ModifiedReinforcementBackPropagation : BackPropagation { this ( NeuralNetwork n , CostFunction c) { super(n, c); } static const real error_clamp = 5.0; void backPropogate(real [] inputs, real expected, int output_neuron_num) { //write( output_neuron_num, " "); // calculate the output layer errors first foreach ( int i , /+inout+/ Neuron no; neuralNetwork.output.neurons ) { if(i == output_neuron_num) { no.error = ( expected - no.value ) * neuralNetwork.output.activationFunction.fDerivative(no.value ); if (isNaN(no.error) ) { writefln("actual: %f, predicted: %f, deriv: %f, epoch: %d",expected, no.value, neuralNetwork.output.activationFunction.fDerivative(no.value ), actualEpochs); } // head off some ReLU nonsense if (no.error > error_clamp) no.error = error_clamp; if (no.error < -error_clamp) no.error = -error_clamp; //debug /+ if(neuralNetwork.output.activationFunction.fDerivative(no.value ) < 0.01) { writefln("expected is: %f, val is %f, derivative is %f",expected,no.value, neuralNetwork.output.activationFunction.fDerivative(no.value )); } +/ } else { no.error = 0.0; } /+++/assert(!isNaN(no.error)); } //now calculate error for all hidden layers Layer operatingLayer; int lastHiddenLayer = neuralNetwork.hidden.length - 1; for ( int currentHiddenLayer = lastHiddenLayer; currentHiddenLayer >= 0;currentHiddenLayer-- ) { if ( currentHiddenLayer == lastHiddenLayer ) operatingLayer = neuralNetwork.output; else operatingLayer = neuralNetwork.hidden[currentHiddenLayer+1]; foreach ( int currentSynapse, /+inout+/ Neuron nh;neuralNetwork.hidden[currentHiddenLayer].neurons) { nh.error = 0; foreach ( int currentNeuron , Neuron nhInner;operatingLayer.neurons ) { nh.error += nhInner.error * nhInner.synapses[currentSynapse]; if (isNaN(nh.error) ) { writefln("error is NaN. next layer error: %s, synapse val: %s", to!string(nhInner.error), to!string(nhInner.synapses[currentSynapse])); } /+++/assert(!isNaN(nh.error)); if (nh.error > error_clamp) nh.error = error_clamp; if (nh.error < -error_clamp) nh.error = -error_clamp; } nh.error *= operatingLayer.activationFunction.fDerivative(nh.value ); /+++/assert(!isNaN(nh.error)); } } updateWeights(inputs); } /** Parameters: 2d array of inputs, 2d array of expected outputs This will loop through all the inputs you give it for NeuralNetwork.epochs ( 10,000 by default ) or until the error limit is reached. */ void train (real [] [] inputs , real [] expectedOutputs, int [] output_neuron_numbers, int depth = 0 ) { assert(inputs.length ); assert(expectedOutputs.length ); assert(inputs.length == expectedOutputs.length ); assert(inputs[0].length == neuralNetwork.input.neurons.length ); // holds the records that are beyond the error threshold. real [][] problem_inputs = []; real [] problem_expected = []; int [] problem_neuron_outputs = []; actualEpochs = 0; int patternCount = 0; real error = 0; real total_abs_error = 0; int last_problem_count = 0; real last_error = 0.0; real largest_error = 0.0; real last_largest_error = 0.0; real expected = 0; //experimental value real actual = 0; // what we calculated from the NN bool write_progress = true; while ( 1 ) { error = 0; feedForward(inputs[patternCount] ); backPropogate(inputs[patternCount],expectedOutputs[patternCount], output_neuron_numbers[patternCount] ); const bool train_on_problem_inputs = false; /+real [] actual; foreach ( int nCount, Neuron no;neuralNetwork.output.neurons) { actual ~= no.value; //error += (expectedOutputs[patternCount][nCount] - no.value ) * (expectedOutputs[patternCount][nCount] - no.value ); } error = costFunction.f(expectedOutputs[patternCount],actual ); /+++/assert(!isNaN(error)); +/ expected = expectedOutputs[patternCount]; actual = neuralNetwork.output.neurons[output_neuron_numbers[patternCount]].value; error = expected - actual; total_abs_error += abs(error); if (abs(error) > largest_error) largest_error = abs(error); if(train_on_problem_inputs && abs(error) > errorThreshold) { problem_inputs ~= inputs[patternCount]; problem_expected ~= expectedOutputs[patternCount]; problem_neuron_outputs ~= output_neuron_numbers[patternCount]; } patternCount++; debug { writef("Iterations [ %d ] Error [ ",actualEpochs ); for ( int i = 0 ; i < neuralNetwork.output.neurons.length; i++ ) { writef(" %s ",to!string(neuralNetwork.output.neurons[i].error) ); } writefln(" ] Cost [ %s ]",error); } if ( patternCount >= inputs.length ) { //for(int i = 0; i < depth; ++i) write(" "); //writef("Learning rate: %f",learningRate); real avg_err = total_abs_error / patternCount; if(last_error == 0.0) last_error = avg_err; if(last_largest_error == 0.0) last_largest_error = largest_error; if(write_progress) { if ( progressCallback !is null ) { progressCallback(actualEpochs+1, avg_err, avg_err - last_error, largest_error, largest_error - last_largest_error); } else { writefln("Average Error: % 7f (%+7f) Largest Error: % 7f (%+7f)", avg_err, avg_err - last_error, largest_error, largest_error - last_largest_error); } write_progress = false; } last_error = avg_err; last_largest_error = largest_error; largest_error = 0.0; // if average error is small enough, we're done! if(total_abs_error / patternCount <= this.errorThreshold) { break; } //otherwise, start at the beginning. patternCount = 0; total_abs_error = 0; if(train_on_problem_inputs && problem_inputs.length > 500) { //for(int i = 0; i < depth; ++i) write(" "); if(last_problem_count == 0) last_problem_count = problem_inputs.length; writefln("%d problem records (%+d)", problem_inputs.length, problem_inputs.length - last_problem_count); last_problem_count = problem_inputs.length; train(problem_inputs, problem_expected, problem_neuron_outputs, depth+1); } } if ( actualEpochs % callBackEpochs == 0 ) { //for(int i = 0; i < depth; ++i) write(" "); /+if ( progressCallback !is null ) { progressCallback( actualEpochs, error, expected, actual ); }+/ write_progress = true; } if ( ++actualEpochs >= epochs ) break; //if ( error <= this.errorThreshold ) break; // negative error is PERFECTLY NORMAL when doing value prediction, like we do for reinforcement learning. // really, I could also make it display SSE, becasue I'm using its derivative in the computation anyway, but displaying raw error is more informative in this context. } } }
D
/Users/mli/Desktop/Develope/Swift/LBE_Demo/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Charts.build/Objects-normal/x86_64/BarLineScatterCandleBubbleChartDataSet.o : /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Filters/DataApproximator+N.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/CombinedChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarLineScatterCandleBubbleChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ScatterChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/ViewPortJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/AnimatedViewPortJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/MoveViewJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/AnimatedMoveViewJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/ZoomViewJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/AnimatedZoomViewJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/Legend.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/MarkerImage.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/Range.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/ChartLimitLine.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/ChartDataRendererBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/AxisRendererBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/AxisBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/ComponentBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/ChartViewBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/BarLineChartViewBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/PieRadarChartViewBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataEntryBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Animation/ChartAnimationEasing.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/Fill.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/Platform.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/Description.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/ChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/CombinedChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/BubbleChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/BarLineScatterCandleBubbleChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/CandleChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/LineChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/BarChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/ScatterChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/IMarker.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/ViewPortHandler.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/Transformer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Renderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/LegendRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/BarLineScatterCandleBubbleRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/IShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/XShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/CircleShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/TriangleShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/SquareShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/ChevronDownShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/ChevronUpShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/CrossShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/LineScatterCandleRadarRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/LineRadarRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/XAxisRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/YAxisRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/CombinedChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/PieChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/BubbleChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/LineChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/CandleStickChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/BarChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/HorizontalBarChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/RadarChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/ScatterChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/IHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/CombinedHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/PieHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/BarHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/HorizontalBarHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/RadarHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/PieRadarHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/ChartHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/IValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/IAxisValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/DefaultAxisValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/IndexAxisValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/DefaultValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/IFillFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/DefaultFillFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Animation/Animator.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Filters/DataApproximator.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/ChartColorTemplates.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/XAxis.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/YAxis.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/ChartUtils.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/ChartBaseDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IPieChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IBubbleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarLineScatterCandleBubbleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IBarLineScatterCandleBubbleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/ICandleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/ILineChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IBarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineScatterCandleRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/ILineScatterCandleRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/ILineRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ScatterChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IScatterChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/Highlight.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/TransformerHorizontalBarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/XAxisRendererHorizontalBarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/YAxisRendererHorizontalBarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/XAxisRendererRadarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/YAxisRendererRadarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/MarkerView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/CombinedChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/PieChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/BubbleChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/LineChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/CandleStickChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/BarChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/HorizontalBarChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/RadarChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/ScatterChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/LegendEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/Platform+Accessibility.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Target\ Support\ Files/Charts/Charts-umbrella.h /Users/mli/Desktop/Develope/VLogVideo/Pods/Headers/Public/RxAtomic/RxAtomic.modulemap /Users/mli/Desktop/Develope/Swift/LBE_Demo/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Charts.build/unextended-module.modulemap /Users/mli/Desktop/Develope/VLogVideo/Pods/Headers/Public/RxSwift/RxSwift.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes /Users/mli/Desktop/Develope/Swift/LBE_Demo/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Charts.build/Objects-normal/x86_64/BarLineScatterCandleBubbleChartDataSet~partial.swiftmodule : /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Filters/DataApproximator+N.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/CombinedChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarLineScatterCandleBubbleChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ScatterChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/ViewPortJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/AnimatedViewPortJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/MoveViewJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/AnimatedMoveViewJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/ZoomViewJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/AnimatedZoomViewJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/Legend.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/MarkerImage.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/Range.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/ChartLimitLine.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/ChartDataRendererBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/AxisRendererBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/AxisBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/ComponentBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/ChartViewBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/BarLineChartViewBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/PieRadarChartViewBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataEntryBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Animation/ChartAnimationEasing.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/Fill.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/Platform.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/Description.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/ChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/CombinedChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/BubbleChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/BarLineScatterCandleBubbleChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/CandleChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/LineChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/BarChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/ScatterChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/IMarker.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/ViewPortHandler.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/Transformer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Renderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/LegendRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/BarLineScatterCandleBubbleRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/IShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/XShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/CircleShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/TriangleShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/SquareShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/ChevronDownShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/ChevronUpShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/CrossShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/LineScatterCandleRadarRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/LineRadarRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/XAxisRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/YAxisRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/CombinedChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/PieChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/BubbleChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/LineChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/CandleStickChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/BarChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/HorizontalBarChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/RadarChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/ScatterChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/IHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/CombinedHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/PieHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/BarHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/HorizontalBarHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/RadarHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/PieRadarHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/ChartHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/IValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/IAxisValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/DefaultAxisValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/IndexAxisValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/DefaultValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/IFillFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/DefaultFillFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Animation/Animator.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Filters/DataApproximator.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/ChartColorTemplates.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/XAxis.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/YAxis.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/ChartUtils.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/ChartBaseDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IPieChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IBubbleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarLineScatterCandleBubbleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IBarLineScatterCandleBubbleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/ICandleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/ILineChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IBarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineScatterCandleRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/ILineScatterCandleRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/ILineRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ScatterChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IScatterChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/Highlight.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/TransformerHorizontalBarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/XAxisRendererHorizontalBarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/YAxisRendererHorizontalBarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/XAxisRendererRadarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/YAxisRendererRadarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/MarkerView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/CombinedChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/PieChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/BubbleChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/LineChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/CandleStickChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/BarChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/HorizontalBarChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/RadarChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/ScatterChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/LegendEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/Platform+Accessibility.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Target\ Support\ Files/Charts/Charts-umbrella.h /Users/mli/Desktop/Develope/VLogVideo/Pods/Headers/Public/RxAtomic/RxAtomic.modulemap /Users/mli/Desktop/Develope/Swift/LBE_Demo/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Charts.build/unextended-module.modulemap /Users/mli/Desktop/Develope/VLogVideo/Pods/Headers/Public/RxSwift/RxSwift.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes /Users/mli/Desktop/Develope/Swift/LBE_Demo/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Charts.build/Objects-normal/x86_64/BarLineScatterCandleBubbleChartDataSet~partial.swiftdoc : /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Filters/DataApproximator+N.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/CombinedChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarLineScatterCandleBubbleChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ScatterChartData.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/ViewPortJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/AnimatedViewPortJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/MoveViewJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/AnimatedMoveViewJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/ZoomViewJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Jobs/AnimatedZoomViewJob.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/Legend.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/MarkerImage.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/Range.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/ChartLimitLine.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/ChartDataRendererBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/AxisRendererBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/AxisBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/ComponentBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/ChartViewBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/BarLineChartViewBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/PieRadarChartViewBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataEntryBase.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Animation/ChartAnimationEasing.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/Fill.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/Platform.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/Description.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/ChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/CombinedChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/BubbleChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/BarLineScatterCandleBubbleChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/CandleChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/LineChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/BarChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Interfaces/ScatterChartDataProvider.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/IMarker.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/ViewPortHandler.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/Transformer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Renderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/LegendRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/BarLineScatterCandleBubbleRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/IShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/XShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/CircleShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/TriangleShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/SquareShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/ChevronDownShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/ChevronUpShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/Scatter/CrossShapeRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/LineScatterCandleRadarRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/LineRadarRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/XAxisRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/YAxisRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/CombinedChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/PieChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/BubbleChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/LineChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/CandleStickChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/BarChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/HorizontalBarChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/RadarChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/ScatterChartRenderer.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/IHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/CombinedHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/PieHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/BarHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/HorizontalBarHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/RadarHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/PieRadarHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/ChartHighlighter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/IValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/IAxisValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/DefaultAxisValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/IndexAxisValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/DefaultValueFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/IFillFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Formatters/DefaultFillFormatter.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Animation/Animator.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Filters/DataApproximator.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/ChartColorTemplates.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/XAxis.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/YAxis.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/ChartUtils.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/ChartBaseDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IPieChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IBubbleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarLineScatterCandleBubbleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IBarLineScatterCandleBubbleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/ICandleChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/ILineChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IBarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineScatterCandleRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/ILineScatterCandleRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/ILineRadarChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ScatterChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Interfaces/IScatterChartDataSet.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Highlight/Highlight.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/TransformerHorizontalBarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/XAxisRendererHorizontalBarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/YAxisRendererHorizontalBarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/XAxisRendererRadarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Renderers/YAxisRendererRadarChart.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/MarkerView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/CombinedChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/PieChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/BubbleChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/LineChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/CandleStickChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/BarChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/HorizontalBarChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/RadarChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Charts/ScatterChartView.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BubbleChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/CandleChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Data/Implementations/Standard/RadarChartDataEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Components/LegendEntry.swift /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Charts/Source/Charts/Utils/Platform+Accessibility.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/mli/Desktop/Develope/Swift/LBE_Demo/Pods/Target\ Support\ Files/Charts/Charts-umbrella.h /Users/mli/Desktop/Develope/VLogVideo/Pods/Headers/Public/RxAtomic/RxAtomic.modulemap /Users/mli/Desktop/Develope/Swift/LBE_Demo/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Charts.build/unextended-module.modulemap /Users/mli/Desktop/Develope/VLogVideo/Pods/Headers/Public/RxSwift/RxSwift.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
D
// Written in the D programming language. /** Classes and functions for handling and transcoding between various encodings. For cases where the _encoding is known at compile-time, functions are provided for arbitrary _encoding and decoding of characters, arbitrary transcoding between strings of different type, as well as validation and sanitization. Encodings currently supported are UTF-8, UTF-16, UTF-32, ASCII, ISO-8859-1 (also known as LATIN-1), and WINDOWS-1252. $(UL $(LI The type $(D AsciiChar) represents an ASCII character.) $(LI The type $(D AsciiString) represents an ASCII string.) $(LI The type $(D Latin1Char) represents an ISO-8859-1 character.) $(LI The type $(D Latin1String) represents an ISO-8859-1 string.) $(LI The type $(D Windows1252Char) represents a Windows-1252 character.) $(LI The type $(D Windows1252String) represents a Windows-1252 string.)) For cases where the _encoding is not known at compile-time, but is known at run-time, we provide the abstract class $(D EncodingScheme) and its subclasses. To construct a run-time encoder/decoder, one does e.g. ---------------------------------------------------- auto e = EncodingScheme.create("utf-8"); ---------------------------------------------------- This library supplies $(D EncodingScheme) subclasses for ASCII, ISO-8859-1 (also known as LATIN-1), WINDOWS-1252, UTF-8, and (on little-endian architectures) UTF-16LE and UTF-32LE; or (on big-endian architectures) UTF-16BE and UTF-32BE. This library provides a mechanism whereby other modules may add $(D EncodingScheme) subclasses for any other _encoding. Macros: WIKI=Phobos/StdEncoding Copyright: Copyright Janice Caron 2008 - 2009. License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>. Authors: Janice Caron Source: $(PHOBOSSRC std/_encoding.d) */ /* Copyright Janice Caron 2008 - 2009. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ module std.encoding; import std.string; import std.traits; import std.range; unittest { static ubyte[][] validStrings = [ // Plain ASCII cast(ubyte[])"hello", // First possible sequence of a certain length [ 0x00 ], // U+00000000 one byte [ 0xC2, 0x80 ], // U+00000080 two bytes [ 0xE0, 0xA0, 0x80 ], // U+00000800 three bytes [ 0xF0, 0x90, 0x80, 0x80 ], // U+00010000 three bytes // Last possible sequence of a certain length [ 0x7F ], // U+0000007F one byte [ 0xDF, 0xBF ], // U+000007FF two bytes [ 0xEF, 0xBF, 0xBF ], // U+0000FFFF three bytes // Other boundary conditions [ 0xED, 0x9F, 0xBF ], // U+0000D7FF Last character before surrogates [ 0xEE, 0x80, 0x80 ], // U+0000E000 First character after surrogates [ 0xEF, 0xBF, 0xBD ], // U+0000FFFD Unicode replacement character [ 0xF4, 0x8F, 0xBF, 0xBF ], // U+0010FFFF Very last character // Non-character code points /* NOTE: These are legal in UTF, and may be converted from one UTF to another, however they do not represent Unicode characters. These code points have been reserved by Unicode as non-character code points. They are permissible for data exchange within an application, but they are are not permitted to be used as characters. Since this module deals with UTF, and not with Unicode per se, we choose to accept them here. */ [ 0xDF, 0xBE ], // U+0000FFFE [ 0xDF, 0xBF ], // U+0000FFFF ]; static ubyte[][] invalidStrings = [ // First possible sequence of a certain length, but greater // than U+10FFFF [ 0xF8, 0x88, 0x80, 0x80, 0x80 ], // U+00200000 five bytes [ 0xFC, 0x84, 0x80, 0x80, 0x80, 0x80 ], // U+04000000 six bytes // Last possible sequence of a certain length, but greater than U+10FFFF [ 0xF7, 0xBF, 0xBF, 0xBF ], // U+001FFFFF four bytes [ 0xFB, 0xBF, 0xBF, 0xBF, 0xBF ], // U+03FFFFFF five bytes [ 0xFD, 0xBF, 0xBF, 0xBF, 0xBF, 0xBF ], // U+7FFFFFFF six bytes // Other boundary conditions [ 0xF4, 0x90, 0x80, 0x80 ], // U+00110000 // First code // point after // last character // Unexpected continuation bytes [ 0x80 ], [ 0xBF ], [ 0x20, 0x80, 0x20 ], [ 0x20, 0xBF, 0x20 ], [ 0x80, 0x9F, 0xA0 ], // Lonely start bytes [ 0xC0 ], [ 0xCF ], [ 0x20, 0xC0, 0x20 ], [ 0x20, 0xCF, 0x20 ], [ 0xD0 ], [ 0xDF ], [ 0x20, 0xD0, 0x20 ], [ 0x20, 0xDF, 0x20 ], [ 0xE0 ], [ 0xEF ], [ 0x20, 0xE0, 0x20 ], [ 0x20, 0xEF, 0x20 ], [ 0xF0 ], [ 0xF1 ], [ 0xF2 ], [ 0xF3 ], [ 0xF4 ], [ 0xF5 ], // If this were legal it would start a character > U+10FFFF [ 0xF6 ], // If this were legal it would start a character > U+10FFFF [ 0xF7 ], // If this were legal it would start a character > U+10FFFF [ 0xEF, 0xBF ], // Three byte sequence with third byte missing [ 0xF7, 0xBF, 0xBF ], // Four byte sequence with fourth byte missing [ 0xEF, 0xBF, 0xF7, 0xBF, 0xBF ], // Concatenation of the above // Impossible bytes [ 0xF8 ], [ 0xF9 ], [ 0xFA ], [ 0xFB ], [ 0xFC ], [ 0xFD ], [ 0xFE ], [ 0xFF ], [ 0x20, 0xF8, 0x20 ], [ 0x20, 0xF9, 0x20 ], [ 0x20, 0xFA, 0x20 ], [ 0x20, 0xFB, 0x20 ], [ 0x20, 0xFC, 0x20 ], [ 0x20, 0xFD, 0x20 ], [ 0x20, 0xFE, 0x20 ], [ 0x20, 0xFF, 0x20 ], // Overlong sequences, all representing U+002F /* With a safe UTF-8 decoder, all of the following five overlong representations of the ASCII character slash ("/") should be rejected like a malformed UTF-8 sequence */ [ 0xC0, 0xAF ], [ 0xE0, 0x80, 0xAF ], [ 0xF0, 0x80, 0x80, 0xAF ], [ 0xF8, 0x80, 0x80, 0x80, 0xAF ], [ 0xFC, 0x80, 0x80, 0x80, 0x80, 0xAF ], // Maximum overlong sequences /* Below you see the highest Unicode value that is still resulting in an overlong sequence if represented with the given number of bytes. This is a boundary test for safe UTF-8 decoders. All five characters should be rejected like malformed UTF-8 sequences. */ [ 0xC1, 0xBF ], // U+0000007F [ 0xE0, 0x9F, 0xBF ], // U+000007FF [ 0xF0, 0x8F, 0xBF, 0xBF ], // U+0000FFFF [ 0xF8, 0x87, 0xBF, 0xBF, 0xBF ], // U+001FFFFF [ 0xFC, 0x83, 0xBF, 0xBF, 0xBF, 0xBF ], // U+03FFFFFF // Overlong representation of the NUL character /* The following five sequences should also be rejected like malformed UTF-8 sequences and should not be treated like the ASCII NUL character. */ [ 0xC0, 0x80 ], [ 0xE0, 0x80, 0x80 ], [ 0xF0, 0x80, 0x80, 0x80 ], [ 0xF8, 0x80, 0x80, 0x80, 0x80 ], [ 0xFC, 0x80, 0x80, 0x80, 0x80, 0x80 ], // Illegal code positions /* The following UTF-8 sequences should be rejected like malformed sequences, because they never represent valid ISO 10646 characters and a UTF-8 decoder that accepts them might introduce security problems comparable to overlong UTF-8 sequences. */ [ 0xED, 0xA0, 0x80 ], // U+D800 [ 0xED, 0xAD, 0xBF ], // U+DB7F [ 0xED, 0xAE, 0x80 ], // U+DB80 [ 0xED, 0xAF, 0xBF ], // U+DBFF [ 0xED, 0xB0, 0x80 ], // U+DC00 [ 0xED, 0xBE, 0x80 ], // U+DF80 [ 0xED, 0xBF, 0xBF ], // U+DFFF ]; static string[] sanitizedStrings = [ "\uFFFD","\uFFFD", "\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD"," \uFFFD ", " \uFFFD ","\uFFFD\uFFFD\uFFFD","\uFFFD","\uFFFD"," \uFFFD "," \uFFFD ", "\uFFFD","\uFFFD"," \uFFFD "," \uFFFD ","\uFFFD","\uFFFD"," \uFFFD ", " \uFFFD ","\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD", "\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD\uFFFD","\uFFFD","\uFFFD", "\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD"," \uFFFD ", " \uFFFD "," \uFFFD "," \uFFFD "," \uFFFD "," \uFFFD "," \uFFFD ", " \uFFFD ","\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD", "\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD", "\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD", ]; // Make sure everything that should be valid, is foreach(a;validStrings) { string s = cast(string)a; assert(isValid(s),"Failed to validate: "~makeReadable(s)); } // Make sure everything that shouldn't be valid, isn't foreach(a;invalidStrings) { string s = cast(string)a; assert(!isValid(s),"Incorrectly validated: "~makeReadable(s)); } // Make sure we can sanitize everything bad assert(invalidStrings.length == sanitizedStrings.length); for(int i=0; i<invalidStrings.length; ++i) { string s = cast(string)invalidStrings[i]; string t = sanitize(s); assert(isValid(t)); assert(t == sanitizedStrings[i]); ubyte[] u = cast(ubyte[])t; validStrings ~= u; } // Make sure all transcodings work in both directions, using both forward // and reverse iteration foreach(a; validStrings) { string s = cast(string)a; string s2; wstring ws, ws2; dstring ds, ds2; transcode(s,ws); assert(isValid(ws)); transcode(ws,s2); assert(s == s2); transcode(s,ds); assert(isValid(ds)); transcode(ds,s2); assert(s == s2); transcode(ws,s); assert(isValid(s)); transcode(s,ws2); assert(ws == ws2); transcode(ws,ds); assert(isValid(ds)); transcode(ds,ws2); assert(ws == ws2); transcode(ds,s); assert(isValid(s)); transcode(s,ds2); assert(ds == ds2); transcode(ds,ws); assert(isValid(ws)); transcode(ws,ds2); assert(ds == ds2); transcodeReverse(s,ws); assert(isValid(ws)); transcodeReverse(ws,s2); assert(s == s2); transcodeReverse(s,ds); assert(isValid(ds)); transcodeReverse(ds,s2); assert(s == s2); transcodeReverse(ws,s); assert(isValid(s)); transcodeReverse(s,ws2); assert(ws == ws2); transcodeReverse(ws,ds); assert(isValid(ds)); transcodeReverse(ds,ws2); assert(ws == ws2); transcodeReverse(ds,s); assert(isValid(s)); transcodeReverse(s,ds2); assert(ds == ds2); transcodeReverse(ds,ws); assert(isValid(ws)); transcodeReverse(ws,ds2); assert(ds == ds2); } // Make sure the non-UTF encodings work too { auto s = "\u20AC100"; Windows1252String t; transcode(s,t); assert(t == cast(Windows1252Char[])[0x80, '1', '0', '0']); string u; transcode(s,u); assert(s == u); Latin1String v; transcode(s,v); assert(cast(string)v == "?100"); AsciiString w; transcode(v,w); assert(cast(string)w == "?100"); } // Make sure we can count properly { assert(encodedLength!(char)('A') == 1); assert(encodedLength!(char)('\u00E3') == 2); assert(encodedLength!(char)('\u2028') == 3); assert(encodedLength!(char)('\U0010FFF0') == 4); assert(encodedLength!(wchar)('A') == 1); assert(encodedLength!(wchar)('\U0010FFF0') == 2); } // Make sure we can write into mutable arrays { char[4] buffer; auto n = encode(cast(dchar)'\u00E3',buffer); assert(n == 2); assert(buffer[0] == 0xC3); assert(buffer[1] == 0xA3); } } //============================================================================= /** Special value returned by $(D safeDecode) */ enum dchar INVALID_SEQUENCE = cast(dchar) 0xFFFFFFFF; template EncoderFunctions() { // Various forms of read template ReadFromString() { @property bool canRead() { return s.length != 0; } E peek() { return s[0]; } E read() { E t = s[0]; s = s[1..$]; return t; } } template ReverseReadFromString() { @property bool canRead() { return s.length != 0; } E peek() { return s[$-1]; } E read() { E t = s[$-1]; s = s[0..$-1]; return t; } } // Various forms of Write template WriteToString() { E[] s; void write(E c) { s ~= c; } } template WriteToArray() { void write(E c) { array[0] = c; array = array[1..$]; } } template WriteToDelegate() { void write(E c) { dg(c); } } // Functions we will export template EncodeViaWrite() { mixin encodeViaWrite; void encode(dchar c) { encodeViaWrite(c); } } template SkipViaRead() { mixin skipViaRead; void skip() { skipViaRead(); } } template DecodeViaRead() { mixin decodeViaRead; dchar decode() { return decodeViaRead(); } } template SafeDecodeViaRead() { mixin safeDecodeViaRead; dchar safeDecode() { return safeDecodeViaRead(); } } template DecodeReverseViaRead() { mixin decodeReverseViaRead; dchar decodeReverse() { return decodeReverseViaRead(); } } // Encoding to different destinations template EncodeToString() { mixin WriteToString; mixin EncodeViaWrite; } template EncodeToArray() { mixin WriteToArray; mixin EncodeViaWrite; } template EncodeToDelegate() { mixin WriteToDelegate; mixin EncodeViaWrite; } // Decoding functions template SkipFromString() { mixin ReadFromString; mixin SkipViaRead; } template DecodeFromString() { mixin ReadFromString; mixin DecodeViaRead; } template SafeDecodeFromString() { mixin ReadFromString; mixin SafeDecodeViaRead; } template DecodeReverseFromString() { mixin ReverseReadFromString; mixin DecodeReverseViaRead; } //========================================================================= // Below are the functions we will ultimately expose to the user E[] encode(dchar c) { mixin EncodeToString e; e.encode(c); return e.s; } void encode(dchar c, ref E[] array) { mixin EncodeToArray e; e.encode(c); } void encode(dchar c, void delegate(E) dg) { mixin EncodeToDelegate e; e.encode(c); } void skip(ref const(E)[] s) { mixin SkipFromString e; e.skip(); } dchar decode(S)(ref S s) { mixin DecodeFromString e; return e.decode(); } dchar safeDecode(S)(ref S s) { mixin SafeDecodeFromString e; return e.safeDecode(); } dchar decodeReverse(ref const(E)[] s) { mixin DecodeReverseFromString e; return e.decodeReverse(); } } //========================================================================= struct CodePoints(E) { const(E)[] s; this(const(E)[] s) in { assert(isValid(s)); } body { this.s = s; } int opApply(scope int delegate(ref dchar) dg) { int result = 0; while (s.length != 0) { dchar c = decode(s); result = dg(c); if (result != 0) break; } return result; } int opApply(scope int delegate(ref size_t, ref dchar) dg) { size_t i = 0; int result = 0; while (s.length != 0) { size_t len = s.length; dchar c = decode(s); size_t j = i; // We don't want the delegate corrupting i result = dg(j,c); if (result != 0) break; i += len - s.length; } return result; } int opApplyReverse(scope int delegate(ref dchar) dg) { int result = 0; while (s.length != 0) { dchar c = decodeReverse(s); result = dg(c); if (result != 0) break; } return result; } int opApplyReverse(scope int delegate(ref size_t, ref dchar) dg) { int result = 0; while (s.length != 0) { dchar c = decodeReverse(s); size_t i = s.length; result = dg(i,c); if (result != 0) break; } return result; } } struct CodeUnits(E) { E[] s; this(dchar d) in { assert(isValidCodePoint(d)); } body { s = encode!(E)(d); } int opApply(scope int delegate(ref E) dg) { int result = 0; foreach(E c;s) { result = dg(c); if (result != 0) break; } return result; } int opApplyReverse(scope int delegate(ref E) dg) { int result = 0; foreach_reverse(E c;s) { result = dg(c); if (result != 0) break; } return result; } } //============================================================================= template EncoderInstance(E) { static assert(false,"Cannot instantiate EncoderInstance for type " ~ E.stringof); } //============================================================================= // ASCII //============================================================================= /** Defines various character sets. */ enum AsciiChar : ubyte { init }; /// Ditto alias immutable(AsciiChar)[] AsciiString; template EncoderInstance(CharType : AsciiChar) { alias AsciiChar E; alias AsciiString EString; @property string encodingName() { return "ASCII"; } bool canEncode(dchar c) { return c < 0x80; } bool isValidCodeUnit(AsciiChar c) { return c < 0x80; } size_t encodedLength(dchar c) in { assert(canEncode(c)); } body { return 1; } void encodeX(Range)(dchar c, Range r) { if (!canEncode(c)) c = '?'; r.write(cast(AsciiChar) c); } void encodeViaWrite()(dchar c) { if (!canEncode(c)) c = '?'; write(cast(AsciiChar)c); } void skipViaRead()() { read(); } dchar decodeViaRead()() { return read(); } dchar safeDecodeViaRead()() { dchar c = read(); return canEncode(c) ? c : INVALID_SEQUENCE; } dchar decodeReverseViaRead()() { return read(); } @property EString replacementSequence() { return cast(EString)("?"); } mixin EncoderFunctions; } //============================================================================= // ISO-8859-1 //============================================================================= /** Defines an Latin1-encoded character. */ enum Latin1Char : ubyte { init }; /** Defines an Latin1-encoded string (as an array of $(D immutable(Latin1Char))). */ alias immutable(Latin1Char)[] Latin1String; /// template EncoderInstance(CharType : Latin1Char) { alias Latin1Char E; alias Latin1String EString; @property string encodingName() { return "ISO-8859-1"; } bool canEncode(dchar c) { return c < 0x100; } bool isValidCodeUnit(Latin1Char c) { return true; } size_t encodedLength(dchar c) in { assert(canEncode(c)); } body { return 1; } void encodeViaWrite()(dchar c) { if (!canEncode(c)) c = '?'; write(cast(Latin1Char)c); } void skipViaRead()() { read(); } dchar decodeViaRead()() { return read(); } dchar safeDecodeViaRead()() { return read(); } dchar decodeReverseViaRead()() { return read(); } @property EString replacementSequence() { return cast(EString)("?"); } mixin EncoderFunctions; } //============================================================================= // WINDOWS-1252 //============================================================================= /** Defines a Windows1252-encoded character. */ enum Windows1252Char : ubyte { init }; /** Defines an Windows1252-encoded string (as an array of $(D immutable(Windows1252Char))). */ alias immutable(Windows1252Char)[] Windows1252String; /// template EncoderInstance(CharType : Windows1252Char) { alias Windows1252Char E; alias Windows1252String EString; @property string encodingName() { return "windows-1252"; } immutable wstring charMap = "\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021" "\u02C6\u2030\u0160\u2039\u0152\uFFFD\u017D\uFFFD" "\uFFFD\u2018\u2019\u201C\u201D\u2022\u2103\u2014" "\u02DC\u2122\u0161\u203A\u0153\uFFFD\u017E\u0178" ; bool canEncode(dchar c) { if (c < 0x80 || (c >= 0xA0 && c < 0x100)) return true; if (c >= 0xFFFD) return false; foreach(wchar d;charMap) { if (c == d) return true; } return false; } bool isValidCodeUnit(Windows1252Char c) { if (c < 0x80 || c >= 0xA0) return true; return (charMap[c-0x80] != 0xFFFD); } size_t encodedLength(dchar c) in { assert(canEncode(c)); } body { return 1; } void encodeViaWrite()(dchar c) { if (c < 0x80 || (c >= 0xA0 && c < 0x100)) {} else if (c >= 0xFFFD) { c = '?'; } else { ptrdiff_t n = -1; foreach (i, wchar d; charMap) { if (c == d) { n = i; break; } } c = n == -1 ? '?' : 0x80 + cast(dchar) n; } write(cast(Windows1252Char)c); } void skipViaRead()() { read(); } dchar decodeViaRead()() { Windows1252Char c = read(); return (c >= 0x80 && c < 0xA0) ? charMap[c-0x80] : c; } dchar safeDecodeViaRead()() { Windows1252Char c = read(); dchar d = (c >= 0x80 && c < 0xA0) ? charMap[c-0x80] : c; return d == 0xFFFD ? INVALID_SEQUENCE : d; } dchar decodeReverseViaRead()() { Windows1252Char c = read(); return (c >= 0x80 && c < 0xA0) ? charMap[c-0x80] : c; } @property EString replacementSequence() { return cast(EString)("?"); } mixin EncoderFunctions; } //============================================================================= // UTF-8 //============================================================================= template EncoderInstance(CharType : char) { alias char E; alias immutable(char)[] EString; @property string encodingName() { return "UTF-8"; } bool canEncode(dchar c) { return isValidCodePoint(c); } bool isValidCodeUnit(char c) { return (c < 0xC0 || (c >= 0xC2 && c < 0xF5)); } immutable ubyte[128] tailTable = [ 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,0,0,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,6,0, ]; private int tails(char c) in { assert(c >= 0x80); } body { return tailTable[c-0x80]; } size_t encodedLength(dchar c) in { assert(canEncode(c)); } body { if (c < 0x80) return 1; if (c < 0x800) return 2; if (c < 0x10000) return 3; return 4; } void encodeViaWrite()(dchar c) { if (c < 0x80) { write(cast(char)c); } else if (c < 0x800) { write(cast(char)((c >> 6) + 0xC0)); write(cast(char)((c & 0x3F) + 0x80)); } else if (c < 0x10000) { write(cast(char)((c >> 12) + 0xE0)); write(cast(char)(((c >> 6) & 0x3F) + 0x80)); write(cast(char)((c & 0x3F) + 0x80)); } else { write(cast(char)((c >> 18) + 0xF0)); write(cast(char)(((c >> 12) & 0x3F) + 0x80)); write(cast(char)(((c >> 6) & 0x3F) + 0x80)); write(cast(char)((c & 0x3F) + 0x80)); } } void skipViaRead()() { auto c = read(); if (c < 0xC0) return; int n = tails(cast(char) c); for (size_t i=0; i<n; ++i) { read(); } } dchar decodeViaRead()() { dchar c = read(); if (c < 0xC0) return c; int n = tails(cast(char) c); c &= (1 << (6 - n)) - 1; for (size_t i=0; i<n; ++i) { c = (c << 6) + (read() & 0x3F); } return c; } dchar safeDecodeViaRead()() { dchar c = read(); if (c < 0x80) return c; int n = tails(cast(char) c); if (n == 0) return INVALID_SEQUENCE; if (!canRead) return INVALID_SEQUENCE; size_t d = peek(); bool err = ( (c < 0xC2) // fail overlong 2-byte sequences || (c > 0xF4) // fail overlong 4-6-byte sequences || (c == 0xE0 && ((d & 0xE0) == 0x80)) // fail overlong 3-byte sequences || (c == 0xED && ((d & 0xE0) == 0xA0)) // fail surrogates || (c == 0xF0 && ((d & 0xF0) == 0x80)) // fail overlong 4-byte sequences || (c == 0xF4 && ((d & 0xF0) >= 0x90)) // fail code points > 0x10FFFF ); c &= (1 << (6 - n)) - 1; for (size_t i=0; i<n; ++i) { if (!canRead) return INVALID_SEQUENCE; d = peek(); if ((d & 0xC0) != 0x80) return INVALID_SEQUENCE; c = (c << 6) + (read() & 0x3F); } return err ? INVALID_SEQUENCE : c; } dchar decodeReverseViaRead()() { dchar c = read(); if (c < 0x80) return c; size_t shift = 0; c &= 0x3F; for (size_t i=0; i<4; ++i) { shift += 6; auto d = read(); size_t n = tails(cast(char) d); size_t mask = n == 0 ? 0x3F : (1 << (6 - n)) - 1; c += ((d & mask) << shift); if (n != 0) break; } return c; } @property EString replacementSequence() { return "\uFFFD"; } mixin EncoderFunctions; } //============================================================================= // UTF-16 //============================================================================= template EncoderInstance(CharType : wchar) { alias wchar E; alias immutable(wchar)[] EString; @property string encodingName() { return "UTF-16"; } bool canEncode(dchar c) { return isValidCodePoint(c); } bool isValidCodeUnit(wchar c) { return true; } size_t encodedLength(dchar c) in { assert(canEncode(c)); } body { return (c < 0x10000) ? 1 : 2; } void encodeViaWrite()(dchar c) { if (c < 0x10000) { write(cast(wchar)c); } else { size_t n = c - 0x10000; write(cast(wchar)(0xD800 + (n >> 10))); write(cast(wchar)(0xDC00 + (n & 0x3FF))); } } void skipViaRead()() { wchar c = read(); if (c < 0xD800 || c >= 0xE000) return; read(); } dchar decodeViaRead()() { wchar c = read(); if (c < 0xD800 || c >= 0xE000) return cast(dchar)c; wchar d = read(); c &= 0x3FF; d &= 0x3FF; return 0x10000 + (c << 10) + d; } dchar safeDecodeViaRead()() { wchar c = read(); if (c < 0xD800 || c >= 0xE000) return cast(dchar)c; if (c >= 0xDC00) return INVALID_SEQUENCE; if (!canRead) return INVALID_SEQUENCE; wchar d = peek(); if (d < 0xDC00 || d >= 0xE000) return INVALID_SEQUENCE; d = read(); c &= 0x3FF; d &= 0x3FF; return 0x10000 + (c << 10) + d; } dchar decodeReverseViaRead()() { wchar c = read(); if (c < 0xD800 || c >= 0xE000) return cast(dchar)c; wchar d = read(); c &= 0x3FF; d &= 0x3FF; return 0x10000 + (d << 10) + c; } @property EString replacementSequence() { return "\uFFFD"w; } mixin EncoderFunctions; } //============================================================================= // UTF-32 //============================================================================= template EncoderInstance(CharType : dchar) { alias dchar E; alias immutable(dchar)[] EString; @property string encodingName() { return "UTF-32"; } bool canEncode(dchar c) { return isValidCodePoint(c); } bool isValidCodeUnit(dchar c) { return isValidCodePoint(c); } size_t encodedLength(dchar c) in { assert(canEncode(c)); } body { return 1; } void encodeViaWrite()(dchar c) { write(c); } void skipViaRead()() { read(); } dchar decodeViaRead()() { return cast(dchar)read(); } dchar safeDecodeViaRead()() { dchar c = read(); return isValidCodePoint(c) ? c : INVALID_SEQUENCE; } dchar decodeReverseViaRead()() { return cast(dchar)read(); } @property EString replacementSequence() { return "\uFFFD"d; } mixin EncoderFunctions; } //============================================================================= // Below are forwarding functions which expose the function to the user /** Returns true if c is a valid code point Note that this includes the non-character code points U+FFFE and U+FFFF, since these are valid code points (even though they are not valid characters). Supercedes: This function supercedes $(D std.utf.startsValidDchar()). Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252 Params: c = the code point to be tested */ bool isValidCodePoint(dchar c) { return c < 0xD800 || (c >= 0xE000 && c < 0x110000); } /** Returns the name of an encoding. The type of encoding cannot be deduced. Therefore, it is necessary to explicitly specify the encoding type. Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252 Examples: ----------------------------------- assert(encodingName!(Latin1Char) == "ISO-8859-1"); ----------------------------------- */ @property string encodingName(T)() { return EncoderInstance!(T).encodingName; } unittest { assert(encodingName!(char) == "UTF-8"); assert(encodingName!(wchar) == "UTF-16"); assert(encodingName!(dchar) == "UTF-32"); assert(encodingName!(AsciiChar) == "ASCII"); assert(encodingName!(Latin1Char) == "ISO-8859-1"); assert(encodingName!(Windows1252Char) == "windows-1252"); } /** Returns true iff it is possible to represent the specifed codepoint in the encoding. The type of encoding cannot be deduced. Therefore, it is necessary to explicitly specify the encoding type. Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252 Examples: ----------------------------------- assert(canEncode!(Latin1Char)('A')); ----------------------------------- */ bool canEncode(E)(dchar c) { return EncoderInstance!(E).canEncode(c); } unittest { assert(!canEncode!(AsciiChar)('\u00A0')); assert(canEncode!(Latin1Char)('\u00A0')); assert(canEncode!(Windows1252Char)('\u20AC')); assert(!canEncode!(Windows1252Char)('\u20AD')); assert(!canEncode!(Windows1252Char)('\uFFFD')); assert(!canEncode!(char)(cast(dchar)0x110000)); } /** Returns true if the code unit is legal. For example, the byte 0x80 would not be legal in ASCII, because ASCII code units must always be in the range 0x00 to 0x7F. Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252 Params: c = the code unit to be tested */ bool isValidCodeUnit(E)(E c) { return EncoderInstance!(E).isValidCodeUnit(c); } unittest { assert(!isValidCodeUnit(cast(AsciiChar)0xA0)); assert( isValidCodeUnit(cast(Windows1252Char)0x80)); assert(!isValidCodeUnit(cast(Windows1252Char)0x81)); assert(!isValidCodeUnit(cast(char)0xC0)); assert(!isValidCodeUnit(cast(char)0xFF)); assert( isValidCodeUnit(cast(wchar)0xD800)); assert(!isValidCodeUnit(cast(dchar)0xD800)); } /** Returns true if the string is encoded correctly Supercedes: This function supercedes std.utf.validate(), however note that this function returns a bool indicating whether the input was valid or not, wheras the older funtion would throw an exception. Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252 Params: s = the string to be tested */ bool isValid(E)(const(E)[] s) { return s.length == validLength(s); } unittest { assert(isValid("\u20AC100")); } /** Returns the length of the longest possible substring, starting from the first code unit, which is validly encoded. Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252 Params: s = the string to be tested */ size_t validLength(E)(const(E)[] s) { size_t result, before = void; while ((before = s.length) > 0) { if (EncoderInstance!(E).safeDecode(s) == INVALID_SEQUENCE) break; result += before - s.length; } return result; } /** Sanitizes a string by replacing malformed code unit sequences with valid code unit sequences. The result is guaranteed to be valid for this encoding. If the input string is already valid, this function returns the original, otherwise it constructs a new string by replacing all illegal code unit sequences with the encoding's replacement character, Invalid sequences will be replaced with the Unicode replacement character (U+FFFD) if the character repertoire contains it, otherwise invalid sequences will be replaced with '?'. Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252 Params: s = the string to be sanitized */ immutable(E)[] sanitize(E)(immutable(E)[] s) { size_t n = validLength(s); if (n == s.length) return s; auto repSeq = EncoderInstance!(E).replacementSequence; // Count how long the string needs to be. // Overestimating is not a problem size_t len = s.length; const(E)[] t = s[n..$]; while (t.length != 0) { dchar c = EncoderInstance!(E).safeDecode(t); assert(c == INVALID_SEQUENCE); len += repSeq.length; t = t[validLength(t)..$]; } // Now do the write E[] array = new E[len]; array[0..n] = s[0..n]; size_t offset = n; t = s[n..$]; while (t.length != 0) { dchar c = EncoderInstance!(E).safeDecode(t); assert(c == INVALID_SEQUENCE); array[offset..offset+repSeq.length] = repSeq[]; offset += repSeq.length; n = validLength(t); array[offset..offset+n] = t[0..n]; offset += n; t = t[n..$]; } return cast(immutable(E)[])array[0..offset]; } unittest { assert(sanitize("hello \xF0\x80world") == "hello \xEF\xBF\xBDworld"); } /** Returns the length of the first encoded sequence. The input to this function MUST be validly encoded. This is enforced by the function's in-contract. Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252 Params: s = the string to be sliced */ size_t firstSequence(E)(const(E)[] s) in { assert(s.length != 0); const(E)[] u = s; assert(safeDecode(u) != INVALID_SEQUENCE); } body { auto before = s.length; EncoderInstance!(E).skip(s); return before - s.length; } unittest { assert(firstSequence("\u20AC1000") == "\u20AC".length); } /** Returns the length the last encoded sequence. The input to this function MUST be validly encoded. This is enforced by the function's in-contract. Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252 Params: s = the string to be sliced */ size_t lastSequence(E)(const(E)[] s) in { assert(s.length != 0); assert(isValid(s)); } body { const(E)[] t = s; EncoderInstance!(E).decodeReverse(s); return t.length - s.length; } unittest { assert(lastSequence("1000\u20AC") == "\u20AC".length); } /** Returns the array index at which the (n+1)th code point begins. The input to this function MUST be validly encoded. This is enforced by the function's in-contract. Supercedes: This function supercedes std.utf.toUTFindex(). Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252 Params: s = the string to be counted */ ptrdiff_t index(E)(const(E)[] s,int n) in { assert(isValid(s)); assert(n >= 0); } body { const(E)[] t = s; for (size_t i=0; i<n; ++i) EncoderInstance!(E).skip(s); return t.length - s.length; } unittest { assert(index("\u20AC100",1) == 3); } /** Decodes a single code point. This function removes one or more code units from the start of a string, and returns the decoded code point which those code units represent. The input to this function MUST be validly encoded. This is enforced by the function's in-contract. Supercedes: This function supercedes std.utf.decode(), however, note that the function codePoints() supercedes it more conveniently. Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252 Params: s = the string whose first code point is to be decoded */ dchar decode(S)(ref S s) in { assert(s.length != 0); auto u = s; assert(safeDecode(u) != INVALID_SEQUENCE); } body { return EncoderInstance!(typeof(s[0])).decode(s); } /** Decodes a single code point from the end of a string. This function removes one or more code units from the end of a string, and returns the decoded code point which those code units represent. The input to this function MUST be validly encoded. This is enforced by the function's in-contract. Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252 Params: s = the string whose first code point is to be decoded */ dchar decodeReverse(E)(ref const(E)[] s) in { assert(s.length != 0); assert(isValid(s)); } body { return EncoderInstance!(E).decodeReverse(s); } /** Decodes a single code point. The input does not have to be valid. This function removes one or more code units from the start of a string, and returns the decoded code point which those code units represent. This function will accept an invalidly encoded string as input. If an invalid sequence is found at the start of the string, this function will remove it, and return the value INVALID_SEQUENCE. Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252 Params: s = the string whose first code point is to be decoded */ dchar safeDecode(S)(ref S s) in { assert(s.length != 0); } body { return EncoderInstance!(typeof(s[0])).safeDecode(s); } /** Returns the number of code units required to encode a single code point. The input to this function MUST be a valid code point. This is enforced by the function's in-contract. The type of the output cannot be deduced. Therefore, it is necessary to explicitly specify the encoding as a template parameter. Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252 Params: c = the code point to be encoded */ size_t encodedLength(E)(dchar c) in { assert(isValidCodePoint(c)); } body { return EncoderInstance!(E).encodedLength(c); } /** Encodes a single code point. This function encodes a single code point into one or more code units. It returns a string containing those code units. The input to this function MUST be a valid code point. This is enforced by the function's in-contract. The type of the output cannot be deduced. Therefore, it is necessary to explicitly specify the encoding as a template parameter. Supercedes: This function supercedes std.utf.encode(), however, note that the function codeUnits() supercedes it more conveniently. Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252 Params: c = the code point to be encoded */ E[] encode(E)(dchar c) in { assert(isValidCodePoint(c)); } body { return EncoderInstance!(E).encode(c); } /** Encodes a single code point into an array. This function encodes a single code point into one or more code units The code units are stored in a user-supplied fixed-size array, which must be passed by reference. The input to this function MUST be a valid code point. This is enforced by the function's in-contract. The type of the output cannot be deduced. Therefore, it is necessary to explicitly specify the encoding as a template parameter. Supercedes: This function supercedes std.utf.encode(), however, note that the function codeUnits() supercedes it more conveniently. Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252 Params: c = the code point to be encoded Returns: the number of code units written to the array */ size_t encode(E)(dchar c, E[] array) in { assert(isValidCodePoint(c)); } body { E[] t = array; EncoderInstance!(E).encode(c,t); return array.length - t.length; } // /** // * Encodes a single code point into a Buffer. // * // * This function encodes a single code point into one or more code units // * The code units are stored in a growable buffer. // * // * The input to this function MUST be a valid code point. // * This is enforced by the function's in-contract. // * // * The type of the output cannot be deduced. Therefore, it is necessary to // * explicitly specify the encoding as a template parameter. // * // * Supercedes: // * This function supercedes std.utf.encode(), however, note that the // * function codeUnits() supercedes it more conveniently. // * // * Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252 // * // * Params: // * c = the code point to be encoded // */ // deprecated void encode(E)(dchar c, ref Buffer!(E) buffer) // in // { // assert(isValidCodePoint(c)); // } // body // { // EncoderInstance!(E).encode(c,buffer); // } /* Encodes $(D c) in units of type $(D E) and writes the result to the output range $(D R). Returns the number of $(D E)s written. */ size_t encode(E, R)(dchar c, R range) { static if (is(Unqual!E == char)) { if (c <= 0x7F) { range.put(cast(char) c); return 1; } if (c <= 0x7FF) { range.put(cast(char)(0xC0 | (c >> 6))); range.put(cast(char)(0x80 | (c & 0x3F))); return 2; } if (c <= 0xFFFF) { range.put(cast(char)(0xE0 | (c >> 12))); range.put(cast(char)(0x80 | ((c >> 6) & 0x3F))); range.put(cast(char)(0x80 | (c & 0x3F))); return 3; } if (c <= 0x10FFFF) { range.put(cast(char)(0xF0 | (c >> 18))); range.put(cast(char)(0x80 | ((c >> 12) & 0x3F))); range.put(cast(char)(0x80 | ((c >> 6) & 0x3F))); range.put(cast(char)(0x80 | (c & 0x3F))); return 4; } else { assert(0); } } else static if (is(Unqual!E == wchar)) { if (c <= 0xFFFF) { r.put(cast(wchar) c); return 1; } r.put(cast(wchar) ((((c - 0x10000) >> 10) & 0x3FF) + 0xD800)); r.put(cast(wchar) (((c - 0x10000) & 0x3FF) + 0xDC00)); return 2; } else static if (is(Unqual!E == dchar)) { r.put(c); return 1; } else { assert(0); } } /** Encodes a single code point to a delegate. This function encodes a single code point into one or more code units. The code units are passed one at a time to the supplied delegate. The input to this function MUST be a valid code point. This is enforced by the function's in-contract. The type of the output cannot be deduced. Therefore, it is necessary to explicitly specify the encoding as a template parameter. Supercedes: This function supercedes std.utf.encode(), however, note that the function codeUnits() supercedes it more conveniently. Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252 Params: c = the code point to be encoded */ void encode(E)(dchar c, void delegate(E) dg) in { assert(isValidCodePoint(c)); } body { EncoderInstance!(E).encode(c,dg); } /** Returns a foreachable struct which can bidirectionally iterate over all code points in a string. The input to this function MUST be validly encoded. This is enforced by the function's in-contract. You can foreach either with or without an index. If an index is specified, it will be initialized at each iteration with the offset into the string at which the code point begins. Supercedes: This function supercedes std.utf.decode(). Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252 Params: s = the string to be decoded Examples: -------------------------------------------------------- string s = "hello world"; foreach(c;codePoints(s)) { // do something with c (which will always be a dchar) } -------------------------------------------------------- Note that, currently, foreach(c:codePoints(s)) is superior to foreach(c;s) in that the latter will fall over on encountering U+FFFF. */ CodePoints!(E) codePoints(E)(immutable(E)[] s) in { assert(isValid(s)); } body { return CodePoints!(E)(s); } unittest { string s = "hello"; string t; foreach(c;codePoints(s)) { t ~= cast(char)c; } assert(s == t); } /** Returns a foreachable struct which can bidirectionally iterate over all code units in a code point. The input to this function MUST be a valid code point. This is enforced by the function's in-contract. The type of the output cannot be deduced. Therefore, it is necessary to explicitly specify the encoding type in the template parameter. Supercedes: This function supercedes std.utf.encode(). Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252 Params: d = the code point to be encoded Examples: -------------------------------------------------------- dchar d = '\u20AC'; foreach(c;codeUnits!(char)(d)) { writefln("%X",c) } // will print // E2 // 82 // AC -------------------------------------------------------- */ CodeUnits!(E) codeUnits(E)(dchar c) in { assert(isValidCodePoint(c)); } body { return CodeUnits!(E)(c); } unittest { char[] a; foreach(c;codeUnits!(char)(cast(dchar)'\u20AC')) { a ~= c; } assert(a.length == 3); assert(a[0] == 0xE2); assert(a[1] == 0x82); assert(a[2] == 0xAC); } /** Encodes $(D c) in units of type $(D E) and writes the result to the output range $(D R). Returns the number of $(D E)s written. */ size_t encode(Tgt, Src, R)(in Src[] s, R range) { size_t result; foreach (c; s) { result += encode!(Tgt)(c, range); } return result; } /** Convert a string from one encoding to another. (See also to!() below). The input to this function MUST be validly encoded. This is enforced by the function's in-contract. Supercedes: This function supercedes std.utf.toUTF8(), std.utf.toUTF16() and std.utf.toUTF32() (but note that to!() supercedes it more conveniently). Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252 Params: s = the source string r = the destination string Examples: -------------------------------------------------------- wstring ws; transcode("hello world",ws); // transcode from UTF-8 to UTF-16 Latin1String ls; transcode(ws, ls); // transcode from UTF-16 to ISO-8859-1 -------------------------------------------------------- */ void transcode(Src,Dst)(immutable(Src)[] s,out immutable(Dst)[] r) in { assert(isValid(s)); } body { static if(is(Src==Dst)) { r = s; } else static if(is(Src==AsciiChar)) { transcode!(char,Dst)(cast(string)s,r); } else { const(Src)[] t = s; while (t.length != 0) { r ~= encode!(Dst)(decode(t)); } } } /* Convert a string from one encoding to another. (See also transcode() above). The input to this function MUST be validly encoded. This is enforced by the function's in-contract. Supercedes: This function supercedes std.utf.toUTF8(), std.utf.toUTF16() and std.utf.toUTF32(). Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252 Params: Dst = the destination encoding type s = the source string Examples: ----------------------------------------------------------------------------- auto ws = to!(wchar)("hello world"); // transcode from UTF-8 to UTF-16 auto ls = to!(Latin1Char)(ws); // transcode from UTF-16 to ISO-8859-1 ----------------------------------------------------------------------------- */ // TODO: Commented out for no - to be moved to std.conv // Dst to(Dst,Src)(immutable(Src)[] s) // in // { // assert(isValid(s)); // } // body // { // Dst r; // transcode(s,r); // return r; // } //============================================================================= /** The base class for exceptions thrown by this module */ class EncodingException : Exception { this(string msg) { super(msg); } } class UnrecognizedEncodingException : EncodingException { private this(string msg) { super(msg); } } /** Abstract base class of all encoding schemes */ abstract class EncodingScheme { /** * Registers a subclass of EncodingScheme. * * This function allows user-defined subclasses of EncodingScheme to * be declared in other modules. * * Examples: * ---------------------------------------------- * class Amiga1251 : EncodingScheme * { * shared static this() * { * EncodingScheme.register("path.to.Amiga1251"); * } * } * ---------------------------------------------- */ static void register(string className) { auto scheme = cast(EncodingScheme)ClassInfo.find(className).create(); if (scheme is null) throw new EncodingException("Unable to create class "~className); foreach(encodingName;scheme.names()) { supported[toLower(encodingName)] = className; } } /** * Obtains a subclass of EncodingScheme which is capable of encoding * and decoding the named encoding scheme. * * This function is only aware of EncodingSchemes which have been * registered with the register() function. * * Examples: * --------------------------------------------------- * auto scheme = EncodingScheme.create("Amiga-1251"); * --------------------------------------------------- */ static EncodingScheme create(string encodingName) { auto p = std.string.toLower(encodingName) in supported; if (p is null) throw new EncodingException("Unrecognized Encoding: "~encodingName); string className = *p; auto scheme = cast(EncodingScheme)ClassInfo.find(className).create(); if (scheme is null) throw new EncodingException("Unable to create class "~className); return scheme; } const { /** * Returns the standard name of the encoding scheme */ abstract override string toString(); /** * Returns an array of all known names for this encoding scheme */ abstract string[] names(); /** * Returns true if the character c can be represented * in this encoding scheme. */ abstract bool canEncode(dchar c); /** * Returns the number of ubytes required to encode this code point. * * The input to this function MUST be a valid code point. * * Params: * c = the code point to be encoded * * Returns: * the number of ubytes required. */ abstract size_t encodedLength(dchar c); /** * Encodes a single code point into a user-supplied, fixed-size buffer. * * This function encodes a single code point into one or more ubytes. * The supplied buffer must be code unit aligned. * (For example, UTF-16LE or UTF-16BE must be wchar-aligned, * UTF-32LE or UTF-32BE must be dchar-aligned, etc.) * * The input to this function MUST be a valid code point. * * Params: * c = the code point to be encoded * * Returns: * the number of ubytes written. */ abstract size_t encode(dchar c, ubyte[] buffer); /** * Decodes a single code point. * * This function removes one or more ubytes from the start of an array, * and returns the decoded code point which those ubytes represent. * * The input to this function MUST be validly encoded. * * Params: * s = the array whose first code point is to be decoded */ abstract dchar decode(ref const(ubyte)[] s); /** * Decodes a single code point. The input does not have to be valid. * * This function removes one or more ubytes from the start of an array, * and returns the decoded code point which those ubytes represent. * * This function will accept an invalidly encoded array as input. * If an invalid sequence is found at the start of the string, this * function will remove it, and return the value INVALID_SEQUENCE. * * Params: * s = the array whose first code point is to be decoded */ abstract dchar safeDecode(ref const(ubyte)[] s); /** * Returns the sequence of ubytes to be used to represent * any character which cannot be represented in the encoding scheme. * * Normally this will be a representation of some substitution * character, such as U+FFFD or '?'. */ abstract @property immutable(ubyte)[] replacementSequence(); } /** * Returns true if the array is encoded correctly * * Params: * s = the array to be tested */ bool isValid(const(ubyte)[] s) { while (s.length != 0) { dchar d = safeDecode(s); if (d == INVALID_SEQUENCE) return false; } return true; } /** * Returns the length of the longest possible substring, starting from * the first element, which is validly encoded. * * Params: * s = the array to be tested */ size_t validLength(const(ubyte)[] s) { const(ubyte)[] r = s; const(ubyte)[] t = s; while (s.length != 0) { if (safeDecode(s) == INVALID_SEQUENCE) break; t = s; } return r.length - t.length; } /** * Sanitizes an array by replacing malformed ubyte sequences with valid * ubyte sequences. The result is guaranteed to be valid for this * encoding scheme. * * If the input array is already valid, this function returns the * original, otherwise it constructs a new array by replacing all illegal * sequences with the encoding scheme's replacement sequence. * * Params: * s = the string to be sanitized */ immutable(ubyte)[] sanitize(immutable(ubyte)[] s) { auto n = validLength(s); if (n == s.length) return s; auto repSeq = replacementSequence; // Count how long the string needs to be. // Overestimating is not a problem auto len = s.length; const(ubyte)[] t = s[n..$]; while (t.length != 0) { dchar c = safeDecode(t); assert(c == INVALID_SEQUENCE); len += repSeq.length; t = t[validLength(t)..$]; } // Now do the write ubyte[] array = new ubyte[len]; array[0..n] = s[0..n]; auto offset = n; t = s[n..$]; while (t.length != 0) { dchar c = safeDecode(t); assert(c == INVALID_SEQUENCE); array[offset..offset+repSeq.length] = repSeq[]; offset += repSeq.length; n = validLength(t); array[offset..offset+n] = t[0..n]; offset += n; t = t[n..$]; } return cast(immutable(ubyte)[])array[0..offset]; } /** * Returns the length of the first encoded sequence. * * The input to this function MUST be validly encoded. * This is enforced by the function's in-contract. * * Params: * s = the array to be sliced */ size_t firstSequence(const(ubyte)[] s) in { assert(s.length != 0); const(ubyte)[] u = s; assert(safeDecode(u) != INVALID_SEQUENCE); } body { const(ubyte)[] t = s; decode(s); return t.length - s.length; } /** * Returns the total number of code points encoded in a ubyte array. * * The input to this function MUST be validly encoded. * This is enforced by the function's in-contract. * * Params: * s = the string to be counted */ size_t count(const(ubyte)[] s) in { assert(isValid(s)); } body { size_t n = 0; while (s.length != 0) { decode(s); ++n; } return n; } /** * Returns the array index at which the (n+1)th code point begins. * * The input to this function MUST be validly encoded. * This is enforced by the function's in-contract. * * Params: * s = the string to be counted */ ptrdiff_t index(const(ubyte)[] s, size_t n) in { assert(isValid(s)); assert(n >= 0); } body { const(ubyte)[] t = s; for (size_t i=0; i<n; ++i) decode(s); return t.length - s.length; } __gshared string[string] supported; } /** EncodingScheme to handle ASCII This scheme recognises the following names: "ANSI_X3.4-1968", "ANSI_X3.4-1986", "ASCII", "IBM367", "ISO646-US", "ISO_646.irv:1991", "US-ASCII", "cp367", "csASCII" "iso-ir-6", "us" */ class EncodingSchemeASCII : EncodingScheme { shared static this() { EncodingScheme.register("std.encoding.EncodingSchemeASCII"); } const { override string[] names() { return [ cast(string) "ANSI_X3.4-1968", "ANSI_X3.4-1986", "ASCII", "IBM367", "ISO646-US", "ISO_646.irv:1991", "US-ASCII", "cp367", "csASCII" "iso-ir-6", "us" ]; } override string toString() { return "ASCII"; } override bool canEncode(dchar c) { return std.encoding.canEncode!(AsciiChar)(c); } override size_t encodedLength(dchar c) { return std.encoding.encodedLength!(AsciiChar)(c); } override size_t encode(dchar c, ubyte[] buffer) { auto r = cast(AsciiChar[])buffer; return std.encoding.encode(c,r); } override dchar decode(ref const(ubyte)[] s) { auto t = cast(const(AsciiChar)[]) s; dchar c = std.encoding.decode(t); s = s[$-t.length..$]; return c; } override dchar safeDecode(ref const(ubyte)[] s) { auto t = cast(const(AsciiChar)[]) s; dchar c = std.encoding.safeDecode(t); s = s[$-t.length..$]; return c; } override @property immutable(ubyte)[] replacementSequence() { return cast(immutable(ubyte)[])"?"; } } } /** EncodingScheme to handle Latin-1 This scheme recognises the following names: "CP819", "IBM819", "ISO-8859-1", "ISO_8859-1", "ISO_8859-1:1987", "csISOLatin1", "iso-ir-100", "l1", "latin1" */ class EncodingSchemeLatin1 : EncodingScheme { shared static this() { EncodingScheme.register("std.encoding.EncodingSchemeLatin1"); } const { override string[] names() { return [ cast(string) "CP819", "IBM819", "ISO-8859-1", "ISO_8859-1", "ISO_8859-1:1987", "csISOLatin1", "iso-ir-100", "l1", "latin1" ]; } override string toString() { return "ISO-8859-1"; } override bool canEncode(dchar c) { return std.encoding.canEncode!(Latin1Char)(c); } override size_t encodedLength(dchar c) { return std.encoding.encodedLength!(Latin1Char)(c); } override size_t encode(dchar c, ubyte[] buffer) { auto r = cast(Latin1Char[])buffer; return std.encoding.encode(c,r); } override dchar decode(ref const(ubyte)[] s) { auto t = cast(const(Latin1Char)[]) s; dchar c = std.encoding.decode(t); s = s[$-t.length..$]; return c; } override dchar safeDecode(ref const(ubyte)[] s) { auto t = cast(const(Latin1Char)[]) s; dchar c = std.encoding.safeDecode(t); s = s[$-t.length..$]; return c; } override @property immutable(ubyte)[] replacementSequence() { return cast(immutable(ubyte)[])"?"; } } } /** EncodingScheme to handle Windows-1252 This scheme recognises the following names: "windows-1252" */ class EncodingSchemeWindows1252 : EncodingScheme { shared static this() { EncodingScheme.register("std.encoding.EncodingSchemeWindows1252"); } const { override string[] names() { return [ cast(string) "windows-1252" ]; } override string toString() { return "windows-1252"; } override bool canEncode(dchar c) { return std.encoding.canEncode!(Windows1252Char)(c); } override size_t encodedLength(dchar c) { return std.encoding.encodedLength!(Windows1252Char)(c); } override size_t encode(dchar c, ubyte[] buffer) { auto r = cast(Windows1252Char[])buffer; return std.encoding.encode(c,r); } override dchar decode(ref const(ubyte)[] s) { auto t = cast(const(Windows1252Char)[]) s; dchar c = std.encoding.decode(t); s = s[$-t.length..$]; return c; } override dchar safeDecode(ref const(ubyte)[] s) { auto t = cast(const(Windows1252Char)[]) s; dchar c = std.encoding.safeDecode(t); s = s[$-t.length..$]; return c; } override @property immutable(ubyte)[] replacementSequence() { return cast(immutable(ubyte)[])"?"; } } } /** EncodingScheme to handle UTF-8 This scheme recognises the following names: "UTF-8" */ class EncodingSchemeUtf8 : EncodingScheme { shared static this() { EncodingScheme.register("std.encoding.EncodingSchemeUtf8"); } const { override string[] names() { return [ cast(string) "UTF-8" ]; } override string toString() { return "UTF-8"; } override bool canEncode(dchar c) { return std.encoding.canEncode!(char)(c); } override size_t encodedLength(dchar c) { return std.encoding.encodedLength!(char)(c); } override size_t encode(dchar c, ubyte[] buffer) { auto r = cast(char[])buffer; return std.encoding.encode(c,r); } override dchar decode(ref const(ubyte)[] s) { auto t = cast(const(char)[]) s; dchar c = std.encoding.decode(t); s = s[$-t.length..$]; return c; } override dchar safeDecode(ref const(ubyte)[] s) { auto t = cast(const(char)[]) s; dchar c = std.encoding.safeDecode(t); s = s[$-t.length..$]; return c; } override @property immutable(ubyte)[] replacementSequence() { return cast(immutable(ubyte)[])"\uFFFD"; } } } /** EncodingScheme to handle UTF-16 in native byte order This scheme recognises the following names: "UTF-16LE" (little-endian architecture only) "UTF-16BE" (big-endian architecture only) */ class EncodingSchemeUtf16Native : EncodingScheme { shared static this() { EncodingScheme.register("std.encoding.EncodingSchemeUtf16Native"); } const { version(LittleEndian) { enum string NAME = "UTF-16LE"; } version(BigEndian) { enum string NAME = "UTF-16BE"; } override string[] names() { return [ NAME ]; } override string toString() { return NAME; } override bool canEncode(dchar c) { return std.encoding.canEncode!(wchar)(c); } override size_t encodedLength(dchar c) { return std.encoding.encodedLength!(wchar)(c); } override size_t encode(dchar c, ubyte[] buffer) { auto r = cast(wchar[])buffer; return wchar.sizeof * std.encoding.encode(c,r); } override dchar decode(ref const(ubyte)[] s) in { assert((s.length & 1) == 0); } body { auto t = cast(const(wchar)[]) s; dchar c = std.encoding.decode(t); s = s[$-t.length..$]; return c; } override dchar safeDecode(ref const(ubyte)[] s) in { assert((s.length & 1) == 0); } body { auto t = cast(const(wchar)[]) s; dchar c = std.encoding.safeDecode(t); s = s[$-t.length..$]; return c; } override @property immutable(ubyte)[] replacementSequence() { return cast(immutable(ubyte)[])"\uFFFD"w; } } } /** EncodingScheme to handle UTF-32 in native byte order This scheme recognises the following names: "UTF-32LE" (little-endian architecture only) "UTF-32BE" (big-endian architecture only) */ class EncodingSchemeUtf32Native : EncodingScheme { shared static this() { EncodingScheme.register("std.encoding.EncodingSchemeUtf32Native"); } const { version(LittleEndian) { enum string NAME = "UTF-32LE"; } version(BigEndian) { enum string NAME = "UTF-32BE"; } override string[] names() { return [ NAME ]; } override string toString() { return NAME; } override bool canEncode(dchar c) { return std.encoding.canEncode!(dchar)(c); } override size_t encodedLength(dchar c) { return std.encoding.encodedLength!(dchar)(c); } override size_t encode(dchar c, ubyte[] buffer) { auto r = cast(dchar[])buffer; return dchar.sizeof * std.encoding.encode(c,r); } override dchar decode(ref const(ubyte)[] s) in { assert((s.length & 3) == 0); } body { auto t = cast(const(dchar)[]) s; dchar c = std.encoding.decode(t); s = s[$-t.length..$]; return c; } override dchar safeDecode(ref const(ubyte)[] s) in { assert((s.length & 3) == 0); } body { auto t = cast(const(dchar)[]) s; dchar c = std.encoding.safeDecode(t); s = s[$-t.length..$]; return c; } override @property immutable(ubyte)[] replacementSequence() { return cast(immutable(ubyte)[])"\uFFFD"d; } } } //============================================================================= // Helper functions version(unittest) { void transcodeReverse(Src,Dst)(immutable(Src)[] s, out immutable(Dst)[] r) { static if(is(Src==Dst)) { return s; } else static if(is(Src==AsciiChar)) { transcodeReverse!(char,Dst)(cast(string)s,r); } else { foreach_reverse(d;codePoints(s)) { foreach_reverse(c;codeUnits!(Dst)(d)) { r = c ~ r; } } } } string makeReadable(string s) { string r = "\""; foreach(char c;s) { if (c >= 0x20 && c < 0x80) { r ~= c; } else { r ~= "\\x"; r ~= toHexDigit(c >> 4); r ~= toHexDigit(c); } } r ~= "\""; return r; } string makeReadable(wstring s) { string r = "\""; foreach(wchar c;s) { if (c >= 0x20 && c < 0x80) { r ~= cast(char) c; } else { r ~= "\\u"; r ~= toHexDigit(c >> 12); r ~= toHexDigit(c >> 8); r ~= toHexDigit(c >> 4); r ~= toHexDigit(c); } } r ~= "\"w"; return r; } string makeReadable(dstring s) { string r = "\""; foreach(dchar c; s) { if (c >= 0x20 && c < 0x80) { r ~= cast(char) c; } else if (c < 0x10000) { r ~= "\\u"; r ~= toHexDigit(c >> 12); r ~= toHexDigit(c >> 8); r ~= toHexDigit(c >> 4); r ~= toHexDigit(c); } else { r ~= "\\U00"; r ~= toHexDigit(c >> 20); r ~= toHexDigit(c >> 16); r ~= toHexDigit(c >> 12); r ~= toHexDigit(c >> 8); r ~= toHexDigit(c >> 4); r ~= toHexDigit(c); } } r ~= "\"d"; return r; } char toHexDigit(int n) { return "0123456789ABCDEF"[n & 0xF]; } }
D
/** * This module contains a packed bit array implementation in the style of D's * built-in dynamic arrays. * * Copyright: Copyright (%C) 2005-2006 Digital Mars, www.digitalmars.com. * All rights reserved. * License: BSD style: $(LICENSE) * Authors: Walter Bright, Sean Kelly */ module tango.core.BitArray; import tango.io.Stdout; private import tango.core.BitManip; /** * This struct represents an array of boolean values, each of which occupy one * bit of memory for storage. Thus an array of 32 bits would occupy the same * space as one integer value. The typical array operations--such as indexing * and sorting--are supported, as well as bitwise operations such as and, or, * xor, and complement. */ struct BitArray { size_t len; size_t* ptr; enum bits_in_size=(size_t.sizeof*8); /** * This initializes a BitArray of bits.length bits, where each bit value * matches the corresponding boolean value in bits. * * Params: * bits = The initialization value. * * Returns: * A BitArray with the same number and sequence of elements as bits. */ /*static BitArray opCall( bool[] bits ) { BitArray temp; temp.length = bits.length; foreach( pos, val; bits ) temp[pos] = val; return temp; }*/ this(size_t _len, size_t* _ptr) pure { len = _len; ptr = _ptr; } this(const bool[] bits) pure { this.length = bits.length; foreach( pos, val; bits ) this[pos] = val; } /** * Get the number of bits in this array. * * Returns: * The number of bits in this array. */ @property const size_t length() pure { return len; } /** * Resizes this array to newlen bits. If newlen is larger than the current * length, the new bits will be initialized to zero. * * Params: * newlen = The number of bits this array should contain. */ @property void length(const size_t newlen ) pure { if( newlen != len ) { auto olddim = dim(); auto newdim = (newlen + (bits_in_size-1)) / bits_in_size; if( newdim != olddim ) { // Create a fake array so we can use D's realloc machinery size_t[] buf = ptr[0 .. olddim]; buf.length = newdim; // realloc ptr = buf.ptr; if( newdim & (bits_in_size-1) ) { // Set any pad bits to 0 ptr[newdim - 1] &= ~(~0 << (newdim & (bits_in_size-1))); } } len = newlen; } } /** * Gets the length of a size_t array large enough to hold all stored bits. * * Returns: * The size a size_t array would have to be to store this array. */ @property const size_t dim() const pure { return (len + (bits_in_size-1)) / bits_in_size; } /** * Duplicates this array, much like the dup property for built-in arrays. * * Returns: * A duplicate of this array. */ @property BitArray dup() const { BitArray ba; size_t[] buf = ptr[0 .. dim].dup; ba.len = len; ba.ptr = buf.ptr; return ba; } debug( UnitTest ) { unittest { BitArray a; BitArray b; a.length = 3; a[0] = 1; a[1] = 0; a[2] = 1; b = a.dup; assert( b.length == 3 ); for( int i = 0; i < 3; ++i ) { assert( b[i] == (((i ^ 1) & 1) ? true : false) ); } } } /** * Resets the length of this array to bits.length and then initializes this * * Resizes this array to hold bits.length bits and initializes each bit * value to match the corresponding boolean value in bits. * * Params: * bits = The initialization value. */ this(this) { ptr = ptr; len = len; } void opAssign( bool[] bits ) { length = bits.length; foreach( i, b; bits ) { (this)[i] = b; } } /** * Copy the bits from one array into this array. This is not a shallow * copy. * * Params: * rhs = A BitArray with at least the same number of bits as this bit * array. * * Returns: * A shallow copy of this array. * * -------------------- * BitArray ba = [0,1,0,1,0]; * BitArray ba2; * ba2.length = ba.length; * ba2[] = ba; // perform the copy * ba[0] = true; * assert(ba2[0] == false); * -------------------- */ BitArray opSliceAssign(BitArray rhs) in { assert(rhs.len == len); } body { size_t mDim=len/bits_in_size; ptr[0..mDim] = rhs.ptr[0..mDim]; int rest=cast(int)(len & cast(size_t)(bits_in_size-1)); if (rest){ size_t mask=(~0u)<<rest; ptr[mDim]=(rhs.ptr[mDim] & (~mask))|(ptr[mDim] & mask); } return this; } /** * Map BitArray onto target, with numbits being the number of bits in the * array. Does not copy the data. This is the inverse of opCast. * * Params: * target = The array to map. * numbits = The number of bits to map in target. */ void init( void[] target, size_t numbits ) in { assert( numbits <= target.length * 8 ); assert( (target.length & 3) == 0 ); } body { ptr = cast(size_t*)target.ptr; len = numbits; } debug( UnitTest ) { unittest { BitArray a = [1,0,1,0,1]; BitArray b; void[] buf; buf = cast(void[])a; b.init( buf, a.length ); assert( b[0] == 1 ); assert( b[1] == 0 ); assert( b[2] == 1 ); assert( b[3] == 0 ); assert( b[4] == 1 ); a[0] = 0; assert( b[0] == 0 ); assert( a == b ); // test opSliceAssign BitArray c; c.length = a.length; c[] = a; assert( c == a ); a[0] = 1; assert( c != a ); } } /** * Reverses the contents of this array in place, much like the reverse * property for built-in arrays. * * Returns: * A shallow copy of this array. */ @property ref BitArray reverse() out( result ) { assert( result == this ); } body { if( len >= 2 ) { bool t; size_t lo, hi; lo = 0; hi = len - 1; for( ; lo < hi; ++lo, --hi ) { t = (this)[lo]; (this)[lo] = (this)[hi]; (this)[hi] = t; } } return this; } debug( UnitTest ) { unittest { static bool[5] data = [1,0,1,1,0]; BitArray b = data; b.reverse; for( size_t i = 0; i < data.length; ++i ) { assert( b[i] == data[4 - i] ); } } } /** * Sorts this array in place, with zero entries sorting before one. This * is equivalent to the sort property for built-in arrays. * * Returns: * A shallow copy of this array. */ @property ref BitArray sort() out( result ) { assert( result == this ); } body { if( len >= 2 ) { size_t lo, hi; lo = 0; hi = len - 1; while( true ) { while( true ) { if( lo >= hi ) goto Ldone; if( (this)[lo] == true ) break; ++lo; } while( true ) { if( lo >= hi ) goto Ldone; if( (this)[hi] == false ) break; --hi; } (this)[lo] = false; (this)[hi] = true; ++lo; --hi; } Ldone: ; } return this; } debug( UnitTest ) { unittest { size_t x = 0b1100011000; auto ba = BitArray(10, &x); ba.sort; for( size_t i = 0; i < 6; ++i ) assert( ba[i] == false ); for( size_t i = 6; i < 10; ++i ) assert( ba[i] == true ); } } /** * Operates on all bits in this array. * * Params: * dg = The supplied code as a delegate. */ int opApply(scope int delegate(ref bool) dg ) { int result; for( size_t i = 0; i < len; ++i ) { bool b = opIndex( i ); result = dg( b ); opIndexAssign( b, i ); if( result ) break; } return result; } /** ditto */ int opApply(scope int delegate(ref size_t, ref bool) dg ) { int result; for( size_t i = 0; i < len; ++i ) { bool b = opIndex( i ); result = dg( i, b ); opIndexAssign( b, i ); if( result ) break; } return result; } debug( UnitTest ) { unittest { BitArray a = [1,0,1]; int i; foreach( b; a ) { switch( i ) { case 0: assert( b == true ); break; case 1: assert( b == false ); break; case 2: assert( b == true ); break; default: assert( false ); } i++; } foreach( j, b; a ) { switch( j ) { case 0: assert( b == true ); break; case 1: assert( b == false ); break; case 2: assert( b == true ); break; default: assert( false ); } } } } /** * Compares this array to another for equality. Two bit arrays are equal * if they are the same size and contain the same series of bits. * * Params: * rhs = The array to compare against. * * Returns: * false if not equal and non-zero otherwise. */ const bool opEquals(ref const(BitArray) rhs) const { if( this.length() != rhs.length() ) return 0; // not equal const size_t* p1 = this.ptr; const size_t* p2 = rhs.ptr; size_t n = this.length / bits_in_size; size_t i; for( i = 0; i < n; ++i ) { if( p1[i] != p2[i] ) return 0; // not equal } int rest = cast(int)(this.length & cast(size_t)(bits_in_size-1)); size_t mask = ~((~0u)<<rest); return (rest == 0) || (p1[i] & mask) == (p2[i] & mask); } debug( UnitTest ) { unittest { BitArray a = [1,0,1,0,1]; BitArray b = [1,0,1]; BitArray c = [1,0,1,0,1,0,1]; const(BitArray) d = [1,0,1,1,1]; auto e = immutable(BitArray)([1,0,1,0,1]); assert(a != b); assert(a != c); assert(a != d); assert(a == e); } } /** * Performs a lexicographical comparison of this array to the supplied * array. * * Params: * rhs = The array to compare against. * * Returns: * A value less than zero if this array sorts before the supplied array, * zero if the arrays are equavalent, and a value greater than zero if * this array sorts after the supplied array. */ int opCmp( ref const(BitArray) rhs ) const { auto len = this.length; if( rhs.length < len ) len = rhs.length; auto p1 = this.ptr; auto p2 = rhs.ptr; size_t n = len / bits_in_size; size_t i; for( i = 0; i < n; ++i ) { if( p1[i] != p2[i] ){ return ((p1[i] < p2[i])?-1:1); } } int rest=cast(int)(len & cast(size_t) (bits_in_size-1)); if (rest>0) { size_t mask=~((~0u)<<rest); size_t v1=p1[i] & mask; size_t v2=p2[i] & mask; if (v1 != v2) return ((v1<v2)?-1:1); } return ((this.length<rhs.length)?-1:((this.length==rhs.length)?0:1)); } debug( UnitTest ) { unittest { BitArray a = [1,0,1,0,1]; BitArray b = [1,0,1]; BitArray c = [1,0,1,0,1,0,1]; BitArray d = [1,0,1,1,1]; BitArray e = [1,0,1,0,1]; BitArray f = [1,0,1,0]; assert( a > b ); assert( a >= b ); assert( a < c ); assert( a <= c ); assert( a < d ); assert( a <= d ); assert( a == e ); assert( a <= e ); assert( a >= e ); assert( f > b ); } } /** * Convert this array to a void array. * * Returns: * This array represented as a void array. */ void[] opCast() const { return cast(void[])ptr[0 .. dim]; } debug( UnitTest ) { unittest { BitArray a = [1,0,1,0,1]; void[] v = cast(void[])a; assert( v.length == a.dim * size_t.sizeof ); } } /** * Support for index operations, much like the behavior of built-in arrays. * * Params: * pos = The desired index position. * * In: * pos must be less than the length of this array. * * Returns: * The value of the bit at pos. */ bool opIndex( size_t pos ) const in { assert( pos < len ); } body { return cast(bool)bt( ptr, pos ); } /** * Generates a copy of this array with the unary complement operation * applied. * * Returns: * A new array which is the complement of this array. */ BitArray opCom() { auto dim = this.dim(); BitArray result; result.length = len; for( size_t i = 0; i < dim; ++i ) result.ptr[i] = ~this.ptr[i]; if( len & (bits_in_size-1) ) result.ptr[dim - 1] &= ~(~0 << (len & (bits_in_size-1))); return result; } debug( UnitTest ) { unittest { BitArray a = [1,0,1,0,1]; BitArray b = ~a; assert(b[0] == 0); assert(b[1] == 1); assert(b[2] == 0); assert(b[3] == 1); assert(b[4] == 0); } } /** * Generates a new array which is the result of a bitwise and operation * between this array and the supplied array. * * Params: * rhs = The array with which to perform the bitwise and operation. * * In: * rhs.length must equal the length of this array. * * Returns: * A new array which is the result of a bitwise and with this array and * the supplied array. */ BitArray opAnd( ref const(BitArray) rhs ) const in { assert( len == rhs.length ); } body { auto dim = this.dim(); BitArray result; result.length = len; for( size_t i = 0; i < dim; ++i ) result.ptr[i] = this.ptr[i] & rhs.ptr[i]; return result; } debug( UnitTest ) { unittest { BitArray a = [1,0,1,0,1]; BitArray b = [1,0,1,1,0]; BitArray c = a & b; assert(c[0] == 1); assert(c[1] == 0); assert(c[2] == 1); assert(c[3] == 0); assert(c[4] == 0); } } /** * Generates a new array which is the result of a bitwise or operation * between this array and the supplied array. * * Params: * rhs = The array with which to perform the bitwise or operation. * * In: * rhs.length must equal the length of this array. * * Returns: * A new array which is the result of a bitwise or with this array and * the supplied array. */ BitArray opOr( ref const(BitArray) rhs ) const in { assert( len == rhs.length ); } body { auto dim = this.dim(); BitArray result; result.length = len; for( size_t i = 0; i < dim; ++i ) result.ptr[i] = this.ptr[i] | rhs.ptr[i]; return result; } debug( UnitTest ) { unittest { BitArray a = [1,0,1,0,1]; BitArray b = [1,0,1,1,0]; BitArray c = a | b; assert(c[0] == 1); assert(c[1] == 0); assert(c[2] == 1); assert(c[3] == 1); assert(c[4] == 1); const BitArray d = [1,1,1,0,0]; c = a | d; assert(c[0] == 1); assert(c[1] == 1); assert(c[2] == 1); assert(c[3] == 0); assert(c[4] == 1); auto e = immutable(BitArray)([1,0,1,0,0]) ; c = a | e; assert(c[0] == 1); assert(c[1] == 0); assert(c[2] == 1); assert(c[3] == 0); assert(c[4] == 1); } } /** * Generates a new array which is the result of a bitwise xor operation * between this array and the supplied array. * * Params: * rhs = The array with which to perform the bitwise xor operation. * * In: * rhs.length must equal the length of this array. * * Returns: * A new array which is the result of a bitwise xor with this array and * the supplied array. */ BitArray opXor( ref const(BitArray) rhs ) const in { assert( len == rhs.length ); } body { auto dim = this.dim(); BitArray result; result.length = len; for( size_t i = 0; i < dim; ++i ) result.ptr[i] = this.ptr[i] ^ rhs.ptr[i]; return result; } debug( UnitTest ) { unittest { BitArray a = [1,0,1,0,1]; BitArray b = [1,0,1,1,0]; BitArray c = a ^ b; assert(c[0] == 0); assert(c[1] == 0); assert(c[2] == 0); assert(c[3] == 1); assert(c[4] == 1); const BitArray d = [0,0,1,1,0]; c = a ^ d; assert(c[0] == 1); assert(c[1] == 0); assert(c[2] == 0); assert(c[3] == 1); assert(c[4] == 1); const BitArray e = [0,0,1,0,0]; c = a ^ e; assert(c[0] == 1); assert(c[1] == 0); assert(c[2] == 0); assert(c[3] == 0); assert(c[4] == 1); } } /** * Generates a new array which is the result of this array minus the * supplied array. $(I a - b) for BitArrays means the same thing as * $(I a &amp; ~b). * * Params: * rhs = The array with which to perform the subtraction operation. * * In: * rhs.length must equal the length of this array. * * Returns: * A new array which is the result of this array minus the supplied array. */ BitArray opSub( ref const(BitArray) rhs ) const in { assert( len == rhs.length ); } body { auto dim = this.dim(); BitArray result; result.length = len; for( size_t i = 0; i < dim; ++i ) result.ptr[i] = this.ptr[i] & ~rhs.ptr[i]; return result; } debug( UnitTest ) { unittest { BitArray a = [1,0,1,0,1]; BitArray b = [1,0,1,1,0]; BitArray c = a - b; assert( c[0] == 0 ); assert( c[1] == 0 ); assert( c[2] == 0 ); assert( c[3] == 0 ); assert( c[4] == 1 ); const BitArray d = [0,0,1,1,0]; c = a - d; assert( c[0] == 1 ); assert( c[1] == 0 ); assert( c[2] == 0 ); assert( c[3] == 0 ); assert( c[4] == 1 ); auto e = immutable(BitArray)([0,0,0,1,1]); c = a - e; assert( c[0] == 1 ); assert( c[1] == 0 ); assert( c[2] == 1 ); assert( c[3] == 0 ); assert( c[4] == 0 ); } } /** * Generates a new array which is the result of this array concatenated * with the supplied array. * * Params: * rhs = The array with which to perform the concatenation operation. * * Returns: * A new array which is the result of this array concatenated with the * supplied array. */ BitArray opCat( bool rhs ) const { BitArray result; result = this.dup; result.length = len + 1; result[len] = rhs; return result; } /** ditto */ BitArray opCat_r( bool lhs ) const { BitArray result; result.length = len + 1; result[0] = lhs; for( size_t i = 0; i < len; ++i ) result[1 + i] = (this)[i]; return result; } /** ditto */ BitArray opCat( ref const(BitArray) rhs ) const { BitArray result; result = this.dup(); result ~= rhs; return result; } debug( UnitTest ) { unittest { BitArray a = [1,0]; BitArray b = [0,1,0]; BitArray c; c = (a ~ b); assert( c.length == 5 ); assert( c[0] == 1 ); assert( c[1] == 0 ); assert( c[2] == 0 ); assert( c[3] == 1 ); assert( c[4] == 0 ); c = (a ~ true); assert( c.length == 3 ); assert( c[0] == 1 ); assert( c[1] == 0 ); assert( c[2] == 1 ); c = (false ~ a); assert( c.length == 3 ); assert( c[0] == 0 ); assert( c[1] == 1 ); assert( c[2] == 0 ); const BitArray d = [0,1,1]; c = (a ~ d); assert( c.length == 5 ); assert( c[0] == 1 ); assert( c[1] == 0 ); assert( c[2] == 0 ); assert( c[3] == 1 ); assert( c[4] == 1 ); auto e = immutable(BitArray)([1,0,1]); c = (a ~ e); assert( c.length == 5 ); assert( c[0] == 1 ); assert( c[1] == 0 ); assert( c[2] == 1 ); assert( c[3] == 0 ); assert( c[4] == 1 ); } } /** * Support for index operations, much like the behavior of built-in arrays. * * Params: * b = The new bit value to set. * pos = The desired index position. * * In: * pos must be less than the length of this array. * * Returns: * The new value of the bit at pos. */ bool opIndexAssign( bool b, size_t pos ) pure in { assert( pos < len ); } body { if( b ) bts( ptr, pos ); else btr( ptr, pos ); return b; } /** * Updates the contents of this array with the result of a bitwise and * operation between this array and the supplied array. * * Params: * rhs = The array with which to perform the bitwise and operation. * * In: * rhs.length must equal the length of this array. * * Returns: * A shallow copy of this array. */ BitArray opAndAssign( const(BitArray) rhs ) in { assert( len == rhs.length ); } body { auto dim = this.dim(); for( size_t i = 0; i < dim; ++i ) ptr[i] &= rhs.ptr[i]; return this; } debug( UnitTest ) { unittest { BitArray a = [1,0,1,0,1]; BitArray b = [1,0,1,1,0]; a &= b; assert( a[0] == 1 ); assert( a[1] == 0 ); assert( a[2] == 1 ); assert( a[3] == 0 ); assert( a[4] == 0 ); const BitArray d = [1,0,0,1,0]; a &= d; assert( a[0] == 1 ); assert( a[1] == 0 ); assert( a[2] == 0 ); assert( a[3] == 0 ); assert( a[4] == 0 ); } } /** * Updates the contents of this array with the result of a bitwise or * operation between this array and the supplied array. * * Params: * rhs = The array with which to perform the bitwise or operation. * * In: * rhs.length must equal the length of this array. * * Returns: * A shallow copy of this array. */ BitArray opOrAssign( const(BitArray) rhs ) in { assert( len == rhs.length ); } body { auto dim = this.dim(); for( size_t i = 0; i < dim; ++i ) ptr[i] |= rhs.ptr[i]; return this; } debug( UnitTest ) { unittest { BitArray a = [1,0,1,0,1]; BitArray b = [1,0,1,1,0]; a |= b; assert( a[0] == 1 ); assert( a[1] == 0 ); assert( a[2] == 1 ); assert( a[3] == 1 ); assert( a[4] == 1 ); const BitArray e = [1,0,1,0,0]; a=[1,0,1,0,1]; a |= e; assert( a[0] == 1 ); assert( a[1] == 0 ); assert( a[2] == 1 ); assert( a[3] == 0 ); assert( a[4] == 1 ); } } /** * Updates the contents of this array with the result of a bitwise xor * operation between this array and the supplied array. * * Params: * rhs = The array with which to perform the bitwise xor operation. * * In: * rhs.length must equal the length of this array. * * Returns: * A shallow copy of this array. */ BitArray opXorAssign( const(BitArray) rhs ) in { assert( len == rhs.length ); } body { auto dim = this.dim(); for( size_t i = 0; i < dim; ++i ) ptr[i] ^= rhs.ptr[i]; return this; } debug( UnitTest ) { unittest { BitArray a = [1,0,1,0,1]; BitArray b = [1,0,1,1,0]; a ^= b; assert( a[0] == 0 ); assert( a[1] == 0 ); assert( a[2] == 0 ); assert( a[3] == 1 ); assert( a[4] == 1 ); const BitArray e = [1,0,1,0,0]; a = [1,0,1,0,1]; a ^= e; assert( a[0] == 0 ); assert( a[1] == 0 ); assert( a[2] == 0 ); assert( a[3] == 0 ); assert( a[4] == 1 ); } } /** * Updates the contents of this array with the result of this array minus * the supplied array. $(I a - b) for BitArrays means the same thing as * $(I a &amp; ~b). * * Params: * rhs = The array with which to perform the subtraction operation. * * In: * rhs.length must equal the length of this array. * * Returns: * A shallow copy of this array. */ BitArray opSubAssign( const(BitArray) rhs ) in { assert( len == rhs.length ); } body { auto dim = this.dim(); for( size_t i = 0; i < dim; ++i ) ptr[i] &= ~rhs.ptr[i]; return this; } debug( UnitTest ) { unittest { BitArray a = [1,0,1,0,1]; BitArray b = [1,0,1,1,0]; a -= b; assert( a[0] == 0 ); assert( a[1] == 0 ); assert( a[2] == 0 ); assert( a[3] == 0 ); assert( a[4] == 1 ); } } /** * Updates the contents of this array with the result of this array * concatenated with the supplied array. * * Params: * rhs = The array with which to perform the concatenation operation. * * Returns: * A shallow copy of this array. */ BitArray opCatAssign( bool b ) { length = len + 1; (this)[len - 1] = b; return this; } debug( UnitTest ) { unittest { BitArray a = [1,0,1,0,1]; BitArray b; b = (a ~= true); assert( a[0] == 1 ); assert( a[1] == 0 ); assert( a[2] == 1 ); assert( a[3] == 0 ); assert( a[4] == 1 ); assert( a[5] == 1 ); assert( b == a ); } } /** ditto */ BitArray opCatAssign( const(BitArray) rhs ) { auto istart = len; length = len + rhs.length; for( auto i = istart; i < len; ++i ) (this)[i] = rhs[i - istart]; return this; } debug( UnitTest ) { unittest { BitArray a = [1,0]; BitArray b = [0,1,0]; BitArray c; c = (a ~= b); assert( a.length == 5 ); assert( a[0] == 1 ); assert( a[1] == 0 ); assert( a[2] == 0 ); assert( a[3] == 1 ); assert( a[4] == 0 ); assert( c == a ); } } }
D
module UnrealScript.Engine.InterpTrackInstColorProp; import ScriptClasses; import UnrealScript.Helpers; import UnrealScript.Core.UObject; import UnrealScript.Engine.InterpTrackInstProperty; extern(C++) interface InterpTrackInstColorProp : InterpTrackInstProperty { public extern(D): private static __gshared ScriptClass mStaticClass; @property final static ScriptClass StaticClass() { mixin(MGSCC("Class Engine.InterpTrackInstColorProp")); } private static __gshared InterpTrackInstColorProp mDefaultProperties; @property final static InterpTrackInstColorProp DefaultProperties() { mixin(MGDPC("InterpTrackInstColorProp", "InterpTrackInstColorProp Engine.Default__InterpTrackInstColorProp")); } @property final auto ref { UObject.Color ResetColor() { mixin(MGPC("UObject.Color", 72)); } Pointer ColorProp() { mixin(MGPC("Pointer", 68)); } } }
D
/** * Perform constant folding. * * Copyright: Copyright (C) 1999-2022 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/optimize.d, _optimize.d) * Documentation: https://dlang.org/phobos/dmd_optimize.html * Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/optimize.d */ module dmd.optimize; import core.stdc.stdio; import dmd.astenums; import dmd.constfold; import dmd.ctfeexpr; import dmd.dclass; import dmd.declaration; import dmd.dsymbol; import dmd.dsymbolsem; import dmd.errors; import dmd.expression; import dmd.expressionsem; import dmd.globals; import dmd.init; import dmd.mtype; import dmd.printast; import dmd.root.ctfloat; import dmd.sideeffect; import dmd.tokens; import dmd.visitor; /************************************* * If variable has a const initializer, * return that initializer. * Returns: * initializer if there is one, * null if not, * ErrorExp if error */ Expression expandVar(int result, VarDeclaration v) { //printf("expandVar(result = %d, v = %p, %s)\n", result, v, v ? v.toChars() : "null"); /******** * Params: * e = initializer expression */ Expression initializerReturn(Expression e) { if (e.type != v.type) { e = e.castTo(null, v.type); } v.inuse++; e = e.optimize(result); v.inuse--; //if (e) printf("\te = %p, %s, e.type = %d, %s\n", e, e.toChars(), e.type.ty, e.type.toChars()); return e; } static Expression nullReturn() { return null; } static Expression errorReturn() { return ErrorExp.get(); } if (!v) return nullReturn(); if (!v.originalType && v.semanticRun < PASS.semanticdone) // semantic() not yet run v.dsymbolSemantic(null); if (v.type && (v.isConst() || v.isImmutable() || v.storage_class & STC.manifest)) { Type tb = v.type.toBasetype(); if (v.storage_class & STC.manifest || tb.isscalar() || ((result & WANTexpand) && (tb.ty != Tsarray && tb.ty != Tstruct))) { if (v._init) { if (v.inuse) { if (v.storage_class & STC.manifest) { v.error("recursive initialization of constant"); return errorReturn(); } return nullReturn(); } Expression ei = v.getConstInitializer(); if (!ei) { if (v.storage_class & STC.manifest) { v.error("enum cannot be initialized with `%s`", v._init.toChars()); return errorReturn(); } return nullReturn(); } if (ei.op == EXP.construct || ei.op == EXP.blit) { AssignExp ae = cast(AssignExp)ei; ei = ae.e2; if (ei.isConst() == 1) { } else if (ei.op == EXP.string_) { // https://issues.dlang.org/show_bug.cgi?id=14459 // Do not constfold the string literal // if it's typed as a C string, because the value expansion // will drop the pointer identity. if (!(result & WANTexpand) && ei.type.toBasetype().ty == Tpointer) return nullReturn(); } else return nullReturn(); if (ei.type == v.type) { // const variable initialized with const expression } else if (ei.implicitConvTo(v.type) >= MATCH.constant) { // const var initialized with non-const expression ei = ei.implicitCastTo(null, v.type); ei = ei.expressionSemantic(null); } else return nullReturn(); } else if (!(v.storage_class & STC.manifest) && ei.isConst() != 1 && ei.op != EXP.string_ && ei.op != EXP.address) { return nullReturn(); } if (!ei.type) { return nullReturn(); } else { // Should remove the copy() operation by // making all mods to expressions copy-on-write return initializerReturn(ei.copy()); } } else { // v does not have an initializer version (all) { return nullReturn(); } else { // BUG: what if const is initialized in constructor? auto e = v.type.defaultInit(); e.loc = e1.loc; return initializerReturn(e); } } assert(0); } } return nullReturn(); } private Expression fromConstInitializer(int result, Expression e1) { //printf("fromConstInitializer(result = %x, %s)\n", result, e1.toChars()); //static int xx; if (xx++ == 10) assert(0); Expression e = e1; if (auto ve = e1.isVarExp()) { VarDeclaration v = ve.var.isVarDeclaration(); e = expandVar(result, v); if (e) { // If it is a comma expression involving a declaration, we mustn't // perform a copy -- we'd get two declarations of the same variable. // See bugzilla 4465. if (e.op == EXP.comma && e.isCommaExp().e1.isDeclarationExp()) e = e1; else if (e.type != e1.type && e1.type && e1.type.ty != Tident) { // Type 'paint' operation e = e.copy(); e.type = e1.type; } e.loc = e1.loc; } else { e = e1; } } return e; } /*** * It is possible for constant folding to change an array expression of * unknown length, into one where the length is known. * If the expression 'arr' is a literal, set lengthVar to be its length. * Params: * lengthVar = variable declaration for the `.length` property * arr = String, ArrayLiteral, or of TypeSArray */ package void setLengthVarIfKnown(VarDeclaration lengthVar, Expression arr) { if (!lengthVar) return; if (lengthVar._init && !lengthVar._init.isVoidInitializer()) return; // we have previously calculated the length dinteger_t len; if (auto se = arr.isStringExp()) len = se.len; else if (auto ale = arr.isArrayLiteralExp()) len = ale.elements.dim; else { auto tsa = arr.type.toBasetype().isTypeSArray(); if (!tsa) return; // we don't know the length yet len = tsa.dim.toInteger(); } Expression dollar = new IntegerExp(Loc.initial, len, Type.tsize_t); lengthVar._init = new ExpInitializer(Loc.initial, dollar); lengthVar.storage_class |= STC.static_ | STC.const_; } /*** * Same as above, but determines the length from 'type'. * Params: * lengthVar = variable declaration for the `.length` property * type = TypeSArray */ package void setLengthVarIfKnown(VarDeclaration lengthVar, Type type) { if (!lengthVar) return; if (lengthVar._init && !lengthVar._init.isVoidInitializer()) return; // we have previously calculated the length auto tsa = type.toBasetype().isTypeSArray(); if (!tsa) return; // we don't know the length yet const len = tsa.dim.toInteger(); Expression dollar = new IntegerExp(Loc.initial, len, Type.tsize_t); lengthVar._init = new ExpInitializer(Loc.initial, dollar); lengthVar.storage_class |= STC.static_ | STC.const_; } /********************************* * Constant fold an Expression. * Params: * e = expression to const fold; this may get modified in-place * result = WANTvalue, WANTexpand, or both * keepLvalue = `e` is an lvalue, and keep it as an lvalue since it is * an argument to a `ref` or `out` parameter, or the operand of `&` operator * Returns: * Constant folded version of `e` */ Expression Expression_optimize(Expression e, int result, bool keepLvalue) { //printf("Expression_optimize() e: %s result: %d keepLvalue %d\n", e.toChars(), result, keepLvalue); Expression ret = e; void error() { ret = ErrorExp.get(); } /* Returns: true if error */ bool expOptimize(ref Expression e, int flags, bool keepLvalue = false) { if (!e) return false; Expression ex = Expression_optimize(e, flags, keepLvalue); if (ex.op == EXP.error) { ret = ex; // store error result return true; } else { e = ex; // modify original return false; } } bool unaOptimize(UnaExp e, int flags) { return expOptimize(e.e1, flags); } bool binOptimize(BinExp e, int flags, bool keepLhsLvalue = false) { return expOptimize(e.e1, flags, keepLhsLvalue) | expOptimize(e.e2, flags); } void visitExp(Expression e) { //printf("Expression::optimize(result = x%x) %s\n", result, e.toChars()); } void visitVar(VarExp e) { VarDeclaration v = e.var.isVarDeclaration(); if (!(keepLvalue && v && !(v.storage_class & STC.manifest))) ret = fromConstInitializer(result, e); // if unoptimized, try to optimize the dtor expression // (e.g., might be a LogicalExp with constant lhs) if (ret == e && v && v.edtor) { // prevent infinite recursion (`<var>.~this()`) if (!v.inuse) { v.inuse++; expOptimize(v.edtor, WANTvalue); v.inuse--; } } } void visitTuple(TupleExp e) { expOptimize(e.e0, WANTvalue); foreach (ref ex; (*e.exps)[]) { expOptimize(ex, WANTvalue); } } void visitArrayLiteral(ArrayLiteralExp e) { if (e.elements) { expOptimize(e.basis, result & WANTexpand); foreach (ref ex; (*e.elements)[]) { expOptimize(ex, result & WANTexpand); } } } void visitAssocArrayLiteral(AssocArrayLiteralExp e) { assert(e.keys.dim == e.values.dim); foreach (i, ref ekey; (*e.keys)[]) { expOptimize(ekey, result & WANTexpand); expOptimize((*e.values)[i], result & WANTexpand); } } void visitStructLiteral(StructLiteralExp e) { if (e.stageflags & stageOptimize) return; int old = e.stageflags; e.stageflags |= stageOptimize; if (e.elements) { foreach (ref ex; (*e.elements)[]) { expOptimize(ex, result & WANTexpand); } } e.stageflags = old; } void visitUna(UnaExp e) { //printf("UnaExp::optimize() %s\n", e.toChars()); if (unaOptimize(e, result)) return; } void visitNeg(NegExp e) { if (unaOptimize(e, result)) return; if (e.e1.isConst() == 1) { ret = Neg(e.type, e.e1).copy(); } } void visitCom(ComExp e) { if (unaOptimize(e, result)) return; if (e.e1.isConst() == 1) { ret = Com(e.type, e.e1).copy(); } } void visitNop(NotExp e) { if (unaOptimize(e, result)) return; if (e.e1.isConst() == 1) { ret = Not(e.type, e.e1).copy(); } } void visitSymOff(SymOffExp e) { assert(e.var); } void visitAddr(AddrExp e) { //printf("AddrExp::optimize(result = %d, keepLvalue = %d) %s\n", result, keepLvalue, e.toChars()); /* Rewrite &(a,b) as (a,&b) */ if (auto ce = e.e1.isCommaExp()) { auto ae = new AddrExp(e.loc, ce.e2, e.type); ret = new CommaExp(ce.loc, ce.e1, ae); ret.type = e.type; return; } // Keep lvalue-ness if (expOptimize(e.e1, result, true)) return; // error return // Convert &*ex to ex if (auto pe = e.e1.isPtrExp()) { Expression ex = pe.e1; if (e.type.equals(ex.type)) ret = ex; else if (e.type.toBasetype().equivalent(ex.type.toBasetype())) { ret = ex.copy(); ret.type = e.type; } return; } if (auto ve = e.e1.isVarExp()) { if (!ve.var.isReference() && !ve.var.isImportedSymbol()) { ret = new SymOffExp(e.loc, ve.var, 0, ve.hasOverloads); ret.type = e.type; return; } } if (e.e1.isDotVarExp()) { /****************************** * Run down the left side of the a.b.c expression to determine the * leftmost variable being addressed (`a`), and accumulate the offsets of the `.b` and `.c`. * Params: * e = the DotVarExp or VarExp * var = set to the VarExp at the end, or null if doesn't end in VarExp * eint = set to the IntegerExp at the end, or null if doesn't end in IntegerExp * offset = accumulation of all the .var offsets encountered * Returns: true on error */ static bool getVarAndOffset(Expression e, out VarDeclaration var, out IntegerExp eint, ref uint offset) { if (e.type.size() == SIZE_INVALID) // trigger computation of v.offset return true; if (auto dve = e.isDotVarExp()) { auto v = dve.var.isVarDeclaration(); if (!v || !v.isField() || v.isBitFieldDeclaration()) return false; if (getVarAndOffset(dve.e1, var, eint, offset)) return true; offset += v.offset; } else if (auto ve = e.isVarExp()) { if (!ve.var.isReference() && !ve.var.isImportedSymbol() && ve.var.isDataseg() && ve.var.isCsymbol()) { var = ve.var.isVarDeclaration(); } } else if (auto ep = e.isPtrExp()) { if (auto ei = ep.e1.isIntegerExp()) { eint = ei; } else if (auto se = ep.e1.isSymOffExp()) { if (!se.var.isReference() && !se.var.isImportedSymbol() && se.var.isDataseg()) { var = se.var.isVarDeclaration(); offset += se.offset; } } } else if (auto ei = e.isIndexExp()) { if (auto ve = ei.e1.isVarExp()) { if (!ve.var.isReference() && !ve.var.isImportedSymbol() && ve.var.isDataseg() && ve.var.isCsymbol()) { if (auto ie = ei.e2.isIntegerExp()) { var = ve.var.isVarDeclaration(); offset += ie.toInteger() * ve.type.toBasetype().nextOf().size(); } } } } return false; } uint offset; VarDeclaration var; IntegerExp eint; if (getVarAndOffset(e.e1, var, eint, offset)) { ret = ErrorExp.get(); return; } if (var) { ret = new SymOffExp(e.loc, var, offset, false); ret.type = e.type; return; } if (eint) { ret = new IntegerExp(e.loc, eint.toInteger() + offset, e.type); return; } } else if (auto ae = e.e1.isIndexExp()) { if (ae.e2.isIntegerExp() && ae.e1.isIndexExp()) { /* Rewrite `(a[i])[index]` to `(&a[i]) + index*size` */ sinteger_t index = ae.e2.toInteger(); auto ae1 = ae.e1.isIndexExp(); // ae1 is a[i] if (auto ts = ae1.type.isTypeSArray()) { sinteger_t dim = ts.dim.toInteger(); if (index < 0 || index > dim) { e.error("array index %lld is out of bounds `[0..%lld]`", index, dim); return error(); } import core.checkedint : mulu; bool overflow; const offset = mulu(index, ts.nextOf().size(e.loc), overflow); // offset = index*size if (overflow) { e.error("array offset overflow"); return error(); } Expression ex = new AddrExp(ae1.loc, ae1); // &a[i] ex.type = ae1.type.pointerTo(); Expression add = new AddExp(ae.loc, ex, new IntegerExp(ae.loc, offset, e.type)); add.type = e.type; ret = Expression_optimize(add, result, keepLvalue); return; } } // Convert &array[n] to &array+n if (ae.e2.isIntegerExp() && ae.e1.isVarExp()) { sinteger_t index = ae.e2.toInteger(); VarExp ve = ae.e1.isVarExp(); if (ve.type.isTypeSArray() && !ve.var.isImportedSymbol()) { TypeSArray ts = ve.type.isTypeSArray(); sinteger_t dim = ts.dim.toInteger(); if (index < 0 || index >= dim) { /* 0 for C static arrays means size is unknown, no need to check, * and address one past the end is OK, too */ if (!((dim == 0 || dim == index) && ve.var.isCsymbol())) { e.error("array index %lld is out of bounds `[0..%lld]`", index, dim); return error(); } } import core.checkedint : mulu; bool overflow; const offset = mulu(index, ts.nextOf().size(e.loc), overflow); if (overflow) { e.error("array offset overflow"); return error(); } ret = new SymOffExp(e.loc, ve.var, offset); ret.type = e.type; return; } } // Convert &((a.b)[index]) to (&a.b)+index*elementsize else if (ae.e2.isIntegerExp() && ae.e1.isDotVarExp()) { sinteger_t index = ae.e2.toInteger(); DotVarExp ve = ae.e1.isDotVarExp(); if (ve.type.isTypeSArray() && ve.var.isField() && ve.e1.isPtrExp()) { TypeSArray ts = ve.type.isTypeSArray(); sinteger_t dim = ts.dim.toInteger(); if (index < 0 || index >= dim) { /* 0 for C static arrays means size is unknown, no need to check, * and address one past the end is OK, too */ if (!((dim == 0 || dim == index) && ve.var.isCsymbol())) { e.error("array index %lld is out of bounds `[0..%lld]`", index, dim); return error(); } } import core.checkedint : mulu; bool overflow; const offset = mulu(index, ts.nextOf().size(e.loc), overflow); // index*elementsize if (overflow) { e.error("array offset overflow"); return error(); } auto pe = new AddrExp(e.loc, ve); pe.type = e.type; ret = new AddExp(e.loc, pe, new IntegerExp(e.loc, offset, Type.tsize_t)); ret.type = e.type; return; } } } } void visitPtr(PtrExp e) { //printf("PtrExp::optimize(result = x%x) %s\n", result, e.toChars()); if (expOptimize(e.e1, result)) return; // Convert *&ex to ex // But only if there is no type punning involved if (auto ey = e.e1.isAddrExp()) { Expression ex = ey.e1; if (e.type.equals(ex.type)) ret = ex; else if (e.type.toBasetype().equivalent(ex.type.toBasetype())) { ret = ex.copy(); ret.type = e.type; } } if (keepLvalue) return; // Constant fold *(&structliteral + offset) if (e.e1.op == EXP.add) { Expression ex = Ptr(e.type, e.e1).copy(); if (!CTFEExp.isCantExp(ex)) { ret = ex; return; } } if (auto se = e.e1.isSymOffExp()) { VarDeclaration v = se.var.isVarDeclaration(); Expression ex = expandVar(result, v); if (ex && ex.isStructLiteralExp()) { StructLiteralExp sle = ex.isStructLiteralExp(); ex = sle.getField(e.type, cast(uint)se.offset); if (ex && !CTFEExp.isCantExp(ex)) { ret = ex; return; } } } } void visitDotVar(DotVarExp e) { //printf("DotVarExp::optimize(result = x%x) %s\n", result, e.toChars()); if (expOptimize(e.e1, result)) return; if (keepLvalue) return; Expression ex = e.e1; if (auto ve = ex.isVarExp()) { VarDeclaration v = ve.var.isVarDeclaration(); ex = expandVar(result, v); } if (ex && ex.isStructLiteralExp()) { StructLiteralExp sle = ex.isStructLiteralExp(); VarDeclaration vf = e.var.isVarDeclaration(); if (vf && !vf.overlapped) { /* https://issues.dlang.org/show_bug.cgi?id=13021 * Prevent optimization if vf has overlapped fields. */ ex = sle.getField(e.type, vf.offset); if (ex && !CTFEExp.isCantExp(ex)) { ret = ex; return; } } } } void visitNew(NewExp e) { expOptimize(e.thisexp, WANTvalue); // Optimize parameters if (e.arguments) { foreach (ref arg; (*e.arguments)[]) { expOptimize(arg, WANTvalue); } } } void visitCall(CallExp e) { //printf("CallExp::optimize(result = %d) %s\n", result, e.toChars()); // Optimize parameters with keeping lvalue-ness if (expOptimize(e.e1, result)) return; if (e.arguments) { Type t1 = e.e1.type.toBasetype(); if (auto td = t1.isTypeDelegate()) t1 = td.next; // t1 can apparently be void for __ArrayDtor(T) calls if (auto tf = t1.isTypeFunction()) { foreach (i, ref arg; (*e.arguments)[]) { Parameter p = tf.parameterList[i]; bool keep = p && p.isReference(); expOptimize(arg, WANTvalue, keep); } } } } void visitCast(CastExp e) { //printf("CastExp::optimize(result = %d) %s\n", result, e.toChars()); //printf("from %s to %s\n", e.type.toChars(), e.to.toChars()); //printf("from %s\n", e.type.toChars()); //printf("e1.type %s\n", e.e1.type.toChars()); //printf("type = %p\n", e.type); assert(e.type); const op1 = e.e1.op; Expression e1old = e.e1; if (expOptimize(e.e1, result, keepLvalue)) return; if (!keepLvalue) e.e1 = fromConstInitializer(result, e.e1); if (e.e1 == e1old && e.e1.op == EXP.arrayLiteral && e.type.toBasetype().ty == Tpointer && e.e1.type.toBasetype().ty != Tsarray) { // Casting this will result in the same expression, and // infinite loop because of Expression::implicitCastTo() return; // no change } if ((e.e1.op == EXP.string_ || e.e1.op == EXP.arrayLiteral) && (e.type.ty == Tpointer || e.type.ty == Tarray)) { const esz = e.type.nextOf().size(e.loc); const e1sz = e.e1.type.toBasetype().nextOf().size(e.e1.loc); if (esz == SIZE_INVALID || e1sz == SIZE_INVALID) return error(); if (e1sz == esz) { // https://issues.dlang.org/show_bug.cgi?id=12937 // If target type is void array, trying to paint // e.e1 with that type will cause infinite recursive optimization. if (e.type.nextOf().ty == Tvoid) return; ret = e.e1.castTo(null, e.type); //printf(" returning1 %s\n", ret.toChars()); return; } } // Returning e.e1 with changing its type void returnE_e1() { ret = (e1old == e.e1 ? e.e1.copy() : e.e1); ret.type = e.type; } if (e.e1.op == EXP.structLiteral && e.e1.type.implicitConvTo(e.type) >= MATCH.constant) { //printf(" returning2 %s\n", e.e1.toChars()); return returnE_e1(); } /* The first test here is to prevent infinite loops */ if (op1 != EXP.arrayLiteral && e.e1.op == EXP.arrayLiteral) { ret = e.e1.castTo(null, e.to); return; } if (e.e1.op == EXP.null_ && (e.type.ty == Tpointer || e.type.ty == Tclass || e.type.ty == Tarray)) { //printf(" returning3 %s\n", e.e1.toChars()); return returnE_e1(); } if (e.type.ty == Tclass && e.e1.type.ty == Tclass) { import dmd.astenums : Sizeok; // See if we can remove an unnecessary cast ClassDeclaration cdfrom = e.e1.type.isClassHandle(); ClassDeclaration cdto = e.type.isClassHandle(); if (cdfrom.errors || cdto.errors) return error(); if (cdto == ClassDeclaration.object && !cdfrom.isInterfaceDeclaration()) return returnE_e1(); // can always convert a class to Object // Need to determine correct offset before optimizing away the cast. // https://issues.dlang.org/show_bug.cgi?id=16980 cdfrom.size(e.loc); assert(cdfrom.sizeok == Sizeok.done); assert(cdto.sizeok == Sizeok.done || !cdto.isBaseOf(cdfrom, null)); int offset; if (cdto.isBaseOf(cdfrom, &offset) && offset == 0) { //printf(" returning4 %s\n", e.e1.toChars()); return returnE_e1(); } } if (e.e1.type.mutableOf().unSharedOf().equals(e.to.mutableOf().unSharedOf())) { //printf(" returning5 %s\n", e.e1.toChars()); return returnE_e1(); } if (e.e1.isConst()) { if (e.e1.op == EXP.symbolOffset) { if (e.type.toBasetype().ty != Tsarray) { const esz = e.type.size(e.loc); const e1sz = e.e1.type.size(e.e1.loc); if (esz == SIZE_INVALID || e1sz == SIZE_INVALID) return error(); if (esz == e1sz) return returnE_e1(); } return; } if (e.to.toBasetype().ty != Tvoid) { if (e.e1.type.equals(e.type) && e.type.equals(e.to)) ret = e.e1; else ret = Cast(e.loc, e.type, e.to, e.e1).copy(); } } //printf(" returning6 %s\n", ret.toChars()); } void visitBinAssign(BinAssignExp e) { //printf("BinAssignExp::optimize(result = %d) %s\n", result, e.toChars()); if (binOptimize(e, result, /*keepLhsLvalue*/ true)) return; if (e.op == EXP.leftShiftAssign || e.op == EXP.rightShiftAssign || e.op == EXP.unsignedRightShiftAssign) { if (e.e2.isConst() == 1) { sinteger_t i2 = e.e2.toInteger(); uinteger_t sz = e.e1.type.size(e.e1.loc); assert(sz != SIZE_INVALID); sz *= 8; if (i2 < 0 || i2 >= sz) { e.error("shift assign by %lld is outside the range `0..%llu`", i2, cast(ulong)sz - 1); return error(); } } } } void visitBin(BinExp e) { //printf("BinExp::optimize(result = %d) %s\n", result, e.toChars()); const keepLhsLvalue = e.op == EXP.construct || e.op == EXP.blit || e.op == EXP.assign || e.op == EXP.plusPlus || e.op == EXP.minusMinus || e.op == EXP.prePlusPlus || e.op == EXP.preMinusMinus; binOptimize(e, result, keepLhsLvalue); } void visitAdd(AddExp e) { //printf("AddExp::optimize(%s)\n", e.toChars()); if (binOptimize(e, result)) return; if (e.e1.isConst() && e.e2.isConst()) { if (e.e1.op == EXP.symbolOffset && e.e2.op == EXP.symbolOffset) return; ret = Add(e.loc, e.type, e.e1, e.e2).copy(); } } void visitMin(MinExp e) { //printf("MinExp::optimize(%s)\n", e.toChars()); if (binOptimize(e, result)) return; if (e.e1.isConst() && e.e2.isConst()) { if (e.e2.op == EXP.symbolOffset) return; ret = Min(e.loc, e.type, e.e1, e.e2).copy(); } } void visitMul(MulExp e) { //printf("MulExp::optimize(result = %d) %s\n", result, e.toChars()); if (binOptimize(e, result)) return; if (e.e1.isConst() == 1 && e.e2.isConst() == 1) { ret = Mul(e.loc, e.type, e.e1, e.e2).copy(); } } void visitDiv(DivExp e) { //printf("DivExp::optimize(%s)\n", e.toChars()); if (binOptimize(e, result)) return; if (e.e1.isConst() == 1 && e.e2.isConst() == 1) { ret = Div(e.loc, e.type, e.e1, e.e2).copy(); } } void visitMod(ModExp e) { if (binOptimize(e, result)) return; if (e.e1.isConst() == 1 && e.e2.isConst() == 1) { ret = Mod(e.loc, e.type, e.e1, e.e2).copy(); } } extern (D) void shift_optimize(BinExp e, UnionExp function(const ref Loc, Type, Expression, Expression) shift) { if (binOptimize(e, result)) return; if (e.e2.isConst() == 1) { sinteger_t i2 = e.e2.toInteger(); uinteger_t sz = e.e1.type.size(e.e1.loc); assert(sz != SIZE_INVALID); sz *= 8; if (i2 < 0 || i2 >= sz) { e.error("shift by %lld is outside the range `0..%llu`", i2, cast(ulong)sz - 1); return error(); } if (e.e1.isConst() == 1) ret = (*shift)(e.loc, e.type, e.e1, e.e2).copy(); } } void visitShl(ShlExp e) { //printf("ShlExp::optimize(result = %d) %s\n", result, e.toChars()); shift_optimize(e, &Shl); } void visitShr(ShrExp e) { //printf("ShrExp::optimize(result = %d) %s\n", result, e.toChars()); shift_optimize(e, &Shr); } void visitUshr(UshrExp e) { //printf("UshrExp::optimize(result = %d) %s\n", result, toChars()); shift_optimize(e, &Ushr); } void visitAnd(AndExp e) { if (binOptimize(e, result)) return; if (e.e1.isConst() == 1 && e.e2.isConst() == 1) ret = And(e.loc, e.type, e.e1, e.e2).copy(); } void visitOr(OrExp e) { if (binOptimize(e, result)) return; if (e.e1.isConst() == 1 && e.e2.isConst() == 1) ret = Or(e.loc, e.type, e.e1, e.e2).copy(); } void visitXor(XorExp e) { if (binOptimize(e, result)) return; if (e.e1.isConst() == 1 && e.e2.isConst() == 1) ret = Xor(e.loc, e.type, e.e1, e.e2).copy(); } void visitPow(PowExp e) { if (binOptimize(e, result)) return; // All negative integral powers are illegal. if (e.e1.type.isintegral() && (e.e2.op == EXP.int64) && cast(sinteger_t)e.e2.toInteger() < 0) { e.error("cannot raise `%s` to a negative integer power. Did you mean `(cast(real)%s)^^%s` ?", e.e1.type.toBasetype().toChars(), e.e1.toChars(), e.e2.toChars()); return error(); } // If e2 *could* have been an integer, make it one. if (e.e2.op == EXP.float64 && e.e2.toReal() == real_t(cast(sinteger_t)e.e2.toReal())) { // This only applies to floating point, or positive integral powers. if (e.e1.type.isfloating() || cast(sinteger_t)e.e2.toInteger() >= 0) e.e2 = new IntegerExp(e.loc, e.e2.toInteger(), Type.tint64); } if (e.e1.isConst() == 1 && e.e2.isConst() == 1) { Expression ex = Pow(e.loc, e.type, e.e1, e.e2).copy(); if (!CTFEExp.isCantExp(ex)) { ret = ex; return; } } } void visitComma(CommaExp e) { //printf("CommaExp::optimize(result = %d) %s\n", result, e.toChars()); // Comma needs special treatment, because it may // contain compiler-generated declarations. We can interpret them, but // otherwise we must NOT attempt to constant-fold them. // In particular, if the comma returns a temporary variable, it needs // to be an lvalue (this is particularly important for struct constructors) expOptimize(e.e1, WANTvalue); expOptimize(e.e2, result, keepLvalue); if (ret.op == EXP.error) return; if (!e.e1 || e.e1.op == EXP.int64 || e.e1.op == EXP.float64 || !hasSideEffect(e.e1)) { ret = e.e2; if (ret) ret.type = e.type; } //printf("-CommaExp::optimize(result = %d) %s\n", result, e.e.toChars()); } void visitArrayLength(ArrayLengthExp e) { //printf("ArrayLengthExp::optimize(result = %d) %s\n", result, e.toChars()); if (unaOptimize(e, WANTexpand)) return; // CTFE interpret static immutable arrays (to get better diagnostics) if (auto ve = e.e1.isVarExp()) { VarDeclaration v = ve.var.isVarDeclaration(); if (v && (v.storage_class & STC.static_) && (v.storage_class & STC.immutable_) && v._init) { if (Expression ci = v.getConstInitializer()) e.e1 = ci; } } if (e.e1.op == EXP.string_ || e.e1.op == EXP.arrayLiteral || e.e1.op == EXP.assocArrayLiteral || e.e1.type.toBasetype().ty == Tsarray || e.e1.op == EXP.null_) { ret = ArrayLength(e.type, e.e1).copy(); } } void visitEqual(EqualExp e) { //printf("EqualExp::optimize(result = %x) %s\n", result, e.toChars()); if (binOptimize(e, WANTvalue)) return; Expression e1 = fromConstInitializer(result, e.e1); Expression e2 = fromConstInitializer(result, e.e2); if (e1.op == EXP.error) { ret = e1; return; } if (e2.op == EXP.error) { ret = e2; return; } ret = Equal(e.op, e.loc, e.type, e1, e2).copy(); if (CTFEExp.isCantExp(ret)) ret = e; } void visitIdentity(IdentityExp e) { //printf("IdentityExp::optimize(result = %d) %s\n", result, e.toChars()); if (binOptimize(e, WANTvalue)) return; if ((e.e1.isConst() && e.e2.isConst()) || (e.e1.op == EXP.null_ && e.e2.op == EXP.null_)) { ret = Identity(e.op, e.loc, e.type, e.e1, e.e2).copy(); if (CTFEExp.isCantExp(ret)) ret = e; } } void visitIndex(IndexExp e) { //printf("IndexExp::optimize(result = %d) %s\n", result, e.toChars()); if (expOptimize(e.e1, result & WANTexpand)) return; Expression ex = fromConstInitializer(result, e.e1); // We might know $ now setLengthVarIfKnown(e.lengthVar, ex); if (expOptimize(e.e2, WANTvalue)) return; // Don't optimize to an array literal element directly in case an lvalue is requested if (keepLvalue && ex.op == EXP.arrayLiteral) return; ret = Index(e.type, ex, e.e2, e.indexIsInBounds).copy(); if (CTFEExp.isCantExp(ret) || (!ret.isErrorExp() && keepLvalue && !ret.isLvalue())) ret = e; } void visitSlice(SliceExp e) { //printf("SliceExp::optimize(result = %d) %s\n", result, e.toChars()); if (expOptimize(e.e1, result & WANTexpand)) return; if (!e.lwr) { if (e.e1.op == EXP.string_) { // Convert slice of string literal into dynamic array Type t = e.e1.type.toBasetype(); if (Type tn = t.nextOf()) ret = e.e1.castTo(null, tn.arrayOf()); } } else { e.e1 = fromConstInitializer(result, e.e1); // We might know $ now setLengthVarIfKnown(e.lengthVar, e.e1); expOptimize(e.lwr, WANTvalue); expOptimize(e.upr, WANTvalue); if (ret.op == EXP.error) return; ret = Slice(e.type, e.e1, e.lwr, e.upr).copy(); if (CTFEExp.isCantExp(ret)) ret = e; } // https://issues.dlang.org/show_bug.cgi?id=14649 // Leave the slice form so it might be // a part of array operation. // Assume that the backend codegen will handle the form `e[]` // as an equal to `e` itself. if (ret.op == EXP.string_) { e.e1 = ret; e.lwr = null; e.upr = null; ret = e; } //printf("-SliceExp::optimize() %s\n", ret.toChars()); } void visitLogical(LogicalExp e) { //printf("LogicalExp::optimize(%d) %s\n", result, e.toChars()); if (expOptimize(e.e1, WANTvalue)) return; const oror = e.op == EXP.orOr; if (e.e1.toBool().hasValue(oror)) { // Replace with (e1, oror) ret = IntegerExp.createBool(oror); ret = Expression.combine(e.e1, ret); if (e.type.toBasetype().ty == Tvoid) { ret = new CastExp(e.loc, ret, Type.tvoid); ret.type = e.type; } ret = Expression_optimize(ret, result, false); return; } expOptimize(e.e2, WANTvalue); if (e.e1.isConst()) { const e1Opt = e.e1.toBool(); if (e.e2.isConst()) { bool n1 = e1Opt.get(); bool n2 = e.e2.toBool().get(); ret = new IntegerExp(e.loc, oror ? (n1 || n2) : (n1 && n2), e.type); } else if (e1Opt.hasValue(!oror)) { if (e.type.toBasetype().ty == Tvoid) ret = e.e2; else { ret = new CastExp(e.loc, e.e2, e.type); ret.type = e.type; } } } } void visitCmp(CmpExp e) { //printf("CmpExp::optimize() %s\n", e.toChars()); if (binOptimize(e, WANTvalue)) return; Expression e1 = fromConstInitializer(result, e.e1); Expression e2 = fromConstInitializer(result, e.e2); ret = Cmp(e.op, e.loc, e.type, e1, e2).copy(); if (CTFEExp.isCantExp(ret)) ret = e; } void visitCat(CatExp e) { //printf("CatExp::optimize(%d) %s\n", result, e.toChars()); if (binOptimize(e, result)) return; if (auto ce1 = e.e1.isCatExp()) { // https://issues.dlang.org/show_bug.cgi?id=12798 // optimize ((expr ~ str1) ~ str2) scope CatExp cex = new CatExp(e.loc, ce1.e2, e.e2); cex.type = e.type; Expression ex = Expression_optimize(cex, result, false); if (ex != cex) { e.e1 = ce1.e1; e.e2 = ex; } } // optimize "str"[] -> "str" if (auto se1 = e.e1.isSliceExp()) { if (se1.e1.op == EXP.string_ && !se1.lwr) e.e1 = se1.e1; } if (auto se2 = e.e2.isSliceExp()) { if (se2.e1.op == EXP.string_ && !se2.lwr) e.e2 = se2.e1; } ret = Cat(e.loc, e.type, e.e1, e.e2).copy(); if (CTFEExp.isCantExp(ret)) ret = e; } void visitCond(CondExp e) { if (expOptimize(e.econd, WANTvalue)) return; const opt = e.econd.toBool(); if (opt.hasValue(true)) ret = Expression_optimize(e.e1, result, keepLvalue); else if (opt.hasValue(false)) ret = Expression_optimize(e.e2, result, keepLvalue); else { expOptimize(e.e1, result, keepLvalue); expOptimize(e.e2, result, keepLvalue); } } // Optimize the expression until it can no longer be simplified. size_t b; while (1) { if (b++ == global.recursionLimit) { e.error("infinite loop while optimizing expression"); fatal(); } auto ex = ret; switch (ex.op) { case EXP.variable: visitVar(ex.isVarExp()); break; case EXP.tuple: visitTuple(ex.isTupleExp()); break; case EXP.arrayLiteral: visitArrayLiteral(ex.isArrayLiteralExp()); break; case EXP.assocArrayLiteral: visitAssocArrayLiteral(ex.isAssocArrayLiteralExp()); break; case EXP.structLiteral: visitStructLiteral(ex.isStructLiteralExp()); break; case EXP.import_: case EXP.assert_: case EXP.dotIdentifier: case EXP.dotTemplateDeclaration: case EXP.dotTemplateInstance: case EXP.delegate_: case EXP.dotType: case EXP.uadd: case EXP.delete_: case EXP.vector: case EXP.vectorArray: case EXP.array: case EXP.delegatePointer: case EXP.delegateFunctionPointer: case EXP.preMinusMinus: case EXP.prePlusPlus: visitUna(cast(UnaExp)ex); break; case EXP.negate: visitNeg(ex.isNegExp()); break; case EXP.tilde: visitCom(ex.isComExp()); break; case EXP.not: visitNop(ex.isNotExp()); break; case EXP.symbolOffset: visitSymOff(ex.isSymOffExp()); break; case EXP.address: visitAddr(ex.isAddrExp()); break; case EXP.star: visitPtr(ex.isPtrExp()); break; case EXP.dotVariable: visitDotVar(ex.isDotVarExp()); break; case EXP.new_: visitNew(ex.isNewExp()); break; case EXP.call: visitCall(ex.isCallExp()); break; case EXP.cast_: visitCast(ex.isCastExp()); break; case EXP.addAssign: case EXP.minAssign: case EXP.mulAssign: case EXP.divAssign: case EXP.modAssign: case EXP.andAssign: case EXP.orAssign: case EXP.xorAssign: case EXP.powAssign: case EXP.leftShiftAssign: case EXP.rightShiftAssign: case EXP.unsignedRightShiftAssign: case EXP.concatenateElemAssign: case EXP.concatenateDcharAssign: case EXP.concatenateAssign: visitBinAssign(ex.isBinAssignExp()); break; case EXP.minusMinus: case EXP.plusPlus: case EXP.assign: case EXP.construct: case EXP.blit: case EXP.in_: case EXP.remove: case EXP.dot: visitBin(cast(BinExp)ex); break; case EXP.add: visitAdd(ex.isAddExp()); break; case EXP.min: visitMin(ex.isMinExp()); break; case EXP.mul: visitMul(ex.isMulExp()); break; case EXP.div: visitDiv(ex.isDivExp()); break; case EXP.mod: visitMod(ex.isModExp()); break; case EXP.leftShift: visitShl(ex.isShlExp()); break; case EXP.rightShift: visitShr(ex.isShrExp()); break; case EXP.unsignedRightShift: visitUshr(ex.isUshrExp()); break; case EXP.and: visitAnd(ex.isAndExp()); break; case EXP.or: visitOr(ex.isOrExp()); break; case EXP.xor: visitXor(ex.isXorExp()); break; case EXP.pow: visitPow(ex.isPowExp()); break; case EXP.comma: visitComma(ex.isCommaExp()); break; case EXP.arrayLength: visitArrayLength(ex.isArrayLengthExp()); break; case EXP.notEqual: case EXP.equal: visitEqual(ex.isEqualExp()); break; case EXP.notIdentity: case EXP.identity: visitIdentity(ex.isIdentityExp()); break; case EXP.index: visitIndex(ex.isIndexExp()); break; case EXP.slice: visitSlice(ex.isSliceExp()); break; case EXP.andAnd: case EXP.orOr: visitLogical(ex.isLogicalExp()); break; case EXP.lessThan: case EXP.lessOrEqual: case EXP.greaterThan: case EXP.greaterOrEqual: visitCmp(cast(CmpExp)ex); break; case EXP.concatenate: visitCat(ex.isCatExp()); break; case EXP.question: visitCond(ex.isCondExp()); break; default: visitExp(ex); break; } if (ex == ret) break; } return ret; }
D
agitation resulting from active worry food prepared by stewing especially meat or fish with vegetables be in a huff bear a grudge cook slowly and for a long time in liquid
D
#source: pr16498a.s #ld: -shared -T pr16498b.t #readelf: -l --wide #target: *-*-linux* *-*-gnu* *-*-nacl* arm*-*-uclinuxfdpiceabi #xfail: ![check_shared_lib_support] #... TLS .* #... [ ]+[0-9]+[ ]+tls_data_init .tbss[ ]* #pass
D
/Users/zaidtayyab/Desktop/Template/Build/Template/Build/Intermediates/Pods.build/Debug-iphonesimulator/SwiftValidator.build/Objects-normal/x86_64/ISBNRule.o : /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Core/Validatable.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/Rule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/IPV4Rule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/ISBNRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/AlphaRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/AlphaNumericRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/RequiredRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/PasswordRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/ZipCodeRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/FullNameRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/MinLengthRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/ExactLengthRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/MaxLengthRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/EmailRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/ConfirmRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/ValidationRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/PhoneNumberRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/HexColorRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/FloatRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/CharacterSetRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/RegexRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Core/ValidationDelegate.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Core/ValidationError.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Core/Validator.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Core/ValidatorDictionary.swift /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.apinotesc /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.apinotesc /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.apinotesc /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.apinotesc /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreText.apinotesc /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/zaidtayyab/Desktop/Template/Pods/Target\ Support\ Files/SwiftValidator/SwiftValidator-umbrella.h /Users/zaidtayyab/Desktop/Template/Build/Template/Build/Intermediates/Pods.build/Debug-iphonesimulator/SwiftValidator.build/unextended-module.modulemap /Users/zaidtayyab/Desktop/Template/Build/Template/Build/Intermediates/Pods.build/Debug-iphonesimulator/SwiftValidator.build/Objects-normal/x86_64/ISBNRule~partial.swiftmodule : /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Core/Validatable.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/Rule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/IPV4Rule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/ISBNRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/AlphaRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/AlphaNumericRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/RequiredRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/PasswordRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/ZipCodeRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/FullNameRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/MinLengthRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/ExactLengthRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/MaxLengthRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/EmailRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/ConfirmRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/ValidationRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/PhoneNumberRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/HexColorRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/FloatRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/CharacterSetRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/RegexRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Core/ValidationDelegate.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Core/ValidationError.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Core/Validator.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Core/ValidatorDictionary.swift /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.apinotesc /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.apinotesc /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.apinotesc /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.apinotesc /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreText.apinotesc /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/zaidtayyab/Desktop/Template/Pods/Target\ Support\ Files/SwiftValidator/SwiftValidator-umbrella.h /Users/zaidtayyab/Desktop/Template/Build/Template/Build/Intermediates/Pods.build/Debug-iphonesimulator/SwiftValidator.build/unextended-module.modulemap /Users/zaidtayyab/Desktop/Template/Build/Template/Build/Intermediates/Pods.build/Debug-iphonesimulator/SwiftValidator.build/Objects-normal/x86_64/ISBNRule~partial.swiftdoc : /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Core/Validatable.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/Rule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/IPV4Rule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/ISBNRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/AlphaRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/AlphaNumericRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/RequiredRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/PasswordRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/ZipCodeRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/FullNameRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/MinLengthRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/ExactLengthRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/MaxLengthRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/EmailRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/ConfirmRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/ValidationRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/PhoneNumberRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/HexColorRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/FloatRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/CharacterSetRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Rules/RegexRule.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Core/ValidationDelegate.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Core/ValidationError.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Core/Validator.swift /Users/zaidtayyab/Desktop/Template/Pods/SwiftValidator/SwiftValidator/Core/ValidatorDictionary.swift /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.apinotesc /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.apinotesc /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.apinotesc /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.apinotesc /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreText.apinotesc /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Users/zaidtayyab/Desktop/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/zaidtayyab/Desktop/Template/Pods/Target\ Support\ Files/SwiftValidator/SwiftValidator-umbrella.h /Users/zaidtayyab/Desktop/Template/Build/Template/Build/Intermediates/Pods.build/Debug-iphonesimulator/SwiftValidator.build/unextended-module.modulemap
D
# FIXED network_common.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/example/common/network_common.c network_common.obj: C:/TI/ccsv6/tools/compiler/ti-cgt-arm_15.12.1.LTS/include/stdlib.h network_common.obj: C:/TI/ccsv6/tools/compiler/ti-cgt-arm_15.12.1.LTS/include/linkage.h network_common.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/simplelink.h network_common.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/../user.h network_common.obj: C:/TI/ccsv6/tools/compiler/ti-cgt-arm_15.12.1.LTS/include/string.h network_common.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/../cc_pal.h network_common.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink_extlib/provisioninglib/provisioning_api.h network_common.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/simplelink.h network_common.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/../source/objInclusion.h network_common.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/trace.h network_common.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/fs.h network_common.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/socket.h network_common.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/netapp.h network_common.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/wlan.h network_common.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/device.h network_common.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/netcfg.h network_common.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/wlan_rx_filters.h network_common.obj: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/../source/nonos.h C:/TI/CC3200SDK_1.2.0/cc3200-sdk/example/common/network_common.c: C:/TI/ccsv6/tools/compiler/ti-cgt-arm_15.12.1.LTS/include/stdlib.h: C:/TI/ccsv6/tools/compiler/ti-cgt-arm_15.12.1.LTS/include/linkage.h: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/simplelink.h: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/../user.h: C:/TI/ccsv6/tools/compiler/ti-cgt-arm_15.12.1.LTS/include/string.h: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/../cc_pal.h: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink_extlib/provisioninglib/provisioning_api.h: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/simplelink.h: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/../source/objInclusion.h: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/trace.h: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/fs.h: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/socket.h: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/netapp.h: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/wlan.h: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/device.h: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/netcfg.h: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/wlan_rx_filters.h: C:/TI/CC3200SDK_1.2.0/cc3200-sdk/simplelink/include/../source/nonos.h:
D
module core.dbg; import colorize : fg, color, cwrite, cwritef; void errorMessage(T...)(string fmt, T args) { cwrite("[ERROR] ".color(fg.red)); cwritef(fmt, args); cwrite("\n"); } void warningMessage(T...)(string fmt, T args) { cwrite("[WARN ] ".color(fg.yellow)); cwritef(fmt, args); cwrite("\n"); } void debugMessage(T...)(string fmt, T args) { cwrite("[DEBUG] ".color(fg.light_black)); cwritef(fmt, args); cwrite("\n"); }
D
/******************************************************************************* * Copyright (c) 2000, 2005 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 dwtx.jface.text.ITextViewerExtension5; import dwtx.jface.text.IRegion; // packageimport import dwtx.jface.text.ITextViewerExtension3; // packageimport import dwt.dwthelper.utils; /** * Extension interface for {@link dwtx.jface.text.ITextViewer}. Defines * a conceptual replacement of the original visible region concept. This interface * replaces {@link dwtx.jface.text.ITextViewerExtension3}. * <p> * Introduces the explicit concept of model and widget coordinates. For example, * a selection returned by the text viewer's control is a widget selection. A * widget selection always maps to a certain range of the viewer's document. * This range is considered the model selection. * <p> * All model ranges that have a corresponding widget ranges are considered * "exposed model ranges". The viewer can be requested to expose a given model * range. Thus, a visible region is a particular degeneration of exposed model * ranges. * <p> * This interface allows implementers to follow a sophisticated presentation * model in which the visible presentation is a complex projection of the * viewer's input document. * * @since 3.0 */ public interface ITextViewerExtension5 : ITextViewerExtension3 { /** * Returns the minimal region of the viewer's input document that completely * comprises everything that is visible in the viewer's widget or * <code>null</code> if there is no such region. * * @return the minimal region of the viewer's document comprising the * contents of the viewer's widget or <code>null</code> */ IRegion getModelCoverage(); /** * Returns the widget line that corresponds to the given line of the * viewer's input document or <code>-1</code> if there is no such line. * * @param modelLine the line of the viewer's document * @return the corresponding widget line or <code>-1</code> */ int modelLine2WidgetLine(int modelLine); /** * Returns the widget offset that corresponds to the given offset in the * viewer's input document or <code>-1</code> if there is no such offset * * @param modelOffset the offset in the viewer's document * @return the corresponding widget offset or <code>-1</code> */ int modelOffset2WidgetOffset(int modelOffset); /** * Returns the minimal region of the viewer's widget that completely * comprises the given region of the viewer's input document or * <code>null</code> if there is no such region. * * @param modelRange the region of the viewer's document * @return the minimal region of the widget comprising * <code>modelRange</code> or <code>null</code> */ IRegion modelRange2WidgetRange(IRegion modelRange); /** * Returns the offset of the viewer's input document that corresponds to the * given widget offset or <code>-1</code> if there is no such offset * * @param widgetOffset the widget offset * @return the corresponding offset in the viewer's document or * <code>-1</code> */ int widgetOffset2ModelOffset(int widgetOffset); /** * Returns the minimal region of the viewer's input document that completely * comprises the given widget region or <code>null</code> if there is no * such region. * * @param widgetRange the widget region * @return the minimal region of the viewer's document comprising * <code>widgetlRange</code> or <code>null</code> */ IRegion widgetRange2ModelRange(IRegion widgetRange); /** * Returns the line of the viewer's input document that corresponds to the * given widget line or <code>-1</code> if there is no such line. * * @param widgetLine the widget line * @return the corresponding line of the viewer's document or * <code>-1</code> */ int widgetLine2ModelLine(int widgetLine); /** * Returns the widget line of the given widget offset. * * @param widgetOffset the widget offset * @return the widget line of the widget offset */ int widgetLineOfWidgetOffset(int widgetOffset); /** * Returns the maximal subranges of the given model range thus that there is * no offset inside a subrange for which there is no image offset. * * @param modelRange the model range * @return the list of subranges */ IRegion[] getCoveredModelRanges(IRegion modelRange); /** * Exposes the given model range. Returns whether this call caused a change * of the set of exposed model ranges. * * @param modelRange the model range to be exposed * @return <code>true</code> if the set of exposed model ranges changed, * <code>false</code> otherwise */ bool exposeModelRange(IRegion modelRange); }
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.txt or copy at http://www.boost.org/LICENSE_1_0.txt module visuald.completion; import visuald.windows; import std.ascii; import std.string; import std.utf; import std.file; import std.path; import std.algorithm; import std.array; import std.conv; import std.uni; import stdext.array; import stdext.file; import stdext.ddocmacros; import stdext.string; import visuald.comutil; import visuald.logutil; import visuald.hierutil; import visuald.fileutil; import visuald.pkgutil; import visuald.stringutil; import visuald.dpackage; import visuald.dproject; import visuald.dlangsvc; import visuald.dimagelist; import visuald.config; import visuald.intellisense; import vdc.lexer; import sdk.port.vsi; import sdk.win32.commctrl; import sdk.vsi.textmgr; import sdk.vsi.textmgr2; import sdk.vsi.textmgr121; import sdk.vsi.vsshell; import sdk.win32.wtypes; /////////////////////////////////////////////////////////////// const int kCompletionSearchLines = 5000; class ImageList {}; struct Declaration { string name; string type; string description; string text; static Declaration split(string s) { Declaration decl; auto pos1 = indexOf(s, ':'); if(pos1 >= 0) { decl.name = s[0 .. pos1]; auto pos2 = indexOf(s[pos1 + 1 .. $], ':'); if(pos2 >= 0) { decl.type = s[pos1 + 1 .. pos1 + 1 + pos2]; decl.description = s[pos1 + 1 + pos2 + 1 .. $]; } else decl.type = s[pos1 + 1 .. $]; } else decl.name = s; auto pos3 = indexOf(decl.name, "|"); if(pos3 >= 0) { decl.text = decl.name[pos3 + 1 .. $]; decl.name = decl.name[0 .. pos3]; } else decl.text = decl.name; return decl; } int compareByType(const ref Declaration other) const { int s1 = Type2Sorting(type); int s2 = Type2Sorting(other.type); if (s1 != s2) return s1 - s2; if (int res = icmp(name, other.name)) return res; return 0; } int compareByName(const ref Declaration other) const { if (int res = icmp(name, other.name)) return res; if (int res = icmp(type, other.type)) return res; return 0; } static int Type2Glyph(string type) { switch(type) { case "KW": return CSIMG_KEYWORD; case "SPRP": return CSIMG_KEYWORD; case "ASKW": return CSIMG_KEYWORD; case "ASOP": return CSIMG_KEYWORD; case "PROP": return CSIMG_PROPERTY; case "SNPT": return CSIMG_SNIPPET; case "TEXT": return CSIMG_TEXT; case "MOD": return CSIMG_DMODULE; case "DIR": return CSIMG_DFOLDER; case "PKG": return CSIMG_PACKAGE; case "FUNC": return CSIMG_FUNCTION; case "MTHD": return CSIMG_MEMBER; case "STRU": return CSIMG_STRUCT; case "UNIO": return CSIMG_UNION; case "CLSS": return CSIMG_CLASS; case "IFAC": return CSIMG_INTERFACE; case "TMPL": return CSIMG_TEMPLATE; case "ENUM": return CSIMG_ENUM; case "EVAL": return CSIMG_ENUMMEMBER; case "NMIX": return CSIMG_UNKNOWN2; case "VAR": return CSIMG_FIELD; case "ALIA": return CSIMG_ALIAS; case "OVR": return CSIMG_UNKNOWN3; default: return 0; } } static int Type2Sorting(string type) { switch(type) { case "PROP": return 1; case "VAR": return 1; case "EVAL": return 1; case "MTHD": return 2; case "STRU": return 3; case "UNIO": return 3; case "CLSS": return 3; case "IFAC": return 3; case "ENUM": return 3; case "KW": return 4; case "SPRP": return 4; // static meta property case "ASKW": return 4; case "ASOP": return 4; case "ALIA": return 4; case "MOD": return 5; case "DIR": return 5; case "PKG": return 5; case "NMIX": return 5; // named teplate mixin mixin case "FUNC": return 6; case "TMPL": return 6; case "OVR": return 6; case "TEXT": return 3; case "SNPT": return 3; default: return 7; } } } class Declarations { Declaration[] mDecls; int mExpansionState = kStateInit; enum { kStateInit, kStateImport, kStateSemantic, kStateNearBy, kStateSymbols, kStateCaseInsensitive } this() { } int GetCount() { return mDecls.length; } dchar OnAutoComplete(IVsTextView textView, string committedWord, dchar commitChar, int commitIndex) { return 0; } int GetGlyph(int index) { if(index < 0 || index >= mDecls.length) return 0; return Declaration.Type2Glyph(mDecls[index].type); } string GetDisplayText(int index) { return GetName(index); } string GetDescription(int index) { if(index < 0 || index >= mDecls.length) return ""; string desc = mDecls[index].description; desc = replace(desc, "\a", "\n"); string res = phobosDdocExpand(desc); return res; } string GetName(int index) { if(index < 0 || index >= mDecls.length) return ""; return mDecls[index].name; } string GetText(IVsTextView view, int index) { if(index < 0 || index >= mDecls.length) return ""; string text = mDecls[index].text; if(text.indexOf('\a') >= 0) { string nl = "\r\n"; if(view) { // copy indentation from current line int line, idx; if(view.GetCaretPos(&line, &idx) == S_OK) { IVsTextLines pBuffer; if(view.GetBuffer(&pBuffer) == S_OK) { nl = GetLineBreakText(pBuffer, line); BSTR btext; if(pBuffer.GetLineText(line, 0, line, idx, &btext) == S_OK) { string txt = detachBSTR(btext); size_t p = 0; while(p < txt.length && std.ascii.isWhite(txt[p])) p++; nl ~= txt[0 .. p]; } release(pBuffer); } } } text = text.replace("\a", nl); } return text; } bool GetInitialExtent(IVsTextView textView, int* line, int* startIdx, int* endIdx) { *line = 0; *startIdx = *endIdx = 0; return false; } void GetBestMatch(string textSoFar, int* index, bool *uniqueMatch) { *index = 0; *uniqueMatch = false; } bool IsCommitChar(string textSoFar, int index, dchar ch) { return ch == '\n' || ch == '\r'; // !(isAlphaNum(ch) || ch == '_'); } string OnCommit(IVsTextView textView, string textSoFar, dchar ch, int index, ref TextSpan initialExtent) { return GetText(textView, index); // textSoFar; } /////////////////////////////////////////////////////////////// bool ImportExpansions(string imp, string file) { string[] imports = GetImportPaths(file); string dir; int dpos = lastIndexOf(imp, '.'); if(dpos >= 0) { dir = replace(imp[0 .. dpos], ".", "\\"); imp = imp[dpos + 1 .. $]; } int namesLength = mDecls.length; foreach(string impdir; imports) { impdir = impdir ~ dir; if(!isExistingDir(impdir)) continue; foreach(string name; dirEntries(impdir, SpanMode.shallow)) { string base = baseName(name); string ext = toLower(extension(name)); bool canImport = false; bool issubdir = isDir(name); if(issubdir) canImport = (ext.length == 0); else if(ext == ".d" || ext == ".di") { base = base[0 .. $-ext.length]; canImport = true; } if(canImport && base.startsWith(imp)) { Declaration decl; decl.name = decl.text = base; decl.type = (issubdir ? "DIR" : "MOD"); addunique(mDecls, decl); } } } return mDecls.length > namesLength; } bool ImportExpansions(IVsTextView textView, Source src) { int line, idx; if(int hr = textView.GetCaretPos(&line, &idx)) return false; wstring wimp = src.GetImportModule(line, idx, true); if(wimp.empty) return false; string txt = to!string(wimp); ImportExpansions(txt, src.GetFileName()); return true; } /////////////////////////////////////////////////////////////// string GetWordBeforeCaret(IVsTextView textView, Source src) { int line, idx; int hr = textView.GetCaretPos(&line, &idx); assert(hr == S_OK); int startIdx, endIdx; if(!src.GetWordExtent(line, idx, WORDEXT_FINDTOKEN, startIdx, endIdx)) return ""; wstring txt = src.GetText(line, startIdx, line, idx); return toUTF8(txt); } bool NearbyExpansions(IVsTextView textView, Source src) { if(!Package.GetGlobalOptions().expandFromBuffer) return false; int line, idx; if(int hr = textView.GetCaretPos(&line, &idx)) return false; int lineCount; src.mBuffer.GetLineCount(&lineCount); //mNames.length = 0; int start = max(0, line - kCompletionSearchLines); int end = min(lineCount, line + kCompletionSearchLines); string tok = GetWordBeforeCaret(textView, src); if(tok.length && !dLex.isIdentifierCharOrDigit(tok.front)) tok = ""; int iState = src.mColorizer.GetLineState(start); if(iState == -1) return false; int namesLength = mDecls.length; for(int ln = start; ln < end; ln++) { wstring text = src.GetText(ln, 0, ln, -1); uint pos = 0; while(pos < text.length) { uint ppos = pos; int type = dLex.scan(iState, text, pos); if(ln != line || pos < idx || ppos > idx) if(type == TokenCat.Identifier || type == TokenCat.Keyword) { string txt = toUTF8(text[ppos .. pos]); if(txt.startsWith(tok)) { Declaration decl; decl.name = decl.text = txt; addunique(mDecls, decl); } } } } return mDecls.length > namesLength; } //////////////////////////////////////////////////////////////////////// bool SymbolExpansions(IVsTextView textView, Source src) { if(!Package.GetGlobalOptions().expandFromJSON) return false; string tok = GetWordBeforeCaret(textView, src); if(tok.length && !dLex.isIdentifierCharOrDigit(tok.front)) tok = ""; if(!tok.length) return false; int namesLength = mDecls.length; string[] completions = Package.GetLibInfos().findCompletions(tok, true); foreach (c; completions) { Declaration decl; decl.name = decl.text = c; addunique(mDecls, decl); } return mDecls.length > namesLength; } //////////////////////////////////////////////////////////////////////// bool SnippetExpansions(IVsTextView textView, Source src) { int line, idx; int hr = textView.GetCaretPos(&line, &idx); assert(hr == S_OK); wstring txt = src.GetText(line, 0, line, -1); if(idx > txt.length) idx = txt.length; int endIdx = idx; dchar ch; for(size_t p = idx; p > 0 && dLex.isIdentifierCharOrDigit(ch = decodeBwd(txt, p)); idx = p) {} int startIdx = idx; for(size_t p = idx; p > 0 && std.uni.isWhite(ch = decodeBwd(txt, p)); idx = p) {} if (ch == '.') return false; wstring tok = txt[startIdx .. endIdx]; IVsTextManager2 textmgr = queryService!(VsTextManager, IVsTextManager2); if(!textmgr) return false; scope(exit) release(textmgr); IVsExpansionManager exmgr; textmgr.GetExpansionManager(&exmgr); if (!exmgr) return false; scope(exit) release(exmgr); int namesLength = mDecls.length; IVsExpansionEnumeration enumExp; hr = exmgr.EnumerateExpansions(g_languageCLSID, FALSE, null, 0, false, false, &enumExp); if(hr == S_OK && enumExp) { DWORD fetched; VsExpansion exp; VsExpansion* pexp = &exp; while(enumExp.Next(1, &pexp, &fetched) == S_OK && fetched == 1) { Declaration decl; decl.name = detachBSTR(exp.title); decl.description = detachBSTR(exp.description); decl.text = detachBSTR(exp.shortcut); decl.type = "SNPT"; freeBSTR(exp.path); if(decl.text.startsWith(tok)) addunique(mDecls, decl); } } return mDecls.length > namesLength; } /////////////////////////////////////////////////////////////////////////// bool SemanticExpansions(IVsTextView textView, Source src) { if(!Package.GetGlobalOptions().expandFromSemantics) return false; try { string tok = GetWordBeforeCaret(textView, src); if(tok.length && !dLex.isIdentifierCharOrDigit(tok.front)) tok = ""; if (tok.length && !Package.GetGlobalOptions().exactExpMatch) tok ~= "*"; int caretLine, caretIdx; int hr = textView.GetCaretPos(&caretLine, &caretIdx); src.ensureCurrentTextParsed(); // pass new text before expansion request auto langsvc = Package.GetLanguageService(); mPendingSource = src; mPendingView = textView; mPendingRequest = langsvc.GetSemanticExpansions(src, tok, caretLine, caretIdx, &OnExpansions); return true; } catch(Error e) { writeToBuildOutputPane(e.msg); } return false; } extern(D) void OnExpansions(uint request, string filename, string tok, int line, int idx, string[] symbols) { if(request != mPendingRequest) return; // without a match, keep existing items bool hasMatch = GetCount() > 0 || symbols.length > 0; if(hasMatch && mPendingSource && mPendingView) { auto activeView = GetActiveView(); scope(exit) release(activeView); int caretLine, caretIdx; int hr = mPendingView.GetCaretPos(&caretLine, &caretIdx); if (activeView == mPendingView && line == caretLine && idx == caretIdx) { // split after second ':' to combine same name and type static string splitName(string name, ref string desc) { auto pos = name.indexOf(':'); if(pos < 0) return name; pos = name.indexOf(':', pos + 1); if(pos < 0) return name; desc = name[pos..$]; return name[0..pos]; } // go through assoc array for faster uniqueness check int[string] decls; // add existing declarations foreach(i, d; mDecls) { string desc; string name = d.name ~ ":" ~ d.type; decls[name] = i; } size_t num = mDecls.length; mDecls.length = num + symbols.length; foreach(s; symbols) { string desc; string name = splitName(s, desc); if(auto p = name in decls) mDecls[*p].description ~= "\a\a" ~ desc[1..$]; // strip ":" else { decls[name] = num; mDecls[num++] = Declaration.split(s); } } mDecls.length = num; // mode 2 keeps order of semantic engine if (Package.GetGlobalOptions().sortExpMode == 1) sort!("a.compareByType(b) < 0", SwapStrategy.stable)(mDecls); else if (Package.GetGlobalOptions().sortExpMode == 0) sort!("a.compareByName(b) < 0", SwapStrategy.stable)(mDecls); InitCompletionSet(mPendingView, mPendingSource); } } mPendingRequest = 0; mPendingView = null; mPendingSource = null; } uint mPendingRequest; IVsTextView mPendingView; Source mPendingSource; bool mAutoInsert; //////////////////////////////////////////////////////////////////////// bool StartExpansions(IVsTextView textView, Source src, bool autoInsert) { mDecls = mDecls.init; mExpansionState = kStateInit; mAutoInsert = autoInsert; if(!_MoreExpansions(textView, src)) return false; if(mPendingView) return false; return InitCompletionSet(textView, src); } bool InitCompletionSet(IVsTextView textView, Source src) { if(mAutoInsert) { while(GetCount() == 1 && _MoreExpansions(textView, src)) {} if(GetCount() == 1) { int line, idx, startIdx, endIdx; textView.GetCaretPos(&line, &idx); if(src.GetWordExtent(line, idx, WORDEXT_FINDTOKEN, startIdx, endIdx)) { wstring txt = to!wstring(GetText(textView, 0)); TextSpan changedSpan; src.mBuffer.ReplaceLines(line, startIdx, line, endIdx, txt.ptr, txt.length, &changedSpan); if (GetGlyph(0) == CSIMG_SNIPPET) if (auto view = Package.GetLanguageService().GetViewFilter(src, textView)) view.HandleSnippet(); return true; } } } src.GetCompletionSet().Init(textView, this, false); return true; } bool _MoreExpansions(IVsTextView textView, Source src) { switch(mExpansionState) { case kStateInit: if(ImportExpansions(textView, src)) { mExpansionState = kStateSymbols; // do not try other symbols but file imports return true; } goto case; case kStateImport: SnippetExpansions(textView, src); if(SemanticExpansions(textView, src)) { mExpansionState = kStateSemantic; return true; } goto case; case kStateSemantic: if(NearbyExpansions(textView, src)) { mExpansionState = kStateNearBy; return true; } goto case; case kStateNearBy: if(SymbolExpansions(textView, src)) { mExpansionState = kStateSymbols; return true; } goto default; default: break; } return false; } bool MoreExpansions(IVsTextView textView, Source src) { mAutoInsert = false; _MoreExpansions(textView, src); if (!mPendingView) src.GetCompletionSet().Init(textView, this, false); return true; } void StopExpansions() { mPendingRequest = 0; mPendingView = null; mPendingSource = null; } } class CompletionSet : DisposingComObject, IVsCompletionSet, IVsCompletionSet3, IVsCompletionSetEx { HIMAGELIST mImageList; bool mDisplayed; bool mCompleteWord; bool mComittedShortcut; string mCommittedWord; dchar mCommitChar; int mCommitIndex; IVsTextView mTextView; Declarations mDecls; Source mSource; TextSpan mInitialExtent; bool mIsCommitted; bool mWasUnique; int mLastDeclCount; this(ImageList imageList, Source source) { mImageList = LoadImageList(g_hInst, MAKEINTRESOURCEA(BMP_COMPLETION), 16, 16); mSource = source; } override HRESULT QueryInterface(in IID* riid, void** pvObject) { if(queryInterface!(IVsCompletionSetEx) (this, riid, pvObject)) return S_OK; if(queryInterface!(IVsCompletionSet) (this, riid, pvObject)) return S_OK; version(none) if(*riid == uuid_IVsCompletionSet3) { *pvObject = cast(void*)cast(IVsCompletionSet3)this; AddRef(); return S_OK; } if(*riid == uuid_IVsCoTaskMemFreeMyStrings) // avoid log message, implement? return E_NOTIMPL; return super.QueryInterface(riid, pvObject); } void Init(IVsTextView textView, Declarations declarations, bool completeWord) { if (mLastDeclCount < declarations.GetCount()) Close(); // without closing first, the box does not update its width mTextView = textView; mDecls = declarations; mCompleteWord = completeWord; //check if we have members mLastDeclCount = mDecls.GetCount(); if (mLastDeclCount <= 0) return; //initialise and refresh UpdateCompletionFlags flags = UCS_NAMESCHANGED; if (mCompleteWord) flags |= UCS_COMPLETEWORD; mWasUnique = false; int hr = textView.UpdateCompletionStatus(this, flags); assert(hr == S_OK); mDisplayed = (!mWasUnique || !completeWord); } bool isActive() { return mDisplayed || (mDecls && mDecls.mPendingSource); } override void Dispose() { Close(); //if (imageList != null) imageList.Dispose(); if(mImageList) { ImageList_Destroy(mImageList); mImageList = null; } } void Close() { if (mDisplayed && mTextView) { // Here we can't throw or exit because we need to call Dispose on // the disposable membres. try { mTextView.UpdateCompletionStatus(null, 0); } catch (Exception e) { } } mDisplayed = false; mComittedShortcut = false; mTextView = null; mDecls = null; mLastDeclCount = 0; } dchar OnAutoComplete() { mIsCommitted = false; if (mDecls) return mDecls.OnAutoComplete(mTextView, mCommittedWord, mCommitChar, mCommitIndex); return '\0'; } //-------------------------------------------------------------------------- //IVsCompletionSet methods //-------------------------------------------------------------------------- override int GetImageList(HANDLE *phImages) { mixin(LogCallMix); *phImages = cast(HANDLE)mImageList; return S_OK; } override int GetFlags() { mixin(LogCallMix); return CSF_HAVEDESCRIPTIONS | CSF_CUSTOMCOMMIT | CSF_INITIALEXTENTKNOWN | CSF_CUSTOMMATCHING; } override int GetCount() { mixin(LogCallMix); return mDecls.GetCount(); } override int GetDisplayText(in int index, WCHAR** text, int* glyph) { //mixin(LogCallMix); if (glyph) *glyph = mDecls.GetGlyph(index); *text = allocBSTR(mDecls.GetDisplayText(index)); return S_OK; } override int GetDescriptionText(in int index, BSTR* description) { mixin(LogCallMix2); *description = allocBSTR(mDecls.GetDescription(index)); return S_OK; } override int GetInitialExtent(int* line, int* startIdx, int* endIdx) { mixin(LogCallMix); int idx; int hr = S_OK; if (mDecls.GetInitialExtent(mTextView, line, startIdx, endIdx)) goto done; hr = mTextView.GetCaretPos(line, &idx); assert(hr == S_OK); hr = GetTokenExtent(*line, idx, *startIdx, *endIdx); done: // Remember the initial extent so we can pass it along on the commit. mInitialExtent.iStartLine = mInitialExtent.iEndLine = *line; mInitialExtent.iStartIndex = *startIdx; mInitialExtent.iEndIndex = *endIdx; //assert(TextSpanHelper.ValidCoord(mSource, line, startIdx) && // TextSpanHelper.ValidCoord(mSource, line, endIdx)); return hr; } int GetTokenExtent(int line, int idx, out int startIdx, out int endIdx) { int hr = S_OK; bool rc = mSource.GetWordExtent(line, idx, WORDEXT_FINDTOKEN, startIdx, endIdx); if (!rc && idx > 0) { //rc = mSource.GetWordExtent(line, idx - 1, WORDEXT_FINDTOKEN, startIdx, endIdx); if (!rc) { // Must stop core text editor from looking at startIdx and endIdx since they are likely // invalid. So we must return a real failure here, not just S_FALSE. startIdx = endIdx = idx; hr = E_NOTIMPL; } } // make sure the span is positive. endIdx = max(endIdx, idx); return hr; } override int GetBestMatch(in WCHAR* wtextSoFar, in int length, int* index, uint* flags) { mixin(LogCallMix); *flags = 0; *index = 0; bool uniqueMatch = false; string textSoFar = to_string(wtextSoFar); if (textSoFar.length != 0) { mDecls.GetBestMatch(textSoFar, index, &uniqueMatch); if (*index < 0 || *index >= mDecls.GetCount()) { *index = 0; uniqueMatch = false; } else { // Indicate that we want to select something in the list. *flags = GBM_SELECT; } } else if (mDecls.GetCount() == 1 && mCompleteWord) { // Only one entry, and user has invoked "word completion", then // simply select this item. *index = 0; *flags = GBM_SELECT; uniqueMatch = true; } if (uniqueMatch) { *flags |= GBM_UNIQUE; mWasUnique = true; } return S_OK; } override int OnCommit(in WCHAR* wtextSoFar, in int index, in BOOL selected, in WCHAR commitChar, BSTR* completeWord) { mixin(LogCallMix); dchar ch = commitChar; bool isCommitChar = true; int selIndex = (selected == 0) ? -1 : index; string textSoFar = to_string(wtextSoFar); if (commitChar != 0) { // if the char is in the list of given member names then obviously it // is not a commit char. int i = textSoFar.length; for (int j = 0, n = mDecls.GetCount(); j < n; j++) { string name = mDecls.GetText(mTextView, j); if (name.length > i && name[i] == commitChar) { if (i == 0 || name[0 .. i] == textSoFar) goto nocommit; // cannot be a commit char if it is an expected char in a matching name } } isCommitChar = mDecls.IsCommitChar(textSoFar, selIndex, ch); } if (isCommitChar) { mCommittedWord = mDecls.OnCommit(mTextView, textSoFar, ch, selIndex, mInitialExtent); mComittedShortcut = (mDecls.GetGlyph(selIndex) == CSIMG_SNIPPET); *completeWord = allocBSTR(mCommittedWord); mCommitChar = ch; mCommitIndex = index; mIsCommitted = true; return S_OK; } nocommit: // S_FALSE return means the character is not a commit character. *completeWord = allocBSTR(textSoFar); return S_FALSE; } override int Dismiss() { mixin(LogCallMix); mDisplayed = false; if (mComittedShortcut) if (auto view = Package.GetLanguageService().GetViewFilter(mSource, mTextView)) view.HandleSnippet(); mComittedShortcut = false; return S_OK; } // IVsCompletionSetEx Members override int CompareItems(in BSTR bstrSoFar, in BSTR bstrOther, in int lCharactersToCompare, int* plResult) { mixin(LogCallMix); *plResult = 0; return E_NOTIMPL; } override int IncreaseFilterLevel(in int iSelectedItem) { mixin(LogCallMix2); return E_NOTIMPL; } override int DecreaseFilterLevel(in int iSelectedItem) { mixin(LogCallMix2); return E_NOTIMPL; } override int GetCompletionItemColor(in int iIndex, COLORREF* dwFGColor, COLORREF* dwBGColor) { mixin(LogCallMix); *dwFGColor = *dwBGColor = 0; return E_NOTIMPL; } override int GetFilterLevel(int* iFilterLevel) { // if implementaed, adds tabs "Common" and "All" mixin(LogCallMix2); *iFilterLevel = 0; return E_NOTIMPL; } override int OnCommitComplete() { mixin(LogCallMix); /+ if(CodeWindowManager mgr = mSource.LanguageService.GetCodeWindowManagerForView(mTextView)) if (ViewFilter filter = mgr.GetFilter(mTextView)) filter.OnAutoComplete(); +/ return S_OK; } // IVsCompletionSet3 adds icons on the right side of the completion list override HRESULT GetContextIcon(in int iIndex, int *piGlyph) { mixin(LogCallMix); *piGlyph = CSIMG_MEMBER; return S_OK; } override HRESULT GetContextImageList (HANDLE *phImageList) { mixin(LogCallMix); *phImageList = cast(HANDLE)mImageList; return S_OK; } } //------------------------------------------------------------------------------------- class MethodData : DisposingComObject, IVsMethodData { IServiceProvider mProvider; IVsMethodTipWindow mMethodTipWindow; Definition[] mMethods; bool mTypePrefixed = true; int mCurrentParameter; int mCurrentMethod; bool mDisplayed; IVsTextView mTextView; TextSpan mContext; this() { auto uuid = uuid_coclass_VsMethodTipWindow; mMethodTipWindow = VsLocalCreateInstance!IVsMethodTipWindow (&uuid, CLSCTX_INPROC_SERVER); if (mMethodTipWindow) mMethodTipWindow.SetMethodData(this); } override HRESULT QueryInterface(in IID* riid, void** pvObject) { if(queryInterface!(IVsMethodData) (this, riid, pvObject)) return S_OK; return super.QueryInterface(riid, pvObject); } void Refresh(IVsTextView textView, Definition[] methods, int currentParameter, TextSpan context) { if (!mDisplayed) mCurrentMethod = 0; // methods.DefaultMethod; mContext = context; mMethods = mMethods.init; defLoop: foreach(ref def; methods) { foreach(ref d; mMethods) if(d.type == def.type) { if (!d.inScope.endsWith(" ...")) d.inScope ~= " ..."; continue defLoop; } mMethods ~= def; } // Apparently this Refresh() method is called as a result of event notification // after the currentMethod is changed, so we do not want to Dismiss anything or // reset the currentMethod here. //Dismiss(); mTextView = textView; mCurrentParameter = currentParameter; AdjustCurrentParameter(0); } void AdjustCurrentParameter(int increment) { mCurrentParameter += increment; if (mCurrentParameter < 0) mCurrentParameter = -1; else if (mCurrentParameter >= GetParameterCount(mCurrentMethod)) mCurrentParameter = GetParameterCount(mCurrentMethod); UpdateView(); } void Close() { Dismiss(); mTextView = null; mMethods = null; } void Dismiss() { if (mDisplayed && mTextView) mTextView.UpdateTipWindow(mMethodTipWindow, UTW_DISMISS); OnDismiss(); } override void Dispose() { Close(); if (mMethodTipWindow) mMethodTipWindow.SetMethodData(null); mMethodTipWindow = release(mMethodTipWindow); } //IVsMethodData override int GetOverloadCount() { if (!mTextView || mMethods.length == 0) return 0; return mMethods.length; } override int GetCurMethod() { return mCurrentMethod; } override int NextMethod() { if (mCurrentMethod < GetOverloadCount() - 1) mCurrentMethod++; return mCurrentMethod; } override int PrevMethod() { if (mCurrentMethod > 0) mCurrentMethod--; return mCurrentMethod; } override int GetParameterCount(in int method) { if (mMethods.length == 0) return 0; if (method < 0 || method >= GetOverloadCount()) return 0; return mMethods[method].GetParameterCount(); } override int GetCurrentParameter(in int method) { return mCurrentParameter; } override void OnDismiss() { mTextView = null; mMethods = mMethods.init; mCurrentMethod = 0; mCurrentParameter = 0; mDisplayed = false; } override void UpdateView() { if (mTextView && mMethodTipWindow) { mTextView.UpdateTipWindow(mMethodTipWindow, UTW_CONTENTCHANGED | UTW_CONTEXTCHANGED); mDisplayed = true; } } override int GetContextStream(int* pos, int* length) { *pos = 0; *length = 0; int line, idx, vspace, endpos; if(HRESULT rc = mTextView.GetCaretPos(&line, &idx)) return rc; line = max(line, mContext.iStartLine); if(HRESULT rc = mTextView.GetNearestPosition(line, mContext.iStartIndex, pos, &vspace)) return rc; line = max(line, mContext.iEndLine); if(HRESULT rc = mTextView.GetNearestPosition(line, mContext.iEndIndex, &endpos, &vspace)) return rc; *length = endpos - *pos; return S_OK; } override WCHAR* GetMethodText(in int method, in MethodTextType type) { if (mMethods.length == 0) return null; if (method < 0 || method >= GetOverloadCount()) return null; string result; //a type if ((type == MTT_TYPEPREFIX && mTypePrefixed) || (type == MTT_TYPEPOSTFIX && !mTypePrefixed)) { string str = mMethods[method].GetReturnType(); if (str.length == 0) return null; result = str; // mMethods.TypePrefix + str + mMethods.TypePostfix; } else { //other switch (type) { case MTT_OPENBRACKET: result = "("; // mMethods.OpenBracket; break; case MTT_CLOSEBRACKET: result = ")"; // mMethods.CloseBracket; break; case MTT_DELIMITER: result = ","; // mMethods.Delimiter; break; case MTT_NAME: result = mMethods[method].name; break; case MTT_DESCRIPTION: if(mMethods[method].help.length) result = phobosDdocExpand(mMethods[method].help); else if(mMethods[method].line > 0) result = format("%s %s @ %s(%d)", mMethods[method].kind, mMethods[method].inScope, mMethods[method].filename, mMethods[method].line); break; case MTT_TYPEPREFIX: case MTT_TYPEPOSTFIX: default: break; } } return result.length == 0 ? null : allocBSTR(result); // produces leaks? } override WCHAR* GetParameterText(in int method, in int parameter, in ParameterTextType type) { if (mMethods.length == 0) return null; if (method < 0 || method >= GetOverloadCount()) return null; if (parameter < 0 || parameter >= GetParameterCount(method)) return null; string name; string description; string display; mMethods[method].GetParameterInfo(parameter, name, display, description); string result; switch (type) { case PTT_NAME: result = name; break; case PTT_DESCRIPTION: result = description; break; case PTT_DECLARATION: result = display; break; default: break; } return result.length == 0 ? null : allocBSTR(result); // produces leaks? } }
D
/********************************************************************************** * Copyright (c) 2008-2009 The Khronos Group Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and/or associated documentation files (the * "Materials"), to deal in the Materials without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Materials, and to * permit persons to whom the Materials are 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 Materials. * * THE MATERIALS ARE 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 * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. **********************************************************************************/ // $Revision: 8407 $ on $Date: 2009-06-12 10:56:38 -0700 (Fri, 12 Jun 2009) $ module opencl.platform; /* scalar types */ alias byte cl_char; alias ubyte cl_uchar; alias short cl_short; alias ushort cl_ushort; alias int cl_int; alias uint cl_uint; alias long cl_long; alias ulong cl_ulong; alias ushort cl_half; alias float cl_float; alias double cl_double; /* * Vector types * * Note: OpenCL requires that all types be naturally aligned. * This means that vector types must be naturally aligned. * For example, a vector of four floats must be aligned to * a 16 byte boundary (calculated as 4 * the natural 4-byte * alignment of the float). The alignment qualifiers here * will only function properly if your compiler supports them * and if you don't actively work to defeat them. For example, * in order for a cl_float4 to be 16 byte aligned in a struct, * the start of the struct must itself be 16-byte aligned. * * Maintaining proper alignment is the user's responsibility. */ alias byte[2] cl_char2; alias byte[4] cl_char4; alias byte[8] cl_char8; alias byte[16] cl_char16; alias ubyte[2] cl_uchar2; alias ubyte[4] cl_uchar4; alias ubyte[8] cl_uchar8; alias ubyte[16] cl_uchar16; alias short[2] cl_short2; alias short[4] cl_short4; alias short[8] cl_short8; alias short[16] cl_short16; alias ushort[2] cl_ushort2; alias ushort[4] cl_ushort4; alias ushort[8] cl_ushort8; alias ushort[16] cl_ushort16; alias int[2] cl_int2; alias int[4] cl_int4; alias int[8] cl_int8; alias int[16] cl_int16; alias uint[2] cl_uint2; alias uint[4] cl_uint4; alias uint[8] cl_uint8; alias uint[16] cl_uint16; alias long[2] cl_long2; alias long[4] cl_long4; alias long[8] cl_long8; alias long[16] cl_long16; alias ulong[2] cl_ulong2; alias ulong[4] cl_ulong4; alias ulong[8] cl_ulong8; alias ulong[16] cl_ulong16; alias float[2] cl_float2; alias float[4] cl_float4; alias float[8] cl_float8; alias float[16] cl_float16; alias double[2] cl_double2; alias double[4] cl_double4; alias double[8] cl_double8; alias double[16] cl_double16; /* There are no vector types for half */
D
in regard to academic matters
D
/** * Check the arguments to `printf` and `scanf` against the `format` string. * * 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/chkformat.d, _chkformat.d) * Documentation: https://dlang.org/phobos/dmd_chkformat.html * Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/chkformat.d */ module dmd.chkformat; //import core.stdc.stdio : printf, scanf; import core.stdc.ctype : isdigit; import dmd.astenums; import dmd.cond; import dmd.errors; import dmd.expression; import dmd.globals; import dmd.identifier; import dmd.location; import dmd.mtype; import dmd.target; /****************************************** * Check that arguments to a printf format string are compatible * with that string. Issue errors for incompatibilities. * * Follows the C99 specification for printf. * * Takes a generous, rather than strict, view of compatiblity. * For example, an unsigned value can be formatted with a signed specifier. * * Diagnosed incompatibilities are: * * 1. incompatible sizes which will cause argument misalignment * 2. deferencing arguments that are not pointers * 3. insufficient number of arguments * 4. struct arguments * 5. array and slice arguments * 6. non-pointer arguments to `s` specifier * 7. non-standard formats * 8. undefined behavior per C99 * * Per the C Standard, extra arguments are ignored. * * No attempt is made to fix the arguments or the format string. * * Params: * loc = location for error messages * format = format string * args = arguments to match with format string * isVa_list = if a "v" function (format check only) * * Returns: * `true` if errors occurred * References: * C99 7.19.6.1 * https://www.cplusplus.com/reference/cstdio/printf/ */ bool checkPrintfFormat(ref const Loc loc, scope const char[] format, scope Expression[] args, bool isVa_list) { //printf("checkPrintFormat('%.*s')\n", cast(int)format.length, format.ptr); size_t n; // index in args for (size_t i = 0; i < format.length;) { if (format[i] != '%') { ++i; continue; } bool widthStar; bool precisionStar; size_t j = i; const fmt = parsePrintfFormatSpecifier(format, j, widthStar, precisionStar); const slice = format[i .. j]; i = j; if (fmt == Format.percent) continue; // "%%", no arguments if (fmt == Format.GNU_m) continue; // "%m", no arguments if (isVa_list) { // format check only if (fmt == Format.error) deprecation(loc, "format specifier `\"%.*s\"` is invalid", cast(int)slice.length, slice.ptr); continue; } Expression getNextArg(ref bool skip) { if (n == args.length) { if (args.length < (n + 1)) deprecation(loc, "more format specifiers than %d arguments", cast(int)n); else skip = true; return null; } return args[n++]; } void errorMsg(const char* prefix, Expression arg, const char* texpect, Type tactual) { deprecation(arg.loc, "%sargument `%s` for format specification `\"%.*s\"` must be `%s`, not `%s`", prefix ? prefix : "", arg.toChars(), cast(int)slice.length, slice.ptr, texpect, tactual.toChars()); } if (widthStar) { bool skip; auto e = getNextArg(skip); if (skip) continue; if (!e) return true; auto t = e.type.toBasetype(); if (t.ty != Tint32 && t.ty != Tuns32) errorMsg("width ", e, "int", t); } if (precisionStar) { bool skip; auto e = getNextArg(skip); if (skip) continue; if (!e) return true; auto t = e.type.toBasetype(); if (t.ty != Tint32 && t.ty != Tuns32) errorMsg("precision ", e, "int", t); } bool skip; auto e = getNextArg(skip); if (skip) continue; if (!e) return true; auto t = e.type.toBasetype(); auto tnext = t.nextOf(); const c_longsize = target.c.longsize; const ptrsize = target.ptrsize; // Types which are promoted to int are allowed. // Spec: C99 6.5.2.2.7 final switch (fmt) { case Format.u: // unsigned int case Format.d: // int if (t.ty != Tint32 && t.ty != Tuns32) errorMsg(null, e, fmt == Format.u ? "uint" : "int", t); break; case Format.hhu: // unsigned char case Format.hhd: // signed char if (t.ty != Tint32 && t.ty != Tuns32 && t.ty != Tint8 && t.ty != Tuns8) errorMsg(null, e, fmt == Format.hhu ? "ubyte" : "byte", t); break; case Format.hu: // unsigned short int case Format.hd: // short int if (t.ty != Tint32 && t.ty != Tuns32 && t.ty != Tint16 && t.ty != Tuns16) errorMsg(null, e, fmt == Format.hu ? "ushort" : "short", t); break; case Format.lu: // unsigned long int case Format.ld: // long int if (!(t.isintegral() && t.size() == c_longsize)) { if (fmt == Format.lu) errorMsg(null, e, (c_longsize == 4 ? "uint" : "ulong"), t); else errorMsg(null, e, (c_longsize == 4 ? "int" : "long"), t); if (t.isintegral() && t.size() != c_longsize) errorSupplemental(e.loc, "C `long` is %d bytes on your system", c_longsize); } break; case Format.llu: // unsigned long long int case Format.lld: // long long int if (t.ty != Tint64 && t.ty != Tuns64) errorMsg(null, e, fmt == Format.llu ? "ulong" : "long", t); break; case Format.ju: // uintmax_t case Format.jd: // intmax_t if (t.ty != Tint64 && t.ty != Tuns64) { if (fmt == Format.ju) errorMsg(null, e, "core.stdc.stdint.uintmax_t", t); else errorMsg(null, e, "core.stdc.stdint.intmax_t", t); } break; case Format.zd: // size_t if (!(t.isintegral() && t.size() == ptrsize)) errorMsg(null, e, "size_t", t); break; case Format.td: // ptrdiff_t if (!(t.isintegral() && t.size() == ptrsize)) errorMsg(null, e, "ptrdiff_t", t); break; case Format.lg: case Format.g: // double if (t.ty != Tfloat64 && t.ty != Timaginary64) errorMsg(null, e, "double", t); break; case Format.Lg: // long double if (t.ty != Tfloat80 && t.ty != Timaginary80) errorMsg(null, e, "real", t); break; case Format.p: // pointer if (t.ty != Tpointer && t.ty != Tnull && t.ty != Tclass && t.ty != Tdelegate && t.ty != Taarray) errorMsg(null, e, "void*", t); break; case Format.n: // pointer to int if (!(t.ty == Tpointer && tnext.ty == Tint32)) errorMsg(null, e, "int*", t); break; case Format.ln: // pointer to long int if (!(t.ty == Tpointer && tnext.isintegral() && tnext.size() == c_longsize)) errorMsg(null, e, (c_longsize == 4 ? "int*" : "long*"), t); break; case Format.lln: // pointer to long long int if (!(t.ty == Tpointer && tnext.ty == Tint64)) errorMsg(null, e, "long*", t); break; case Format.hn: // pointer to short if (!(t.ty == Tpointer && tnext.ty == Tint16)) errorMsg(null, e, "short*", t); break; case Format.hhn: // pointer to signed char if (!(t.ty == Tpointer && tnext.ty == Tint16)) errorMsg(null, e, "byte*", t); break; case Format.jn: // pointer to intmax_t if (!(t.ty == Tpointer && tnext.ty == Tint64)) errorMsg(null, e, "core.stdc.stdint.intmax_t*", t); break; case Format.zn: // pointer to size_t if (!(t.ty == Tpointer && tnext.isintegral() && tnext.isunsigned() && tnext.size() == ptrsize)) errorMsg(null, e, "size_t*", t); break; case Format.tn: // pointer to ptrdiff_t if (!(t.ty == Tpointer && tnext.isintegral() && !tnext.isunsigned() && tnext.size() == ptrsize)) errorMsg(null, e, "ptrdiff_t*", t); break; case Format.c: // char if (t.ty != Tint32 && t.ty != Tuns32) errorMsg(null, e, "char", t); break; case Format.lc: // wint_t if (t.ty != Tint32 && t.ty != Tuns32) errorMsg(null, e, "wchar_t", t); break; case Format.s: // pointer to char string if (!(t.ty == Tpointer && (tnext.ty == Tchar || tnext.ty == Tint8 || tnext.ty == Tuns8))) errorMsg(null, e, "char*", t); break; case Format.ls: // pointer to wchar_t string if (!(t.ty == Tpointer && tnext.ty.isSomeChar && tnext.size() == target.c.wchar_tsize)) errorMsg(null, e, "wchar_t*", t); break; case Format.error: deprecation(loc, "format specifier `\"%.*s\"` is invalid", cast(int)slice.length, slice.ptr); break; case Format.GNU_m: case Format.POSIX_ms: case Format.POSIX_mls: case Format.percent: assert(0); } } return false; } /****************************************** * Check that arguments to a scanf format string are compatible * with that string. Issue errors for incompatibilities. * * Follows the C99 specification for scanf. * * Takes a generous, rather than strict, view of compatiblity. * For example, an unsigned value can be formatted with a signed specifier. * * Diagnosed incompatibilities are: * * 1. incompatible sizes which will cause argument misalignment * 2. deferencing arguments that are not pointers * 3. insufficient number of arguments * 4. struct arguments * 5. array and slice arguments * 6. non-standard formats * 7. undefined behavior per C99 * * Per the C Standard, extra arguments are ignored. * * No attempt is made to fix the arguments or the format string. * * Params: * loc = location for error messages * format = format string * args = arguments to match with format string * isVa_list = if a "v" function (format check only) * * Returns: * `true` if errors occurred * References: * C99 7.19.6.2 * https://www.cplusplus.com/reference/cstdio/scanf/ */ bool checkScanfFormat(ref const Loc loc, scope const char[] format, scope Expression[] args, bool isVa_list) { size_t n = 0; for (size_t i = 0; i < format.length;) { if (format[i] != '%') { ++i; continue; } bool asterisk; size_t j = i; const fmt = parseScanfFormatSpecifier(format, j, asterisk); const slice = format[i .. j]; i = j; if (fmt == Format.percent || asterisk) continue; // "%%", "%*": no arguments if (isVa_list) { // format check only if (fmt == Format.error) deprecation(loc, "format specifier `\"%.*s\"` is invalid", cast(int)slice.length, slice.ptr); continue; } Expression getNextArg() { if (n == args.length) { if (!asterisk) deprecation(loc, "more format specifiers than %d arguments", cast(int)n); return null; } return args[n++]; } void errorMsg(const char* prefix, Expression arg, const char* texpect, Type tactual) { deprecation(arg.loc, "%sargument `%s` for format specification `\"%.*s\"` must be `%s`, not `%s`", prefix ? prefix : "", arg.toChars(), cast(int)slice.length, slice.ptr, texpect, tactual.toChars()); } auto e = getNextArg(); if (!e) return true; auto t = e.type.toBasetype(); auto tnext = t.nextOf(); const c_longsize = target.c.longsize; const ptrsize = target.ptrsize; final switch (fmt) { case Format.n: case Format.d: // pointer to int if (!(t.ty == Tpointer && tnext.ty == Tint32)) errorMsg(null, e, "int*", t); break; case Format.hhn: case Format.hhd: // pointer to signed char if (!(t.ty == Tpointer && tnext.ty == Tint16)) errorMsg(null, e, "byte*", t); break; case Format.hn: case Format.hd: // pointer to short if (!(t.ty == Tpointer && tnext.ty == Tint16)) errorMsg(null, e, "short*", t); break; case Format.ln: case Format.ld: // pointer to long int if (!(t.ty == Tpointer && tnext.isintegral() && !tnext.isunsigned() && tnext.size() == c_longsize)) errorMsg(null, e, (c_longsize == 4 ? "int*" : "long*"), t); break; case Format.lln: case Format.lld: // pointer to long long int if (!(t.ty == Tpointer && tnext.ty == Tint64)) errorMsg(null, e, "long*", t); break; case Format.jn: case Format.jd: // pointer to intmax_t if (!(t.ty == Tpointer && tnext.ty == Tint64)) errorMsg(null, e, "core.stdc.stdint.intmax_t*", t); break; case Format.zn: case Format.zd: // pointer to size_t if (!(t.ty == Tpointer && tnext.isintegral() && tnext.isunsigned() && tnext.size() == ptrsize)) errorMsg(null, e, "size_t*", t); break; case Format.tn: case Format.td: // pointer to ptrdiff_t if (!(t.ty == Tpointer && tnext.isintegral() && !tnext.isunsigned() && tnext.size() == ptrsize)) errorMsg(null, e, "ptrdiff_t*", t); break; case Format.u: // pointer to unsigned int if (!(t.ty == Tpointer && tnext.ty == Tuns32)) errorMsg(null, e, "uint*", t); break; case Format.hhu: // pointer to unsigned char if (!(t.ty == Tpointer && tnext.ty == Tuns8)) errorMsg(null, e, "ubyte*", t); break; case Format.hu: // pointer to unsigned short int if (!(t.ty == Tpointer && tnext.ty == Tuns16)) errorMsg(null, e, "ushort*", t); break; case Format.lu: // pointer to unsigned long int if (!(t.ty == Tpointer && tnext.isintegral() && tnext.isunsigned() && tnext.size() == c_longsize)) errorMsg(null, e, (c_longsize == 4 ? "uint*" : "ulong*"), t); break; case Format.llu: // pointer to unsigned long long int if (!(t.ty == Tpointer && tnext.ty == Tuns64)) errorMsg(null, e, "ulong*", t); break; case Format.ju: // pointer to uintmax_t if (!(t.ty == Tpointer && tnext.ty == Tuns64)) errorMsg(null, e, "core.stdc.stdint.uintmax_t*", t); break; case Format.g: // pointer to float if (!(t.ty == Tpointer && tnext.ty == Tfloat32)) errorMsg(null, e, "float*", t); break; case Format.lg: // pointer to double if (!(t.ty == Tpointer && tnext.ty == Tfloat64)) errorMsg(null, e, "double*", t); break; case Format.Lg: // pointer to long double if (!(t.ty == Tpointer && tnext.ty == Tfloat80)) errorMsg(null, e, "real*", t); break; case Format.c: case Format.s: // pointer to char string if (!(t.ty == Tpointer && (tnext.ty == Tchar || tnext.ty == Tint8 || tnext.ty == Tuns8))) errorMsg(null, e, "char*", t); break; case Format.lc: case Format.ls: // pointer to wchar_t string if (!(t.ty == Tpointer && tnext.ty.isSomeChar && tnext.size() == target.c.wchar_tsize)) errorMsg(null, e, "wchar_t*", t); break; case Format.p: // double pointer if (!(t.ty == Tpointer && tnext.ty == Tpointer)) errorMsg(null, e, "void**", t); break; case Format.POSIX_ms: // pointer to pointer to char string Type tnext2 = tnext ? tnext.nextOf() : null; if (!(t.ty == Tpointer && tnext.ty == Tpointer && (tnext2.ty == Tchar || tnext2.ty == Tint8 || tnext2.ty == Tuns8))) errorMsg(null, e, "char**", t); break; case Format.POSIX_mls: // pointer to pointer to wchar_t string Type tnext2 = tnext ? tnext.nextOf() : null; if (!(t.ty == Tpointer && tnext.ty == Tpointer && tnext2.ty.isSomeChar && tnext2.size() == target.c.wchar_tsize)) errorMsg(null, e, "wchar_t**", t); break; case Format.error: deprecation(loc, "format specifier `\"%.*s\"` is invalid", cast(int)slice.length, slice.ptr); break; case Format.GNU_m: case Format.percent: assert(0); } } return false; } private: /************************************** * Parse the *format specifier* which is of the form: * * `%[*][width][length]specifier` * * Params: * format = format string * idx = index of `%` of start of format specifier, * which gets updated to index past the end of it, * even if `Format.error` is returned * asterisk = set if there is a `*` sub-specifier * Returns: * Format */ Format parseScanfFormatSpecifier(scope const char[] format, ref size_t idx, out bool asterisk) nothrow pure @safe { auto i = idx; assert(format[i] == '%'); const length = format.length; Format error() { idx = i; return Format.error; } ++i; if (i == length) return error(); if (format[i] == '%') { idx = i + 1; return Format.percent; } // * sub-specifier if (format[i] == '*') { ++i; if (i == length) return error(); asterisk = true; } // fieldWidth while (isdigit(format[i])) { i++; if (i == length) return error(); } /* Read the specifier */ Format specifier; Modifier flags = Modifier.none; switch (format[i]) { case 'm': // https://pubs.opengroup.org/onlinepubs/9699919799/functions/scanf.html // POSIX.1-2017 C Extension (CX) flags = Modifier.m; ++i; if (i == length) return error(); if (format[i] == 'l') { ++i; if (i == length) return error(); flags = Modifier.ml; } // Check valid conversion types for %m. if (format[i] == 'c' || format[i] == 's') specifier = flags == Modifier.ml ? Format.POSIX_mls : Format.POSIX_ms; else if (format[i] == 'C' || format[i] == 'S') specifier = flags == Modifier.m ? Format.POSIX_mls : Format.error; else if (format[i] == '[') goto case '['; else specifier = Format.error; ++i; break; case 'l': // Look for wchar_t scanset %l[..] immutable j = i + 1; if (j < length && format[j] == '[') { i = j; flags = Modifier.l; goto case '['; } goto default; case '[': // Read the scanset i++; if (i == length) return error(); // If the conversion specifier begins with `[]` or `[^]`, the right // bracket character is not the terminator, but in the scanlist. if (format[i] == '^') { i++; if (i == length) return error(); } if (format[i] == ']') { i++; if (i == length) return error(); } // A scanset can be anything, so we just check that it is paired while (i < length) { if (format[i] == ']') break; ++i; } // no `]` found if (i == length) return error(); specifier = flags == Modifier.none ? Format.s : flags == Modifier.l ? Format.ls : flags == Modifier.m ? Format.POSIX_ms : flags == Modifier.ml ? Format.POSIX_mls : Format.error; ++i; break; default: char genSpec; specifier = parseGenericFormatSpecifier(format, i, genSpec); if (specifier == Format.error) return error(); break; } idx = i; return specifier; // success } /************************************** * Parse the *format specifier* which is of the form: * * `%[flags][field width][.precision][length modifier]specifier` * * Params: * format = format string * idx = index of `%` of start of format specifier, * which gets updated to index past the end of it, * even if `Format.error` is returned * widthStar = set if * for width * precisionStar = set if * for precision * useGNUExts = true if parsing GNU format extensions * Returns: * Format */ Format parsePrintfFormatSpecifier(scope const char[] format, ref size_t idx, out bool widthStar, out bool precisionStar, bool useGNUExts = findCondition(global.versionids, Identifier.idPool("CRuntime_Glibc"))) nothrow pure @safe { auto i = idx; assert(format[i] == '%'); const length = format.length; bool hash; bool zero; bool flags; bool width; bool precision; Format error() { idx = i; return Format.error; } ++i; if (i == length) return error(); if (format[i] == '%') { idx = i + 1; return Format.percent; } /* Read the `flags` */ while (1) { const c = format[i]; if (c == '-' || c == '+' || c == ' ') { flags = true; } else if (c == '#') { hash = true; } else if (c == '0') { zero = true; } else break; ++i; if (i == length) return error(); } /* Read the `field width` */ { const c = format[i]; if (c == '*') { width = true; widthStar = true; ++i; if (i == length) return error(); } else if ('1' <= c && c <= '9') { width = true; ++i; if (i == length) return error(); while ('0' <= format[i] && format[i] <= '9') { ++i; if (i == length) return error(); } } } /* Read the `precision` */ if (format[i] == '.') { precision = true; ++i; if (i == length) return error(); const c = format[i]; if (c == '*') { precisionStar = true; ++i; if (i == length) return error(); } else if ('0' <= c && c <= '9') { ++i; if (i == length) return error(); while ('0' <= format[i] && format[i] <= '9') { ++i; if (i == length) return error(); } } } /* Read the specifier */ char genSpec; Format specifier; switch (format[i]) { case 'm': // https://www.gnu.org/software/libc/manual/html_node/Other-Output-Conversions.html if (useGNUExts) { specifier = Format.GNU_m; genSpec = format[i]; ++i; break; } goto default; default: specifier = parseGenericFormatSpecifier(format, i, genSpec); if (specifier == Format.error) return error(); break; } switch (genSpec) { case 'c': case 's': case 'C': case 'S': if (hash || zero) return error(); break; case 'd': case 'i': if (hash) return error(); break; case 'm': if (hash || zero || flags) return error(); break; case 'n': if (hash || zero || precision || width || flags) return error(); break; default: break; } idx = i; return specifier; // success } /* Different kinds of conversion modifiers. */ enum Modifier { none, h, // short hh, // char j, // intmax_t l, // wint_t/wchar_t ll, // long long int L, // long double m, // char** ml, // wchar_t** t, // ptrdiff_t z // size_t } /* Different kinds of formatting specifications, variations we don't care about are merged. (Like we don't care about the difference between f, e, g, a, etc.) For `scanf`, every format is a pointer. */ enum Format { d, // int hhd, // signed char hd, // short int ld, // long int lld, // long long int jd, // intmax_t zd, // size_t td, // ptrdiff_t u, // unsigned int hhu, // unsigned char hu, // unsigned short int lu, // unsigned long int llu, // unsigned long long int ju, // uintmax_t g, // float (scanf) / double (printf) lg, // double (scanf) Lg, // long double (both) s, // char string (both) ls, // wchar_t string (both) c, // char (printf) lc, // wint_t (printf) p, // pointer n, // pointer to int hhn, // pointer to signed char hn, // pointer to short ln, // pointer to long int lln, // pointer to long long int jn, // pointer to intmax_t zn, // pointer to size_t tn, // pointer to ptrdiff_t GNU_m, // GNU ext. : string corresponding to the error code in errno (printf) POSIX_ms, // POSIX ext. : dynamically allocated char string (scanf) POSIX_mls, // POSIX ext. : dynamically allocated wchar_t string (scanf) percent, // %% (i.e. no argument) error, // invalid format specification } /************************************** * Parse the *length specifier* and the *specifier* of the following form: * `[length]specifier` * * Params: * format = format string * idx = index of of start of format specifier, * which gets updated to index past the end of it, * even if `Format.error` is returned * genSpecifier = Generic specifier. For instance, it will be set to `d` if the * format is `hdd`. * Returns: * Format */ Format parseGenericFormatSpecifier(scope const char[] format, ref size_t idx, out char genSpecifier) nothrow pure @safe { const length = format.length; /* Read the `length modifier` */ const lm = format[idx]; Modifier flags; switch (lm) { case 'j': case 'z': case 't': case 'L': flags = lm == 'j' ? Modifier.j : lm == 'z' ? Modifier.z : lm == 't' ? Modifier.t : Modifier.L; ++idx; if (idx == length) return Format.error; break; case 'h': case 'l': ++idx; if (idx == length) return Format.error; if (lm == format[idx]) { flags = lm == 'h' ? Modifier.hh : Modifier.ll; ++idx; if (idx == length) return Format.error; } else flags = lm == 'h' ? Modifier.h : Modifier.l; break; default: flags = Modifier.none; break; } /* Read the `specifier` */ Format specifier; const sc = format[idx]; genSpecifier = sc; switch (sc) { case 'd': case 'i': specifier = flags == Modifier.none ? Format.d : flags == Modifier.hh ? Format.hhd : flags == Modifier.h ? Format.hd : flags == Modifier.ll ? Format.lld : flags == Modifier.l ? Format.ld : flags == Modifier.j ? Format.jd : flags == Modifier.z ? Format.zd : flags == Modifier.t ? Format.td : Format.error; break; case 'u': case 'o': case 'x': case 'X': specifier = flags == Modifier.none ? Format.u : flags == Modifier.hh ? Format.hhu : flags == Modifier.h ? Format.hu : flags == Modifier.ll ? Format.llu : flags == Modifier.l ? Format.lu : flags == Modifier.j ? Format.ju : flags == Modifier.z ? Format.zd : flags == Modifier.t ? Format.td : Format.error; break; case 'f': case 'F': case 'e': case 'E': case 'g': case 'G': case 'a': case 'A': specifier = flags == Modifier.none ? Format.g : flags == Modifier.L ? Format.Lg : flags == Modifier.l ? Format.lg : Format.error; break; case 'c': specifier = flags == Modifier.none ? Format.c : flags == Modifier.l ? Format.lc : Format.error; break; case 's': specifier = flags == Modifier.none ? Format.s : flags == Modifier.l ? Format.ls : Format.error; break; case 'p': specifier = flags == Modifier.none ? Format.p : Format.error; break; case 'n': specifier = flags == Modifier.none ? Format.n : flags == Modifier.ll ? Format.lln : flags == Modifier.l ? Format.ln : flags == Modifier.hh ? Format.hhn : flags == Modifier.h ? Format.hn : flags == Modifier.j ? Format.jn : flags == Modifier.z ? Format.zn : flags == Modifier.t ? Format.tn : Format.error; break; case 'C': // POSIX.1-2017 X/Open System Interfaces (XSI) // %C format is equivalent to %lc specifier = flags == Modifier.none ? Format.lc : Format.error; break; case 'S': // POSIX.1-2017 X/Open System Interfaces (XSI) // %S format is equivalent to %ls specifier = flags == Modifier.none ? Format.ls : Format.error; break; default: specifier = Format.error; break; } ++idx; return specifier; // success } @("parseGenericFormatSpecifier") unittest { char genSpecifier; size_t idx; void testG(string fmtStr, Format expectedFormat, char expectedGenSpecifier) { idx = 0; assert(parseGenericFormatSpecifier(fmtStr, idx, genSpecifier) == expectedFormat); assert(genSpecifier == expectedGenSpecifier); } testG("hhd", Format.hhd, 'd'); testG("hn", Format.hn, 'n'); testG("ji", Format.jd, 'i'); testG("lu", Format.lu, 'u'); idx = 0; assert(parseGenericFormatSpecifier("k", idx, genSpecifier) == Format.error); } @("parsePrintfFormatSpecifier") unittest { bool useGNUExts = false; size_t idx = 0; bool widthStar; bool precisionStar; void testP(string fmtStr, Format expectedFormat, size_t expectedIdx) { idx = 0; assert(parsePrintfFormatSpecifier(fmtStr, idx, widthStar, precisionStar, useGNUExts) == expectedFormat); assert(idx == expectedIdx); } // one for each Format testP("%d", Format.d, 2); assert(!widthStar && !precisionStar); testP("%ld", Format.ld, 3); testP("%lld", Format.lld, 4); testP("%jd", Format.jd, 3); testP("%zd", Format.zd, 3); testP("%td", Format.td, 3); testP("%g", Format.g, 2); testP("%Lg", Format.Lg, 3); testP("%p", Format.p, 2); testP("%n", Format.n, 2); testP("%ln", Format.ln, 3); testP("%lln", Format.lln, 4); testP("%hn", Format.hn, 3); testP("%hhn", Format.hhn, 4); testP("%jn", Format.jn, 3); testP("%zn", Format.zn, 3); testP("%tn", Format.tn, 3); testP("%c", Format.c, 2); testP("%lc", Format.lc, 3); testP("%s", Format.s, 2); testP("%ls", Format.ls, 3); testP("%%", Format.percent, 2); // Synonyms testP("%i", Format.d, 2); testP("%u", Format.u, 2); testP("%o", Format.u, 2); testP("%x", Format.u, 2); testP("%X", Format.u, 2); testP("%f", Format.g, 2); testP("%F", Format.g, 2); testP("%G", Format.g, 2); testP("%a", Format.g, 2); testP("%La", Format.Lg, 3); testP("%A", Format.g, 2); testP("%lg", Format.lg, 3); // width, precision testP("%*d", Format.d, 3); assert(widthStar && !precisionStar); testP("%.*d", Format.d, 4); assert(!widthStar && precisionStar); testP("%*.*d", Format.d, 5); assert(widthStar && precisionStar); // Too short formats foreach (s; ["%", "%-", "%+", "% ", "%#", "%0", "%*", "%1", "%19", "%.", "%.*", "%.1", "%.12", "%j", "%z", "%t", "%l", "%h", "%ll", "%hh"]) { testP(s, Format.error, s.length); } // Undefined format combinations foreach (s; ["%#d", "%llg", "%jg", "%zg", "%tg", "%hg", "%hhg", "%#c", "%0c", "%jc", "%zc", "%tc", "%Lc", "%hc", "%hhc", "%llc", "%#s", "%0s", "%js", "%zs", "%ts", "%Ls", "%hs", "%hhs", "%lls", "%jp", "%zp", "%tp", "%Lp", "%hp", "%lp", "%hhp", "%llp", "%-n", "%+n", "% n", "%#n", "%0n", "%*n", "%1n", "%19n", "%.n", "%.*n", "%.1n", "%.12n", "%Ln", "%K"]) { testP(s, Format.error, s.length); } testP("%C", Format.lc, 2); testP("%S", Format.ls, 2); // GNU extensions: explicitly toggle ISO/GNU flag. foreach (s; ["%jm", "%zm", "%tm", "%Lm", "%hm", "%hhm", "%lm", "%llm", "%#m", "%+m", "%-m", "% m", "%0m"]) { useGNUExts = false; testP(s, Format.error, s.length); useGNUExts = true; testP(s, Format.error, s.length); } foreach (s; ["%m", "%md", "%mz", "%mc", "%mm", "%msyz", "%ml", "%mlz", "%mlc", "%mlm"]) { // valid cases, all parsed as `%m` // GNU printf() useGNUExts = true; testP(s, Format.GNU_m, 2); // ISO printf() useGNUExts = false; testP(s, Format.error, 2); } } @("parseScanfFormatSpecifier") unittest { size_t idx; bool asterisk; void testS(string fmtStr, Format expectedFormat, size_t expectedIdx) { idx = 0; assert(parseScanfFormatSpecifier(fmtStr, idx, asterisk) == expectedFormat); assert(idx == expectedIdx); } // one for each Format testS("%d", Format.d, 2); testS("%hhd", Format.hhd, 4); testS("%hd", Format.hd, 3); testS("%ld", Format.ld, 3); testS("%lld", Format.lld, 4); testS("%jd", Format.jd, 3); testS("%zd", Format.zd, 3); testS("%td", Format.td, 3); testS("%u", Format.u, 2); testS("%hhu", Format.hhu, 4); testS("%hu", Format.hu, 3); testS("%lu", Format.lu, 3); testS("%llu", Format.llu, 4); testS("%ju", Format.ju, 3); testS("%g", Format.g, 2); testS("%lg", Format.lg, 3); testS("%Lg", Format.Lg, 3); testS("%p", Format.p, 2); testS("%s", Format.s, 2); testS("%ls", Format.ls, 3); testS("%%", Format.percent, 2); // Synonyms testS("%i", Format.d, 2); testS("%n", Format.n, 2); testS("%o", Format.u, 2); testS("%x", Format.u, 2); testS("%f", Format.g, 2); testS("%e", Format.g, 2); testS("%a", Format.g, 2); testS("%c", Format.c, 2); // asterisk testS("%*d", Format.d, 3); assert(asterisk); testS("%9ld", Format.ld, 4); assert(!asterisk); testS("%*25984hhd", Format.hhd, 10); assert(asterisk); // scansets testS("%[a-zA-Z]", Format.s, 9); assert(!asterisk); testS("%*25l[a-z]", Format.ls, 10); assert(asterisk); testS("%[]]", Format.s, 4); assert(!asterisk); testS("%[^]]", Format.s, 5); assert(!asterisk); // Too short formats foreach (s; ["%", "% ", "%#", "%0", "%*", "%1", "%19", "%j", "%z", "%t", "%l", "%h", "%ll", "%hh", "%K"]) { testS(s, Format.error, s.length); } // Undefined format combinations foreach (s; ["%Ld", "%llg", "%jg", "%zg", "%tg", "%hg", "%hhg", "%jc", "%zc", "%tc", "%Lc", "%hc", "%hhc", "%llc", "%jp", "%zp", "%tp", "%Lp", "%hp", "%lp", "%hhp", "%llp", "%-", "%+", "%#", "%0", "%.", "%Ln"]) { testS(s, Format.error, s.length); } // Invalid scansets foreach (s; ["%[]", "%[^", "%[^]", "%[s", "%[0-9lld", "%[", "%l[^]"]) { testS(s, Format.error, s.length); } // Posix extensions foreach (s; ["%jm", "%zm", "%tm", "%Lm", "%hm", "%hhm", "%lm", "%llm", "%m", "%ma", "%md", "%ml", "%mm", "%mlb", "%mlj", "%mlr", "%mlz", "%LC", "%lC", "%llC", "%jC", "%tC", "%hC", "%hhC", "%zC", "%LS", "%lS", "%llS", "%jS", "%tS", "%hS", "%hhS", "%zS"]) { testS(s, Format.error, s.length); } testS("%mc", Format.POSIX_ms, 3); testS("%ms", Format.POSIX_ms, 3); testS("%m[0-9]", Format.POSIX_ms, 7); testS("%mlc", Format.POSIX_mls, 4); testS("%mls", Format.POSIX_mls, 4); testS("%ml[^0-9]", Format.POSIX_mls, 9); testS("%mC", Format.POSIX_mls, 3); testS("%mS", Format.POSIX_mls, 3); testS("%C", Format.lc, 2); testS("%S", Format.ls, 2); }
D
module gbaid.memory; import core.thread; import core.time; import core.atomic; import std.stdio; import std.string; import std.file; import gbaid.util; public enum uint BYTES_PER_KIB = 1024; public enum uint BYTES_PER_MIB = BYTES_PER_KIB * BYTES_PER_KIB; public abstract class Memory { public abstract size_t getCapacity(); public abstract void[] getArray(uint address); public abstract void* getPointer(uint address); public abstract byte getByte(uint address); public abstract void setByte(uint address, byte b); public abstract short getShort(uint address); public abstract void setShort(uint address, short s); public abstract int getInt(uint address); public abstract void setInt(uint address, int i); public abstract bool compareAndSet(uint address, int expected, int update); } public class ROM : Memory { protected shared void[] memory; protected this(size_t capacity) { this.memory = new shared byte[capacity]; } public this(void[] memory) { this(memory.length); this.memory[] = memory[]; } public this(string file, uint maxSize) { try { this(read(file, maxSize)); } catch (FileException ex) { throw new Exception("Cannot initialize ROM", ex); } } public override size_t getCapacity() { return memory.length; } public override void[] getArray(uint address) { return cast(void[]) memory[address .. $]; } public override void* getPointer(uint address) { return cast(void*) memory.ptr + address; } public override byte getByte(uint address) { return (cast(byte[]) memory)[address]; } public override void setByte(uint address, byte b) { } public override short getShort(uint address) { return (cast(short[]) memory)[address >> 1]; } public override void setShort(uint address, short s) { } public override int getInt(uint address) { return (cast(int[]) memory)[address >> 2]; } public override void setInt(uint address, int i) { } public override bool compareAndSet(uint address, int expected, int update) { return false; } } public class RAM : ROM { public this(size_t capacity) { super(capacity); } public this(void[] memory) { super(memory); } public this(string file, uint maxByteSize) { super(file, maxByteSize); } public override void setByte(uint address, byte b) { (cast(byte[]) memory)[address] = b; } public override void setShort(uint address, short s) { (cast(short[]) memory)[address >> 1] = s; } public override void setInt(uint address, int i) { (cast(int[]) memory)[address >> 2] = i; } public override bool compareAndSet(uint address, int expected, int update) { return cas(cast(shared int*) getPointer(address), expected, update); } } public class Flash : RAM { private static enum uint PANASONIC_64K_ID = 0x1B32; private static enum uint SANYO_128K_ID = 0x1362; private static enum uint DEVICE_ID_ADDRESS = 0x1; private static enum uint FIRST_CMD_ADDRESS = 0x5555; private static enum uint SECOND_CMD_ADDRESS = 0x2AAA; private static enum uint FIRST_CMD_START_BYTE = 0xAA; private static enum uint SECOND_CMD_START_BYTE = 0x55; private static enum uint ID_MODE_START_CMD_BYTE = 0x90; private static enum uint ID_MODE_STOP_CMD_BYTE = 0xF0; private static enum uint ERASE_CMD_BYTE = 0x80; private static enum uint ERASE_ALL_CMD_BYTE = 0x10; private static enum uint ERASE_SECTOR_CMD_BYTE = 0x30; private static enum uint WRITE_BYTE_CMD_BYTE = 0xA0; private static enum uint SWITCH_BANK_CMD_BYTE = 0xB0; private static TickDuration WRITE_TIMEOUT = 10; private static TickDuration ERASE_SECTOR_TIMEOUT = 500; private static TickDuration ERASE_ALL_TIMEOUT = 500; private uint deviceID; private Mode mode = Mode.NORMAL; private uint cmdStage = 0; private bool timedCMD = false; private TickDuration cmdStartTime; private TickDuration cmdTimeOut; private uint eraseSectorTarget; private uint sectorOffset = 0; static this() { WRITE_TIMEOUT = TickDuration.from!"msecs"(10); ERASE_SECTOR_TIMEOUT = TickDuration.from!"msecs"(500); ERASE_ALL_TIMEOUT = TickDuration.from!"msecs"(500); } public this(size_t capacity) { super(capacity); erase(0, cast(uint) capacity); idChip(); } public this(void[] memory) { super(memory); idChip(); } public this(string file, uint maxByteSize) { super(file, maxByteSize); idChip(); } private void idChip() { if (memory.length > 64 * BYTES_PER_KIB) { deviceID = SANYO_128K_ID; } else { deviceID = PANASONIC_64K_ID; } } public override byte getByte(uint address) { if (mode == Mode.ID && address <= DEVICE_ID_ADDRESS) { return cast(byte) (deviceID >> ((address & 0b1) << 3)); } return super.getByte(address + sectorOffset); } public override void setByte(uint address, byte b) { uint value = b & 0xFF; // Handle command time-outs if (timedCMD && TickDuration.currSystemTick >= cmdTimeOut) { endCMD(); } // Handle commands completions switch (mode) { case Mode.ERASE_ALL: if (address == 0x0 && value == 0xFF) { endCMD(); } break; case Mode.ERASE_SECTOR: if (address == eraseSectorTarget && value == 0xFF) { endCMD(); } break; case Mode.WRITE_BYTE: super.setByte(address + sectorOffset, b); endCMD(); break; case Mode.SWITCH_BANK: sectorOffset = (b & 0b1) << 16; endCMD(); break; default: } // Handle command initialization and execution if (address == FIRST_CMD_ADDRESS && value == FIRST_CMD_START_BYTE) { cmdStage = 1; } else if (cmdStage == 1) { if (address == SECOND_CMD_ADDRESS && value == SECOND_CMD_START_BYTE) { cmdStage = 2; } else { cmdStage = 0; } } else if (cmdStage == 2) { cmdStage = 0; // execute if (address == FIRST_CMD_ADDRESS) { switch (value) { case ID_MODE_START_CMD_BYTE: mode = Mode.ID; break; case ID_MODE_STOP_CMD_BYTE: mode = Mode.NORMAL; break; case ERASE_CMD_BYTE: mode = Mode.ERASE; break; case ERASE_ALL_CMD_BYTE: if (mode == Mode.ERASE) { mode = Mode.ERASE_ALL; startTimedCMD(ERASE_ALL_TIMEOUT); erase(0x0, cast(uint) getCapacity()); } break; case WRITE_BYTE_CMD_BYTE: mode = Mode.WRITE_BYTE; startTimedCMD(WRITE_TIMEOUT); break; case SWITCH_BANK_CMD_BYTE: if (deviceID == SANYO_128K_ID) { mode = Mode.SWITCH_BANK; } break; default: } } else if (!(address & 0xFF0FFF) && value == ERASE_SECTOR_CMD_BYTE && mode == Mode.ERASE) { mode = Mode.ERASE_SECTOR; eraseSectorTarget = address; startTimedCMD(ERASE_SECTOR_TIMEOUT); erase(address, 4 * BYTES_PER_KIB); } } } private void startTimedCMD(TickDuration timeOut) { cmdStartTime = TickDuration.currSystemTick(); cmdTimeOut = cmdStartTime + timeOut; timedCMD = true; } private void endCMD() { mode = Mode.NORMAL; timedCMD = false; } private void erase(uint address, uint size) { foreach (i; address .. address + size) { super.setByte(i, cast(byte) 0xFF); } } public override short getShort(uint address) { throw new UnsupportedMemoryWidthException(address, 2); } public override void setShort(uint address, short s) { throw new UnsupportedMemoryWidthException(address, 2); } public override int getInt(uint address) { throw new UnsupportedMemoryWidthException(address, 4); } public override void setInt(uint address, int i) { throw new UnsupportedMemoryWidthException(address, 4); } public override bool compareAndSet(uint address, int expected, int update) { throw new UnsupportedMemoryOperationException("compareAndSet"); } private static enum Mode { NORMAL, ID, ERASE, ERASE_ALL, ERASE_SECTOR, WRITE_BYTE, SWITCH_BANK } } public class EEPROM : RAM { private Mode mode = Mode.NORMAL; private int validCMD = false; private int targetAddress = 0; private int currentAddressBit = 0, currentReadBit = 0; private int[3] writeBuffer = new int[3]; public this(size_t capacity) { super(capacity); } public this(void[] memory) { super(memory); } public this(string file, uint maxByteSize) { super(file, maxByteSize); } public override byte getByte(uint address) { throw new UnsupportedMemoryWidthException(address, 1); } public override void setByte(uint address, byte b) { throw new UnsupportedMemoryWidthException(address, 1); } public override short getShort(uint address) { if (mode == Mode.WRITE) { // get write address and offset in write buffer int actualAddress = void; int bitOffset = void; if (currentAddressBit > 73) { actualAddress = targetAddress >>> 14; bitOffset = 14; } else { actualAddress = targetAddress >>> 23; bitOffset = 6; } // get data to write from buffer long toWrite = 0; foreach (int i; 0 .. 64) { toWrite |= ucast(getBit(writeBuffer[i + bitOffset >> 5], i + bitOffset & 31)) << 63 - i; } // write data super.setInt(actualAddress, cast(int) toWrite); super.setInt(actualAddress + 4, cast(int) (toWrite >>> 32)); // end write mode mode = Mode.NORMAL; validCMD = false; targetAddress = 0; currentAddressBit = 0; currentReadBit = 0; // return ready return 1; } else if (mode == Mode.READ) { // get data short data = void; if (currentReadBit < 4) { // first 4 bits are 0 data = 0; } else { // get read address depending on amount of bits received int actualAddress = void; if (currentAddressBit > 9) { actualAddress = targetAddress >>> 14; } else { actualAddress = targetAddress >>> 23; } actualAddress += 7 - (currentReadBit - 4 >> 3); // get the data bit data = cast(short) getBit(super.getByte(actualAddress), 7 - (currentReadBit - 4 & 7)); } // end read mode on last bit if (currentReadBit == 67) { mode = Mode.NORMAL; validCMD = false; targetAddress = 0; currentAddressBit = 0; currentReadBit = 0; } else { // increment current read bit and save address currentReadBit++; } return data; } return 0; } public override void setShort(uint address, short s) { // get relevant bit int bit = s & 0b1; // if in write mode, buffer the bit if (mode == Mode.WRITE) { setBit(writeBuffer[currentAddressBit - 2 >> 5], currentAddressBit - 2 & 31, bit); } // then process as command or address bit if (currentAddressBit == 0) { // first command bit if (bit == 0b1) { // mark as valid if it corresponds to a command validCMD = true; } } else if (currentAddressBit == 1) { // second command bit if (validCMD) { // set mode if we have a proper command mode = cast(Mode) bit; } } else if (validCMD && currentAddressBit < 16) { // set address bit if command was valid setBit(targetAddress, 33 - currentAddressBit, bit); } // increment bit count and save address currentAddressBit++; } public override int getInt(uint address) { throw new UnsupportedMemoryWidthException(address, 4); } public override void setInt(uint address, int i) { throw new UnsupportedMemoryWidthException(address, 4); } public override bool compareAndSet(uint address, int expected, int update) { throw new UnsupportedMemoryOperationException("compareAndSet"); } private static enum Mode { NORMAL = 2, READ = 1, WRITE = 0 } } public abstract class MappedMemory : Memory { protected Memory map(ref uint address); public override void[] getArray(uint address) { Memory memory = map(address); return memory.getArray(address); } public override void* getPointer(uint address) { Memory memory = map(address); return memory.getPointer(address); } public override byte getByte(uint address) { Memory memory = map(address); return memory.getByte(address); } public override void setByte(uint address, byte b) { Memory memory = map(address); memory.setByte(address, b); } public override short getShort(uint address) { Memory memory = map(address); return memory.getShort(address); } public override void setShort(uint address, short s) { Memory memory = map(address); memory.setShort(address, s); } public override int getInt(uint address) { Memory memory = map(address); return memory.getInt(address); } public override void setInt(uint address, int i) { Memory memory = map(address); memory.setInt(address, i); } public override bool compareAndSet(uint address, int expected, int update) { Memory memory = map(address); return memory.compareAndSet(address, expected, update); } } public class MonitoredMemory(M : Memory) : Memory { private alias ReadMonitorDelegate = void delegate(Memory, int, int, int, ref int); private alias PreWriteMonitorDelegate = bool delegate(Memory, int, int, int, ref int); private alias PostWriteMonitorDelegate = void delegate(Memory, int, int, int, int, int); private M memory; private MemoryMonitor[] monitors; public this(M memory) { this.memory = memory; monitors = new MemoryMonitor[divFourRoundUp(memory.getCapacity())]; } public void addMonitor(ReadMonitorDelegate monitor, int address, int size) { addMonitor(new ReadMemoryMonitor(monitor), address, size); } public void addMonitor(PreWriteMonitorDelegate monitor, int address, int size) { addMonitor(new PreWriteMemoryMonitor(monitor), address, size); } public void addMonitor(PostWriteMonitorDelegate monitor, int address, int size) { addMonitor(new PostWriteMemoryMonitor(monitor), address, size); } public void addMonitor(MemoryMonitor monitor, int address, int size) { address >>= 2; size = divFourRoundUp(size); foreach (i; address .. address + size) { monitors[i] = monitor; } } public M getMonitored() { return memory; } public override size_t getCapacity() { return memory.getCapacity(); } public override void[] getArray(uint address) { return memory.getArray(address); } public override void* getPointer(uint address) { return memory.getPointer(address); } public override byte getByte(uint address) { byte b = memory.getByte(address); MemoryMonitor monitor = getMonitor(address); if (monitor !is null) { int alignedAddress = address & ~3; int shift = ((address & 3) << 3); int mask = 0xFF << shift; int intValue = ucast(b) << shift; monitor.onRead(memory, alignedAddress, shift, mask, intValue); b = cast(byte) ((intValue & mask) >> shift); } return b; } public override void setByte(uint address, byte b) { MemoryMonitor monitor = getMonitor(address); if (monitor !is null) { int alignedAddress = address & ~3; int shift = ((address & 3) << 3); int mask = 0xFF << shift; int intValue = ucast(b) << shift; bool write = monitor.onPreWrite(memory, alignedAddress, shift, mask, intValue); if (write) { int oldValue = memory.getInt(alignedAddress); b = cast(byte) ((intValue & mask) >> shift); memory.setByte(address, b); int newValue = oldValue & ~mask | intValue & mask; monitor.onPostWrite(memory, alignedAddress, shift, mask, oldValue, newValue); } } else { memory.setByte(address, b); } } public override short getShort(uint address) { address &= ~1; short s = memory.getShort(address); MemoryMonitor monitor = getMonitor(address); if (monitor !is null) { int alignedAddress = address & ~3; int shift = ((address & 2) << 3); int mask = 0xFFFF << shift; int intValue = ucast(s) << shift; monitor.onRead(memory, alignedAddress, shift, mask, intValue); s = cast(short) ((intValue & mask) >> shift); } return s; } public override void setShort(uint address, short s) { address &= ~1; MemoryMonitor monitor = getMonitor(address); if (monitor !is null) { int alignedAddress = address & ~3; int shift = ((address & 2) << 3); int mask = 0xFFFF << shift; int intValue = ucast(s) << shift; bool write = monitor.onPreWrite(memory, alignedAddress, shift, mask, intValue); if (write) { int oldValue = memory.getInt(alignedAddress); s = cast(short) ((intValue & mask) >> shift); memory.setShort(address, s); int newValue = oldValue & ~mask | intValue & mask; monitor.onPostWrite(memory, alignedAddress, shift, mask, oldValue, newValue); } } else { memory.setShort(address, s); } } public override int getInt(uint address) { address &= ~3; int i = memory.getInt(address); MemoryMonitor monitor = getMonitor(address); if (monitor !is null) { int alignedAddress = address; int shift = 0; int mask = 0xFFFFFFFF; int intValue = i; monitor.onRead(memory, alignedAddress, shift, mask, intValue); i = intValue; } return i; } public override void setInt(uint address, int i) { address &= ~3; MemoryMonitor monitor = getMonitor(address); if (monitor !is null) { int alignedAddress = address; int shift = 0; int mask = 0xFFFFFFFF; int intValue = i; bool write = monitor.onPreWrite(memory, alignedAddress, shift, mask, intValue); if (write) { int oldValue = memory.getInt(alignedAddress); i = intValue; memory.setInt(address, i); int newValue = oldValue & ~mask | intValue & mask; monitor.onPostWrite(memory, alignedAddress, shift, mask, oldValue, newValue); } } else { memory.setInt(address, i); } } public override bool compareAndSet(uint address, int expected, int update) { return memory.compareAndSet(address, expected, update); } private MemoryMonitor getMonitor(int address) { return monitors[address >> 2]; } private static int divFourRoundUp(size_t i) { return cast(int) ((i >> 2) + ((i & 0b11) ? 1 : 0)); } private static class ReadMemoryMonitor : MemoryMonitor { private ReadMonitorDelegate monitor; private this(ReadMonitorDelegate monitor) { this.monitor = monitor; } protected override void onRead(Memory memory, int address, int shift, int mask, ref int value) { monitor(memory, address, shift, mask, value); } } private static class PreWriteMemoryMonitor : MemoryMonitor { private PreWriteMonitorDelegate monitor; private this(PreWriteMonitorDelegate monitor) { this.monitor = monitor; } protected override bool onPreWrite(Memory memory, int address, int shift, int mask, ref int value) { return monitor(memory, address, shift, mask, value); } } private static class PostWriteMemoryMonitor : MemoryMonitor { private PostWriteMonitorDelegate monitor; private this(PostWriteMonitorDelegate monitor) { this.monitor = monitor; } protected override void onPostWrite(Memory memory, int address, int shift, int mask, int oldValue, int newValue) { monitor(memory, address, shift, mask, oldValue, newValue); } } } public abstract class MemoryMonitor { protected void onRead(Memory memory, int address, int shift, int mask, ref int value) { } protected bool onPreWrite(Memory memory, int address, int shift, int mask, ref int value) { return true; } protected void onPostWrite(Memory memory, int address, int shift, int mask, int oldValue, int newValue) { } } public class ProtectedROM : ROM { private bool delegate(uint) guard; private int delegate(uint) fallback; public this(void[] memory) { super(memory); guard = &unguarded; fallback = &nullFallback; } public this(string file, uint maxSize) { super(file, maxSize); guard = &unguarded; fallback = &nullFallback; } public void setGuard(bool delegate(uint) guard) { this.guard = guard; } public void setFallback(int delegate(uint) fallback) { this.fallback = fallback; } public override byte getByte(uint address) { if (guard(address)) { return super.getByte(address); } return cast(byte) fallback(address); } public override short getShort(uint address) { if (guard(address)) { return super.getShort(address); } return cast(short) fallback(address); } public override int getInt(uint address) { if (guard(address)) { return super.getInt(address); } return fallback(address); } private bool unguarded(uint address) { return true; } private int nullFallback(uint address) { return 0; } } public class DelegatedROM : Memory { private int delegate(uint) memory; private size_t apparentCapacity; public this(size_t apparentCapacity) { this.apparentCapacity = apparentCapacity; memory = &nullDelegate; } public void setDelegate(int delegate(uint) memory) { this.memory = memory; } public override size_t getCapacity() { return apparentCapacity; } public override void[] getArray(uint address) { throw new UnsupportedMemoryOperationException("getArray"); } public override void* getPointer(uint address) { throw new UnsupportedMemoryOperationException("getPointer"); } public override byte getByte(uint address) { return cast(byte) memory(address); } public override void setByte(uint address, byte b) { } public override short getShort(uint address) { return cast(short) memory(address); } public override void setShort(uint address, short s) { } public override int getInt(uint address) { return memory(address); } public override void setInt(uint address, int i) { } public override bool compareAndSet(uint address, int expected, int update) { throw new UnsupportedMemoryOperationException("compareAndSet"); } private int nullDelegate(uint address) { return 0; } } public class NullMemory : Memory { public override size_t getCapacity() { return 0; } public override void[] getArray(uint address) { return null; } public override void* getPointer(uint address) { return null; } public override byte getByte(uint address) { return 0; } public override void setByte(uint address, byte b) { } public override short getShort(uint address) { return 0; } public override void setShort(uint address, short s) { } public override int getInt(uint address) { return 0; } public override void setInt(uint address, int i) { } public override bool compareAndSet(uint address, int expected, int update) { return false; } } public class ReadOnlyException : Exception { public this(uint address) { super(format("Memory is read only: 0x%08X", address)); } } public class UnsupportedMemoryWidthException : Exception { public this(uint address, uint badByteWidth) { super(format("Attempted to access 0x%08X with unsupported memory width of %s bytes", address, badByteWidth)); } } public class BadAddressException : Exception { public this(uint address) { this("Invalid address", address); } public this(string message, uint address) { super(format("%s: 0x%08X", message, address)); } } public class UnsupportedMemoryOperationException : Exception { public this(string operation) { super(format("Unsupported operation: %s", operation)); } } /* Format: Header: 1 int: number of memory objects (n) n int pairs: 1 int: memory type ID 0: ROM 1: RAM 2: Flash 3: EEPROM 1 int: memory capacity in bytes (c) Body: n byte groups: c bytes: memory */ public Memory[] loadFromFile(string filePath) { Memory fromTypeID(int id, void[] contents) { final switch (id) { case 0: return new ROM(contents); case 1: return new RAM(contents); case 2: return new Flash(contents); case 3: return new EEPROM(contents); } } // open file in binary read File file = File(filePath, "rb"); // read size of header int[1] lengthBytes = new int[1]; file.rawRead(lengthBytes); int length = lengthBytes[0]; // read type and capacity information int[] header = new int[length * 2]; file.rawRead(header); // read memory objects Memory[] memories = new Memory[length]; foreach (i; 0 .. length) { int pair = i * 2; int type = header[pair]; int capacity = header[pair + 1]; void[] contents = new byte[capacity]; file.rawRead(contents); memories[i] = fromTypeID(type, contents); } return memories; // closing is done automatically } public void saveToFile(string filePath, Memory[] memories ...) { int toTypeID(Memory memory) { // order matters because of inheritance, check subclasses first if (cast(EEPROM) memory) { return 3; } if (cast(Flash) memory) { return 2; } if (cast(RAM) memory) { return 1; } if (cast(ROM) memory) { return 0; } throw new Exception("Unsupported memory type: " ~ typeid(memory).name); } // build the header int length = cast(int) memories.length; int[] header = new int[1 + length * 2]; header[0] = length; foreach (int i, Memory memory; memories) { int pair = 1 + i * 2; header[pair] = toTypeID(memory); header[pair + 1] = cast(int) memory.getCapacity(); } // open the file in binary write mode File file = File(filePath, "wb"); // write the header file.rawWrite(header); // write the rest of the memory objects foreach (Memory memory; memories) { file.rawWrite(memory.getArray(0)); } // closing is done automatically }
D
module test.PropertySetterTest; import hunt.util.ObjectUtils; import hunt.util.ObjectUtils; import hunt.logging.ConsoleLogger; struct Foo { string name = "dog"; int bar = 42; int baz = 31337; void setBar(int value) { tracef("setting: value=%d", value); bar = value; } void setBar(string name, int value) { tracef("setting: name=%s, value=%d", name, value); this.name = name; this.bar = value; } int getBar() { return bar; } } interface IFoo { void setBaseBar(int value); } abstract class FooBase : IFoo { abstract void setBaseBar(int value); } class FooClass : FooBase { string name = "dog"; int bar = 42; int baz = 31337; override void setBaseBar(int value) { tracef("setting: value=%d", value); bar = value; } void setBar(int value) { tracef("setting: value=%d", value); bar = value; } void setBar(string name, int value) { tracef("setting: name=%s, value=%d", name, value); this.name = name; this.bar = value; } int getBar() { return bar; } } void testPropertySetter() { Foo foo; setProperty(foo, "bar", 12); assert(foo.bar == 12); setProperty(foo, "bar", "112"); assert(foo.bar == 112); setProperty(foo, "bar", "age", 16); assert(foo.name == "age"); assert(foo.bar == 16); setProperty(foo, "bar", "age", "36"); assert(foo.name == "age"); assert(foo.bar == 36); bool r; FooClass fooClass = new FooClass(); setProperty(fooClass, "bar", "age", "26"); assert(fooClass.bar == 26); FooBase fooBase = fooClass; r = setProperty(fooBase, "bar", "age", "36"); assert(!r); assert(fooClass.bar == 26); FooClass fooBase2 = cast(FooClass) fooBase; setProperty(fooBase2, "bar", "age", "16"); assert(fooClass.bar == 16); IFoo foolInterface = fooClass; r = foolInterface.setProperty("BaseBar", "age", "46"); assert(!r); assert(fooClass.bar == 16); r = foolInterface.setProperty("BaseBar", "46"); assert(r); assert(fooClass.bar == 46); }
D
/Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/Fluent.build/Utilities/UUID.swift.o : /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Utilities/UUID.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/Database+Schema.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/Blob.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/Field.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/ComputedField.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/NodeUtilities/Method+Node.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/NodeUtilities/Filter+Node.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Pagination/Query+Page.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Pagination/Page.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Entity/Storage.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Entity/Timestampable.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Pagination/Paginatable.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Database/Transactable.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Entity/SoftDeletable.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/QueryRepresentable.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Row/RowConvertible.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/Filter+Scope.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/IdentifierType.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Database/Database.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Aggregate.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/NodeUtilities/Scope+String.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/NodeUtilities/Relation+String.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/NodeUtilities/Comparison+String.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Log.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Chunk.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Pivot/PivotProtocol.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Database/ThreadConnectionPool.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Relations/Children.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Join.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Preparation/Database+Preparation.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Preparation/Preparation.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Preparation/Migration.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Action.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Database/Connection.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Entity/KeyNamingConvention.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/Comparison.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/Query+Group.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/Builder.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/Modifier.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/Query+Filter.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/Filter.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Database/Driver.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/SQLite/SQLiteDriver.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/SQL/SQLSerializer.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/SQL/GeneralSQLSerializer.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/SQLite/SQLiteSerializer.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Relations/RelationError.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Pagination/PaginationError.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Preparation/PreparationError.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Pivot/PivotError.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/QueryError.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Entity/EntityError.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/Creator.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Database/Executor.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Relations/Siblings.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Utilities/Exports.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Distinct.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Limit.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Relations/Parent.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Pivot/Pivot.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Pivot/DoublePivot.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Sort.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Row/RowContext.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Raw.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Row/Row.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/Index.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/ForeignKey.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Query.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Entity/Entity.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Entity/Dirty.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/libc.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/Node.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/PathIndexable.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/Core.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/SQLite.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/Debugging.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/Random.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/Bits.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/sqlite.git--8232814251736334455/Sources/CSQLite/include/sqlite3.h /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/CHTTP.build/module.modulemap /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/CSQLite.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/Darwin.apinotes /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/Fluent.build/UUID~partial.swiftmodule : /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Utilities/UUID.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/Database+Schema.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/Blob.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/Field.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/ComputedField.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/NodeUtilities/Method+Node.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/NodeUtilities/Filter+Node.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Pagination/Query+Page.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Pagination/Page.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Entity/Storage.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Entity/Timestampable.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Pagination/Paginatable.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Database/Transactable.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Entity/SoftDeletable.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/QueryRepresentable.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Row/RowConvertible.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/Filter+Scope.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/IdentifierType.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Database/Database.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Aggregate.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/NodeUtilities/Scope+String.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/NodeUtilities/Relation+String.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/NodeUtilities/Comparison+String.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Log.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Chunk.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Pivot/PivotProtocol.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Database/ThreadConnectionPool.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Relations/Children.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Join.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Preparation/Database+Preparation.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Preparation/Preparation.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Preparation/Migration.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Action.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Database/Connection.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Entity/KeyNamingConvention.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/Comparison.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/Query+Group.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/Builder.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/Modifier.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/Query+Filter.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/Filter.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Database/Driver.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/SQLite/SQLiteDriver.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/SQL/SQLSerializer.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/SQL/GeneralSQLSerializer.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/SQLite/SQLiteSerializer.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Relations/RelationError.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Pagination/PaginationError.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Preparation/PreparationError.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Pivot/PivotError.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/QueryError.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Entity/EntityError.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/Creator.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Database/Executor.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Relations/Siblings.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Utilities/Exports.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Distinct.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Limit.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Relations/Parent.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Pivot/Pivot.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Pivot/DoublePivot.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Sort.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Row/RowContext.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Raw.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Row/Row.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/Index.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/ForeignKey.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Query.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Entity/Entity.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Entity/Dirty.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/libc.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/Node.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/PathIndexable.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/Core.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/SQLite.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/Debugging.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/Random.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/Bits.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/sqlite.git--8232814251736334455/Sources/CSQLite/include/sqlite3.h /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/CHTTP.build/module.modulemap /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/CSQLite.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/Darwin.apinotes /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/Fluent.build/UUID~partial.swiftdoc : /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Utilities/UUID.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/Database+Schema.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/Blob.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/Field.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/ComputedField.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/NodeUtilities/Method+Node.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/NodeUtilities/Filter+Node.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Pagination/Query+Page.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Pagination/Page.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Entity/Storage.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Entity/Timestampable.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Pagination/Paginatable.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Database/Transactable.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Entity/SoftDeletable.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/QueryRepresentable.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Row/RowConvertible.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/Filter+Scope.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/IdentifierType.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Database/Database.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Aggregate.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/NodeUtilities/Scope+String.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/NodeUtilities/Relation+String.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/NodeUtilities/Comparison+String.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Log.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Chunk.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Pivot/PivotProtocol.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Database/ThreadConnectionPool.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Relations/Children.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Join.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Preparation/Database+Preparation.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Preparation/Preparation.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Preparation/Migration.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Action.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Database/Connection.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Entity/KeyNamingConvention.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/Comparison.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/Query+Group.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/Builder.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/Modifier.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/Query+Filter.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Filter/Filter.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Database/Driver.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/SQLite/SQLiteDriver.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/SQL/SQLSerializer.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/SQL/GeneralSQLSerializer.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/SQLite/SQLiteSerializer.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Relations/RelationError.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Pagination/PaginationError.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Preparation/PreparationError.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Pivot/PivotError.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/QueryError.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Entity/EntityError.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/Creator.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Database/Executor.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Relations/Siblings.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Utilities/Exports.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Distinct.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Limit.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Relations/Parent.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Pivot/Pivot.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Pivot/DoublePivot.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Sort.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Row/RowContext.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Raw.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Row/Row.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/Index.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Schema/ForeignKey.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Query/Query.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Entity/Entity.swift /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/fluent.git-6251908308727715749/Sources/Fluent/Entity/Dirty.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/libc.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/Node.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/PathIndexable.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/Core.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/SQLite.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/Debugging.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/Random.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/Bits.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/checkouts/sqlite.git--8232814251736334455/Sources/CSQLite/include/sqlite3.h /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/CHTTP.build/module.modulemap /Users/AleixDiaz/Desktop/VaporProject/LaSalleChat/.build/x86_64-apple-macosx10.10/debug/CSQLite.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/Darwin.apinotes
D
/Users/apple-1/Downloads/InteractiveSlideOutMenua-master/Build/Intermediates/InteractiveSlideoutMenu.build/Debug-iphonesimulator/InteractiveSlideoutMenu.build/Objects-normal/x86_64/MenuViewController.o : /Users/apple-1/Downloads/InteractiveSlideOutMenua-master/InteractiveSlideoutMenu/AppDelegate.swift /Users/apple-1/Downloads/InteractiveSlideOutMenua-master/InteractiveSlideoutMenu/MainViewController.swift /Users/apple-1/Downloads/InteractiveSlideOutMenua-master/InteractiveSlideoutMenu/MenuViewController.swift /Users/apple-1/Downloads/InteractiveSlideOutMenua-master/InteractiveSlideoutMenu/MenuHelper.swift /Users/apple-1/Downloads/InteractiveSlideOutMenua-master/InteractiveSlideoutMenu/DismissMenuAnimator.swift /Users/apple-1/Downloads/InteractiveSlideOutMenua-master/InteractiveSlideoutMenu/PresentMenuAnimator.swift /Users/apple-1/Downloads/InteractiveSlideOutMenua-master/InteractiveSlideoutMenu/Interactor.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/apple-1/Downloads/InteractiveSlideOutMenua-master/Build/Intermediates/InteractiveSlideoutMenu.build/Debug-iphonesimulator/InteractiveSlideoutMenu.build/Objects-normal/x86_64/MenuViewController~partial.swiftmodule : /Users/apple-1/Downloads/InteractiveSlideOutMenua-master/InteractiveSlideoutMenu/AppDelegate.swift /Users/apple-1/Downloads/InteractiveSlideOutMenua-master/InteractiveSlideoutMenu/MainViewController.swift /Users/apple-1/Downloads/InteractiveSlideOutMenua-master/InteractiveSlideoutMenu/MenuViewController.swift /Users/apple-1/Downloads/InteractiveSlideOutMenua-master/InteractiveSlideoutMenu/MenuHelper.swift /Users/apple-1/Downloads/InteractiveSlideOutMenua-master/InteractiveSlideoutMenu/DismissMenuAnimator.swift /Users/apple-1/Downloads/InteractiveSlideOutMenua-master/InteractiveSlideoutMenu/PresentMenuAnimator.swift /Users/apple-1/Downloads/InteractiveSlideOutMenua-master/InteractiveSlideoutMenu/Interactor.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/apple-1/Downloads/InteractiveSlideOutMenua-master/Build/Intermediates/InteractiveSlideoutMenu.build/Debug-iphonesimulator/InteractiveSlideoutMenu.build/Objects-normal/x86_64/MenuViewController~partial.swiftdoc : /Users/apple-1/Downloads/InteractiveSlideOutMenua-master/InteractiveSlideoutMenu/AppDelegate.swift /Users/apple-1/Downloads/InteractiveSlideOutMenua-master/InteractiveSlideoutMenu/MainViewController.swift /Users/apple-1/Downloads/InteractiveSlideOutMenua-master/InteractiveSlideoutMenu/MenuViewController.swift /Users/apple-1/Downloads/InteractiveSlideOutMenua-master/InteractiveSlideoutMenu/MenuHelper.swift /Users/apple-1/Downloads/InteractiveSlideOutMenua-master/InteractiveSlideoutMenu/DismissMenuAnimator.swift /Users/apple-1/Downloads/InteractiveSlideOutMenua-master/InteractiveSlideoutMenu/PresentMenuAnimator.swift /Users/apple-1/Downloads/InteractiveSlideOutMenua-master/InteractiveSlideoutMenu/Interactor.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule
D
// DerelictCL - a Derelict based dynamic binding for OpenCL // written in the D programming language // // Copyright: MeinMein 2013-2014. // License: Boost License 1.0 // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // Authors: Gerbrand Kamphuis (meinmein.com), // Marvin Meeng (meinmein.com). module derelict.opencl.loader; import std.string; import derelict.opencl.cl; // All functions tagged at the end by KHR, EXT or vendor-specific (ie. APPLE) // need to be queried using this function. // // From: http://www.khronos.org/registry/cl/sdk/1.1/docs/man/xhtml/clGetExtensionFunctionAddress.html // A return value of NULL indicates that the specified function does not exist for the implementation. // A non-NULL return value for clGetExtensionFunctionAddress does not guarantee that // an extension function is actually supported. The application must also make a corresponding query // using clGetPlatformInfo(platform, CL_PLATFORM_EXTENSIONS, ... ) or clGetDeviceInfo(device, CL_DEVICE_EXTENSIONS, ... ) // to determine if an extension is supported by the OpenCL implementation. // // Note: In OpenCL 1.2 a cl_platform-id is required to retrieve the function adresses. void loadExtensionFunction(void** ptr, string funcName, CLVersion clVer, cl_platform_id platform = null) { // OpenCL 1.1 Deprecated in 1.2 if(clVer <= CLVersion.CL11) *ptr = clGetExtensionFunctionAddress(funcName.toStringz()); // OpenCL 1.2 else *ptr = clGetExtensionFunctionAddressForPlatform(platform, funcName.toStringz()); }
D
/Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/.build/x86_64-apple-macosx/debug/LIFXHTTPKit.build/Group.swift.o : /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/Scene.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/State.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/HTTPSession.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/Location.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/ProductInformation.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/HTTPOperation.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/Group.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/LightTargetObserver.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/ClientObserver.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/Color.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/LightTargetSelector.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/Errors.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/LightTarget.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/Light.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/Result.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/Client.swift /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/XPC.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/ObjectiveC.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Dispatch.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Darwin.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Foundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/CoreFoundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/CoreGraphics.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Swift.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/IOKit.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/SwiftOnoneSupport.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Combine.framework/Modules/Combine.swiftmodule/x86_64-apple-macos.swiftinterface /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/XPC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Combine.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Swift.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/IOKit.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/xpc/XPC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/.build/x86_64-apple-macosx/debug/LIFXHTTPKit.build/Group~partial.swiftmodule : /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/Scene.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/State.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/HTTPSession.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/Location.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/ProductInformation.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/HTTPOperation.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/Group.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/LightTargetObserver.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/ClientObserver.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/Color.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/LightTargetSelector.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/Errors.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/LightTarget.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/Light.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/Result.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/Client.swift /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/XPC.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/ObjectiveC.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Dispatch.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Darwin.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Foundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/CoreFoundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/CoreGraphics.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Swift.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/IOKit.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/SwiftOnoneSupport.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Combine.framework/Modules/Combine.swiftmodule/x86_64-apple-macos.swiftinterface /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/XPC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Combine.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Swift.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/IOKit.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/xpc/XPC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/.build/x86_64-apple-macosx/debug/LIFXHTTPKit.build/Group~partial.swiftdoc : /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/Scene.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/State.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/HTTPSession.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/Location.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/ProductInformation.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/HTTPOperation.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/Group.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/LightTargetObserver.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/ClientObserver.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/Color.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/LightTargetSelector.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/Errors.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/LightTarget.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/Light.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/Result.swift /Users/awllwa/Library/Mobile\ Documents/com~apple~CloudDocs/Code/Github/LIFXHTTPKit/Sources/LIFXHTTPKit/Client.swift /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/XPC.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/ObjectiveC.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Dispatch.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Darwin.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Foundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/CoreFoundation.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/CoreGraphics.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/Swift.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/IOKit.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/lib/swift/SwiftOnoneSupport.swiftmodule/x86_64.swiftinterface /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Combine.framework/Modules/Combine.swiftmodule/x86_64-apple-macos.swiftinterface /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/XPC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Combine.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Swift.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/IOKit.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/xpc/XPC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
D
/home/hustccc/OS_Tutorial_Summer_of_Code/rCore_Labs/Lab5/os/target/rls/riscv64imac-unknown-none-elf/debug/deps/bare_metal-0f9969fa69518217.rmeta: /home/hustccc/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/bare-metal-0.2.5/src/lib.rs /home/hustccc/OS_Tutorial_Summer_of_Code/rCore_Labs/Lab5/os/target/rls/riscv64imac-unknown-none-elf/debug/deps/bare_metal-0f9969fa69518217.d: /home/hustccc/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/bare-metal-0.2.5/src/lib.rs /home/hustccc/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/bare-metal-0.2.5/src/lib.rs:
D
module dlangui.core.config; //version = USE_CONSOLE; version(USE_CONSOLE) { version = NO_OPENGL; version = NO_FREETYPE; enum ENABLE_OPENGL = false; enum ENABLE_FREETYPE = false; enum BACKEND_CONSOLE = true; enum BACKEND_GUI = false; enum BACKEND_SDL = false; enum BACKEND_X11 = false; enum BACKEND_DSFML = false; enum BACKEND_WIN32 = false; enum BACKEND_ANDROID = false; } else { version(USE_EXTERNAL) {} else enum BACKEND_GUI = true; version (NO_FREETYPE) { enum ENABLE_FREETYPE = false; } else version (USE_FREETYPE) { enum ENABLE_FREETYPE = true; } else { version (Windows) { enum ENABLE_FREETYPE = false; } else { enum ENABLE_FREETYPE = true; } } // provide default configuratino definitions version (USE_SDL) { // SDL backend already selected using version identifier version (USE_OPENGL) { enum ENABLE_OPENGL = true; } else { enum ENABLE_OPENGL = false; } enum BACKEND_SDL = true; enum BACKEND_X11 = false; enum BACKEND_DSFML = false; enum BACKEND_WIN32 = false; enum BACKEND_ANDROID = false; enum BACKEND_CONSOLE = false; } else version (USE_ANDROID) { // Android backend already selected using version identifier version (USE_OPENGL) { enum ENABLE_OPENGL = true; } else { enum ENABLE_OPENGL = false; } enum BACKEND_SDL = false; enum BACKEND_X11 = false; enum BACKEND_DSFML = false; enum BACKEND_WIN32 = false; enum BACKEND_ANDROID = true; enum BACKEND_CONSOLE = false; } else version (USE_X11) { // X11 backend already selected using version identifier version (USE_OPENGL) { enum ENABLE_OPENGL = true; } else { enum ENABLE_OPENGL = false; } enum BACKEND_SDL = false; enum BACKEND_X11 = true; enum BACKEND_DSFML = false; enum BACKEND_WIN32 = false; enum BACKEND_CONSOLE = false; } else version (USE_WIN32) { // Win32 backend already selected using version identifier version (USE_OPENGL) { enum ENABLE_OPENGL = true; } else { enum ENABLE_OPENGL = false; } enum BACKEND_SDL = false; enum BACKEND_X11 = false; enum BACKEND_DSFML = false; enum BACKEND_WIN32 = true; enum BACKEND_ANDROID = false; enum BACKEND_CONSOLE = false; } else version (USE_DSFML) { // DSFML backend already selected using version identifier version (USE_OPENGL) { enum ENABLE_OPENGL = true; } else { enum ENABLE_OPENGL = false; } enum BACKEND_SDL = false; enum BACKEND_X11 = false; enum BACKEND_DSFML = true; enum BACKEND_WIN32 = false; enum BACKEND_ANDROID = false; enum BACKEND_CONSOLE = false; } else version (USE_EXTERNAL) { // External backend already selected using version identifier version (USE_OPENGL) { enum ENABLE_OPENGL = true; } else { enum ENABLE_OPENGL = false; } enum BACKEND_GUI = false; enum BACKEND_CONSOLE = false; enum BACKEND_SDL = false; enum BACKEND_X11 = false; enum BACKEND_DSFML = false; enum BACKEND_WIN32 = false; } else { // no backend selected: set default based on platform version (Windows) { // For Windows version (NO_OPENGL) { enum ENABLE_OPENGL = false; } else { enum ENABLE_OPENGL = true; } enum BACKEND_SDL = false; enum BACKEND_X11 = false; enum BACKEND_DSFML = false; enum BACKEND_WIN32 = true; enum BACKEND_ANDROID = false; enum BACKEND_CONSOLE = false; } else version(Android) { // Default for Linux: use SDL and OpenGL enum ENABLE_OPENGL = true; enum BACKEND_SDL = true; enum BACKEND_X11 = false; enum BACKEND_DSFML = false; enum BACKEND_WIN32 = false; enum BACKEND_ANDROID = true; enum BACKEND_CONSOLE = false; } else version(linux) { // Default for Linux: use SDL and OpenGL version (NO_OPENGL) { enum ENABLE_OPENGL = false; } else { enum ENABLE_OPENGL = true; } enum BACKEND_SDL = true; enum BACKEND_X11 = false; enum BACKEND_DSFML = false; enum BACKEND_WIN32 = false; enum BACKEND_ANDROID = false; enum BACKEND_CONSOLE = false; } else version(OSX) { // Default: use SDL and OpenGL version (NO_OPENGL) { enum ENABLE_OPENGL = false; } else { enum ENABLE_OPENGL = true; } enum BACKEND_SDL = true; enum BACKEND_X11 = false; enum BACKEND_DSFML = false; enum BACKEND_WIN32 = false; enum BACKEND_ANDROID = false; enum BACKEND_CONSOLE = false; } else { // Unknown platform: use SDL and OpenGL version (NO_OPENGL) { enum ENABLE_OPENGL = false; } else { enum ENABLE_OPENGL = true; } enum BACKEND_SDL = true; enum BACKEND_X11 = false; enum BACKEND_DSFML = false; enum BACKEND_WIN32 = false; enum BACKEND_ANDROID = false; enum BACKEND_CONSOLE = false; } } }
D
void main() { runSolver(); } void problem() { auto QN = scan!int; auto solve() { auto subSolve() { auto S = scan; const ub = 'a' - 'A'; return YESNO["RGB".all!(c => S.countUntil(c) > S.countUntil(c + ub))]; } foreach(i; 0..QN) { subSolve().writeln; } } outputForAtCoder(&solve); } // ---------------------------------------------- import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop; T[][] combinations(T)(T[] s, in long m) { if (!m) return [[]]; if (s.empty) return []; return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); } string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; } T scan(T)(){ return scan.to!T; } T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; } void deb(T ...)(T t){ debug writeln(t); } alias Point = Tuple!(long, "x", long, "y"); Point invert(Point p) { return Point(p.y, p.x); } long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; } bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; } bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; } string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; } ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}} T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; } string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; } struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}} alias MInt1 = ModInt!(10^^9 + 7); alias MInt9 = ModInt!(998_244_353); void outputForAtCoder(T)(T delegate() fn) { static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn()); else static if (is(T == void)) fn(); else static if (is(T == string)) fn().writeln; else static if (isInputRange!T) { static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln; else foreach(r; fn()) r.writeln; } else fn().writeln; } void runSolver() { enum BORDER = "=================================="; debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } } else problem(); } enum YESNO = [true: "Yes", false: "No"]; // -----------------------------------------------
D
// Written in the D programming language. /** * Elementary mathematical functions * * Contains the elementary mathematical functions (powers, roots, * and trigonometric functions), and low-level floating-point operations. * Mathematical special functions are available in std.mathspecial. * * The functionality closely follows the IEEE754-2008 standard for * floating-point arithmetic, including the use of camelCase names rather * than C99-style lower case names. All of these functions behave correctly * when presented with an infinity or NaN. * * The following IEEE 'real' formats are currently supported: * $(UL * $(LI 64 bit Big-endian 'double' (eg PowerPC)) * $(LI 128 bit Big-endian 'quadruple' (eg SPARC)) * $(LI 64 bit Little-endian 'double' (eg x86-SSE2)) * $(LI 80 bit Little-endian, with implied bit 'real80' (eg x87, Itanium)) * $(LI 128 bit Little-endian 'quadruple' (not implemented on any known processor!)) * $(LI Non-IEEE 128 bit Big-endian 'doubledouble' (eg PowerPC) has partial support) * ) * Unlike C, there is no global 'errno' variable. Consequently, almost all of * these functions are pure nothrow. * * Status: * The semantics and names of feqrel and approxEqual will be revised. * * Macros: * WIKI = Phobos/StdMath * * TABLE_SV = <table border=1 cellpadding=4 cellspacing=0> * <caption>Special Values</caption> * $0</table> * SVH = $(TR $(TH $1) $(TH $2)) * SV = $(TR $(TD $1) $(TD $2)) * * NAN = $(RED NAN) * SUP = <span style="vertical-align:super;font-size:smaller">$0</span> * GAMMA = &#915; * THETA = &theta; * INTEGRAL = &#8747; * INTEGRATE = $(BIG &#8747;<sub>$(SMALL $1)</sub><sup>$2</sup>) * POWER = $1<sup>$2</sup> * SUB = $1<sub>$2</sub> * BIGSUM = $(BIG &Sigma; <sup>$2</sup><sub>$(SMALL $1)</sub>) * CHOOSE = $(BIG &#40;) <sup>$(SMALL $1)</sup><sub>$(SMALL $2)</sub> $(BIG &#41;) * PLUSMN = &plusmn; * INFIN = &infin; * PLUSMNINF = &plusmn;&infin; * PI = &pi; * LT = &lt; * GT = &gt; * SQRT = &radic; * HALF = &frac12; * * Copyright: Copyright Digital Mars 2000 - 2011. * D implementations of tan, atan, atan2, exp, expm1, exp2, log, log10, log1p, * log2, floor, ceil and lrint functions are based on the CEPHES math library, * which is Copyright (C) 2001 Stephen L. Moshier <steve@moshier.net> * and are incorporated herein by permission of the author. The author * reserves the right to distribute this material elsewhere under different * copying permissions. These modifications are distributed here under * the following terms: * License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>. * Authors: $(WEB digitalmars.com, Walter Bright), Don Clugston, * Conversion of CEPHES math library to D by Iain Buclaw * Source: $(PHOBOSSRC std/_math.d) */ /* NOTE: This file has been patched from the original DMD distribution to * work with the GDC compiler. */ module std.math; version (Win64) { version (D_InlineAsm_X86_64) version = Win64_DMD_InlineAsm; } import core.stdc.math; import std.traits; version(LDC) { import ldc.intrinsics; } version(DigitalMars) { version = INLINE_YL2X; // x87 has opcodes for these } version (X86) { version = X86_Any; } version (X86_64) { version = X86_Any; } version(D_InlineAsm_X86) { version = InlineAsm_X86_Any; } else version(D_InlineAsm_X86_64) { version = InlineAsm_X86_Any; } version(unittest) { import core.stdc.stdio; static if(real.sizeof > double.sizeof) enum uint useDigits = 16; else enum uint useDigits = 15; /****************************************** * Compare floating point numbers to n decimal digits of precision. * Returns: * 1 match * 0 nomatch */ private bool equalsDigit(real x, real y, uint ndigits) { if (signbit(x) != signbit(y)) return 0; if (isinf(x) && isinf(y)) return 1; if (isinf(x) || isinf(y)) return 0; if (isnan(x) && isnan(y)) return 1; if (isnan(x) || isnan(y)) return 0; char[30] bufx; char[30] bufy; assert(ndigits < bufx.length); int ix; int iy; version(Win64) alias double real_t; else alias real real_t; ix = sprintf(bufx.ptr, "%.*Lg", ndigits, cast(real_t) x); iy = sprintf(bufy.ptr, "%.*Lg", ndigits, cast(real_t) y); assert(ix < bufx.length && ix > 0); assert(ix < bufy.length && ix > 0); return bufx[0 .. ix] == bufy[0 .. iy]; } } private: // The following IEEE 'real' formats are currently supported. version(LittleEndian) { static assert(real.mant_dig == 53 || real.mant_dig == 64 || real.mant_dig == 113, "Only 64-bit, 80-bit, and 128-bit reals"~ " are supported for LittleEndian CPUs"); } else { static assert(real.mant_dig == 53 || real.mant_dig == 106 || real.mant_dig == 113, "Only 64-bit and 128-bit reals are supported for BigEndian CPUs."~ " double-double reals have partial support"); } // Underlying format exposed through floatTraits enum RealFormat { ieeeHalf, ieeeSingle, ieeeDouble, ieeeExtended, // x87 80-bit real ieeeExtended53, // x87 real rounded to precision of double. ibmExtended, // IBM 128-bit extended ieeeQuadruple, } // Constants used for extracting the components of the representation. // They supplement the built-in floating point properties. template floatTraits(T) { // EXPMASK is a ushort mask to select the exponent portion (without sign) // EXPPOS_SHORT is the index of the exponent when represented as a ushort array. // SIGNPOS_BYTE is the index of the sign when represented as a ubyte array. // RECIP_EPSILON is the value such that (smallest_subnormal) * RECIP_EPSILON == T.min_normal enum T RECIP_EPSILON = (1/T.epsilon); static if (T.mant_dig == 24) { // Single precision float enum ushort EXPMASK = 0x7F80; enum ushort EXPBIAS = 0x3F00; enum uint EXPMASK_INT = 0x7F80_0000; enum uint MANTISSAMASK_INT = 0x007F_FFFF; enum realFormat = RealFormat.ieeeSingle; version(LittleEndian) { enum EXPPOS_SHORT = 1; enum SIGNPOS_BYTE = 3; } else { enum EXPPOS_SHORT = 0; enum SIGNPOS_BYTE = 0; } } else static if (T.mant_dig == 53) { static if (T.sizeof == 8) { // Double precision float, or real == double enum ushort EXPMASK = 0x7FF0; enum ushort EXPBIAS = 0x3FE0; enum uint EXPMASK_INT = 0x7FF0_0000; enum uint MANTISSAMASK_INT = 0x000F_FFFF; // for the MSB only enum realFormat = RealFormat.ieeeDouble; version(LittleEndian) { enum EXPPOS_SHORT = 3; enum SIGNPOS_BYTE = 7; } else { enum EXPPOS_SHORT = 0; enum SIGNPOS_BYTE = 0; } } else static if (T.sizeof == 12) { // Intel extended real80 rounded to double enum ushort EXPMASK = 0x7FFF; enum ushort EXPBIAS = 0x3FFE; enum realFormat = RealFormat.ieeeExtended53; version(LittleEndian) { enum EXPPOS_SHORT = 4; enum SIGNPOS_BYTE = 9; } else { enum EXPPOS_SHORT = 0; enum SIGNPOS_BYTE = 0; } } else static assert(false, "No traits support for " ~ T.stringof); } else static if (T.mant_dig == 64) { // Intel extended real80 enum ushort EXPMASK = 0x7FFF; enum ushort EXPBIAS = 0x3FFE; enum realFormat = RealFormat.ieeeExtended; version(LittleEndian) { enum EXPPOS_SHORT = 4; enum SIGNPOS_BYTE = 9; } else { enum EXPPOS_SHORT = 0; enum SIGNPOS_BYTE = 0; } } else static if (T.mant_dig == 113) { // Quadruple precision float enum ushort EXPMASK = 0x7FFF; enum realFormat = RealFormat.ieeeQuadruple; version(LittleEndian) { enum EXPPOS_SHORT = 7; enum SIGNPOS_BYTE = 15; } else { enum EXPPOS_SHORT = 0; enum SIGNPOS_BYTE = 0; } } else static if (T.mant_dig == 106) { // IBM Extended doubledouble enum ushort EXPMASK = 0x7FF0; enum realFormat = RealFormat.ibmExtended; // the exponent byte is not unique version(LittleEndian) { enum EXPPOS_SHORT = 7; // [3] is also an exp short enum SIGNPOS_BYTE = 15; } else { enum EXPPOS_SHORT = 0; // [4] is also an exp short enum SIGNPOS_BYTE = 0; } } else static assert(false, "No traits support for " ~ T.stringof); } // These apply to all floating-point types version(LittleEndian) { enum MANTISSA_LSB = 0; enum MANTISSA_MSB = 1; } else { enum MANTISSA_LSB = 1; enum MANTISSA_MSB = 0; } // Common code for math implementations. // Helper for floor/ceil T floorImpl(T)(T x) @trusted pure nothrow @nogc { alias F = floatTraits!(T); // Take care not to trigger library calls from the compiler, // while ensuring that we don't get defeated by some optimizers. union floatBits { T rv; ushort[T.sizeof/2] vu; } floatBits y = void; y.rv = x; // Find the exponent (power of 2) static if (F.realFormat == RealFormat.ieeeSingle) { int exp = ((y.vu[F.EXPPOS_SHORT] >> 7) & 0xff) - 0x7f; version (LittleEndian) int pos = 0; else int pos = 3; } else static if (F.realFormat == RealFormat.ieeeDouble) { int exp = ((y.vu[F.EXPPOS_SHORT] >> 4) & 0x7ff) - 0x3ff; version (LittleEndian) int pos = 0; else int pos = 3; } else static if (F.realFormat == RealFormat.ieeeExtended) { int exp = (y.vu[F.EXPPOS_SHORT] & 0x7fff) - 0x3fff; version (LittleEndian) int pos = 0; else int pos = 4; } else static if (F.realFormat == RealFormat.ieeeQuadruple) { int exp = (y.vu[F.EXPPOS_SHORT] & 0x7fff) - 0x3fff; version (LittleEndian) int pos = 0; else int pos = 7; } else static assert(false, "Not implemented for this architecture"); if (exp < 0) { if (x < 0.0) return -1.0; else return 0.0; } exp = (T.mant_dig - 1) - exp; // Zero 16 bits at a time. while (exp >= 16) { version (LittleEndian) y.vu[pos++] = 0; else y.vu[pos--] = 0; exp -= 16; } // Clear the remaining bits. if (exp > 0) y.vu[pos] &= 0xffff ^ ((1 << exp) - 1); if ((x < 0.0) && (x != y.rv)) y.rv -= 1.0; return y.rv; } public: // Values obtained from Wolfram Alpha. 116 bits ought to be enough for anybody. // Wolfram Alpha LLC. 2011. Wolfram|Alpha. http://www.wolframalpha.com/input/?i=e+in+base+16 (access July 6, 2011). enum real E = 0x1.5bf0a8b1457695355fb8ac404e7a8p+1L; /** e = 2.718281... */ enum real LOG2T = 0x1.a934f0979a3715fc9257edfe9b5fbp+1L; /** $(SUB log, 2)10 = 3.321928... */ enum real LOG2E = 0x1.71547652b82fe1777d0ffda0d23a8p+0L; /** $(SUB log, 2)e = 1.442695... */ enum real LOG2 = 0x1.34413509f79fef311f12b35816f92p-2L; /** $(SUB log, 10)2 = 0.301029... */ enum real LOG10E = 0x1.bcb7b1526e50e32a6ab7555f5a67cp-2L; /** $(SUB log, 10)e = 0.434294... */ enum real LN2 = 0x1.62e42fefa39ef35793c7673007e5fp-1L; /** ln 2 = 0.693147... */ enum real LN10 = 0x1.26bb1bbb5551582dd4adac5705a61p+1L; /** ln 10 = 2.302585... */ enum real PI = 0x1.921fb54442d18469898cc51701b84p+1L; /** $(_PI) = 3.141592... */ enum real PI_2 = PI/2; /** $(PI) / 2 = 1.570796... */ enum real PI_4 = PI/4; /** $(PI) / 4 = 0.785398... */ enum real M_1_PI = 0x1.45f306dc9c882a53f84eafa3ea69cp-2L; /** 1 / $(PI) = 0.318309... */ enum real M_2_PI = 2*M_1_PI; /** 2 / $(PI) = 0.636619... */ enum real M_2_SQRTPI = 0x1.20dd750429b6d11ae3a914fed7fd8p+0L; /** 2 / $(SQRT)$(PI) = 1.128379... */ enum real SQRT2 = 0x1.6a09e667f3bcc908b2fb1366ea958p+0L; /** $(SQRT)2 = 1.414213... */ enum real SQRT1_2 = SQRT2/2; /** $(SQRT)$(HALF) = 0.707106... */ // Note: Make sure the magic numbers in compiler backend for x87 match these. /*********************************** * Calculates the absolute value * * For complex numbers, abs(z) = sqrt( $(POWER z.re, 2) + $(POWER z.im, 2) ) * = hypot(z.re, z.im). */ Num abs(Num)(Num x) @safe pure nothrow if (is(typeof(Num.init >= 0)) && is(typeof(-Num.init)) && !(is(Num* : const(ifloat*)) || is(Num* : const(idouble*)) || is(Num* : const(ireal*)))) { static if (isFloatingPoint!(Num)) return fabs(x); else return x>=0 ? x : -x; } auto abs(Num)(Num z) @safe pure nothrow @nogc if (is(Num* : const(cfloat*)) || is(Num* : const(cdouble*)) || is(Num* : const(creal*))) { return hypot(z.re, z.im); } /** ditto */ real abs(Num)(Num y) @safe pure nothrow @nogc if (is(Num* : const(ifloat*)) || is(Num* : const(idouble*)) || is(Num* : const(ireal*))) { return fabs(y.im); } unittest { assert(isIdentical(abs(-0.0L), 0.0L)); assert(isNaN(abs(real.nan))); assert(abs(-real.infinity) == real.infinity); assert(abs(-3.2Li) == 3.2L); assert(abs(71.6Li) == 71.6L); assert(abs(-56) == 56); assert(abs(2321312L) == 2321312L); assert(abs(-1+1i) == sqrt(2.0L)); } /*********************************** * Complex conjugate * * conj(x + iy) = x - iy * * Note that z * conj(z) = $(POWER z.re, 2) - $(POWER z.im, 2) * is always a real number */ creal conj(creal z) @safe pure nothrow @nogc { return z.re - z.im*1i; } /** ditto */ ireal conj(ireal y) @safe pure nothrow @nogc { return -y; } unittest { assert(conj(7 + 3i) == 7-3i); ireal z = -3.2Li; assert(conj(z) == -z); } /*********************************** * Returns cosine of x. x is in radians. * * $(TABLE_SV * $(TR $(TH x) $(TH cos(x)) $(TH invalid?)) * $(TR $(TD $(NAN)) $(TD $(NAN)) $(TD yes) ) * $(TR $(TD $(PLUSMN)$(INFIN)) $(TD $(NAN)) $(TD yes) ) * ) * Bugs: * Results are undefined if |x| >= $(POWER 2,64). */ real cos(real x) @safe pure nothrow @nogc; /* intrinsic */ /*********************************** * Returns sine of x. x is in radians. * * $(TABLE_SV * $(TR $(TH x) $(TH sin(x)) $(TH invalid?)) * $(TR $(TD $(NAN)) $(TD $(NAN)) $(TD yes)) * $(TR $(TD $(PLUSMN)0.0) $(TD $(PLUSMN)0.0) $(TD no)) * $(TR $(TD $(PLUSMNINF)) $(TD $(NAN)) $(TD yes)) * ) * Bugs: * Results are undefined if |x| >= $(POWER 2,64). */ real sin(real x) @safe pure nothrow @nogc; /* intrinsic */ /*********************************** * sine, complex and imaginary * * sin(z) = sin(z.re)*cosh(z.im) + cos(z.re)*sinh(z.im)i * * If both sin($(THETA)) and cos($(THETA)) are required, * it is most efficient to use expi($(THETA)). */ creal sin(creal z) @safe pure nothrow @nogc { creal cs = expi(z.re); creal csh = coshisinh(z.im); return cs.im * csh.re + cs.re * csh.im * 1i; } /** ditto */ ireal sin(ireal y) @safe pure nothrow @nogc { return cosh(y.im)*1i; } unittest { assert(sin(0.0+0.0i) == 0.0); assert(sin(2.0+0.0i) == sin(2.0L) ); } /*********************************** * cosine, complex and imaginary * * cos(z) = cos(z.re)*cosh(z.im) - sin(z.re)*sinh(z.im)i */ creal cos(creal z) @safe pure nothrow @nogc { creal cs = expi(z.re); creal csh = coshisinh(z.im); return cs.re * csh.re - cs.im * csh.im * 1i; } /** ditto */ real cos(ireal y) @safe pure nothrow @nogc { return cosh(y.im); } unittest { assert(cos(0.0+0.0i)==1.0); assert(cos(1.3L+0.0i)==cos(1.3L)); assert(cos(5.2Li)== cosh(5.2L)); } /**************************************************************************** * Returns tangent of x. x is in radians. * * $(TABLE_SV * $(TR $(TH x) $(TH tan(x)) $(TH invalid?)) * $(TR $(TD $(NAN)) $(TD $(NAN)) $(TD yes)) * $(TR $(TD $(PLUSMN)0.0) $(TD $(PLUSMN)0.0) $(TD no)) * $(TR $(TD $(PLUSMNINF)) $(TD $(NAN)) $(TD yes)) * ) */ real tan(real x) @trusted pure nothrow @nogc { version(D_InlineAsm_X86) { asm { fld x[EBP] ; // load theta fxam ; // test for oddball values fstsw AX ; sahf ; jc trigerr ; // x is NAN, infinity, or empty // 387's can handle subnormals SC18: fptan ; fstp ST(0) ; // dump X, which is always 1 fstsw AX ; sahf ; jnp Lret ; // C2 = 1 (x is out of range) // Do argument reduction to bring x into range fldpi ; fxch ; SC17: fprem1 ; fstsw AX ; sahf ; jp SC17 ; fstp ST(1) ; // remove pi from stack jmp SC18 ; trigerr: jnp Lret ; // if theta is NAN, return theta fstp ST(0) ; // dump theta } return real.nan; Lret: {} } else version(D_InlineAsm_X86_64) { version (Win64) { asm { fld real ptr [RCX] ; // load theta } } else { asm { fld x[RBP] ; // load theta } } asm { fxam ; // test for oddball values fstsw AX ; test AH,1 ; jnz trigerr ; // x is NAN, infinity, or empty // 387's can handle subnormals SC18: fptan ; fstp ST(0) ; // dump X, which is always 1 fstsw AX ; test AH,4 ; jz Lret ; // C2 = 1 (x is out of range) // Do argument reduction to bring x into range fldpi ; fxch ; SC17: fprem1 ; fstsw AX ; test AH,4 ; jnz SC17 ; fstp ST(1) ; // remove pi from stack jmp SC18 ; trigerr: test AH,4 ; jz Lret ; // if theta is NAN, return theta fstp ST(0) ; // dump theta } return real.nan; Lret: {} } else { // Coefficients for tan(x) static immutable real[3] P = [ -1.7956525197648487798769E7L, 1.1535166483858741613983E6L, -1.3093693918138377764608E4L, ]; static immutable real[5] Q = [ -5.3869575592945462988123E7L, 2.5008380182335791583922E7L, -1.3208923444021096744731E6L, 1.3681296347069295467845E4L, 1.0000000000000000000000E0L, ]; // PI/4 split into three parts. enum real P1 = 7.853981554508209228515625E-1L; enum real P2 = 7.946627356147928367136046290398E-9L; enum real P3 = 3.061616997868382943065164830688E-17L; // Special cases. if (x == 0.0 || isNaN(x)) return x; if (isInfinity(x)) return real.nan; // Make argument positive but save the sign. bool sign = false; if (signbit(x)) { sign = true; x = -x; } // Compute x mod PI/4. real y = floor(x / PI_4); // Strip high bits of integer part. real z = ldexp(y, -4); // Compute y - 16 * (y / 16). z = y - ldexp(floor(z), 4); // Integer and fraction part modulo one octant. int j = cast(int)(z); // Map zeros and singularities to origin. if (j & 1) { j += 1; y += 1.0; } z = ((x - y * P1) - y * P2) - y * P3; real zz = z * z; if (zz > 1.0e-20L) y = z + z * (zz * poly(zz, P) / poly(zz, Q)); else y = z; if (j & 2) y = -1.0 / y; return (sign) ? -y : y; } } unittest { static real[2][] vals = // angle,tan [ [ 0, 0], [ .5, .5463024898], [ 1, 1.557407725], [ 1.5, 14.10141995], [ 2, -2.185039863], [ 2.5,-.7470222972], [ 3, -.1425465431], [ 3.5, .3745856402], [ 4, 1.157821282], [ 4.5, 4.637332055], [ 5, -3.380515006], [ 5.5,-.9955840522], [ 6, -.2910061914], [ 6.5, .2202772003], [ 10, .6483608275], // special angles [ PI_4, 1], //[ PI_2, real.infinity], // PI_2 is not _exactly_ pi/2. [ 3*PI_4, -1], [ PI, 0], [ 5*PI_4, 1], //[ 3*PI_2, -real.infinity], [ 7*PI_4, -1], [ 2*PI, 0], ]; int i; for (i = 0; i < vals.length; i++) { real x = vals[i][0]; real r = vals[i][1]; real t = tan(x); //printf("tan(%Lg) = %Lg, should be %Lg\n", x, t, r); if (!isIdentical(r, t)) assert(fabs(r-t) <= .0000001); x = -x; r = -r; t = tan(x); //printf("tan(%Lg) = %Lg, should be %Lg\n", x, t, r); if (!isIdentical(r, t) && !(r!=r && t!=t)) assert(fabs(r-t) <= .0000001); } // overflow assert(isNaN(tan(real.infinity))); assert(isNaN(tan(-real.infinity))); // NaN propagation assert(isIdentical( tan(NaN(0x0123L)), NaN(0x0123L) )); } unittest { assert(equalsDigit(tan(PI / 3), std.math.sqrt(3.0), useDigits)); } /*************** * Calculates the arc cosine of x, * returning a value ranging from 0 to $(PI). * * $(TABLE_SV * $(TR $(TH x) $(TH acos(x)) $(TH invalid?)) * $(TR $(TD $(GT)1.0) $(TD $(NAN)) $(TD yes)) * $(TR $(TD $(LT)-1.0) $(TD $(NAN)) $(TD yes)) * $(TR $(TD $(NAN)) $(TD $(NAN)) $(TD yes)) * ) */ real acos(real x) @safe pure nothrow @nogc { return atan2(sqrt(1-x*x), x); } /// ditto double acos(double x) @safe pure nothrow @nogc { return acos(cast(real)x); } /// ditto float acos(float x) @safe pure nothrow @nogc { return acos(cast(real)x); } unittest { assert(equalsDigit(acos(0.5), std.math.PI / 3, useDigits)); } /*************** * Calculates the arc sine of x, * returning a value ranging from -$(PI)/2 to $(PI)/2. * * $(TABLE_SV * $(TR $(TH x) $(TH asin(x)) $(TH invalid?)) * $(TR $(TD $(PLUSMN)0.0) $(TD $(PLUSMN)0.0) $(TD no)) * $(TR $(TD $(GT)1.0) $(TD $(NAN)) $(TD yes)) * $(TR $(TD $(LT)-1.0) $(TD $(NAN)) $(TD yes)) * ) */ real asin(real x) @safe pure nothrow @nogc { return atan2(x, sqrt(1-x*x)); } /// ditto double asin(double x) @safe pure nothrow @nogc { return asin(cast(real)x); } /// ditto float asin(float x) @safe pure nothrow @nogc { return asin(cast(real)x); } unittest { assert(equalsDigit(asin(0.5), PI / 6, useDigits)); } /*************** * Calculates the arc tangent of x, * returning a value ranging from -$(PI)/2 to $(PI)/2. * * $(TABLE_SV * $(TR $(TH x) $(TH atan(x)) $(TH invalid?)) * $(TR $(TD $(PLUSMN)0.0) $(TD $(PLUSMN)0.0) $(TD no)) * $(TR $(TD $(PLUSMN)$(INFIN)) $(TD $(NAN)) $(TD yes)) * ) */ real atan(real x) @safe pure nothrow @nogc { version(InlineAsm_X86_Any) { return atan2(x, 1.0L); } else { // Coefficients for atan(x) static immutable real[5] P = [ -5.0894116899623603312185E1L, -9.9988763777265819915721E1L, -6.3976888655834347413154E1L, -1.4683508633175792446076E1L, -8.6863818178092187535440E-1L, ]; static immutable real[6] Q = [ 1.5268235069887081006606E2L, 3.9157570175111990631099E2L, 3.6144079386152023162701E2L, 1.4399096122250781605352E2L, 2.2981886733594175366172E1L, 1.0000000000000000000000E0L, ]; // tan(PI/8) enum real TAN_PI_8 = 4.1421356237309504880169e-1L; // tan(3 * PI/8) enum real TAN3_PI_8 = 2.41421356237309504880169L; // Special cases. if (x == 0.0) return x; if (isInfinity(x)) return copysign(PI_2, x); // Make argument positive but save the sign. bool sign = false; if (signbit(x)) { sign = true; x = -x; } // Range reduction. real y; if (x > TAN3_PI_8) { y = PI_2; x = -(1.0 / x); } else if (x > TAN_PI_8) { y = PI_4; x = (x - 1.0)/(x + 1.0); } else y = 0.0; // Rational form in x^^2. real z = x * x; y = y + (poly(z, P) / poly(z, Q)) * z * x + x; return (sign) ? -y : y; } } /// ditto double atan(double x) @safe pure nothrow @nogc { return atan(cast(real)x); } /// ditto float atan(float x) @safe pure nothrow @nogc { return atan(cast(real)x); } unittest { assert(equalsDigit(atan(std.math.sqrt(3.0)), PI / 3, useDigits)); } /*************** * Calculates the arc tangent of y / x, * returning a value ranging from -$(PI) to $(PI). * * $(TABLE_SV * $(TR $(TH y) $(TH x) $(TH atan(y, x))) * $(TR $(TD $(NAN)) $(TD anything) $(TD $(NAN)) ) * $(TR $(TD anything) $(TD $(NAN)) $(TD $(NAN)) ) * $(TR $(TD $(PLUSMN)0.0) $(TD $(GT)0.0) $(TD $(PLUSMN)0.0) ) * $(TR $(TD $(PLUSMN)0.0) $(TD +0.0) $(TD $(PLUSMN)0.0) ) * $(TR $(TD $(PLUSMN)0.0) $(TD $(LT)0.0) $(TD $(PLUSMN)$(PI))) * $(TR $(TD $(PLUSMN)0.0) $(TD -0.0) $(TD $(PLUSMN)$(PI))) * $(TR $(TD $(GT)0.0) $(TD $(PLUSMN)0.0) $(TD $(PI)/2) ) * $(TR $(TD $(LT)0.0) $(TD $(PLUSMN)0.0) $(TD -$(PI)/2) ) * $(TR $(TD $(GT)0.0) $(TD $(INFIN)) $(TD $(PLUSMN)0.0) ) * $(TR $(TD $(PLUSMN)$(INFIN)) $(TD anything) $(TD $(PLUSMN)$(PI)/2)) * $(TR $(TD $(GT)0.0) $(TD -$(INFIN)) $(TD $(PLUSMN)$(PI)) ) * $(TR $(TD $(PLUSMN)$(INFIN)) $(TD $(INFIN)) $(TD $(PLUSMN)$(PI)/4)) * $(TR $(TD $(PLUSMN)$(INFIN)) $(TD -$(INFIN)) $(TD $(PLUSMN)3$(PI)/4)) * ) */ real atan2(real y, real x) @trusted pure nothrow @nogc { version(InlineAsm_X86_Any) { version (Win64) { asm { naked; fld real ptr [RDX]; // y fld real ptr [RCX]; // x fpatan; ret; } } else { asm { fld y; fld x; fpatan; } } } else { // Special cases. if (isNaN(x) || isNaN(y)) return real.nan; if (y == 0.0) { if (x >= 0 && !signbit(x)) return copysign(0, y); else return copysign(PI, y); } if (x == 0.0) return copysign(PI_2, y); if (isInfinity(x)) { if (signbit(x)) { if (isInfinity(y)) return copysign(3*PI_4, y); else return copysign(PI, y); } else { if (isInfinity(y)) return copysign(PI_4, y); else return copysign(0.0, y); } } if (isInfinity(y)) return copysign(PI_2, y); // Call atan and determine the quadrant. real z = atan(y / x); if (signbit(x)) { if (signbit(y)) z = z - PI; else z = z + PI; } if (z == 0.0) return copysign(z, y); return z; } } /// ditto double atan2(double y, double x) @safe pure nothrow @nogc { return atan2(cast(real)y, cast(real)x); } /// ditto float atan2(float y, float x) @safe pure nothrow @nogc { return atan2(cast(real)y, cast(real)x); } unittest { assert(equalsDigit(atan2(1.0L, std.math.sqrt(3.0L)), PI / 6, useDigits)); } /*********************************** * Calculates the hyperbolic cosine of x. * * $(TABLE_SV * $(TR $(TH x) $(TH cosh(x)) $(TH invalid?)) * $(TR $(TD $(PLUSMN)$(INFIN)) $(TD $(PLUSMN)0.0) $(TD no) ) * ) */ real cosh(real x) @safe pure nothrow @nogc { // cosh = (exp(x)+exp(-x))/2. // The naive implementation works correctly. real y = exp(x); return (y + 1.0/y) * 0.5; } /// ditto double cosh(double x) @safe pure nothrow @nogc { return cosh(cast(real)x); } /// ditto float cosh(float x) @safe pure nothrow @nogc { return cosh(cast(real)x); } unittest { assert(equalsDigit(cosh(1.0), (E + 1.0 / E) / 2, useDigits)); } /*********************************** * Calculates the hyperbolic sine of x. * * $(TABLE_SV * $(TR $(TH x) $(TH sinh(x)) $(TH invalid?)) * $(TR $(TD $(PLUSMN)0.0) $(TD $(PLUSMN)0.0) $(TD no)) * $(TR $(TD $(PLUSMN)$(INFIN)) $(TD $(PLUSMN)$(INFIN)) $(TD no)) * ) */ real sinh(real x) @safe pure nothrow @nogc { // sinh(x) = (exp(x)-exp(-x))/2; // Very large arguments could cause an overflow, but // the maximum value of x for which exp(x) + exp(-x)) != exp(x) // is x = 0.5 * (real.mant_dig) * LN2. // = 22.1807 for real80. if (fabs(x) > real.mant_dig * LN2) { return copysign(0.5 * exp(fabs(x)), x); } real y = expm1(x); return 0.5 * y / (y+1) * (y+2); } /// ditto double sinh(double x) @safe pure nothrow @nogc { return sinh(cast(real)x); } /// ditto float sinh(float x) @safe pure nothrow @nogc { return sinh(cast(real)x); } unittest { assert(equalsDigit(sinh(1.0), (E - 1.0 / E) / 2, useDigits)); } /*********************************** * Calculates the hyperbolic tangent of x. * * $(TABLE_SV * $(TR $(TH x) $(TH tanh(x)) $(TH invalid?)) * $(TR $(TD $(PLUSMN)0.0) $(TD $(PLUSMN)0.0) $(TD no) ) * $(TR $(TD $(PLUSMN)$(INFIN)) $(TD $(PLUSMN)1.0) $(TD no)) * ) */ real tanh(real x) @safe pure nothrow @nogc { // tanh(x) = (exp(x) - exp(-x))/(exp(x)+exp(-x)) if (fabs(x) > real.mant_dig * LN2) { return copysign(1, x); } real y = expm1(2*x); return y / (y + 2); } /// ditto double tanh(double x) @safe pure nothrow @nogc { return tanh(cast(real)x); } /// ditto float tanh(float x) @safe pure nothrow @nogc { return tanh(cast(real)x); } unittest { assert(equalsDigit(tanh(1.0), sinh(1.0) / cosh(1.0), 15)); } package: /* Returns cosh(x) + I * sinh(x) * Only one call to exp() is performed. */ creal coshisinh(real x) @safe pure nothrow @nogc { // See comments for cosh, sinh. if (fabs(x) > real.mant_dig * LN2) { real y = exp(fabs(x)); return y * 0.5 + 0.5i * copysign(y, x); } else { real y = expm1(x); return (y + 1.0 + 1.0/(y + 1.0)) * 0.5 + 0.5i * y / (y+1) * (y+2); } } unittest { creal c = coshisinh(3.0L); assert(c.re == cosh(3.0L)); assert(c.im == sinh(3.0L)); } public: /*********************************** * Calculates the inverse hyperbolic cosine of x. * * Mathematically, acosh(x) = log(x + sqrt( x*x - 1)) * * $(TABLE_DOMRG * $(DOMAIN 1..$(INFIN)) * $(RANGE 1..log(real.max), $(INFIN)) ) * $(TABLE_SV * $(SVH x, acosh(x) ) * $(SV $(NAN), $(NAN) ) * $(SV $(LT)1, $(NAN) ) * $(SV 1, 0 ) * $(SV +$(INFIN),+$(INFIN)) * ) */ real acosh(real x) @safe pure nothrow @nogc { if (x > 1/real.epsilon) return LN2 + log(x); else return log(x + sqrt(x*x - 1)); } /// ditto double acosh(double x) @safe pure nothrow @nogc { return acosh(cast(real)x); } /// ditto float acosh(float x) @safe pure nothrow @nogc { return acosh(cast(real)x); } unittest { assert(isNaN(acosh(0.9))); assert(isNaN(acosh(real.nan))); assert(acosh(1.0)==0.0); assert(acosh(real.infinity) == real.infinity); assert(isNaN(acosh(0.5))); assert(equalsDigit(acosh(cosh(3.0)), 3, useDigits)); } /*********************************** * Calculates the inverse hyperbolic sine of x. * * Mathematically, * --------------- * asinh(x) = log( x + sqrt( x*x + 1 )) // if x >= +0 * asinh(x) = -log(-x + sqrt( x*x + 1 )) // if x <= -0 * ------------- * * $(TABLE_SV * $(SVH x, asinh(x) ) * $(SV $(NAN), $(NAN) ) * $(SV $(PLUSMN)0, $(PLUSMN)0 ) * $(SV $(PLUSMN)$(INFIN),$(PLUSMN)$(INFIN)) * ) */ real asinh(real x) @safe pure nothrow @nogc { return (fabs(x) > 1 / real.epsilon) // beyond this point, x*x + 1 == x*x ? copysign(LN2 + log(fabs(x)), x) // sqrt(x*x + 1) == 1 + x * x / ( 1 + sqrt(x*x + 1) ) : copysign(log1p(fabs(x) + x*x / (1 + sqrt(x*x + 1)) ), x); } /// ditto double asinh(double x) @safe pure nothrow @nogc { return asinh(cast(real)x); } /// ditto float asinh(float x) @safe pure nothrow @nogc { return asinh(cast(real)x); } unittest { assert(isIdentical(asinh(0.0), 0.0)); assert(isIdentical(asinh(-0.0), -0.0)); assert(asinh(real.infinity) == real.infinity); assert(asinh(-real.infinity) == -real.infinity); assert(isNaN(asinh(real.nan))); assert(equalsDigit(asinh(sinh(3.0)), 3, useDigits)); } /*********************************** * Calculates the inverse hyperbolic tangent of x, * returning a value from ranging from -1 to 1. * * Mathematically, atanh(x) = log( (1+x)/(1-x) ) / 2 * * * $(TABLE_DOMRG * $(DOMAIN -$(INFIN)..$(INFIN)) * $(RANGE -1..1) ) * $(TABLE_SV * $(SVH x, acosh(x) ) * $(SV $(NAN), $(NAN) ) * $(SV $(PLUSMN)0, $(PLUSMN)0) * $(SV -$(INFIN), -0) * ) */ real atanh(real x) @safe pure nothrow @nogc { // log( (1+x)/(1-x) ) == log ( 1 + (2*x)/(1-x) ) return 0.5 * log1p( 2 * x / (1 - x) ); } /// ditto double atanh(double x) @safe pure nothrow @nogc { return atanh(cast(real)x); } /// ditto float atanh(float x) @safe pure nothrow @nogc { return atanh(cast(real)x); } unittest { assert(isIdentical(atanh(0.0), 0.0)); assert(isIdentical(atanh(-0.0),-0.0)); assert(isNaN(atanh(real.nan))); assert(isNaN(atanh(-real.infinity))); assert(atanh(0.0) == 0); assert(equalsDigit(atanh(tanh(0.5L)), 0.5, useDigits)); } /***************************************** * Returns x rounded to a long value using the current rounding mode. * If the integer value of x is * greater than long.max, the result is * indeterminate. */ long rndtol(real x) @nogc @safe pure nothrow; /* intrinsic */ /***************************************** * Returns x rounded to a long value using the FE_TONEAREST rounding mode. * If the integer value of x is * greater than long.max, the result is * indeterminate. */ extern (C) real rndtonl(real x); /*************************************** * Compute square root of x. * * $(TABLE_SV * $(TR $(TH x) $(TH sqrt(x)) $(TH invalid?)) * $(TR $(TD -0.0) $(TD -0.0) $(TD no)) * $(TR $(TD $(LT)0.0) $(TD $(NAN)) $(TD yes)) * $(TR $(TD +$(INFIN)) $(TD +$(INFIN)) $(TD no)) * ) */ float sqrt(float x) @nogc @safe pure nothrow; /* intrinsic */ /// ditto double sqrt(double x) @nogc @safe pure nothrow; /* intrinsic */ /// ditto real sqrt(real x) @nogc @safe pure nothrow; /* intrinsic */ unittest { //ctfe enum ZX80 = sqrt(7.0f); enum ZX81 = sqrt(7.0); enum ZX82 = sqrt(7.0L); } creal sqrt(creal z) @nogc @safe pure nothrow { creal c; real x,y,w,r; if (z == 0) { c = 0 + 0i; } else { real z_re = z.re; real z_im = z.im; x = fabs(z_re); y = fabs(z_im); if (x >= y) { r = y / x; w = sqrt(x) * sqrt(0.5 * (1 + sqrt(1 + r * r))); } else { r = x / y; w = sqrt(y) * sqrt(0.5 * (r + sqrt(1 + r * r))); } if (z_re >= 0) { c = w + (z_im / (w + w)) * 1.0i; } else { if (z_im < 0) w = -w; c = z_im / (w + w) + w * 1.0i; } } return c; } /** * Calculates e$(SUP x). * * $(TABLE_SV * $(TR $(TH x) $(TH e$(SUP x)) ) * $(TR $(TD +$(INFIN)) $(TD +$(INFIN)) ) * $(TR $(TD -$(INFIN)) $(TD +0.0) ) * $(TR $(TD $(NAN)) $(TD $(NAN)) ) * ) */ real exp(real x) @trusted pure nothrow @nogc { version(D_InlineAsm_X86) { // e^^x = 2^^(LOG2E*x) // (This is valid because the overflow & underflow limits for exp // and exp2 are so similar). return exp2(LOG2E*x); } else version(D_InlineAsm_X86_64) { // e^^x = 2^^(LOG2E*x) // (This is valid because the overflow & underflow limits for exp // and exp2 are so similar). return exp2(LOG2E*x); } else { // Coefficients for exp(x) static immutable real[3] P = [ 9.9999999999999999991025E-1L, 3.0299440770744196129956E-2L, 1.2617719307481059087798E-4L, ]; static immutable real[4] Q = [ 2.0000000000000000000897E0L, 2.2726554820815502876593E-1L, 2.5244834034968410419224E-3L, 3.0019850513866445504159E-6L, ]; // C1 + C2 = LN2. enum real C1 = 6.9314575195312500000000E-1L; enum real C2 = 1.428606820309417232121458176568075500134E-6L; // Overflow and Underflow limits. enum real OF = 1.1356523406294143949492E4L; enum real UF = -1.1432769596155737933527E4L; // Special cases. if (isNaN(x)) return x; if (x > OF) return real.infinity; if (x < UF) return 0.0; // Express: e^^x = e^^g * 2^^n // = e^^g * e^^(n * LOG2E) // = e^^(g + n * LOG2E) int n = cast(int)floor(LOG2E * x + 0.5); x -= n * C1; x -= n * C2; // Rational approximation for exponential of the fractional part: // e^^x = 1 + 2x P(x^^2) / (Q(x^^2) - P(x^^2)) real xx = x * x; real px = x * poly(xx, P); x = px / (poly(xx, Q) - px); x = 1.0 + ldexp(x, 1); // Scale by power of 2. x = ldexp(x, n); return x; } } /// ditto double exp(double x) @safe pure nothrow @nogc { return exp(cast(real)x); } /// ditto float exp(float x) @safe pure nothrow @nogc { return exp(cast(real)x); } unittest { assert(equalsDigit(exp(3.0L), E * E * E, useDigits)); } /** * Calculates the value of the natural logarithm base (e) * raised to the power of x, minus 1. * * For very small x, expm1(x) is more accurate * than exp(x)-1. * * $(TABLE_SV * $(TR $(TH x) $(TH e$(SUP x)-1) ) * $(TR $(TD $(PLUSMN)0.0) $(TD $(PLUSMN)0.0) ) * $(TR $(TD +$(INFIN)) $(TD +$(INFIN)) ) * $(TR $(TD -$(INFIN)) $(TD -1.0) ) * $(TR $(TD $(NAN)) $(TD $(NAN)) ) * ) */ real expm1(real x) @trusted pure nothrow @nogc { version(D_InlineAsm_X86) { enum PARAMSIZE = (real.sizeof+3)&(0xFFFF_FFFC); // always a multiple of 4 asm { /* expm1() for x87 80-bit reals, IEEE754-2008 conformant. * Author: Don Clugston. * * expm1(x) = 2^^(rndint(y))* 2^^(y-rndint(y)) - 1 where y = LN2*x. * = 2rndy * 2ym1 + 2rndy - 1, where 2rndy = 2^^(rndint(y)) * and 2ym1 = (2^^(y-rndint(y))-1). * If 2rndy < 0.5*real.epsilon, result is -1. * Implementation is otherwise the same as for exp2() */ naked; fld real ptr [ESP+4] ; // x mov AX, [ESP+4+8]; // AX = exponent and sign sub ESP, 12+8; // Create scratch space on the stack // [ESP,ESP+2] = scratchint // [ESP+4..+6, +8..+10, +10] = scratchreal // set scratchreal mantissa = 1.0 mov dword ptr [ESP+8], 0; mov dword ptr [ESP+8+4], 0x80000000; and AX, 0x7FFF; // drop sign bit cmp AX, 0x401D; // avoid InvalidException in fist jae L_extreme; fldl2e; fmulp ST(1), ST; // y = x*log2(e) fist dword ptr [ESP]; // scratchint = rndint(y) fisub dword ptr [ESP]; // y - rndint(y) // and now set scratchreal exponent mov EAX, [ESP]; add EAX, 0x3fff; jle short L_largenegative; cmp EAX,0x8000; jge short L_largepositive; mov [ESP+8+8],AX; f2xm1; // 2ym1 = 2^^(y-rndint(y)) -1 fld real ptr [ESP+8] ; // 2rndy = 2^^rndint(y) fmul ST(1), ST; // ST=2rndy, ST(1)=2rndy*2ym1 fld1; fsubp ST(1), ST; // ST = 2rndy-1, ST(1) = 2rndy * 2ym1 - 1 faddp ST(1), ST; // ST = 2rndy * 2ym1 + 2rndy - 1 add ESP,12+8; ret PARAMSIZE; L_extreme: // Extreme exponent. X is very large positive, very // large negative, infinity, or NaN. fxam; fstsw AX; test AX, 0x0400; // NaN_or_zero, but we already know x!=0 jz L_was_nan; // if x is NaN, returns x test AX, 0x0200; jnz L_largenegative; L_largepositive: // Set scratchreal = real.max. // squaring it will create infinity, and set overflow flag. mov word ptr [ESP+8+8], 0x7FFE; fstp ST(0); fld real ptr [ESP+8]; // load scratchreal fmul ST(0), ST; // square it, to create havoc! L_was_nan: add ESP,12+8; ret PARAMSIZE; L_largenegative: fstp ST(0); fld1; fchs; // return -1. Underflow flag is not set. add ESP,12+8; ret PARAMSIZE; } } else version(D_InlineAsm_X86_64) { asm { naked; } version (Win64) { asm { fld real ptr [RCX]; // x mov AX,[RCX+8]; // AX = exponent and sign } } else { asm { fld real ptr [RSP+8]; // x mov AX,[RSP+8+8]; // AX = exponent and sign } } asm { /* expm1() for x87 80-bit reals, IEEE754-2008 conformant. * Author: Don Clugston. * * expm1(x) = 2^(rndint(y))* 2^(y-rndint(y)) - 1 where y = LN2*x. * = 2rndy * 2ym1 + 2rndy - 1, where 2rndy = 2^(rndint(y)) * and 2ym1 = (2^(y-rndint(y))-1). * If 2rndy < 0.5*real.epsilon, result is -1. * Implementation is otherwise the same as for exp2() */ sub RSP, 24; // Create scratch space on the stack // [RSP,RSP+2] = scratchint // [RSP+4..+6, +8..+10, +10] = scratchreal // set scratchreal mantissa = 1.0 mov dword ptr [RSP+8], 0; mov dword ptr [RSP+8+4], 0x80000000; and AX, 0x7FFF; // drop sign bit cmp AX, 0x401D; // avoid InvalidException in fist jae L_extreme; fldl2e; fmul ; // y = x*log2(e) fist dword ptr [RSP]; // scratchint = rndint(y) fisub dword ptr [RSP]; // y - rndint(y) // and now set scratchreal exponent mov EAX, [RSP]; add EAX, 0x3fff; jle short L_largenegative; cmp EAX,0x8000; jge short L_largepositive; mov [RSP+8+8],AX; f2xm1; // 2^(y-rndint(y)) -1 fld real ptr [RSP+8] ; // 2^rndint(y) fmul ST(1), ST; fld1; fsubp ST(1), ST; fadd; add RSP,24; ret; L_extreme: // Extreme exponent. X is very large positive, very // large negative, infinity, or NaN. fxam; fstsw AX; test AX, 0x0400; // NaN_or_zero, but we already know x!=0 jz L_was_nan; // if x is NaN, returns x test AX, 0x0200; jnz L_largenegative; L_largepositive: // Set scratchreal = real.max. // squaring it will create infinity, and set overflow flag. mov word ptr [RSP+8+8], 0x7FFE; fstp ST(0); fld real ptr [RSP+8]; // load scratchreal fmul ST(0), ST; // square it, to create havoc! L_was_nan: add RSP,24; ret; L_largenegative: fstp ST(0); fld1; fchs; // return -1. Underflow flag is not set. add RSP,24; ret; } } else { // Coefficients for exp(x) - 1 static immutable real[5] P = [ -1.586135578666346600772998894928250240826E4L, 2.642771505685952966904660652518429479531E3L, -3.423199068835684263987132888286791620673E2L, 1.800826371455042224581246202420972737840E1L, -5.238523121205561042771939008061958820811E-1L, ]; static immutable real[6] Q = [ -9.516813471998079611319047060563358064497E4L, 3.964866271411091674556850458227710004570E4L, -7.207678383830091850230366618190187434796E3L, 7.206038318724600171970199625081491823079E2L, -4.002027679107076077238836622982900945173E1L, 1.000000000000000000000000000000000000000E0L, ]; // C1 + C2 = LN2. enum real C1 = 6.9314575195312500000000E-1L; enum real C2 = 1.4286068203094172321215E-6L; // Overflow and Underflow limits. enum real OF = 1.1356523406294143949492E4L; enum real UF = -4.5054566736396445112120088E1L; // Special cases. if (x > OF) return real.infinity; if (x == 0.0) return x; if (x < UF) return -1.0; // Express x = LN2 (n + remainder), remainder not exceeding 1/2. int n = cast(int)floor(0.5 + x / LN2); x -= n * C1; x -= n * C2; // Rational approximation: // exp(x) - 1 = x + 0.5 x^^2 + x^^3 P(x) / Q(x) real px = x * poly(x, P); real qx = poly(x, Q); real xx = x * x; qx = x + (0.5 * xx + xx * px / qx); // We have qx = exp(remainder LN2) - 1, so: // exp(x) - 1 = 2^^n (qx + 1) - 1 = 2^^n qx + 2^^n - 1. px = ldexp(1.0, n); x = px * qx + (px - 1.0); return x; } } /** * Calculates 2$(SUP x). * * $(TABLE_SV * $(TR $(TH x) $(TH exp2(x)) ) * $(TR $(TD +$(INFIN)) $(TD +$(INFIN)) ) * $(TR $(TD -$(INFIN)) $(TD +0.0) ) * $(TR $(TD $(NAN)) $(TD $(NAN)) ) * ) */ real exp2(real x) @nogc @trusted pure nothrow { version(D_InlineAsm_X86) { enum PARAMSIZE = (real.sizeof+3)&(0xFFFF_FFFC); // always a multiple of 4 asm { /* exp2() for x87 80-bit reals, IEEE754-2008 conformant. * Author: Don Clugston. * * exp2(x) = 2^^(rndint(x))* 2^^(y-rndint(x)) * The trick for high performance is to avoid the fscale(28cycles on core2), * frndint(19 cycles), leaving f2xm1(19 cycles) as the only slow instruction. * * We can do frndint by using fist. BUT we can't use it for huge numbers, * because it will set the Invalid Operation flag if overflow or NaN occurs. * Fortunately, whenever this happens the result would be zero or infinity. * * We can perform fscale by directly poking into the exponent. BUT this doesn't * work for the (very rare) cases where the result is subnormal. So we fall back * to the slow method in that case. */ naked; fld real ptr [ESP+4] ; // x mov AX, [ESP+4+8]; // AX = exponent and sign sub ESP, 12+8; // Create scratch space on the stack // [ESP,ESP+2] = scratchint // [ESP+4..+6, +8..+10, +10] = scratchreal // set scratchreal mantissa = 1.0 mov dword ptr [ESP+8], 0; mov dword ptr [ESP+8+4], 0x80000000; and AX, 0x7FFF; // drop sign bit cmp AX, 0x401D; // avoid InvalidException in fist jae L_extreme; fist dword ptr [ESP]; // scratchint = rndint(x) fisub dword ptr [ESP]; // x - rndint(x) // and now set scratchreal exponent mov EAX, [ESP]; add EAX, 0x3fff; jle short L_subnormal; cmp EAX,0x8000; jge short L_overflow; mov [ESP+8+8],AX; L_normal: f2xm1; fld1; faddp ST(1), ST; // 2^^(x-rndint(x)) fld real ptr [ESP+8] ; // 2^^rndint(x) add ESP,12+8; fmulp ST(1), ST; ret PARAMSIZE; L_subnormal: // Result will be subnormal. // In this rare case, the simple poking method doesn't work. // The speed doesn't matter, so use the slow fscale method. fild dword ptr [ESP]; // scratchint fld1; fscale; fstp real ptr [ESP+8]; // scratchreal = 2^^scratchint fstp ST(0); // drop scratchint jmp L_normal; L_extreme: // Extreme exponent. X is very large positive, very // large negative, infinity, or NaN. fxam; fstsw AX; test AX, 0x0400; // NaN_or_zero, but we already know x!=0 jz L_was_nan; // if x is NaN, returns x // set scratchreal = real.min_normal // squaring it will return 0, setting underflow flag mov word ptr [ESP+8+8], 1; test AX, 0x0200; jnz L_waslargenegative; L_overflow: // Set scratchreal = real.max. // squaring it will create infinity, and set overflow flag. mov word ptr [ESP+8+8], 0x7FFE; L_waslargenegative: fstp ST(0); fld real ptr [ESP+8]; // load scratchreal fmul ST(0), ST; // square it, to create havoc! L_was_nan: add ESP,12+8; ret PARAMSIZE; } } else version(D_InlineAsm_X86_64) { asm { naked; } version (Win64) { asm { fld real ptr [RCX]; // x mov AX,[RCX+8]; // AX = exponent and sign } } else { asm { fld real ptr [RSP+8]; // x mov AX,[RSP+8+8]; // AX = exponent and sign } } asm { /* exp2() for x87 80-bit reals, IEEE754-2008 conformant. * Author: Don Clugston. * * exp2(x) = 2^(rndint(x))* 2^(y-rndint(x)) * The trick for high performance is to avoid the fscale(28cycles on core2), * frndint(19 cycles), leaving f2xm1(19 cycles) as the only slow instruction. * * We can do frndint by using fist. BUT we can't use it for huge numbers, * because it will set the Invalid Operation flag is overflow or NaN occurs. * Fortunately, whenever this happens the result would be zero or infinity. * * We can perform fscale by directly poking into the exponent. BUT this doesn't * work for the (very rare) cases where the result is subnormal. So we fall back * to the slow method in that case. */ sub RSP, 24; // Create scratch space on the stack // [RSP,RSP+2] = scratchint // [RSP+4..+6, +8..+10, +10] = scratchreal // set scratchreal mantissa = 1.0 mov dword ptr [RSP+8], 0; mov dword ptr [RSP+8+4], 0x80000000; and AX, 0x7FFF; // drop sign bit cmp AX, 0x401D; // avoid InvalidException in fist jae L_extreme; fist dword ptr [RSP]; // scratchint = rndint(x) fisub dword ptr [RSP]; // x - rndint(x) // and now set scratchreal exponent mov EAX, [RSP]; add EAX, 0x3fff; jle short L_subnormal; cmp EAX,0x8000; jge short L_overflow; mov [RSP+8+8],AX; L_normal: f2xm1; fld1; fadd; // 2^(x-rndint(x)) fld real ptr [RSP+8] ; // 2^rndint(x) add RSP,24; fmulp ST(1), ST; ret; L_subnormal: // Result will be subnormal. // In this rare case, the simple poking method doesn't work. // The speed doesn't matter, so use the slow fscale method. fild dword ptr [RSP]; // scratchint fld1; fscale; fstp real ptr [RSP+8]; // scratchreal = 2^scratchint fstp ST(0); // drop scratchint jmp L_normal; L_extreme: // Extreme exponent. X is very large positive, very // large negative, infinity, or NaN. fxam; fstsw AX; test AX, 0x0400; // NaN_or_zero, but we already know x!=0 jz L_was_nan; // if x is NaN, returns x // set scratchreal = real.min // squaring it will return 0, setting underflow flag mov word ptr [RSP+8+8], 1; test AX, 0x0200; jnz L_waslargenegative; L_overflow: // Set scratchreal = real.max. // squaring it will create infinity, and set overflow flag. mov word ptr [RSP+8+8], 0x7FFE; L_waslargenegative: fstp ST(0); fld real ptr [RSP+8]; // load scratchreal fmul ST(0), ST; // square it, to create havoc! L_was_nan: add RSP,24; ret; } } else { // Coefficients for exp2(x) static immutable real[3] P = [ 2.0803843631901852422887E6L, 3.0286971917562792508623E4L, 6.0614853552242266094567E1L, ]; static immutable real[4] Q = [ 6.0027204078348487957118E6L, 3.2772515434906797273099E5L, 1.7492876999891839021063E3L, 1.0000000000000000000000E0L, ]; // Overflow and Underflow limits. enum real OF = 16384.0L; enum real UF = -16382.0L; // Special cases. if (isNaN(x)) return x; if (x > OF) return real.infinity; if (x < UF) return 0.0; // Separate into integer and fractional parts. int n = cast(int)floor(x + 0.5); x -= n; // Rational approximation: // exp2(x) = 1.0 + 2x P(x^^2) / (Q(x^^2) - P(x^^2)) real xx = x * x; real px = x * poly(xx, P); x = px / (poly(xx, Q) - px); x = 1.0 + ldexp(x, 1); // Scale by power of 2. x = ldexp(x, n); return x; } } unittest { assert(feqrel(exp2(0.5L), SQRT2) >= real.mant_dig -1); assert(exp2(8.0L) == 256.0); assert(exp2(-9.0L)== 1.0L/512.0); version(Win64) {} else // aexp2/exp2f/exp2l not implemented { assert( core.stdc.math.exp2f(0.0f) == 1 ); assert( core.stdc.math.exp2 (0.0) == 1 ); assert( core.stdc.math.exp2l(0.0L) == 1 ); } } unittest { FloatingPointControl ctrl; if(FloatingPointControl.hasExceptionTraps) ctrl.disableExceptions(FloatingPointControl.allExceptions); ctrl.rounding = FloatingPointControl.roundToNearest; // @@BUG@@: Non-immutable array literals are ridiculous. // Note that these are only valid for 80-bit reals: overflow will be different for 64-bit reals. static const real [2][] exptestpoints = [ // x, exp(x) [1.0L, E ], [0.5L, 0x1.A612_98E1_E069_BC97p+0L ], [3.0L, E*E*E ], [0x1.1p13L, 0x1.29aeffefc8ec645p+12557L ], // near overflow [-0x1.18p13L, 0x1.5e4bf54b4806db9p-12927L ], // near underflow [-0x1.625p13L, 0x1.a6bd68a39d11f35cp-16358L], [-0x1p30L, 0 ], // underflow - subnormal [-0x1.62DAFp13L, 0x1.96c53d30277021dp-16383L ], [-0x1.643p13L, 0x1p-16444L ], [-0x1.645p13L, 0 ], // underflow to zero [0x1p80L, real.infinity ], // far overflow [real.infinity, real.infinity ], [0x1.7p13L, real.infinity ] // close overflow ]; real x; IeeeFlags f; for (int i=0; i<exptestpoints.length;++i) { resetIeeeFlags(); x = exp(exptestpoints[i][0]); f = ieeeFlags; assert(equalsDigit(x, exptestpoints[i][1], 15)); // Check the overflow bit //assert(f.overflow == (fabs(x) == real.infinity)); // Check the underflow bit //assert(f.underflow == (fabs(x) < real.min_normal)); // Invalid and div by zero shouldn't be affected. assert(!f.invalid); assert(!f.divByZero); } // Ideally, exp(0) would not set the inexact flag. // Unfortunately, fldl2e sets it! // So it's not realistic to avoid setting it. assert(exp(0.0L) == 1.0); // NaN propagation. Doesn't set flags, bcos was already NaN. resetIeeeFlags(); x = exp(real.nan); f = ieeeFlags; assert(isIdentical(abs(x), real.nan)); assert(f.flags == 0); resetIeeeFlags(); x = exp(-real.nan); f = ieeeFlags; assert(isIdentical(abs(x), real.nan)); assert(f.flags == 0); x = exp(NaN(0x123)); assert(isIdentical(x, NaN(0x123))); // High resolution test assert(exp(0.5L) == 0x1.A612_98E1_E069_BC97_2DFE_FAB6D_33Fp+0L); } /** * Calculate cos(y) + i sin(y). * * On many CPUs (such as x86), this is a very efficient operation; * almost twice as fast as calculating sin(y) and cos(y) separately, * and is the preferred method when both are required. */ creal expi(real y) @trusted pure nothrow @nogc { version(InlineAsm_X86_Any) { version (Win64) { asm { naked; fld real ptr [ECX]; fsincos; fxch ST(1), ST(0); ret; } } else { asm { fld y; fsincos; fxch ST(1), ST(0); } } } else { return cos(y) + sin(y)*1i; } } unittest { real value = 1.3e5L; // Avoid constant folding assert(expi(value) == cos(value) + sin(value) * 1i); assert(expi(0.0L) == 1L + 0.0Li); } /********************************************************************* * Separate floating point value into significand and exponent. * * Returns: * Calculate and return $(I x) and $(I exp) such that * value =$(I x)*2$(SUP exp) and * .5 $(LT)= |$(I x)| $(LT) 1.0 * * $(I x) has same sign as value. * * $(TABLE_SV * $(TR $(TH value) $(TH returns) $(TH exp)) * $(TR $(TD $(PLUSMN)0.0) $(TD $(PLUSMN)0.0) $(TD 0)) * $(TR $(TD +$(INFIN)) $(TD +$(INFIN)) $(TD int.max)) * $(TR $(TD -$(INFIN)) $(TD -$(INFIN)) $(TD int.min)) * $(TR $(TD $(PLUSMN)$(NAN)) $(TD $(PLUSMN)$(NAN)) $(TD int.min)) * ) */ real frexp(real value, out int exp) @trusted pure nothrow @nogc { ushort* vu = cast(ushort*)&value; long* vl = cast(long*)&value; int ex; alias F = floatTraits!(real); ex = vu[F.EXPPOS_SHORT] & F.EXPMASK; static if (F.realFormat == RealFormat.ieeeExtended) { if (ex) { // If exponent is non-zero if (ex == F.EXPMASK) // infinity or NaN { if (*vl & 0x7FFF_FFFF_FFFF_FFFF) // NaN { *vl |= 0xC000_0000_0000_0000; // convert NaNS to NaNQ exp = int.min; } else if (vu[F.EXPPOS_SHORT] & 0x8000) // negative infinity exp = int.min; else // positive infinity exp = int.max; } else { exp = ex - F.EXPBIAS; vu[F.EXPPOS_SHORT] = (0x8000 & vu[F.EXPPOS_SHORT]) | 0x3FFE; } } else if (!*vl) { // value is +-0.0 exp = 0; } else { // subnormal value *= F.RECIP_EPSILON; ex = vu[F.EXPPOS_SHORT] & F.EXPMASK; exp = ex - F.EXPBIAS - real.mant_dig + 1; vu[F.EXPPOS_SHORT] = (0x8000 & vu[F.EXPPOS_SHORT]) | 0x3FFE; } return value; } else static if (F.realFormat == RealFormat.ieeeQuadruple) { if (ex) // If exponent is non-zero { if (ex == F.EXPMASK) { // infinity or NaN if (vl[MANTISSA_LSB] | ( vl[MANTISSA_MSB] & 0x0000_FFFF_FFFF_FFFF)) // NaN { // convert NaNS to NaNQ vl[MANTISSA_MSB] |= 0x0000_8000_0000_0000; exp = int.min; } else if (vu[F.EXPPOS_SHORT] & 0x8000) // negative infinity exp = int.min; else // positive infinity exp = int.max; } else { exp = ex - F.EXPBIAS; vu[F.EXPPOS_SHORT] = cast(ushort)((0x8000 & vu[F.EXPPOS_SHORT]) | 0x3FFE); } } else if ((vl[MANTISSA_LSB] |(vl[MANTISSA_MSB] & 0x0000_FFFF_FFFF_FFFF)) == 0) { // value is +-0.0 exp = 0; } else { // subnormal value *= F.RECIP_EPSILON; ex = vu[F.EXPPOS_SHORT] & F.EXPMASK; exp = ex - F.EXPBIAS - real.mant_dig + 1; vu[F.EXPPOS_SHORT] = cast(ushort)((0x8000 & vu[F.EXPPOS_SHORT]) | 0x3FFE); } return value; } else static if (F.realFormat == RealFormat.ieeeDouble) { if (ex) // If exponent is non-zero { if (ex == F.EXPMASK) // infinity or NaN { if (*vl == 0x7FF0_0000_0000_0000) // positive infinity { exp = int.max; } else if (*vl == 0xFFF0_0000_0000_0000) // negative infinity exp = int.min; else { // NaN *vl |= 0x0008_0000_0000_0000; // convert NaNS to NaNQ exp = int.min; } } else { exp = (ex - F.EXPBIAS) >> 4; vu[F.EXPPOS_SHORT] = cast(ushort)((0x800F & vu[F.EXPPOS_SHORT]) | 0x3FE0); } } else if (!(*vl & 0x7FFF_FFFF_FFFF_FFFF)) { // value is +-0.0 exp = 0; } else { // subnormal value *= F.RECIP_EPSILON; ex = vu[F.EXPPOS_SHORT] & F.EXPMASK; exp = ((ex - F.EXPBIAS)>> 4) - real.mant_dig + 1; vu[F.EXPPOS_SHORT] = cast(ushort)((0x8000 & vu[F.EXPPOS_SHORT]) | 0x3FE0); } return value; } else // static if (F.realFormat == RealFormat.ibmExtended) { assert (0, "frexp not implemented"); } } unittest { static real[3][] vals = // x,frexp,exp [ [0.0, 0.0, 0], [-0.0, -0.0, 0], [1.0, .5, 1], [-1.0, -.5, 1], [2.0, .5, 2], [double.min_normal/2.0, .5, -1022], [real.infinity,real.infinity,int.max], [-real.infinity,-real.infinity,int.min], [real.nan,real.nan,int.min], [-real.nan,-real.nan,int.min], ]; int i; for (i = 0; i < vals.length; i++) { real x = vals[i][0]; real e = vals[i][1]; int exp = cast(int)vals[i][2]; int eptr; real v = frexp(x, eptr); assert(isIdentical(e, v)); assert(exp == eptr); } static if (floatTraits!(real).realFormat == RealFormat.ieeeExtended) { static real[3][] extendedvals = [ // x,frexp,exp [0x1.a5f1c2eb3fe4efp+73L, 0x1.A5F1C2EB3FE4EFp-1L, 74], // normal [0x1.fa01712e8f0471ap-1064L, 0x1.fa01712e8f0471ap-1L, -1063], [real.min_normal, .5, -16381], [real.min_normal/2.0L, .5, -16382] // subnormal ]; for (i = 0; i < extendedvals.length; i++) { real x = extendedvals[i][0]; real e = extendedvals[i][1]; int exp = cast(int)extendedvals[i][2]; int eptr; real v = frexp(x, eptr); assert(isIdentical(e, v)); assert(exp == eptr); } } } unittest { int exp; real mantissa = frexp(123.456, exp); assert(equalsDigit(mantissa * pow(2.0L, cast(real)exp), 123.456, 19)); assert(frexp(-real.nan, exp) && exp == int.min); assert(frexp(real.nan, exp) && exp == int.min); assert(frexp(-real.infinity, exp) == -real.infinity && exp == int.min); assert(frexp(real.infinity, exp) == real.infinity && exp == int.max); assert(frexp(-0.0, exp) == -0.0 && exp == 0); assert(frexp(0.0, exp) == 0.0 && exp == 0); } /****************************************** * Extracts the exponent of x as a signed integral value. * * If x is not a special value, the result is the same as * $(D cast(int)logb(x)). * * $(TABLE_SV * $(TR $(TH x) $(TH ilogb(x)) $(TH Range error?)) * $(TR $(TD 0) $(TD FP_ILOGB0) $(TD yes)) * $(TR $(TD $(PLUSMN)$(INFIN)) $(TD int.max) $(TD no)) * $(TR $(TD $(NAN)) $(TD FP_ILOGBNAN) $(TD no)) * ) */ int ilogb(real x) @trusted nothrow @nogc { version (Win64_DMD_InlineAsm) { asm { naked ; fld real ptr [RCX] ; fxam ; fstsw AX ; and AH,0x45 ; cmp AH,0x40 ; jz Lzeronan ; cmp AH,5 ; jz Linfinity ; cmp AH,1 ; jz Lzeronan ; fxtract ; fstp ST(0) ; fistp dword ptr 8[RSP] ; mov EAX,8[RSP] ; ret ; Lzeronan: mov EAX,0x80000000 ; fstp ST(0) ; ret ; Linfinity: mov EAX,0x7FFFFFFF ; fstp ST(0) ; ret ; } } else return core.stdc.math.ilogbl(x); } alias FP_ILOGB0 = core.stdc.math.FP_ILOGB0; alias FP_ILOGBNAN = core.stdc.math.FP_ILOGBNAN; /******************************************* * Compute n * 2$(SUP exp) * References: frexp */ real ldexp(real n, int exp) @nogc @safe pure nothrow; /* intrinsic */ unittest { static if (floatTraits!(real).realFormat == RealFormat.ieeeExtended) { assert(ldexp(1, -16384) == 0x1p-16384L); assert(ldexp(1, -16382) == 0x1p-16382L); int x; real n = frexp(0x1p-16384L, x); assert(n==0.5L); assert(x==-16383); assert(ldexp(n, x)==0x1p-16384L); } else static if (floatTraits!(real).realFormat == RealFormat.ieeeDouble) { assert(ldexp(1, -1024) == 0x1p-1024L); assert(ldexp(1, -1022) == 0x1p-1022L); int x; real n = frexp(0x1p-1024L, x); assert(n==0.5L); assert(x==-1023); assert(ldexp(n, x)==0x1p-1024L); } else static assert(false, "Floating point type real not supported"); } unittest { static real[3][] vals = // value,exp,ldexp [ [ 0, 0, 0], [ 1, 0, 1], [ -1, 0, -1], [ 1, 1, 2], [ 123, 10, 125952], [ real.max, int.max, real.infinity], [ real.max, -int.max, 0], [ real.min_normal, -int.max, 0], ]; int i; for (i = 0; i < vals.length; i++) { real x = vals[i][0]; int exp = cast(int)vals[i][1]; real z = vals[i][2]; real l = ldexp(x, exp); assert(equalsDigit(z, l, 7)); } } unittest { real r; r = ldexp(3.0L, 3); assert(r == 24); r = ldexp(cast(real) 3.0, cast(int) 3); assert(r == 24); real n = 3.0; int exp = 3; r = ldexp(n, exp); assert(r == 24); } /************************************** * Calculate the natural logarithm of x. * * $(TABLE_SV * $(TR $(TH x) $(TH log(x)) $(TH divide by 0?) $(TH invalid?)) * $(TR $(TD $(PLUSMN)0.0) $(TD -$(INFIN)) $(TD yes) $(TD no)) * $(TR $(TD $(LT)0.0) $(TD $(NAN)) $(TD no) $(TD yes)) * $(TR $(TD +$(INFIN)) $(TD +$(INFIN)) $(TD no) $(TD no)) * ) */ real log(real x) @safe pure nothrow @nogc { version (INLINE_YL2X) return yl2x(x, LN2); else { // Coefficients for log(1 + x) static immutable real[7] P = [ 2.0039553499201281259648E1L, 5.7112963590585538103336E1L, 6.0949667980987787057556E1L, 2.9911919328553073277375E1L, 6.5787325942061044846969E0L, 4.9854102823193375972212E-1L, 4.5270000862445199635215E-5L, ]; static immutable real[7] Q = [ 6.0118660497603843919306E1L, 2.1642788614495947685003E2L, 3.0909872225312059774938E2L, 2.2176239823732856465394E2L, 8.3047565967967209469434E1L, 1.5062909083469192043167E1L, 1.0000000000000000000000E0L, ]; // Coefficients for log(x) static immutable real[4] R = [ -3.5717684488096787370998E1L, 1.0777257190312272158094E1L, -7.1990767473014147232598E-1L, 1.9757429581415468984296E-3L, ]; static immutable real[4] S = [ -4.2861221385716144629696E2L, 1.9361891836232102174846E2L, -2.6201045551331104417768E1L, 1.0000000000000000000000E0L, ]; // C1 + C2 = LN2. enum real C1 = 6.9314575195312500000000E-1L; enum real C2 = 1.4286068203094172321215E-6L; // Special cases. if (isNaN(x)) return x; if (isInfinity(x) && !signbit(x)) return x; if (x == 0.0) return -real.infinity; if (x < 0.0) return real.nan; // Separate mantissa from exponent. // Note, frexp is used so that denormal numbers will be handled properly. real y, z; int exp; x = frexp(x, exp); // Logarithm using log(x) = z + z^^3 P(z) / Q(z), // where z = 2(x - 1)/(x + 1) if((exp > 2) || (exp < -2)) { if(x < SQRT1_2) { // 2(2x - 1)/(2x + 1) exp -= 1; z = x - 0.5; y = 0.5 * z + 0.5; } else { // 2(x - 1)/(x + 1) z = x - 0.5; z -= 0.5; y = 0.5 * x + 0.5; } x = z / y; z = x * x; z = x * (z * poly(z, R) / poly(z, S)); z += exp * C2; z += x; z += exp * C1; return z; } // Logarithm using log(1 + x) = x - .5x^^2 + x^^3 P(x) / Q(x) if (x < SQRT1_2) { // 2x - 1 exp -= 1; x = ldexp(x, 1) - 1.0; } else { x = x - 1.0; } z = x * x; y = x * (z * poly(x, P) / poly(x, Q)); y += exp * C2; z = y - ldexp(z, -1); // Note, the sum of above terms does not exceed x/4, // so it contributes at most about 1/4 lsb to the error. z += x; z += exp * C1; return z; } } unittest { assert(log(E) == 1); } /************************************** * Calculate the base-10 logarithm of x. * * $(TABLE_SV * $(TR $(TH x) $(TH log10(x)) $(TH divide by 0?) $(TH invalid?)) * $(TR $(TD $(PLUSMN)0.0) $(TD -$(INFIN)) $(TD yes) $(TD no)) * $(TR $(TD $(LT)0.0) $(TD $(NAN)) $(TD no) $(TD yes)) * $(TR $(TD +$(INFIN)) $(TD +$(INFIN)) $(TD no) $(TD no)) * ) */ real log10(real x) @safe pure nothrow @nogc { version (INLINE_YL2X) return yl2x(x, LOG2); else { // Coefficients for log(1 + x) static immutable real[7] P = [ 2.0039553499201281259648E1L, 5.7112963590585538103336E1L, 6.0949667980987787057556E1L, 2.9911919328553073277375E1L, 6.5787325942061044846969E0L, 4.9854102823193375972212E-1L, 4.5270000862445199635215E-5L, ]; static immutable real[7] Q = [ 6.0118660497603843919306E1L, 2.1642788614495947685003E2L, 3.0909872225312059774938E2L, 2.2176239823732856465394E2L, 8.3047565967967209469434E1L, 1.5062909083469192043167E1L, 1.0000000000000000000000E0L, ]; // Coefficients for log(x) static immutable real[4] R = [ -3.5717684488096787370998E1L, 1.0777257190312272158094E1L, -7.1990767473014147232598E-1L, 1.9757429581415468984296E-3L, ]; static immutable real[4] S = [ -4.2861221385716144629696E2L, 1.9361891836232102174846E2L, -2.6201045551331104417768E1L, 1.0000000000000000000000E0L, ]; // log10(2) split into two parts. enum real L102A = 0.3125L; enum real L102B = -1.14700043360188047862611052755069732318101185E-2L; // log10(e) split into two parts. enum real L10EA = 0.5L; enum real L10EB = -6.570551809674817234887108108339491770560299E-2L; // Special cases are the same as for log. if (isNaN(x)) return x; if (isInfinity(x) && !signbit(x)) return x; if (x == 0.0) return -real.infinity; if (x < 0.0) return real.nan; // Separate mantissa from exponent. // Note, frexp is used so that denormal numbers will be handled properly. real y, z; int exp; x = frexp(x, exp); // Logarithm using log(x) = z + z^^3 P(z) / Q(z), // where z = 2(x - 1)/(x + 1) if((exp > 2) || (exp < -2)) { if(x < SQRT1_2) { // 2(2x - 1)/(2x + 1) exp -= 1; z = x - 0.5; y = 0.5 * z + 0.5; } else { // 2(x - 1)/(x + 1) z = x - 0.5; z -= 0.5; y = 0.5 * x + 0.5; } x = z / y; z = x * x; y = x * (z * poly(z, R) / poly(z, S)); goto Ldone; } // Logarithm using log(1 + x) = x - .5x^^2 + x^^3 P(x) / Q(x) if (x < SQRT1_2) { // 2x - 1 exp -= 1; x = ldexp(x, 1) - 1.0; } else x = x - 1.0; z = x * x; y = x * (z * poly(x, P) / poly(x, Q)); y = y - ldexp(z, -1); // Multiply log of fraction by log10(e) and base 2 exponent by log10(2). // This sequence of operations is critical and it may be horribly // defeated by some compiler optimizers. Ldone: z = y * L10EB; z += x * L10EB; z += exp * L102B; z += y * L10EA; z += x * L10EA; z += exp * L102A; return z; } } unittest { //printf("%Lg\n", log10(1000) - 3); assert(fabs(log10(1000) - 3) < .000001); } /****************************************** * Calculates the natural logarithm of 1 + x. * * For very small x, log1p(x) will be more accurate than * log(1 + x). * * $(TABLE_SV * $(TR $(TH x) $(TH log1p(x)) $(TH divide by 0?) $(TH invalid?)) * $(TR $(TD $(PLUSMN)0.0) $(TD $(PLUSMN)0.0) $(TD no) $(TD no)) * $(TR $(TD -1.0) $(TD -$(INFIN)) $(TD yes) $(TD no)) * $(TR $(TD $(LT)-1.0) $(TD $(NAN)) $(TD no) $(TD yes)) * $(TR $(TD +$(INFIN)) $(TD -$(INFIN)) $(TD no) $(TD no)) * ) */ real log1p(real x) @safe pure nothrow @nogc { version(INLINE_YL2X) { // On x87, yl2xp1 is valid if and only if -0.5 <= lg(x) <= 0.5, // ie if -0.29<=x<=0.414 return (fabs(x) <= 0.25) ? yl2xp1(x, LN2) : yl2x(x+1, LN2); } else { // Special cases. if (isNaN(x) || x == 0.0) return x; if (isInfinity(x) && !signbit(x)) return x; if (x == -1.0) return -real.infinity; if (x < -1.0) return real.nan; return log(x + 1.0); } } /*************************************** * Calculates the base-2 logarithm of x: * $(SUB log, 2)x * * $(TABLE_SV * $(TR $(TH x) $(TH log2(x)) $(TH divide by 0?) $(TH invalid?)) * $(TR $(TD $(PLUSMN)0.0) $(TD -$(INFIN)) $(TD yes) $(TD no) ) * $(TR $(TD $(LT)0.0) $(TD $(NAN)) $(TD no) $(TD yes) ) * $(TR $(TD +$(INFIN)) $(TD +$(INFIN)) $(TD no) $(TD no) ) * ) */ real log2(real x) @safe pure nothrow @nogc { version (INLINE_YL2X) return yl2x(x, 1); else { // Coefficients for log(1 + x) static immutable real[7] P = [ 2.0039553499201281259648E1L, 5.7112963590585538103336E1L, 6.0949667980987787057556E1L, 2.9911919328553073277375E1L, 6.5787325942061044846969E0L, 4.9854102823193375972212E-1L, 4.5270000862445199635215E-5L, ]; static immutable real[7] Q = [ 6.0118660497603843919306E1L, 2.1642788614495947685003E2L, 3.0909872225312059774938E2L, 2.2176239823732856465394E2L, 8.3047565967967209469434E1L, 1.5062909083469192043167E1L, 1.0000000000000000000000E0L, ]; // Coefficients for log(x) static immutable real[4] R = [ -3.5717684488096787370998E1L, 1.0777257190312272158094E1L, -7.1990767473014147232598E-1L, 1.9757429581415468984296E-3L, ]; static immutable real[4] S = [ -4.2861221385716144629696E2L, 1.9361891836232102174846E2L, -2.6201045551331104417768E1L, 1.0000000000000000000000E0L, ]; // Special cases are the same as for log. if (isNaN(x)) return x; if (isInfinity(x) && !signbit(x)) return x; if (x == 0.0) return -real.infinity; if (x < 0.0) return real.nan; // Separate mantissa from exponent. // Note, frexp is used so that denormal numbers will be handled properly. real y, z; int exp; x = frexp(x, exp); // Logarithm using log(x) = z + z^^3 P(z) / Q(z), // where z = 2(x - 1)/(x + 1) if((exp > 2) || (exp < -2)) { if(x < SQRT1_2) { // 2(2x - 1)/(2x + 1) exp -= 1; z = x - 0.5; y = 0.5 * z + 0.5; } else { // 2(x - 1)/(x + 1) z = x - 0.5; z -= 0.5; y = 0.5 * x + 0.5; } x = z / y; z = x * x; y = x * (z * poly(z, R) / poly(z, S)); goto Ldone; } // Logarithm using log(1 + x) = x - .5x^^2 + x^^3 P(x) / Q(x) if (x < SQRT1_2) { // 2x - 1 exp -= 1; x = ldexp(x, 1) - 1.0; } else x = x - 1.0; z = x * x; y = x * (z * poly(x, P) / poly(x, Q)); y = y - ldexp(z, -1); // Multiply log of fraction by log10(e) and base 2 exponent by log10(2). // This sequence of operations is critical and it may be horribly // defeated by some compiler optimizers. Ldone: z = y * (LOG2E - 1.0); z += x * (LOG2E - 1.0); z += y; z += x; z += exp; return z; } } unittest { assert(equalsDigit(log2(1024), 10, 19)); } /***************************************** * Extracts the exponent of x as a signed integral value. * * If x is subnormal, it is treated as if it were normalized. * For a positive, finite x: * * 1 $(LT)= $(I x) * FLT_RADIX$(SUP -logb(x)) $(LT) FLT_RADIX * * $(TABLE_SV * $(TR $(TH x) $(TH logb(x)) $(TH divide by 0?) ) * $(TR $(TD $(PLUSMN)$(INFIN)) $(TD +$(INFIN)) $(TD no)) * $(TR $(TD $(PLUSMN)0.0) $(TD -$(INFIN)) $(TD yes) ) * ) */ real logb(real x) @trusted nothrow @nogc { version (Win64_DMD_InlineAsm) { asm { naked ; fld real ptr [RCX] ; fxtract ; fstp ST(0) ; ret ; } } else return core.stdc.math.logbl(x); } /************************************ * Calculates the remainder from the calculation x/y. * Returns: * The value of x - i * y, where i is the number of times that y can * be completely subtracted from x. The result has the same sign as x. * * $(TABLE_SV * $(TR $(TH x) $(TH y) $(TH fmod(x, y)) $(TH invalid?)) * $(TR $(TD $(PLUSMN)0.0) $(TD not 0.0) $(TD $(PLUSMN)0.0) $(TD no)) * $(TR $(TD $(PLUSMNINF)) $(TD anything) $(TD $(NAN)) $(TD yes)) * $(TR $(TD anything) $(TD $(PLUSMN)0.0) $(TD $(NAN)) $(TD yes)) * $(TR $(TD !=$(PLUSMNINF)) $(TD $(PLUSMNINF)) $(TD x) $(TD no)) * ) */ real fmod(real x, real y) @trusted nothrow @nogc { version (Win64) { return x % y; } else return core.stdc.math.fmodl(x, y); } /************************************ * Breaks x into an integral part and a fractional part, each of which has * the same sign as x. The integral part is stored in i. * Returns: * The fractional part of x. * * $(TABLE_SV * $(TR $(TH x) $(TH i (on input)) $(TH modf(x, i)) $(TH i (on return))) * $(TR $(TD $(PLUSMNINF)) $(TD anything) $(TD $(PLUSMN)0.0) $(TD $(PLUSMNINF))) * ) */ real modf(real x, ref real i) @trusted nothrow @nogc { version (Win64) { i = trunc(x); return copysign(isInfinity(x) ? 0.0 : x - i, x); } else return core.stdc.math.modfl(x,&i); } /************************************* * Efficiently calculates x * 2$(SUP n). * * scalbn handles underflow and overflow in * the same fashion as the basic arithmetic operators. * * $(TABLE_SV * $(TR $(TH x) $(TH scalb(x))) * $(TR $(TD $(PLUSMNINF)) $(TD $(PLUSMNINF)) ) * $(TR $(TD $(PLUSMN)0.0) $(TD $(PLUSMN)0.0) ) * ) */ real scalbn(real x, int n) @trusted nothrow @nogc { version(InlineAsm_X86_Any) { // scalbnl is not supported on DMD-Windows, so use asm. version (Win64) { asm { naked ; mov 16[RSP],RCX ; fild word ptr 16[RSP] ; fld real ptr [RDX] ; fscale ; fstp ST(1) ; ret ; } } else { asm { fild n; fld x; fscale; fstp ST(1); } } } else { return core.stdc.math.scalbnl(x, n); } } unittest { assert(scalbn(-real.infinity, 5) == -real.infinity); } /*************** * Calculates the cube root of x. * * $(TABLE_SV * $(TR $(TH $(I x)) $(TH cbrt(x)) $(TH invalid?)) * $(TR $(TD $(PLUSMN)0.0) $(TD $(PLUSMN)0.0) $(TD no) ) * $(TR $(TD $(NAN)) $(TD $(NAN)) $(TD yes) ) * $(TR $(TD $(PLUSMN)$(INFIN)) $(TD $(PLUSMN)$(INFIN)) $(TD no) ) * ) */ real cbrt(real x) @trusted nothrow @nogc { version (Win64) { version (INLINE_YL2X) return copysign(exp2(yl2x(fabs(x), 1.0L/3.0L)), x); else return core.stdc.math.cbrtl(x); } else return core.stdc.math.cbrtl(x); } /******************************* * Returns |x| * * $(TABLE_SV * $(TR $(TH x) $(TH fabs(x))) * $(TR $(TD $(PLUSMN)0.0) $(TD +0.0) ) * $(TR $(TD $(PLUSMN)$(INFIN)) $(TD +$(INFIN)) ) * ) */ real fabs(real x) @safe pure nothrow @nogc; /* intrinsic */ /*********************************************************************** * Calculates the length of the * hypotenuse of a right-angled triangle with sides of length x and y. * The hypotenuse is the value of the square root of * the sums of the squares of x and y: * * sqrt($(POWER x, 2) + $(POWER y, 2)) * * Note that hypot(x, y), hypot(y, x) and * hypot(x, -y) are equivalent. * * $(TABLE_SV * $(TR $(TH x) $(TH y) $(TH hypot(x, y)) $(TH invalid?)) * $(TR $(TD x) $(TD $(PLUSMN)0.0) $(TD |x|) $(TD no)) * $(TR $(TD $(PLUSMNINF)) $(TD y) $(TD +$(INFIN)) $(TD no)) * $(TR $(TD $(PLUSMNINF)) $(TD $(NAN)) $(TD +$(INFIN)) $(TD no)) * ) */ real hypot(real x, real y) @safe pure nothrow @nogc { // Scale x and y to avoid underflow and overflow. // If one is huge and the other tiny, return the larger. // If both are huge, avoid overflow by scaling by 1/sqrt(real.max/2). // If both are tiny, avoid underflow by scaling by sqrt(real.min_normal*real.epsilon). enum real SQRTMIN = 0.5 * sqrt(real.min_normal); // This is a power of 2. enum real SQRTMAX = 1.0L / SQRTMIN; // 2^^((max_exp)/2) = nextUp(sqrt(real.max)) static assert(2*(SQRTMAX/2)*(SQRTMAX/2) <= real.max); // Proves that sqrt(real.max) ~~ 0.5/sqrt(real.min_normal) static assert(real.min_normal*real.max > 2 && real.min_normal*real.max <= 4); real u = fabs(x); real v = fabs(y); if (!(u >= v)) // check for NaN as well. { v = u; u = fabs(y); if (u == real.infinity) return u; // hypot(inf, nan) == inf if (v == real.infinity) return v; // hypot(nan, inf) == inf } // Now u >= v, or else one is NaN. if (v >= SQRTMAX*0.5) { // hypot(huge, huge) -- avoid overflow u *= SQRTMIN*0.5; v *= SQRTMIN*0.5; return sqrt(u*u + v*v) * SQRTMAX * 2.0; } if (u <= SQRTMIN) { // hypot (tiny, tiny) -- avoid underflow // This is only necessary to avoid setting the underflow // flag. u *= SQRTMAX / real.epsilon; v *= SQRTMAX / real.epsilon; return sqrt(u*u + v*v) * SQRTMIN * real.epsilon; } if (u * real.epsilon > v) { // hypot (huge, tiny) = huge return u; } // both are in the normal range return sqrt(u*u + v*v); } unittest { static real[3][] vals = // x,y,hypot [ [ 0.0, 0.0, 0.0], [ 0.0, -0.0, 0.0], [ -0.0, -0.0, 0.0], [ 3.0, 4.0, 5.0], [ -300, -400, 500], [0.0, 7.0, 7.0], [9.0, 9*real.epsilon, 9.0], [88/(64*sqrt(real.min_normal)), 105/(64*sqrt(real.min_normal)), 137/(64*sqrt(real.min_normal))], [88/(128*sqrt(real.min_normal)), 105/(128*sqrt(real.min_normal)), 137/(128*sqrt(real.min_normal))], [3*real.min_normal*real.epsilon, 4*real.min_normal*real.epsilon, 5*real.min_normal*real.epsilon], [ real.min_normal, real.min_normal, sqrt(2.0L)*real.min_normal], [ real.max/sqrt(2.0L), real.max/sqrt(2.0L), real.max], [ real.infinity, real.nan, real.infinity], [ real.nan, real.infinity, real.infinity], [ real.nan, real.nan, real.nan], [ real.nan, real.max, real.nan], [ real.max, real.nan, real.nan], ]; for (int i = 0; i < vals.length; i++) { real x = vals[i][0]; real y = vals[i][1]; real z = vals[i][2]; real h = hypot(x, y); assert(isIdentical(z,h) || feqrel(z, h) >= real.mant_dig - 1); } } /************************************** * Returns the value of x rounded upward to the next integer * (toward positive infinity). */ real ceil(real x) @trusted pure nothrow @nogc { version (Win64_DMD_InlineAsm) { asm { naked ; fld real ptr [RCX] ; fstcw 8[RSP] ; mov AL,9[RSP] ; mov DL,AL ; and AL,0xC3 ; or AL,0x08 ; // round to +infinity mov 9[RSP],AL ; fldcw 8[RSP] ; frndint ; mov 9[RSP],DL ; fldcw 8[RSP] ; ret ; } } else { // Special cases. if (isNaN(x) || isInfinity(x)) return x; real y = floorImpl(x); if (y < x) y += 1.0; return y; } } unittest { assert(ceil(+123.456L) == +124); assert(ceil(-123.456L) == -123); assert(ceil(-1.234L) == -1); assert(ceil(-0.123L) == 0); assert(ceil(0.0L) == 0); assert(ceil(+0.123L) == 1); assert(ceil(+1.234L) == 2); assert(ceil(real.infinity) == real.infinity); assert(isNaN(ceil(real.nan))); assert(isNaN(ceil(real.init))); } // ditto double ceil(double x) @trusted pure nothrow @nogc { // Special cases. if (isNaN(x) || isInfinity(x)) return x; double y = floorImpl(x); if (y < x) y += 1.0; return y; } unittest { assert(ceil(+123.456) == +124); assert(ceil(-123.456) == -123); assert(ceil(-1.234) == -1); assert(ceil(-0.123) == 0); assert(ceil(0.0) == 0); assert(ceil(+0.123) == 1); assert(ceil(+1.234) == 2); assert(ceil(double.infinity) == double.infinity); assert(isNaN(ceil(double.nan))); assert(isNaN(ceil(double.init))); } // ditto float ceil(float x) @trusted pure nothrow @nogc { // Special cases. if (isNaN(x) || isInfinity(x)) return x; float y = floorImpl(x); if (y < x) y += 1.0; return y; } unittest { assert(ceil(+123.456f) == +124); assert(ceil(-123.456f) == -123); assert(ceil(-1.234f) == -1); assert(ceil(-0.123f) == 0); assert(ceil(0.0f) == 0); assert(ceil(+0.123f) == 1); assert(ceil(+1.234f) == 2); assert(ceil(float.infinity) == float.infinity); assert(isNaN(ceil(float.nan))); assert(isNaN(ceil(float.init))); } /************************************** * Returns the value of x rounded downward to the next integer * (toward negative infinity). */ real floor(real x) @trusted pure nothrow @nogc { version (Win64_DMD_InlineAsm) { asm { naked ; fld real ptr [RCX] ; fstcw 8[RSP] ; mov AL,9[RSP] ; mov DL,AL ; and AL,0xC3 ; or AL,0x04 ; // round to -infinity mov 9[RSP],AL ; fldcw 8[RSP] ; frndint ; mov 9[RSP],DL ; fldcw 8[RSP] ; ret ; } } else { // Special cases. if (isNaN(x) || isInfinity(x) || x == 0.0) return x; return floorImpl(x); } } unittest { assert(floor(+123.456L) == +123); assert(floor(-123.456L) == -124); assert(floor(-1.234L) == -2); assert(floor(-0.123L) == -1); assert(floor(0.0L) == 0); assert(floor(+0.123L) == 0); assert(floor(+1.234L) == 1); assert(floor(real.infinity) == real.infinity); assert(isNaN(floor(real.nan))); assert(isNaN(floor(real.init))); } // ditto double floor(double x) @trusted pure nothrow @nogc { // Special cases. if (isNaN(x) || isInfinity(x) || x == 0.0) return x; return floorImpl(x); } unittest { assert(floor(+123.456) == +123); assert(floor(-123.456) == -124); assert(floor(-1.234) == -2); assert(floor(-0.123) == -1); assert(floor(0.0) == 0); assert(floor(+0.123) == 0); assert(floor(+1.234) == 1); assert(floor(double.infinity) == double.infinity); assert(isNaN(floor(double.nan))); assert(isNaN(floor(double.init))); } // ditto float floor(float x) @trusted pure nothrow @nogc { // Special cases. if (isNaN(x) || isInfinity(x) || x == 0.0) return x; return floorImpl(x); } unittest { assert(floor(+123.456f) == +123); assert(floor(-123.456f) == -124); assert(floor(-1.234f) == -2); assert(floor(-0.123f) == -1); assert(floor(0.0f) == 0); assert(floor(+0.123f) == 0); assert(floor(+1.234f) == 1); assert(floor(float.infinity) == float.infinity); assert(isNaN(floor(float.nan))); assert(isNaN(floor(float.init))); } /****************************************** * Rounds x to the nearest integer value, using the current rounding * mode. * * Unlike the rint functions, nearbyint does not raise the * FE_INEXACT exception. */ real nearbyint(real x) @trusted nothrow @nogc { version (Win64) { assert(0); // not implemented in C library } else return core.stdc.math.nearbyintl(x); } /********************************** * Rounds x to the nearest integer value, using the current rounding * mode. * If the return value is not equal to x, the FE_INEXACT * exception is raised. * $(B nearbyint) performs * the same operation, but does not set the FE_INEXACT exception. */ real rint(real x) @safe pure nothrow @nogc; /* intrinsic */ /*************************************** * Rounds x to the nearest integer value, using the current rounding * mode. * * This is generally the fastest method to convert a floating-point number * to an integer. Note that the results from this function * depend on the rounding mode, if the fractional part of x is exactly 0.5. * If using the default rounding mode (ties round to even integers) * lrint(4.5) == 4, lrint(5.5)==6. */ long lrint(real x) @trusted pure nothrow @nogc { version(InlineAsm_X86_Any) { version (Win64) { asm { naked; fld real ptr [RCX]; fistp qword ptr 8[RSP]; mov RAX,8[RSP]; ret; } } else { long n; asm { fld x; fistp n; } return n; } } else { alias F = floatTraits!(real); static if (F.realFormat == RealFormat.ieeeDouble) { long result; // Rounding limit when casting from real(double) to ulong. enum real OF = 4.50359962737049600000E15L; uint* vi = cast(uint*)(&x); // Find the exponent and sign uint msb = vi[MANTISSA_MSB]; uint lsb = vi[MANTISSA_LSB]; int exp = ((msb >> 20) & 0x7ff) - 0x3ff; int sign = msb >> 31; msb &= 0xfffff; msb |= 0x100000; if (exp < 63) { if (exp >= 52) result = (cast(long) msb << (exp - 20)) | (lsb << (exp - 52)); else { // Adjust x and check result. real j = sign ? -OF : OF; x = (j + x) - j; msb = vi[MANTISSA_MSB]; lsb = vi[MANTISSA_LSB]; exp = ((msb >> 20) & 0x7ff) - 0x3ff; msb &= 0xfffff; msb |= 0x100000; if (exp < 0) result = 0; else if (exp < 20) result = cast(long) msb >> (20 - exp); else if (exp == 20) result = cast(long) msb; else result = (cast(long) msb << (exp - 20)) | (lsb >> (52 - exp)); } } else { // It is left implementation defined when the number is too large. return cast(long) x; } return sign ? -result : result; } else static if (F.realFormat == RealFormat.ieeeExtended) { long result; // Rounding limit when casting from real(80-bit) to ulong. enum real OF = 9.22337203685477580800E18L; ushort* vu = cast(ushort*)(&x); uint* vi = cast(uint*)(&x); // Find the exponent and sign int exp = (vu[F.EXPPOS_SHORT] & 0x7fff) - 0x3fff; int sign = (vu[F.EXPPOS_SHORT] >> 15) & 1; if (exp < 63) { // Adjust x and check result. real j = sign ? -OF : OF; x = (j + x) - j; exp = (vu[F.EXPPOS_SHORT] & 0x7fff) - 0x3fff; version (LittleEndian) { if (exp < 0) result = 0; else if (exp <= 31) result = vi[1] >> (31 - exp); else result = (cast(long) vi[1] << (exp - 31)) | (vi[0] >> (63 - exp)); } else { if (exp < 0) result = 0; else if (exp <= 31) result = vi[1] >> (31 - exp); else result = (cast(long) vi[1] << (exp - 31)) | (vi[2] >> (63 - exp)); } } else { // It is left implementation defined when the number is too large // to fit in a 64bit long. return cast(long) x; } return sign ? -result : result; } else { static assert(false, "Only 64-bit and 80-bit reals are supported by lrint()"); } } } unittest { assert(lrint(4.5) == 4); assert(lrint(5.5) == 6); assert(lrint(-4.5) == -4); assert(lrint(-5.5) == -6); assert(lrint(int.max - 0.5) == 2147483646L); assert(lrint(int.max + 0.5) == 2147483648L); assert(lrint(int.min - 0.5) == -2147483648L); assert(lrint(int.min + 0.5) == -2147483648L); } /******************************************* * Return the value of x rounded to the nearest integer. * If the fractional part of x is exactly 0.5, the return value is rounded to * the even integer. */ real round(real x) @trusted nothrow @nogc { version (Win64) { auto old = FloatingPointControl.getControlState(); FloatingPointControl.setControlState((old & ~FloatingPointControl.ROUNDING_MASK) | FloatingPointControl.roundToZero); x = rint((x >= 0) ? x + 0.5 : x - 0.5); FloatingPointControl.setControlState(old); return x; } else return core.stdc.math.roundl(x); } /********************************************** * Return the value of x rounded to the nearest integer. * * If the fractional part of x is exactly 0.5, the return value is rounded * away from zero. */ long lround(real x) @trusted nothrow @nogc { version (Posix) return core.stdc.math.llroundl(x); else assert (0, "lround not implemented"); } version(Posix) { unittest { assert(lround(0.49) == 0); assert(lround(0.5) == 1); assert(lround(1.5) == 2); } } /**************************************************** * Returns the integer portion of x, dropping the fractional portion. * * This is also known as "chop" rounding. */ real trunc(real x) @trusted nothrow @nogc { version (Win64_DMD_InlineAsm) { asm { naked ; fld real ptr [RCX] ; fstcw 8[RSP] ; mov AL,9[RSP] ; mov DL,AL ; and AL,0xC3 ; or AL,0x0C ; // round to 0 mov 9[RSP],AL ; fldcw 8[RSP] ; frndint ; mov 9[RSP],DL ; fldcw 8[RSP] ; ret ; } } else return core.stdc.math.truncl(x); } /**************************************************** * Calculate the remainder x REM y, following IEC 60559. * * REM is the value of x - y * n, where n is the integer nearest the exact * value of x / y. * If |n - x / y| == 0.5, n is even. * If the result is zero, it has the same sign as x. * Otherwise, the sign of the result is the sign of x / y. * Precision mode has no effect on the remainder functions. * * remquo returns n in the parameter n. * * $(TABLE_SV * $(TR $(TH x) $(TH y) $(TH remainder(x, y)) $(TH n) $(TH invalid?)) * $(TR $(TD $(PLUSMN)0.0) $(TD not 0.0) $(TD $(PLUSMN)0.0) $(TD 0.0) $(TD no)) * $(TR $(TD $(PLUSMNINF)) $(TD anything) $(TD $(NAN)) $(TD ?) $(TD yes)) * $(TR $(TD anything) $(TD $(PLUSMN)0.0) $(TD $(NAN)) $(TD ?) $(TD yes)) * $(TR $(TD != $(PLUSMNINF)) $(TD $(PLUSMNINF)) $(TD x) $(TD ?) $(TD no)) * ) * * Note: remquo not supported on windows */ real remainder(real x, real y) @trusted nothrow @nogc { version (Win64) { int n; return remquo(x, y, n); } else return core.stdc.math.remainderl(x, y); } real remquo(real x, real y, out int n) @trusted nothrow @nogc /// ditto { version (Posix) return core.stdc.math.remquol(x, y, &n); else assert (0, "remquo not implemented"); } /** IEEE exception status flags ('sticky bits') These flags indicate that an exceptional floating-point condition has occurred. They indicate that a NaN or an infinity has been generated, that a result is inexact, or that a signalling NaN has been encountered. If floating-point exceptions are enabled (unmasked), a hardware exception will be generated instead of setting these flags. Example: ---- real a=3.5; // Set all the flags to zero resetIeeeFlags(); assert(!ieeeFlags.divByZero); // Perform a division by zero. a/=0.0L; assert(a==real.infinity); assert(ieeeFlags.divByZero); // Create a NaN a*=0.0L; assert(ieeeFlags.invalid); assert(isNaN(a)); // Check that calling func() has no effect on the // status flags. IeeeFlags f = ieeeFlags; func(); assert(ieeeFlags == f); ---- */ struct IeeeFlags { private: // The x87 FPU status register is 16 bits. // The Pentium SSE2 status register is 32 bits. uint flags; version (X86_Any) { // Applies to both x87 status word (16 bits) and SSE2 status word(32 bits). enum : int { INEXACT_MASK = 0x20, UNDERFLOW_MASK = 0x10, OVERFLOW_MASK = 0x08, DIVBYZERO_MASK = 0x04, INVALID_MASK = 0x01 } // Don't bother about subnormals, they are not supported on most CPUs. // SUBNORMAL_MASK = 0x02; } else version (PPC) { // PowerPC FPSCR is a 32-bit register. enum : int { INEXACT_MASK = 0x600, UNDERFLOW_MASK = 0x010, OVERFLOW_MASK = 0x008, DIVBYZERO_MASK = 0x020, INVALID_MASK = 0xF80 // PowerPC has five types of invalid exceptions. } } else version (PPC64) { // PowerPC FPSCR is a 32-bit register. enum : int { INEXACT_MASK = 0x600, UNDERFLOW_MASK = 0x010, OVERFLOW_MASK = 0x008, DIVBYZERO_MASK = 0x020, INVALID_MASK = 0xF80 // PowerPC has five types of invalid exceptions. } } else version (ARM) { enum : int { INEXACT_MASK = 0x10, UNDERFLOW_MASK = 0x08, OVERFLOW_MASK = 0x04, DIVBYZERO_MASK = 0x02, INVALID_MASK = 0x01 } } else version(SPARC) { // SPARC FSR is a 32bit register //(64 bits for Sparc 7 & 8, but high 32 bits are uninteresting). enum : int { INEXACT_MASK = 0x020, UNDERFLOW_MASK = 0x080, OVERFLOW_MASK = 0x100, DIVBYZERO_MASK = 0x040, INVALID_MASK = 0x200 } } else static assert(0, "Not implemented"); private: static uint getIeeeFlags() { version(D_InlineAsm_X86) { asm { fstsw AX; // NOTE: If compiler supports SSE2, need to OR the result with // the SSE2 status register. // Clear all irrelevant bits and EAX, 0x03D; } } else version(D_InlineAsm_X86_64) { asm { fstsw AX; // NOTE: If compiler supports SSE2, need to OR the result with // the SSE2 status register. // Clear all irrelevant bits and RAX, 0x03D; } } else version (GNU) { uint result; version (X86) asm { "fstsw %%ax; andl $0x03D, %%eax;" : "=a" result; } else version (X86_64) asm { "fstsw %%ax; andq $0x03D, %%rax;" : "=a" result; } else version (ARM_SoftFloat) { result = 0; } else version (ARM) asm { "vmrs %0, FPSCR; and %0, %0, #0x1F;" : "=r" result; } else assert(0, "Not yet supported"); return result; } else version (SPARC) { /* int retval; asm { st %fsr, retval; } return retval; */ assert(0, "Not yet supported"); } else version (ARM) { assert(false, "Not yet supported."); } else assert(0, "Not yet supported"); } static void resetIeeeFlags() { version(InlineAsm_X86_Any) { asm { fnclex; } } else version (GNU) { version (X86) asm { "fnclex;"; } else version (X86_64) asm { "fnclex;"; } else version (ARM_SoftFloat) { } else version (ARM) { uint old = void; asm { "vmrs %0, FPSCR" : "=r" (old); } old &= ~0b11111; // http://infocenter.arm.com/help/topic/com.arm.doc.ddi0408i/Chdfifdc.html asm {"vmsr FPSCR, %0;" : : "r" (old);} } else assert(0, "Not yet supported"); } else { /* SPARC: int tmpval; asm { st %fsr, tmpval; } tmpval &=0xFFFF_FC00; asm { ld tmpval, %fsr; } */ assert(0, "Not yet supported"); } } public: version (IeeeFlagsSupport) { /// The result cannot be represented exactly, so rounding occurred. /// (example: x = sin(0.1); ) @property bool inexact() { return (flags & INEXACT_MASK) != 0; } /// A zero was generated by underflow (example: x = real.min*real.epsilon/2;) @property bool underflow() { return (flags & UNDERFLOW_MASK) != 0; } /// An infinity was generated by overflow (example: x = real.max*2;) @property bool overflow() { return (flags & OVERFLOW_MASK) != 0; } /// An infinity was generated by division by zero (example: x = 3/0.0; ) @property bool divByZero() { return (flags & DIVBYZERO_MASK) != 0; } /// A machine NaN was generated. (example: x = real.infinity * 0.0; ) @property bool invalid() { return (flags & INVALID_MASK) != 0; } } } version(X86_Any) { version = IeeeFlagsSupport; } else version(ARM) { version = IeeeFlagsSupport; } /// Set all of the floating-point status flags to false. void resetIeeeFlags() { IeeeFlags.resetIeeeFlags(); } /// Return a snapshot of the current state of the floating-point status flags. @property IeeeFlags ieeeFlags() { return IeeeFlags(IeeeFlags.getIeeeFlags()); } /** Control the Floating point hardware Change the IEEE754 floating-point rounding mode and the floating-point hardware exceptions. By default, the rounding mode is roundToNearest and all hardware exceptions are disabled. For most applications, debugging is easier if the $(I division by zero), $(I overflow), and $(I invalid operation) exceptions are enabled. These three are combined into a $(I severeExceptions) value for convenience. Note in particular that if $(I invalidException) is enabled, a hardware trap will be generated whenever an uninitialized floating-point variable is used. All changes are temporary. The previous state is restored at the end of the scope. Example: ---- { FloatingPointControl fpctrl; // Enable hardware exceptions for division by zero, overflow to infinity, // invalid operations, and uninitialized floating-point variables. fpctrl.enableExceptions(FloatingPointControl.severeExceptions); // This will generate a hardware exception, if x is a // default-initialized floating point variable: real x; // Add `= 0` or even `= real.nan` to not throw the exception. real y = x * 3.0; // The exception is only thrown for default-uninitialized NaN-s. // NaN-s with other payload are valid: real z = y * real.nan; // ok // Changing the rounding mode: fpctrl.rounding = FloatingPointControl.roundUp; assert(rint(1.1) == 2); // The set hardware exceptions will be disabled when leaving this scope. // The original rounding mode will also be restored. } // Ensure previous values are returned: assert(!FloatingPointControl.enabledExceptions); assert(FloatingPointControl.rounding == FloatingPointControl.roundToNearest); assert(rint(1.1) == 1); ---- */ struct FloatingPointControl { alias RoundingMode = uint; /** IEEE rounding modes. * The default mode is roundToNearest. */ version(ARM) { enum : RoundingMode { roundToNearest = 0x000000, roundDown = 0x800000, roundUp = 0x400000, roundToZero = 0xC00000 } } else { enum : RoundingMode { roundToNearest = 0x0000, roundDown = 0x0400, roundUp = 0x0800, roundToZero = 0x0C00 } } /** IEEE hardware exceptions. * By default, all exceptions are masked (disabled). */ version(ARM) { enum : uint { subnormalException = 0x8000, inexactException = 0x1000, underflowException = 0x0800, overflowException = 0x0400, divByZeroException = 0x0200, invalidException = 0x0100, /// Severe = The overflow, division by zero, and invalid exceptions. severeExceptions = overflowException | divByZeroException | invalidException, allExceptions = severeExceptions | underflowException | inexactException | subnormalException, } } else { enum : uint { inexactException = 0x20, underflowException = 0x10, overflowException = 0x08, divByZeroException = 0x04, subnormalException = 0x02, invalidException = 0x01, /// Severe = The overflow, division by zero, and invalid exceptions. severeExceptions = overflowException | divByZeroException | invalidException, allExceptions = severeExceptions | underflowException | inexactException | subnormalException, } } private: version(ARM) { enum uint EXCEPTION_MASK = 0x9F00; enum uint ROUNDING_MASK = 0xC00000; } else version(X86) { enum ushort EXCEPTION_MASK = 0x3F; enum ushort ROUNDING_MASK = 0xC00; } else version(X86_64) { enum ushort EXCEPTION_MASK = 0x3F; enum ushort ROUNDING_MASK = 0xC00; } else static assert(false, "Architecture not supported"); public: /// Returns true if the current FPU supports exception trapping @property static bool hasExceptionTraps() @safe nothrow @nogc { version(X86) return true; else version(X86_64) return true; else version(ARM) { auto oldState = getControlState(); // If exceptions are not supported, we set the bit but read it back as zero // https://sourceware.org/ml/libc-ports/2012-06/msg00091.html setControlState(oldState | (divByZeroException & EXCEPTION_MASK)); bool result = (getControlState() & EXCEPTION_MASK) != 0; setControlState(oldState); return result; } else static assert(false, "Not implemented for this architecture"); } /// Enable (unmask) specific hardware exceptions. Multiple exceptions may be ORed together. void enableExceptions(uint exceptions) @nogc { assert(hasExceptionTraps); initialize(); version(ARM) setControlState(getControlState() | (exceptions & EXCEPTION_MASK)); else setControlState(getControlState() & ~(exceptions & EXCEPTION_MASK)); } /// Disable (mask) specific hardware exceptions. Multiple exceptions may be ORed together. void disableExceptions(uint exceptions) @nogc { assert(hasExceptionTraps); initialize(); version(ARM) setControlState(getControlState() & ~(exceptions & EXCEPTION_MASK)); else setControlState(getControlState() | (exceptions & EXCEPTION_MASK)); } //// Change the floating-point hardware rounding mode @property void rounding(RoundingMode newMode) @nogc { initialize(); setControlState((getControlState() & ~ROUNDING_MASK) | (newMode & ROUNDING_MASK)); } /// Return the exceptions which are currently enabled (unmasked) @property static uint enabledExceptions() @nogc { assert(hasExceptionTraps); version(ARM) return (getControlState() & EXCEPTION_MASK); else return (getControlState() & EXCEPTION_MASK) ^ EXCEPTION_MASK; } /// Return the currently active rounding mode @property static RoundingMode rounding() @nogc { return cast(RoundingMode)(getControlState() & ROUNDING_MASK); } /// Clear all pending exceptions, then restore the original exception state and rounding mode. ~this() @nogc { clearExceptions(); if (initialized) setControlState(savedState); } private: ControlState savedState; bool initialized = false; version(ARM) { alias ControlState = uint; } else { alias ControlState = ushort; } void initialize() @nogc { // BUG: This works around the absence of this() constructors. if (initialized) return; clearExceptions(); savedState = getControlState(); initialized = true; } // Clear all pending exceptions static void clearExceptions() @nogc { version (InlineAsm_X86_Any) { asm { fclex; } } else version (GNU) { version (X86) asm { "fclex;"; } else version (X86_64) asm { "fclex;"; } else version (ARM_SoftFloat) { } else version (ARM) { uint old = getControlState(); old &= ~0b11111; // http://infocenter.arm.com/help/topic/com.arm.doc.ddi0408i/Chdfifdc.html asm {"vmsr FPSCR, %0;" : : "r" (old);} } else assert(0, "Not yet supported"); } else assert(0, "Not yet supported"); } // Read from the control register static ControlState getControlState() @trusted nothrow @nogc { version (D_InlineAsm_X86) { short cont; asm { xor EAX, EAX; fstcw cont; } return cont; } else version (D_InlineAsm_X86_64) { short cont; asm { xor RAX, RAX; fstcw cont; } return cont; } else version (GNU) { ControlState cont; version (X86) asm { "xor %%eax, %%eax; fstcw %[cw];" : [cw] "=m" cont :: "eax"; } else version (X86_64) asm { "xor %%rax, %%rax; fstcw %[cw];" : [cw] "=m" cont :: "rax"; } else version (ARM) { version (ARM_SoftFloat) cont = 0; else asm { "vmrs %0, FPSCR;" : "=r" cont; } } else assert(0, "Not yet supported"); return cont; } else assert(0, "Not yet supported"); } // Set the control register static void setControlState(ControlState newState) @trusted nothrow @nogc { version (InlineAsm_X86_Any) { version (Win64) { asm { naked; mov 8[RSP],RCX; fclex; fldcw 8[RSP]; ret; } } else { asm { fclex; fldcw newState; } } } else version (GNU) { version (X86) asm { "fclex; fldcw %[cw]" : : [cw] "m" newState; } else version (X86_64) asm { "fclex; fldcw %[cw]" : : [cw] "m" newState; } else version (ARM) { version (ARM_SoftFloat) return; else asm { "vmsr FPSCR, %0;" : : "r" (newState); } } else assert(0, "Not yet supported"); } else assert(0, "Not yet supported"); } } unittest { //GCC floating point emulation doesn't allow changing //rounding modes, getting error bits etc version(GNU) version(D_SoftFloat) return; void ensureDefaults() { assert(FloatingPointControl.rounding == FloatingPointControl.roundToNearest); if(FloatingPointControl.hasExceptionTraps) assert(FloatingPointControl.enabledExceptions == 0); } { FloatingPointControl ctrl; } ensureDefaults(); { FloatingPointControl ctrl; ctrl.rounding = FloatingPointControl.roundDown; assert(FloatingPointControl.rounding == FloatingPointControl.roundDown); } ensureDefaults(); if(FloatingPointControl.hasExceptionTraps) { FloatingPointControl ctrl; ctrl.enableExceptions(FloatingPointControl.divByZeroException | FloatingPointControl.overflowException); assert(ctrl.enabledExceptions == (FloatingPointControl.divByZeroException | FloatingPointControl.overflowException)); ctrl.rounding = FloatingPointControl.roundUp; assert(FloatingPointControl.rounding == FloatingPointControl.roundUp); } ensureDefaults(); } /********************************* * Returns !=0 if e is a NaN. */ bool isNaN(X)(X x) @nogc @trusted pure nothrow if (isFloatingPoint!(X)) { alias F = floatTraits!(X); static if (F.realFormat == RealFormat.ieeeSingle) { uint* p = cast(uint *)&x; return ((*p & 0x7F80_0000) == 0x7F80_0000) && *p & 0x007F_FFFF; // not infinity } else static if (F.realFormat == RealFormat.ieeeDouble) { ulong* p = cast(ulong *)&x; return ((*p & 0x7FF0_0000_0000_0000) == 0x7FF0_0000_0000_0000) && *p & 0x000F_FFFF_FFFF_FFFF; // not infinity } else static if (F.realFormat == RealFormat.ieeeExtended) { ushort e = F.EXPMASK & (cast(ushort *)&x)[F.EXPPOS_SHORT]; ulong* ps = cast(ulong *)&x; return e == F.EXPMASK && *ps & 0x7FFF_FFFF_FFFF_FFFF; // not infinity } else static if (F.realFormat == RealFormat.ieeeQuadruple) { ushort e = F.EXPMASK & (cast(ushort *)&x)[F.EXPPOS_SHORT]; ulong* ps = cast(ulong *)&x; return e == F.EXPMASK && (ps[MANTISSA_LSB] | (ps[MANTISSA_MSB]& 0x0000_FFFF_FFFF_FFFF)) != 0; } else { return x != x; } } deprecated("isNaN is not defined for integer types") bool isNaN(X)(X x) @nogc @trusted pure nothrow if (isIntegral!(X)) { return isNaN(cast(float)x); } unittest { import std.typetuple; foreach(T; TypeTuple!(float, double, real)) { // CTFE-able tests assert(isNaN(T.init)); assert(isNaN(-T.init)); assert(isNaN(T.nan)); assert(isNaN(-T.nan)); assert(!isNaN(T.infinity)); assert(!isNaN(-T.infinity)); assert(!isNaN(cast(T)53.6)); assert(!isNaN(cast(T)-53.6)); // Runtime tests shared T f; f = T.init; assert(isNaN(f)); assert(isNaN(-f)); f = T.nan; assert(isNaN(f)); assert(isNaN(-f)); f = T.infinity; assert(!isNaN(f)); assert(!isNaN(-f)); f = cast(T)53.6; assert(!isNaN(f)); assert(!isNaN(-f)); } } /********************************* * Returns !=0 if e is finite (not infinite or $(NAN)). */ int isFinite(X)(X e) @trusted pure nothrow @nogc { alias F = floatTraits!(X); ushort* pe = cast(ushort *)&e; return (pe[F.EXPPOS_SHORT] & F.EXPMASK) != F.EXPMASK; } unittest { assert(isFinite(1.23f)); assert(isFinite(float.max)); assert(isFinite(float.min_normal)); assert(!isFinite(float.nan)); assert(!isFinite(float.infinity)); assert(isFinite(1.23)); assert(isFinite(double.max)); assert(isFinite(double.min_normal)); assert(!isFinite(double.nan)); assert(!isFinite(double.infinity)); assert(isFinite(1.23L)); assert(isFinite(real.max)); assert(isFinite(real.min_normal)); assert(!isFinite(real.nan)); assert(!isFinite(real.infinity)); } deprecated("isFinite is not defined for integer types") int isFinite(X)(X x) @trusted pure nothrow @nogc if (isIntegral!(X)) { return isFinite(cast(float)x); } /********************************* * Returns !=0 if x is normalized (not zero, subnormal, infinite, or $(NAN)). */ /* Need one for each format because subnormal floats might * be converted to normal reals. */ int isNormal(X)(X x) @trusted pure nothrow @nogc { alias F = floatTraits!(X); static if (F.realFormat == RealFormat.ibmExtended) { // doubledouble is normal if the least significant part is normal. return isNormal((cast(double*)&x)[MANTISSA_LSB]); } else { ushort e = F.EXPMASK & (cast(ushort *)&x)[F.EXPPOS_SHORT]; return (e != F.EXPMASK && e != 0); } } unittest { float f = 3; double d = 500; real e = 10e+48; assert(isNormal(f)); assert(isNormal(d)); assert(isNormal(e)); f = d = e = 0; assert(!isNormal(f)); assert(!isNormal(d)); assert(!isNormal(e)); assert(!isNormal(real.infinity)); assert(isNormal(-real.max)); assert(!isNormal(real.min_normal/4)); } /********************************* * Is number subnormal? (Also called "denormal".) * Subnormals have a 0 exponent and a 0 most significant mantissa bit. */ /* Need one for each format because subnormal floats might * be converted to normal reals. */ int isSubnormal(X)(X x) @trusted pure nothrow @nogc { alias F = floatTraits!(X); static if (F.realFormat == RealFormat.ieeeSingle) { uint *p = cast(uint *)&x; return (*p & F.EXPMASK_INT) == 0 && *p & F.MANTISSAMASK_INT; } else static if (F.realFormat == RealFormat.ieeeDouble) { uint *p = cast(uint *)&x; return (p[MANTISSA_MSB] & F.EXPMASK_INT) == 0 && (p[MANTISSA_LSB] || p[MANTISSA_MSB] & F.MANTISSAMASK_INT); } else static if (F.realFormat == RealFormat.ieeeQuadruple) { ushort e = F.EXPMASK & (cast(ushort *)&x)[F.EXPPOS_SHORT]; long* ps = cast(long *)&x; return (e == 0 && (((ps[MANTISSA_LSB]|(ps[MANTISSA_MSB]& 0x0000_FFFF_FFFF_FFFF))) != 0)); } else static if (F.realFormat == RealFormat.ieeeExtended) { ushort* pe = cast(ushort *)&x; long* ps = cast(long *)&x; return (pe[F.EXPPOS_SHORT] & F.EXPMASK) == 0 && *ps > 0; } else static if (F.realFormat == RealFormat.ibmExtended) { return isSubnormal((cast(double*)&x)[MANTISSA_MSB]); } else { static assert(false, "Not implemented for this architecture"); } } unittest { import std.typetuple; foreach (T; TypeTuple!(float, double, real)) { T f; for (f = 1.0; !isSubnormal(f); f /= 2) assert(f != 0); } } deprecated("isSubnormal is not defined for integer types") int isSubnormal(X)(X x) @trusted pure nothrow @nogc if (isIntegral!X) { return isSubnormal(cast(double)x); } /********************************* * Return !=0 if e is $(PLUSMN)$(INFIN). */ bool isInfinity(X)(X x) @nogc @trusted pure nothrow if (isFloatingPoint!(X)) { alias F = floatTraits!(X); static if (F.realFormat == RealFormat.ieeeSingle) { return ((*cast(uint *)&x) & 0x7FFF_FFFF) == 0x7F80_0000; } else static if (F.realFormat == RealFormat.ieeeDouble) { return ((*cast(ulong *)&x) & 0x7FFF_FFFF_FFFF_FFFF) == 0x7FF0_0000_0000_0000; } else static if (F.realFormat == RealFormat.ieeeExtended) { ushort e = cast(ushort)(F.EXPMASK & (cast(ushort *)&x)[F.EXPPOS_SHORT]); ulong* ps = cast(ulong *)&x; // On Motorola 68K, infinity can have hidden bit = 1 or 0. On x86, it is always 1. return e == F.EXPMASK && (*ps & 0x7FFF_FFFF_FFFF_FFFF) == 0; } else static if (F.realFormat == RealFormat.ibmExtended) { return (((cast(ulong *)&x)[MANTISSA_MSB]) & 0x7FFF_FFFF_FFFF_FFFF) == 0x7FF8_0000_0000_0000; } else static if (F.realFormat == RealFormat.ieeeQuadruple) { long* ps = cast(long *)&x; return (ps[MANTISSA_LSB] == 0) && (ps[MANTISSA_MSB] & 0x7FFF_FFFF_FFFF_FFFF) == 0x7FFF_0000_0000_0000; } else { return (x - 1) == x; } } unittest { // CTFE-able tests assert(!isInfinity(float.init)); assert(!isInfinity(-float.init)); assert(!isInfinity(float.nan)); assert(!isInfinity(-float.nan)); assert(isInfinity(float.infinity)); assert(isInfinity(-float.infinity)); assert(isInfinity(-1.0f / 0.0f)); assert(!isInfinity(double.init)); assert(!isInfinity(-double.init)); assert(!isInfinity(double.nan)); assert(!isInfinity(-double.nan)); assert(isInfinity(double.infinity)); assert(isInfinity(-double.infinity)); assert(isInfinity(-1.0 / 0.0)); assert(!isInfinity(real.init)); assert(!isInfinity(-real.init)); assert(!isInfinity(real.nan)); assert(!isInfinity(-real.nan)); assert(isInfinity(real.infinity)); assert(isInfinity(-real.infinity)); assert(isInfinity(-1.0L / 0.0L)); // Runtime tests shared float f; f = float.init; assert(!isInfinity(f)); assert(!isInfinity(-f)); f = float.nan; assert(!isInfinity(f)); assert(!isInfinity(-f)); f = float.infinity; assert(isInfinity(f)); assert(isInfinity(-f)); f = (-1.0f / 0.0f); assert(isInfinity(f)); shared double d; d = double.init; assert(!isInfinity(d)); assert(!isInfinity(-d)); d = double.nan; assert(!isInfinity(d)); assert(!isInfinity(-d)); d = double.infinity; assert(isInfinity(d)); assert(isInfinity(-d)); d = (-1.0 / 0.0); assert(isInfinity(d)); shared real e; e = real.init; assert(!isInfinity(e)); assert(!isInfinity(-e)); e = real.nan; assert(!isInfinity(e)); assert(!isInfinity(-e)); e = real.infinity; assert(isInfinity(e)); assert(isInfinity(-e)); e = (-1.0L / 0.0L); assert(isInfinity(e)); } /********************************* * Is the binary representation of x identical to y? * * Same as ==, except that positive and negative zero are not identical, * and two $(NAN)s are identical if they have the same 'payload'. */ bool isIdentical(real x, real y) @trusted pure nothrow @nogc { // We're doing a bitwise comparison so the endianness is irrelevant. long* pxs = cast(long *)&x; long* pys = cast(long *)&y; alias F = floatTraits!(real); static if (F.realFormat == RealFormat.ieeeDouble) { return pxs[0] == pys[0]; } else static if (F.realFormat == RealFormat.ieeeQuadruple || F.realFormat == RealFormat.ibmExtended) { return pxs[0] == pys[0] && pxs[1] == pys[1]; } else { ushort* pxe = cast(ushort *)&x; ushort* pye = cast(ushort *)&y; return pxe[4] == pye[4] && pxs[0] == pys[0]; } } /********************************* * Return 1 if sign bit of e is set, 0 if not. */ int signbit(X)(X x) @nogc @trusted pure nothrow { alias F = floatTraits!(X); return ((cast(ubyte *)&x)[F.SIGNPOS_BYTE] & 0x80) != 0; } unittest { debug (math) printf("math.signbit.unittest\n"); assert(!signbit(float.nan)); assert(signbit(-float.nan)); assert(!signbit(168.1234f)); assert(signbit(-168.1234f)); assert(!signbit(0.0f)); assert(signbit(-0.0f)); assert(signbit(-float.max)); assert(!signbit(float.max)); assert(!signbit(double.nan)); assert(signbit(-double.nan)); assert(!signbit(168.1234)); assert(signbit(-168.1234)); assert(!signbit(0.0)); assert(signbit(-0.0)); assert(signbit(-double.max)); assert(!signbit(double.max)); assert(!signbit(real.nan)); assert(signbit(-real.nan)); assert(!signbit(168.1234L)); assert(signbit(-168.1234L)); assert(!signbit(0.0L)); assert(signbit(-0.0L)); assert(signbit(-real.max)); assert(!signbit(real.max)); } deprecated("signbit is not defined for integer types") int signbit(X)(X x) @nogc @trusted pure nothrow if (isIntegral!X) { return signbit(cast(float)x); } /********************************* * Return a value composed of to with from's sign bit. */ R copysign(R, X)(R to, X from) @trusted pure nothrow @nogc if (isFloatingPoint!(R) && isFloatingPoint!(X)) { ubyte* pto = cast(ubyte *)&to; const ubyte* pfrom = cast(ubyte *)&from; alias T = floatTraits!(R); alias F = floatTraits!(X); pto[T.SIGNPOS_BYTE] &= 0x7F; pto[T.SIGNPOS_BYTE] |= pfrom[F.SIGNPOS_BYTE] & 0x80; return to; } // ditto R copysign(R, X)(X to, R from) @trusted pure nothrow @nogc if (isIntegral!(X) && isFloatingPoint!(R)) { return copysign(cast(R)to, from); } unittest { import std.typetuple; foreach (X; TypeTuple!(float, double, real, int, long)) { foreach (Y; TypeTuple!(float, double, real)) { X x = 21; Y y = 23.8; Y e = void; e = copysign(x, y); assert(e == 21.0); e = copysign(-x, y); assert(e == 21.0); e = copysign(x, -y); assert(e == -21.0); e = copysign(-x, -y); assert(e == -21.0); static if (isFloatingPoint!X) { e = copysign(X.nan, y); assert(isNaN(e) && !signbit(e)); e = copysign(X.nan, -y); assert(isNaN(e) && signbit(e)); } } } } deprecated("copysign : from can't be of integer type") R copysign(R, X)(X to, R from) @trusted pure nothrow @nogc if (isIntegral!R) { return copysign(to, cast(float)from); } /********************************* Returns $(D -1) if $(D x < 0), $(D x) if $(D x == 0), $(D 1) if $(D x > 0), and $(NAN) if x==$(NAN). */ F sgn(F)(F x) @safe pure nothrow @nogc { // @@@TODO@@@: make this faster return x > 0 ? 1 : x < 0 ? -1 : x; } unittest { debug (math) printf("math.sgn.unittest\n"); assert(sgn(168.1234) == 1); assert(sgn(-168.1234) == -1); assert(sgn(0.0) == 0); assert(sgn(-0.0) == 0); } // Functions for NaN payloads /* * A 'payload' can be stored in the significand of a $(NAN). One bit is required * to distinguish between a quiet and a signalling $(NAN). This leaves 22 bits * of payload for a float; 51 bits for a double; 62 bits for an 80-bit real; * and 111 bits for a 128-bit quad. */ /** * Create a quiet $(NAN), storing an integer inside the payload. * * For floats, the largest possible payload is 0x3F_FFFF. * For doubles, it is 0x3_FFFF_FFFF_FFFF. * For 80-bit or 128-bit reals, it is 0x3FFF_FFFF_FFFF_FFFF. */ real NaN(ulong payload) @trusted pure nothrow @nogc { alias F = floatTraits!(real); static if (F.realFormat == RealFormat.ieeeExtended) { // real80 (in x86 real format, the implied bit is actually // not implied but a real bit which is stored in the real) ulong v = 3; // implied bit = 1, quiet bit = 1 } else { ulong v = 1; // no implied bit. quiet bit = 1 } ulong a = payload; // 22 Float bits ulong w = a & 0x3F_FFFF; a -= w; v <<=22; v |= w; a >>=22; // 29 Double bits v <<=29; w = a & 0xFFF_FFFF; v |= w; a -= w; a >>=29; static if (F.realFormat == RealFormat.ieeeDouble) { v |= 0x7FF0_0000_0000_0000; real x; * cast(ulong *)(&x) = v; return x; } else { v <<=11; a &= 0x7FF; v |= a; real x = real.nan; // Extended real bits static if (F.realFormat == RealFormat.ieeeQuadruple) { v <<= 1; // there's no implicit bit version(LittleEndian) { *cast(ulong*)(6+cast(ubyte*)(&x)) = v; } else { *cast(ulong*)(2+cast(ubyte*)(&x)) = v; } } else { *cast(ulong *)(&x) = v; } return x; } } unittest { static if (floatTraits!(real).realFormat == RealFormat.ieeeDouble) { auto x = NaN(1); auto xl = *cast(ulong*)&x; assert(xl & 0x8_0000_0000_0000UL); //non-signaling bit, bit 52 assert((xl & 0x7FF0_0000_0000_0000UL) == 0x7FF0_0000_0000_0000UL); //all exp bits set } } /** * Extract an integral payload from a $(NAN). * * Returns: * the integer payload as a ulong. * * For floats, the largest possible payload is 0x3F_FFFF. * For doubles, it is 0x3_FFFF_FFFF_FFFF. * For 80-bit or 128-bit reals, it is 0x3FFF_FFFF_FFFF_FFFF. */ ulong getNaNPayload(real x) @trusted pure nothrow @nogc { // assert(isNaN(x)); alias F = floatTraits!(real); static if (F.realFormat == RealFormat.ieeeDouble) { ulong m = *cast(ulong *)(&x); // Make it look like an 80-bit significand. // Skip exponent, and quiet bit m &= 0x0007_FFFF_FFFF_FFFF; m <<= 10; } else static if (F.realFormat == RealFormat.ieeeQuadruple) { version(LittleEndian) { ulong m = *cast(ulong*)(6+cast(ubyte*)(&x)); } else { ulong m = *cast(ulong*)(2+cast(ubyte*)(&x)); } m >>= 1; // there's no implicit bit } else { ulong m = *cast(ulong *)(&x); } // ignore implicit bit and quiet bit ulong f = m & 0x3FFF_FF00_0000_0000L; ulong w = f >>> 40; w |= (m & 0x00FF_FFFF_F800L) << (22 - 11); w |= (m & 0x7FF) << 51; return w; } debug(UnitTest) { unittest { real nan4 = NaN(0x789_ABCD_EF12_3456); static if (floatTraits!(real).realFormat == RealFormat.ieeeExtended || floatTraits!(real).realFormat == RealFormat.ieeeQuadruple) { assert (getNaNPayload(nan4) == 0x789_ABCD_EF12_3456); } else { assert (getNaNPayload(nan4) == 0x1_ABCD_EF12_3456); } double nan5 = nan4; assert (getNaNPayload(nan5) == 0x1_ABCD_EF12_3456); float nan6 = nan4; assert (getNaNPayload(nan6) == 0x12_3456); nan4 = NaN(0xFABCD); assert (getNaNPayload(nan4) == 0xFABCD); nan6 = nan4; assert (getNaNPayload(nan6) == 0xFABCD); nan5 = NaN(0x100_0000_0000_3456); assert(getNaNPayload(nan5) == 0x0000_0000_3456); } } /** * Calculate the next largest floating point value after x. * * Return the least number greater than x that is representable as a real; * thus, it gives the next point on the IEEE number line. * * $(TABLE_SV * $(SVH x, nextUp(x) ) * $(SV -$(INFIN), -real.max ) * $(SV $(PLUSMN)0.0, real.min_normal*real.epsilon ) * $(SV real.max, $(INFIN) ) * $(SV $(INFIN), $(INFIN) ) * $(SV $(NAN), $(NAN) ) * ) */ real nextUp(real x) @trusted pure nothrow @nogc { alias F = floatTraits!(real); static if (F.realFormat == RealFormat.ieeeDouble) { return nextUp(cast(double)x); } else static if (F.realFormat == RealFormat.ieeeQuadruple) { ushort e = F.EXPMASK & (cast(ushort *)&x)[F.EXPPOS_SHORT]; if (e == F.EXPMASK) { // NaN or Infinity if (x == -real.infinity) return -real.max; return x; // +Inf and NaN are unchanged. } ulong* ps = cast(ulong *)&e; if (ps[MANTISSA_LSB] & 0x8000_0000_0000_0000) { // Negative number if (ps[MANTISSA_LSB] == 0 && ps[MANTISSA_MSB] == 0x8000_0000_0000_0000) { // it was negative zero, change to smallest subnormal ps[MANTISSA_LSB] = 0x0000_0000_0000_0001; ps[MANTISSA_MSB] = 0; return x; } --*ps; if (ps[MANTISSA_LSB] == 0) --ps[MANTISSA_MSB]; } else { // Positive number ++ps[MANTISSA_LSB]; if (ps[MANTISSA_LSB] == 0) ++ps[MANTISSA_MSB]; } return x; } else static if (F.realFormat == RealFormat.ieeeExtended) { // For 80-bit reals, the "implied bit" is a nuisance... ushort *pe = cast(ushort *)&x; ulong *ps = cast(ulong *)&x; if ((pe[F.EXPPOS_SHORT] & F.EXPMASK) == F.EXPMASK) { // First, deal with NANs and infinity if (x == -real.infinity) return -real.max; return x; // +Inf and NaN are unchanged. } if (pe[F.EXPPOS_SHORT] & 0x8000) { // Negative number -- need to decrease the significand --*ps; // Need to mask with 0x7FFF... so subnormals are treated correctly. if ((*ps & 0x7FFF_FFFF_FFFF_FFFF) == 0x7FFF_FFFF_FFFF_FFFF) { if (pe[F.EXPPOS_SHORT] == 0x8000) // it was negative zero { *ps = 1; pe[F.EXPPOS_SHORT] = 0; // smallest subnormal. return x; } --pe[F.EXPPOS_SHORT]; if (pe[F.EXPPOS_SHORT] == 0x8000) return x; // it's become a subnormal, implied bit stays low. *ps = 0xFFFF_FFFF_FFFF_FFFF; // set the implied bit return x; } return x; } else { // Positive number -- need to increase the significand. // Works automatically for positive zero. ++*ps; if ((*ps & 0x7FFF_FFFF_FFFF_FFFF) == 0) { // change in exponent ++pe[F.EXPPOS_SHORT]; *ps = 0x8000_0000_0000_0000; // set the high bit } } return x; } else // static if (F.realFormat == RealFormat.ibmExtended) { assert (0, "nextUp not implemented"); } } /** ditto */ double nextUp(double x) @trusted pure nothrow @nogc { ulong *ps = cast(ulong *)&x; if ((*ps & 0x7FF0_0000_0000_0000) == 0x7FF0_0000_0000_0000) { // First, deal with NANs and infinity if (x == -x.infinity) return -x.max; return x; // +INF and NAN are unchanged. } if (*ps & 0x8000_0000_0000_0000) // Negative number { if (*ps == 0x8000_0000_0000_0000) // it was negative zero { *ps = 0x0000_0000_0000_0001; // change to smallest subnormal return x; } --*ps; } else { // Positive number ++*ps; } return x; } /** ditto */ float nextUp(float x) @trusted pure nothrow @nogc { uint *ps = cast(uint *)&x; if ((*ps & 0x7F80_0000) == 0x7F80_0000) { // First, deal with NANs and infinity if (x == -x.infinity) return -x.max; return x; // +INF and NAN are unchanged. } if (*ps & 0x8000_0000) // Negative number { if (*ps == 0x8000_0000) // it was negative zero { *ps = 0x0000_0001; // change to smallest subnormal return x; } --*ps; } else { // Positive number ++*ps; } return x; } /** * Calculate the next smallest floating point value before x. * * Return the greatest number less than x that is representable as a real; * thus, it gives the previous point on the IEEE number line. * * $(TABLE_SV * $(SVH x, nextDown(x) ) * $(SV $(INFIN), real.max ) * $(SV $(PLUSMN)0.0, -real.min_normal*real.epsilon ) * $(SV -real.max, -$(INFIN) ) * $(SV -$(INFIN), -$(INFIN) ) * $(SV $(NAN), $(NAN) ) * ) */ real nextDown(real x) @safe pure nothrow @nogc { return -nextUp(-x); } /** ditto */ double nextDown(double x) @safe pure nothrow @nogc { return -nextUp(-x); } /** ditto */ float nextDown(float x) @safe pure nothrow @nogc { return -nextUp(-x); } unittest { assert( nextDown(1.0 + real.epsilon) == 1.0); } unittest { static if (floatTraits!(real).realFormat == RealFormat.ieeeExtended) { // Tests for 80-bit reals assert(isIdentical(nextUp(NaN(0xABC)), NaN(0xABC))); // negative numbers assert( nextUp(-real.infinity) == -real.max ); assert( nextUp(-1.0L-real.epsilon) == -1.0 ); assert( nextUp(-2.0L) == -2.0 + real.epsilon); // subnormals and zero assert( nextUp(-real.min_normal) == -real.min_normal*(1-real.epsilon) ); assert( nextUp(-real.min_normal*(1-real.epsilon)) == -real.min_normal*(1-2*real.epsilon) ); assert( isIdentical(-0.0L, nextUp(-real.min_normal*real.epsilon)) ); assert( nextUp(-0.0L) == real.min_normal*real.epsilon ); assert( nextUp(0.0L) == real.min_normal*real.epsilon ); assert( nextUp(real.min_normal*(1-real.epsilon)) == real.min_normal ); assert( nextUp(real.min_normal) == real.min_normal*(1+real.epsilon) ); // positive numbers assert( nextUp(1.0L) == 1.0 + real.epsilon ); assert( nextUp(2.0L-real.epsilon) == 2.0 ); assert( nextUp(real.max) == real.infinity ); assert( nextUp(real.infinity)==real.infinity ); } double n = NaN(0xABC); assert(isIdentical(nextUp(n), n)); // negative numbers assert( nextUp(-double.infinity) == -double.max ); assert( nextUp(-1-double.epsilon) == -1.0 ); assert( nextUp(-2.0) == -2.0 + double.epsilon); // subnormals and zero assert( nextUp(-double.min_normal) == -double.min_normal*(1-double.epsilon) ); assert( nextUp(-double.min_normal*(1-double.epsilon)) == -double.min_normal*(1-2*double.epsilon) ); assert( isIdentical(-0.0, nextUp(-double.min_normal*double.epsilon)) ); assert( nextUp(0.0) == double.min_normal*double.epsilon ); assert( nextUp(-0.0) == double.min_normal*double.epsilon ); assert( nextUp(double.min_normal*(1-double.epsilon)) == double.min_normal ); assert( nextUp(double.min_normal) == double.min_normal*(1+double.epsilon) ); // positive numbers assert( nextUp(1.0) == 1.0 + double.epsilon ); assert( nextUp(2.0-double.epsilon) == 2.0 ); assert( nextUp(double.max) == double.infinity ); float fn = NaN(0xABC); assert(isIdentical(nextUp(fn), fn)); float f = -float.min_normal*(1-float.epsilon); float f1 = -float.min_normal; assert( nextUp(f1) == f); f = 1.0f+float.epsilon; f1 = 1.0f; assert( nextUp(f1) == f ); f1 = -0.0f; assert( nextUp(f1) == float.min_normal*float.epsilon); assert( nextUp(float.infinity)==float.infinity ); assert(nextDown(1.0L+real.epsilon)==1.0); assert(nextDown(1.0+double.epsilon)==1.0); f = 1.0f+float.epsilon; assert(nextDown(f)==1.0); assert(nextafter(1.0+real.epsilon, -real.infinity)==1.0); } /****************************************** * Calculates the next representable value after x in the direction of y. * * If y > x, the result will be the next largest floating-point value; * if y < x, the result will be the next smallest value. * If x == y, the result is y. * * Remarks: * This function is not generally very useful; it's almost always better to use * the faster functions nextUp() or nextDown() instead. * * The FE_INEXACT and FE_OVERFLOW exceptions will be raised if x is finite and * the function result is infinite. The FE_INEXACT and FE_UNDERFLOW * exceptions will be raised if the function value is subnormal, and x is * not equal to y. */ T nextafter(T)(T x, T y) @safe pure nothrow @nogc { if (x == y) return y; return ((y>x) ? nextUp(x) : nextDown(x)); } unittest { float a = 1; assert(is(typeof(nextafter(a, a)) == float)); assert(nextafter(a, a.infinity) > a); double b = 2; assert(is(typeof(nextafter(b, b)) == double)); assert(nextafter(b, b.infinity) > b); real c = 3; assert(is(typeof(nextafter(c, c)) == real)); assert(nextafter(c, c.infinity) > c); } //real nexttoward(real x, real y) { return core.stdc.math.nexttowardl(x, y); } /******************************************* * Returns the positive difference between x and y. * Returns: * $(TABLE_SV * $(TR $(TH x, y) $(TH fdim(x, y))) * $(TR $(TD x $(GT) y) $(TD x - y)) * $(TR $(TD x $(LT)= y) $(TD +0.0)) * ) */ real fdim(real x, real y) @safe pure nothrow @nogc { return (x > y) ? x - y : +0.0; } /**************************************** * Returns the larger of x and y. */ real fmax(real x, real y) @safe pure nothrow @nogc { return x > y ? x : y; } /**************************************** * Returns the smaller of x and y. */ real fmin(real x, real y) @safe pure nothrow @nogc { return x < y ? x : y; } /************************************** * Returns (x * y) + z, rounding only once according to the * current rounding mode. * * BUGS: Not currently implemented - rounds twice. */ real fma(real x, real y, real z) @safe pure nothrow @nogc { return (x * y) + z; } /******************************************************************* * Compute the value of x $(SUP n), where n is an integer */ Unqual!F pow(F, G)(F x, G n) @nogc @trusted pure nothrow if (isFloatingPoint!(F) && isIntegral!(G)) { real p = 1.0, v = void; Unsigned!(Unqual!G) m = n; if (n < 0) { switch (n) { case -1: return 1 / x; case -2: return 1 / (x * x); default: } m = -n; v = p / x; } else { switch (n) { case 0: return 1.0; case 1: return x; case 2: return x * x; default: } v = x; } while (1) { if (m & 1) p *= v; m >>= 1; if (!m) break; v *= v; } return p; } unittest { // Make sure it instantiates and works properly on immutable values and // with various integer and float types. immutable real x = 46; immutable float xf = x; immutable double xd = x; immutable uint one = 1; immutable ushort two = 2; immutable ubyte three = 3; immutable ulong eight = 8; immutable int neg1 = -1; immutable short neg2 = -2; immutable byte neg3 = -3; immutable long neg8 = -8; assert(pow(x,0) == 1.0); assert(pow(xd,one) == x); assert(pow(xf,two) == x * x); assert(pow(x,three) == x * x * x); assert(pow(x,eight) == (x * x) * (x * x) * (x * x) * (x * x)); assert(pow(x, neg1) == 1 / x); version(X86_64) { pragma(msg, "test disabled on x86_64, see bug 5628"); } else version(ARM) { pragma(msg, "test disabled on ARM, see bug 5628"); } else { assert(pow(xd, neg2) == 1 / (x * x)); assert(pow(xf, neg8) == 1 / ((x * x) * (x * x) * (x * x) * (x * x))); } assert(feqrel(pow(x, neg3), 1 / (x * x * x)) >= real.mant_dig - 1); } unittest { assert(equalsDigit(pow(2.0L, 10.0L), 1024, 19)); } /** Compute the value of an integer x, raised to the power of a positive * integer n. * * If both x and n are 0, the result is 1. * If n is negative, an integer divide error will occur at runtime, * regardless of the value of x. */ typeof(Unqual!(F).init * Unqual!(G).init) pow(F, G)(F x, G n) @nogc @trusted pure nothrow if (isIntegral!(F) && isIntegral!(G)) { if (n<0) return x/0; // Only support positive powers typeof(return) p, v = void; Unqual!G m = n; switch (m) { case 0: p = 1; break; case 1: p = x; break; case 2: p = x * x; break; default: v = x; p = 1; while (1){ if (m & 1) p *= v; m >>= 1; if (!m) break; v *= v; } break; } return p; } unittest { immutable int one = 1; immutable byte two = 2; immutable ubyte three = 3; immutable short four = 4; immutable long ten = 10; assert(pow(two, three) == 8); assert(pow(two, ten) == 1024); assert(pow(one, ten) == 1); assert(pow(ten, four) == 10_000); assert(pow(four, 10) == 1_048_576); assert(pow(three, four) == 81); } /**Computes integer to floating point powers.*/ real pow(I, F)(I x, F y) @nogc @trusted pure nothrow if(isIntegral!I && isFloatingPoint!F) { return pow(cast(real) x, cast(Unqual!F) y); } /********************************************* * Calculates x$(SUP y). * * $(TABLE_SV * $(TR $(TH x) $(TH y) $(TH pow(x, y)) * $(TH div 0) $(TH invalid?)) * $(TR $(TD anything) $(TD $(PLUSMN)0.0) $(TD 1.0) * $(TD no) $(TD no) ) * $(TR $(TD |x| $(GT) 1) $(TD +$(INFIN)) $(TD +$(INFIN)) * $(TD no) $(TD no) ) * $(TR $(TD |x| $(LT) 1) $(TD +$(INFIN)) $(TD +0.0) * $(TD no) $(TD no) ) * $(TR $(TD |x| $(GT) 1) $(TD -$(INFIN)) $(TD +0.0) * $(TD no) $(TD no) ) * $(TR $(TD |x| $(LT) 1) $(TD -$(INFIN)) $(TD +$(INFIN)) * $(TD no) $(TD no) ) * $(TR $(TD +$(INFIN)) $(TD $(GT) 0.0) $(TD +$(INFIN)) * $(TD no) $(TD no) ) * $(TR $(TD +$(INFIN)) $(TD $(LT) 0.0) $(TD +0.0) * $(TD no) $(TD no) ) * $(TR $(TD -$(INFIN)) $(TD odd integer $(GT) 0.0) $(TD -$(INFIN)) * $(TD no) $(TD no) ) * $(TR $(TD -$(INFIN)) $(TD $(GT) 0.0, not odd integer) $(TD +$(INFIN)) * $(TD no) $(TD no)) * $(TR $(TD -$(INFIN)) $(TD odd integer $(LT) 0.0) $(TD -0.0) * $(TD no) $(TD no) ) * $(TR $(TD -$(INFIN)) $(TD $(LT) 0.0, not odd integer) $(TD +0.0) * $(TD no) $(TD no) ) * $(TR $(TD $(PLUSMN)1.0) $(TD $(PLUSMN)$(INFIN)) $(TD $(NAN)) * $(TD no) $(TD yes) ) * $(TR $(TD $(LT) 0.0) $(TD finite, nonintegral) $(TD $(NAN)) * $(TD no) $(TD yes)) * $(TR $(TD $(PLUSMN)0.0) $(TD odd integer $(LT) 0.0) $(TD $(PLUSMNINF)) * $(TD yes) $(TD no) ) * $(TR $(TD $(PLUSMN)0.0) $(TD $(LT) 0.0, not odd integer) $(TD +$(INFIN)) * $(TD yes) $(TD no)) * $(TR $(TD $(PLUSMN)0.0) $(TD odd integer $(GT) 0.0) $(TD $(PLUSMN)0.0) * $(TD no) $(TD no) ) * $(TR $(TD $(PLUSMN)0.0) $(TD $(GT) 0.0, not odd integer) $(TD +0.0) * $(TD no) $(TD no) ) * ) */ Unqual!(Largest!(F, G)) pow(F, G)(F x, G y) @nogc @trusted pure nothrow if (isFloatingPoint!(F) && isFloatingPoint!(G)) { alias Float = typeof(return); static real impl(real x, real y) @nogc pure nothrow { // Special cases. if (isNaN(y)) return y; if (isNaN(x) && y != 0.0) return x; // Even if x is NaN. if (y == 0.0) return 1.0; if (y == 1.0) return x; if (isInfinity(y)) { if (fabs(x) > 1) { if (signbit(y)) return +0.0; else return F.infinity; } else if (fabs(x) == 1) { return y * 0; // generate NaN. } else // < 1 { if (signbit(y)) return F.infinity; else return +0.0; } } if (isInfinity(x)) { if (signbit(x)) { long i = cast(long)y; if (y > 0.0) { if (i == y && i & 1) return -F.infinity; else return F.infinity; } else if (y < 0.0) { if (i == y && i & 1) return -0.0; else return +0.0; } } else { if (y > 0.0) return F.infinity; else if (y < 0.0) return +0.0; } } if (x == 0.0) { if (signbit(x)) { long i = cast(long)y; if (y > 0.0) { if (i == y && i & 1) return -0.0; else return +0.0; } else if (y < 0.0) { if (i == y && i & 1) return -F.infinity; else return F.infinity; } } else { if (y > 0.0) return +0.0; else if (y < 0.0) return F.infinity; } } if (x == 1.0) return 1.0; if (y >= F.max) { if ((x > 0.0 && x < 1.0) || (x > -1.0 && x < 0.0)) return 0.0; if (x > 1.0 || x < -1.0) return F.infinity; } if (y <= -F.max) { if ((x > 0.0 && x < 1.0) || (x > -1.0 && x < 0.0)) return F.infinity; if (x > 1.0 || x < -1.0) return 0.0; } if (x >= F.max) { if (y > 0.0) return F.infinity; else return 0.0; } if (x <= -F.max) { long i = cast(long)y; if (y > 0.0) { if (i == y && i & 1) return -F.infinity; else return F.infinity; } else if (y < 0.0) { if (i == y && i & 1) return -0.0; else return +0.0; } } // Integer power of x. long iy = cast(long)y; if (iy == y && fabs(y) < 32768.0) return pow(x, iy); double sign = 1.0; if (x < 0) { // Result is real only if y is an integer // Check for a non-zero fractional part if (y > -1.0 / real.epsilon && y < 1.0 / real.epsilon) { long w = cast(long)y; if (w != y) return sqrt(x); // Complex result -- create a NaN if (w & 1) sign = -1.0; } x = -x; } version(INLINE_YL2X) { // If x > 0, x ^^ y == 2 ^^ ( y * log2(x) ) // TODO: This is not accurate in practice. A fast and accurate // (though complicated) method is described in: // "An efficient rounding boundary test for pow(x, y) // in double precision", C.Q. Lauter and V. Lefèvre, INRIA (2007). return sign * exp2( yl2x(x, y) ); } else { // If x > 0, x ^^ y == 2 ^^ ( y * log2(x) ) // TODO: This is not accurate in practice. A fast and accurate // (though complicated) method is described in: // "An efficient rounding boundary test for pow(x, y) // in double precision", C.Q. Lauter and V. Lefèvre, INRIA (2007). Float w = exp2(y * log2(x)); return sign * w; } } return impl(x, y); } unittest { // Test all the special values. These unittests can be run on Windows // by temporarily changing the version(linux) to version(all). immutable float zero = 0; immutable real one = 1; immutable double two = 2; immutable float three = 3; immutable float fnan = float.nan; immutable double dnan = double.nan; immutable real rnan = real.nan; immutable dinf = double.infinity; immutable rninf = -real.infinity; assert(pow(fnan, zero) == 1); assert(pow(dnan, zero) == 1); assert(pow(rnan, zero) == 1); assert(pow(two, dinf) == double.infinity); assert(isIdentical(pow(0.2f, dinf), +0.0)); assert(pow(0.99999999L, rninf) == real.infinity); assert(isIdentical(pow(1.000000001, rninf), +0.0)); assert(pow(dinf, 0.001) == dinf); assert(isIdentical(pow(dinf, -0.001), +0.0)); assert(pow(rninf, 3.0L) == rninf); assert(pow(rninf, 2.0L) == real.infinity); assert(isIdentical(pow(rninf, -3.0), -0.0)); assert(isIdentical(pow(rninf, -2.0), +0.0)); // @@@BUG@@@ somewhere version(OSX) {} else assert(isNaN(pow(one, dinf))); version(OSX) {} else assert(isNaN(pow(-one, dinf))); assert(isNaN(pow(-0.2, PI))); // boundary cases. Note that epsilon == 2^^-n for some n, // so 1/epsilon == 2^^n is always even. assert(pow(-1.0L, 1/real.epsilon - 1.0L) == -1.0L); assert(pow(-1.0L, 1/real.epsilon) == 1.0L); assert(isNaN(pow(-1.0L, 1/real.epsilon-0.5L))); assert(isNaN(pow(-1.0L, -1/real.epsilon+0.5L))); assert(pow(0.0, -3.0) == double.infinity); assert(pow(-0.0, -3.0) == -double.infinity); assert(pow(0.0, -PI) == double.infinity); assert(pow(-0.0, -PI) == double.infinity); assert(isIdentical(pow(0.0, 5.0), 0.0)); assert(isIdentical(pow(-0.0, 5.0), -0.0)); assert(isIdentical(pow(0.0, 6.0), 0.0)); assert(isIdentical(pow(-0.0, 6.0), 0.0)); // Now, actual numbers. assert(approxEqual(pow(two, three), 8.0)); assert(approxEqual(pow(two, -2.5), 0.1767767)); // Test integer to float power. immutable uint twoI = 2; assert(approxEqual(pow(twoI, three), 8.0)); } /************************************** * To what precision is x equal to y? * * Returns: the number of mantissa bits which are equal in x and y. * eg, 0x1.F8p+60 and 0x1.F1p+60 are equal to 5 bits of precision. * * $(TABLE_SV * $(TR $(TH x) $(TH y) $(TH feqrel(x, y))) * $(TR $(TD x) $(TD x) $(TD real.mant_dig)) * $(TR $(TD x) $(TD $(GT)= 2*x) $(TD 0)) * $(TR $(TD x) $(TD $(LT)= x/2) $(TD 0)) * $(TR $(TD $(NAN)) $(TD any) $(TD 0)) * $(TR $(TD any) $(TD $(NAN)) $(TD 0)) * ) */ int feqrel(X)(X x, X y) @trusted pure nothrow @nogc if (isFloatingPoint!(X)) { /* Public Domain. Author: Don Clugston, 18 Aug 2005. */ alias F = floatTraits!(X); static if (F.realFormat == RealFormat.ibmExtended) { if (cast(double*)(&x)[MANTISSA_MSB] == cast(double*)(&y)[MANTISSA_MSB]) { return double.mant_dig + feqrel(cast(double*)(&x)[MANTISSA_LSB], cast(double*)(&y)[MANTISSA_LSB]); } else { return feqrel(cast(double*)(&x)[MANTISSA_MSB], cast(double*)(&y)[MANTISSA_MSB]); } } else { static assert (F.realFormat == RealFormat.ieeeSingle || F.realFormat == RealFormat.ieeeDouble || F.realFormat == RealFormat.ieeeExtended || F.realFormat == RealFormat.ieeeQuadruple); if (x == y) return X.mant_dig; // ensure diff!=0, cope with INF. X diff = fabs(x - y); ushort *pa = cast(ushort *)(&x); ushort *pb = cast(ushort *)(&y); ushort *pd = cast(ushort *)(&diff); // The difference in abs(exponent) between x or y and abs(x-y) // is equal to the number of significand bits of x which are // equal to y. If negative, x and y have different exponents. // If positive, x and y are equal to 'bitsdiff' bits. // AND with 0x7FFF to form the absolute value. // To avoid out-by-1 errors, we subtract 1 so it rounds down // if the exponents were different. This means 'bitsdiff' is // always 1 lower than we want, except that if bitsdiff==0, // they could have 0 or 1 bits in common. static if (F.realFormat == RealFormat.ieeeExtended || F.realFormat == RealFormat.ieeeQuadruple) { int bitsdiff = ( ((pa[F.EXPPOS_SHORT] & F.EXPMASK) + (pb[F.EXPPOS_SHORT] & F.EXPMASK) - 1) >> 1) - pd[F.EXPPOS_SHORT]; } else static if (F.realFormat == RealFormat.ieeeDouble) { int bitsdiff = (( ((pa[F.EXPPOS_SHORT]&0x7FF0) + (pb[F.EXPPOS_SHORT]&0x7FF0)-0x10)>>1) - (pd[F.EXPPOS_SHORT]&0x7FF0))>>4; } else static if (F.realFormat == RealFormat.ieeeSingle) { int bitsdiff = (( ((pa[F.EXPPOS_SHORT]&0x7F80) + (pb[F.EXPPOS_SHORT]&0x7F80)-0x80)>>1) - (pd[F.EXPPOS_SHORT]&0x7F80))>>7; } if ( (pd[F.EXPPOS_SHORT] & F.EXPMASK) == 0) { // Difference is subnormal // For subnormals, we need to add the number of zeros that // lie at the start of diff's significand. // We do this by multiplying by 2^^real.mant_dig diff *= F.RECIP_EPSILON; return bitsdiff + X.mant_dig - pd[F.EXPPOS_SHORT]; } if (bitsdiff > 0) return bitsdiff + 1; // add the 1 we subtracted before // Avoid out-by-1 errors when factor is almost 2. static if (F.realFormat == RealFormat.ieeeExtended || F.realFormat == RealFormat.ieeeQuadruple) { return (bitsdiff == 0) ? (pa[F.EXPPOS_SHORT] == pb[F.EXPPOS_SHORT]) : 0; } else static if (F.realFormat == RealFormat.ieeeDouble || F.realFormat == RealFormat.ieeeSingle) { if (bitsdiff == 0 && !((pa[F.EXPPOS_SHORT] ^ pb[F.EXPPOS_SHORT]) & F.EXPMASK)) { return 1; } else return 0; } } } unittest { void testFeqrel(F)() { // Exact equality assert(feqrel(F.max, F.max) == F.mant_dig); assert(feqrel!(F)(0.0, 0.0) == F.mant_dig); assert(feqrel(F.infinity, F.infinity) == F.mant_dig); // a few bits away from exact equality F w=1; for (int i = 1; i < F.mant_dig - 1; ++i) { assert(feqrel!(F)(1.0 + w * F.epsilon, 1.0) == F.mant_dig-i); assert(feqrel!(F)(1.0 - w * F.epsilon, 1.0) == F.mant_dig-i); assert(feqrel!(F)(1.0, 1 + (w-1) * F.epsilon) == F.mant_dig - i + 1); w*=2; } assert(feqrel!(F)(1.5+F.epsilon, 1.5) == F.mant_dig-1); assert(feqrel!(F)(1.5-F.epsilon, 1.5) == F.mant_dig-1); assert(feqrel!(F)(1.5-F.epsilon, 1.5+F.epsilon) == F.mant_dig-2); // Numbers that are close assert(feqrel!(F)(0x1.Bp+84, 0x1.B8p+84) == 5); assert(feqrel!(F)(0x1.8p+10, 0x1.Cp+10) == 2); assert(feqrel!(F)(1.5 * (1 - F.epsilon), 1.0L) == 2); assert(feqrel!(F)(1.5, 1.0) == 1); assert(feqrel!(F)(2 * (1 - F.epsilon), 1.0L) == 1); // Factors of 2 assert(feqrel(F.max, F.infinity) == 0); assert(feqrel!(F)(2 * (1 - F.epsilon), 1.0L) == 1); assert(feqrel!(F)(1.0, 2.0) == 0); assert(feqrel!(F)(4.0, 1.0) == 0); // Extreme inequality assert(feqrel(F.nan, F.nan) == 0); assert(feqrel!(F)(0.0L, -F.nan) == 0); assert(feqrel(F.nan, F.infinity) == 0); assert(feqrel(F.infinity, -F.infinity) == 0); assert(feqrel(F.max, -F.max) == 0); } assert(feqrel(7.1824L, 7.1824L) == real.mant_dig); static if (floatTraits!(real).realFormat == RealFormat.ieeeExtended) { assert(feqrel(real.min_normal / 8, real.min_normal / 17) == 3); } testFeqrel!(real)(); testFeqrel!(double)(); testFeqrel!(float)(); } package: // Not public yet /* Return the value that lies halfway between x and y on the IEEE number line. * * Formally, the result is the arithmetic mean of the binary significands of x * and y, multiplied by the geometric mean of the binary exponents of x and y. * x and y must have the same sign, and must not be NaN. * Note: this function is useful for ensuring O(log n) behaviour in algorithms * involving a 'binary chop'. * * Special cases: * If x and y are within a factor of 2, (ie, feqrel(x, y) > 0), the return value * is the arithmetic mean (x + y) / 2. * If x and y are even powers of 2, the return value is the geometric mean, * ieeeMean(x, y) = sqrt(x * y). * */ T ieeeMean(T)(T x, T y) @trusted pure nothrow @nogc in { // both x and y must have the same sign, and must not be NaN. assert(signbit(x) == signbit(y)); assert(x == x && y == y); } body { // Runtime behaviour for contract violation: // If signs are opposite, or one is a NaN, return 0. if (!((x>=0 && y>=0) || (x<=0 && y<=0))) return 0.0; // The implementation is simple: cast x and y to integers, // average them (avoiding overflow), and cast the result back to a floating-point number. alias F = floatTraits!(T); T u; static if (F.realFormat == RealFormat.ieeeExtended) { // There's slight additional complexity because they are actually // 79-bit reals... ushort *ue = cast(ushort *)&u; ulong *ul = cast(ulong *)&u; ushort *xe = cast(ushort *)&x; ulong *xl = cast(ulong *)&x; ushort *ye = cast(ushort *)&y; ulong *yl = cast(ulong *)&y; // Ignore the useless implicit bit. (Bonus: this prevents overflows) ulong m = ((*xl) & 0x7FFF_FFFF_FFFF_FFFFL) + ((*yl) & 0x7FFF_FFFF_FFFF_FFFFL); // @@@ BUG? @@@ // Cast shouldn't be here ushort e = cast(ushort) ((xe[F.EXPPOS_SHORT] & F.EXPMASK) + (ye[F.EXPPOS_SHORT] & F.EXPMASK)); if (m & 0x8000_0000_0000_0000L) { ++e; m &= 0x7FFF_FFFF_FFFF_FFFFL; } // Now do a multi-byte right shift uint c = e & 1; // carry e >>= 1; m >>>= 1; if (c) m |= 0x4000_0000_0000_0000L; // shift carry into significand if (e) *ul = m | 0x8000_0000_0000_0000L; // set implicit bit... else *ul = m; // ... unless exponent is 0 (subnormal or zero). ue[4]= e | (xe[F.EXPPOS_SHORT]& 0x8000); // restore sign bit } else static if (F.realFormat == RealFormat.ieeeQuadruple) { // This would be trivial if 'ucent' were implemented... ulong *ul = cast(ulong *)&u; ulong *xl = cast(ulong *)&x; ulong *yl = cast(ulong *)&y; // Multi-byte add, then multi-byte right shift. ulong mh = ((xl[MANTISSA_MSB] & 0x7FFF_FFFF_FFFF_FFFFL) + (yl[MANTISSA_MSB] & 0x7FFF_FFFF_FFFF_FFFFL)); // Discard the lowest bit (to avoid overflow) ulong ml = (xl[MANTISSA_LSB]>>>1) + (yl[MANTISSA_LSB]>>>1); // add the lowest bit back in, if necessary. if (xl[MANTISSA_LSB] & yl[MANTISSA_LSB] & 1) { ++ml; if (ml == 0) ++mh; } mh >>>=1; ul[MANTISSA_MSB] = mh | (xl[MANTISSA_MSB] & 0x8000_0000_0000_0000); ul[MANTISSA_LSB] = ml; } else static if (F.realFormat == RealFormat.ieeeDouble) { ulong *ul = cast(ulong *)&u; ulong *xl = cast(ulong *)&x; ulong *yl = cast(ulong *)&y; ulong m = (((*xl) & 0x7FFF_FFFF_FFFF_FFFFL) + ((*yl) & 0x7FFF_FFFF_FFFF_FFFFL)) >>> 1; m |= ((*xl) & 0x8000_0000_0000_0000L); *ul = m; } else static if (F.realFormat == RealFormat.ieeeSingle) { uint *ul = cast(uint *)&u; uint *xl = cast(uint *)&x; uint *yl = cast(uint *)&y; uint m = (((*xl) & 0x7FFF_FFFF) + ((*yl) & 0x7FFF_FFFF)) >>> 1; m |= ((*xl) & 0x8000_0000); *ul = m; } else { assert(0, "Not implemented"); } return u; } unittest { assert(ieeeMean(-0.0,-1e-20)<0); assert(ieeeMean(0.0,1e-20)>0); assert(ieeeMean(1.0L,4.0L)==2L); assert(ieeeMean(2.0*1.013,8.0*1.013)==4*1.013); assert(ieeeMean(-1.0L,-4.0L)==-2L); assert(ieeeMean(-1.0,-4.0)==-2); assert(ieeeMean(-1.0f,-4.0f)==-2f); assert(ieeeMean(-1.0,-2.0)==-1.5); assert(ieeeMean(-1*(1+8*real.epsilon),-2*(1+8*real.epsilon)) ==-1.5*(1+5*real.epsilon)); assert(ieeeMean(0x1p60,0x1p-10)==0x1p25); static if (floatTraits!(real).realFormat == RealFormat.ieeeExtended) { assert(ieeeMean(1.0L,real.infinity)==0x1p8192L); assert(ieeeMean(0.0L,real.infinity)==1.5); } assert(ieeeMean(0.5*real.min_normal*(1-4*real.epsilon),0.5*real.min_normal) == 0.5*real.min_normal*(1-2*real.epsilon)); } public: /*********************************** * Evaluate polynomial A(x) = $(SUB a, 0) + $(SUB a, 1)x + $(SUB a, 2)$(POWER x,2) * + $(SUB a,3)$(POWER x,3); ... * * Uses Horner's rule A(x) = $(SUB a, 0) + x($(SUB a, 1) + x($(SUB a, 2) * + x($(SUB a, 3) + ...))) * Params: * x = the value to evaluate. * A = array of coefficients $(SUB a, 0), $(SUB a, 1), etc. */ real poly(real x, const real[] A) @trusted pure nothrow @nogc in { assert(A.length > 0); } body { version (D_InlineAsm_X86) { version (Windows) { // BUG: This code assumes a frame pointer in EBP. asm // assembler by W. Bright { // EDX = (A.length - 1) * real.sizeof mov ECX,A[EBP] ; // ECX = A.length dec ECX ; lea EDX,[ECX][ECX*8] ; add EDX,ECX ; add EDX,A+4[EBP] ; fld real ptr [EDX] ; // ST0 = coeff[ECX] jecxz return_ST ; fld x[EBP] ; // ST0 = x fxch ST(1) ; // ST1 = x, ST0 = r align 4 ; L2: fmul ST,ST(1) ; // r *= x fld real ptr -10[EDX] ; sub EDX,10 ; // deg-- faddp ST(1),ST ; dec ECX ; jne L2 ; fxch ST(1) ; // ST1 = r, ST0 = x fstp ST(0) ; // dump x align 4 ; return_ST: ; ; } } else version (linux) { asm // assembler by W. Bright { // EDX = (A.length - 1) * real.sizeof mov ECX,A[EBP] ; // ECX = A.length dec ECX ; lea EDX,[ECX*8] ; lea EDX,[EDX][ECX*4] ; add EDX,A+4[EBP] ; fld real ptr [EDX] ; // ST0 = coeff[ECX] jecxz return_ST ; fld x[EBP] ; // ST0 = x fxch ST(1) ; // ST1 = x, ST0 = r align 4 ; L2: fmul ST,ST(1) ; // r *= x fld real ptr -12[EDX] ; sub EDX,12 ; // deg-- faddp ST(1),ST ; dec ECX ; jne L2 ; fxch ST(1) ; // ST1 = r, ST0 = x fstp ST(0) ; // dump x align 4 ; return_ST: ; ; } } else version (OSX) { asm // assembler by W. Bright { // EDX = (A.length - 1) * real.sizeof mov ECX,A[EBP] ; // ECX = A.length dec ECX ; lea EDX,[ECX*8] ; add EDX,EDX ; add EDX,A+4[EBP] ; fld real ptr [EDX] ; // ST0 = coeff[ECX] jecxz return_ST ; fld x[EBP] ; // ST0 = x fxch ST(1) ; // ST1 = x, ST0 = r align 4 ; L2: fmul ST,ST(1) ; // r *= x fld real ptr -16[EDX] ; sub EDX,16 ; // deg-- faddp ST(1),ST ; dec ECX ; jne L2 ; fxch ST(1) ; // ST1 = r, ST0 = x fstp ST(0) ; // dump x align 4 ; return_ST: ; ; } } else version (FreeBSD) { asm // assembler by W. Bright { // EDX = (A.length - 1) * real.sizeof mov ECX,A[EBP] ; // ECX = A.length dec ECX ; lea EDX,[ECX*8] ; lea EDX,[EDX][ECX*4] ; add EDX,A+4[EBP] ; fld real ptr [EDX] ; // ST0 = coeff[ECX] jecxz return_ST ; fld x[EBP] ; // ST0 = x fxch ST(1) ; // ST1 = x, ST0 = r align 4 ; L2: fmul ST,ST(1) ; // r *= x fld real ptr -12[EDX] ; sub EDX,12 ; // deg-- faddp ST(1),ST ; dec ECX ; jne L2 ; fxch ST(1) ; // ST1 = r, ST0 = x fstp ST(0) ; // dump x align 4 ; return_ST: ; ; } } else { static assert(0); } } else { ptrdiff_t i = A.length - 1; real r = A[i]; while (--i >= 0) { r *= x; r += A[i]; } return r; } } unittest { debug (math) printf("math.poly.unittest\n"); real x = 3.1; static real[] pp = [56.1, 32.7, 6]; assert( poly(x, pp) == (56.1L + (32.7L + 6L * x) * x) ); } /** Computes whether $(D lhs) is approximately equal to $(D rhs) admitting a maximum relative difference $(D maxRelDiff) and a maximum absolute difference $(D maxAbsDiff). If the two inputs are ranges, $(D approxEqual) returns true if and only if the ranges have the same number of elements and if $(D approxEqual) evaluates to $(D true) for each pair of elements. */ bool approxEqual(T, U, V)(T lhs, U rhs, V maxRelDiff, V maxAbsDiff = 1e-5) { import std.range; static if (isInputRange!T) { static if (isInputRange!U) { // Two ranges for (;; lhs.popFront(), rhs.popFront()) { if (lhs.empty) return rhs.empty; if (rhs.empty) return lhs.empty; if (!approxEqual(lhs.front, rhs.front, maxRelDiff, maxAbsDiff)) return false; } } else { // lhs is range, rhs is number for (; !lhs.empty; lhs.popFront()) { if (!approxEqual(lhs.front, rhs, maxRelDiff, maxAbsDiff)) return false; } return true; } } else { static if (isInputRange!U) { // lhs is number, rhs is array return approxEqual(rhs, lhs, maxRelDiff, maxAbsDiff); } else { // two numbers //static assert(is(T : real) && is(U : real)); if (rhs == 0) { return fabs(lhs) <= maxAbsDiff; } static if (is(typeof(lhs.infinity)) && is(typeof(rhs.infinity))) { if (lhs == lhs.infinity && rhs == rhs.infinity || lhs == -lhs.infinity && rhs == -rhs.infinity) return true; } return fabs((lhs - rhs) / rhs) <= maxRelDiff || maxAbsDiff != 0 && fabs(lhs - rhs) <= maxAbsDiff; } } } /** Returns $(D approxEqual(lhs, rhs, 1e-2, 1e-5)). */ bool approxEqual(T, U)(T lhs, U rhs) { return approxEqual(lhs, rhs, 1e-2, 1e-5); } unittest { assert(approxEqual(1.0, 1.0099)); assert(!approxEqual(1.0, 1.011)); float[] arr1 = [ 1.0, 2.0, 3.0 ]; double[] arr2 = [ 1.001, 1.999, 3 ]; assert(approxEqual(arr1, arr2)); real num = real.infinity; assert(num == real.infinity); // Passes. assert(approxEqual(num, real.infinity)); // Fails. num = -real.infinity; assert(num == -real.infinity); // Passes. assert(approxEqual(num, -real.infinity)); // Fails. } // Included for backwards compatibility with Phobos1 alias isnan = isNaN; alias isfinite = isFinite; alias isnormal = isNormal; alias issubnormal = isSubnormal; alias isinf = isInfinity; /* ********************************** * Building block functions, they * translate to a single x87 instruction. */ real yl2x(real x, real y) @nogc @safe pure nothrow; // y * log2(x) real yl2xp1(real x, real y) @nogc @safe pure nothrow; // y * log2(x + 1) unittest { version (INLINE_YL2X) { assert(yl2x(1024, 1) == 10); assert(yl2xp1(1023, 1) == 10); } } unittest { real num = real.infinity; assert(num == real.infinity); // Passes. assert(approxEqual(num, real.infinity)); // Fails. } unittest { float f = sqrt(2.0f); assert(fabs(f * f - 2.0f) < .00001); double d = sqrt(2.0); assert(fabs(d * d - 2.0) < .00001); real r = sqrt(2.0L); assert(fabs(r * r - 2.0) < .00001); } unittest { float f = fabs(-2.0f); assert(f == 2); double d = fabs(-2.0); assert(d == 2); real r = fabs(-2.0L); assert(r == 2); } unittest { float f = sin(-2.0f); assert(fabs(f - -0.909297f) < .00001); double d = sin(-2.0); assert(fabs(d - -0.909297f) < .00001); real r = sin(-2.0L); assert(fabs(r - -0.909297f) < .00001); } unittest { float f = cos(-2.0f); assert(fabs(f - -0.416147f) < .00001); double d = cos(-2.0); assert(fabs(d - -0.416147f) < .00001); real r = cos(-2.0L); assert(fabs(r - -0.416147f) < .00001); } unittest { float f = tan(-2.0f); assert(fabs(f - 2.18504f) < .00001); double d = tan(-2.0); assert(fabs(d - 2.18504f) < .00001); real r = tan(-2.0L); assert(fabs(r - 2.18504f) < .00001); } @safe pure nothrow unittest { // issue 6381: floor/ceil should be usable in pure function. auto x = floor(1.2); auto y = ceil(1.2); }
D
/******************************************************************************* Helper struct for client-side suspendable requests which behave as follows: * Operate on all nodes. * Receive a stream of data, broken down into individual messages. * The stream can be suspended, resumed, and stopped by the user. These actions are known as "state changes". * While a state change is in progress, the user is unable to request another state change. * State changes are initiated by the user via a "controller" -- an interface to the active request, allowing it to be controlled while in progress. The struct handles all state change logic and communication with the node (on a per-request-on-conn basis). Request specifics such as codes and messages sent back and forth between the client and node are left deliberately abstract and must be provided by the request implementation which uses this helper. Each request-on-conn should have an instance of SuspendableRequest. The request's shared working data should contain an instance of the nested struct SuspendableRequest.SharedWorking. A note about the state handling methods: As control is sometimes given over to the caller, via the delegates that these methods use, it is possible that the user may have the opportunity to use the request controller while a method of SuspendableRequest is in progress. This possibility is handled, internally, by remembering the desired state at the beginning of the method and checking whether it's changed. Copyright: Copyright (c) 2016-2017 sociomantic labs GmbH. All rights reserved License: Boost Software License Version 1.0. See LICENSE_BOOST.txt for details. *******************************************************************************/ deprecated module swarm.neo.client.helper.SuspendableRequest; /// ditto deprecated("Adapt your request to use RequestEventDispatcher and multiple fibers " "instead. See swarm.neo.client.mixins.SuspendableRequestCore") struct SuspendableRequest { import ocean.transition; import swarm.neo.client.RequestOnConn; import swarm.neo.request.Command; /*************************************************************************** Shared working data required for a suspendable request. An instance of this struct should be placed in your request's shared working data struct, where it is accessible to all request-on-conns of the request. All fields of this struct pertain to the request, not to any individual request-on-conn! ***************************************************************************/ public static struct SharedWorking { /*********************************************************************** Possible states of the request. ***********************************************************************/ public enum RequestState { None, Running, Suspended, Stopped } public RequestState desired_state = RequestState.Running; /*********************************************************************** The number of request-on-conns that are currently waiting for an acknowledgement message from the node after the request was started or its state changed. Changing the request state is possible if and only if this number is 0. ***********************************************************************/ private uint waiting_for_ack_count; /*********************************************************************** The number of request-on-conns which have successfully initialised the request (and are thus ready to send state change messages to the node). ***********************************************************************/ private uint initialised_count; /*********************************************************************** Set to true when the request has been successfully initialised on all active request-on-conns for the first time. ***********************************************************************/ private bool first_initialisation; /*********************************************************************** Changes the desired state to that specified, if it is currently possible to change the request's state (i.e. all request-on-conns have initialised the request and are not waiting for an ACK for a previous state change). Sets the desired state flag and resumes any request-on-conn fibers which are suspended, via the provided delegate (which should resume the fiber with a predetermined control message so that in the fiber the resumed suspend() call returns that message). If one or more connections are not ready to change state, the control change does not occur. A connection is ready to change the request state unless the handler is currently waiting for an acknowledgement message when beginning the request or changing its state. Params: new_state = desired state begin_state_change = delegate called when the state change may be initiated. The delegate must resume any handler fibers which are suspended, passing a predetermined control message flag to the fiber via the return value of suspend() state_changed = delegate called when no request-on-conns are ready to change state. The delegate should notify the user that the state change has been carried out. (The reason for this behaviour if no request-on-conns are ready is that the the request will be initialised in the desired state, when the connection is ready. See initialiseRequest().) Returns: true if the state change has been accepted and will be sent to all active nodes, false if one or more connections is already in the middle of changing state ***********************************************************************/ public bool setDesiredState ( RequestState new_state, void delegate ( ) begin_state_change, void delegate ( ) state_changed ) { // It's illegal to change the state while still waiting for an ACK // on the last state change. if ( this.waiting_for_ack_count ) return false; this.desired_state = new_state; // If one or more connections are ready to send a state change // message to the node, we initiate this. if ( this.initialised_count ) { begin_state_change(); } // If no connections are ready to send state change messages (i.e. // the request has not begun on those connections), the state change // essentially occurs immediately (without the need for node // contact). else { state_changed(); } return true; } } /*************************************************************************** Note: all subsequent members of this struct pertain to an individual request-on-conn. ***************************************************************************/ /*************************************************************************** Event dispatcher for this request-on-conn. ***************************************************************************/ private RequestOnConn.EventDispatcherAllNodes conn; /*************************************************************************** Pointer to the shared working data for this request. ***************************************************************************/ private SharedWorking* shared_working; /*************************************************************************** Set when the request has been successfully initialised on this connection (in initialiseRequest()). State changes are allowed after this point. (The actual purpose of this flag is for setNotReadyForStateChange() to tell whether shared_working.initialised_count was already decremented.) ***************************************************************************/ private bool ready_for_state_change; /*************************************************************************** Enum defining the states in which a request-on-conn of a suspendable request may be. ***************************************************************************/ public enum State { /// Waiting for the connection to come up EstablishingConnection, /// Initialising the request on this connection Initialising, /// In the main loop of receiving data from the node Receiving, /// Sending a message to the node to initiate a state change RequestingStateChange, /// Request finished on this connection Exit } /*************************************************************************** Enum defining the actions which a message received from the node may trigger. ***************************************************************************/ public enum ReceivedMessageAction { /// The received message was of an unknown type Undefined, /// The received message contained an acknowledgement from the node that /// a requested state change has taken effect Ack, /// The received message indicates that the request should end on this /// connection Exit, /// The received message indicates that no action need be taken Continue } /*************************************************************************** Alias for a delegate which handles a received message and returns a decision on what action need be taken. ***************************************************************************/ private alias ReceivedMessageAction delegate ( Const!(void)[] received ) ReceivedMessageDg; /*************************************************************************** Initialises this instance. Params: conn = event dispatcher for this request-on-conn shared_working = pointer to the shared working data for this request ***************************************************************************/ public void initialise ( RequestOnConn.EventDispatcherAllNodes conn, SharedWorking* shared_working ) in { assert(conn !is null); assert(shared_working !is null); } body { this.conn = conn; this.shared_working = shared_working; } /*************************************************************************** Waits for the connection to be established. (May exit immediately, if the connection is already up.) Params: resumed_by_controller = delegate called to determine whether the call to conn.waitForReconnect() exited because the request-on-conn fiber was resumed by the controller (at the user's behest). In this case, we usually continue trying to connect. Returns: the next state to enter (normally Initialising; may also be Exit, if the user instructed the request to stop, via the controller) ***************************************************************************/ public State establishConnection ( bool delegate ( int resume_code ) resumed_by_controller ) { while ( true ) { int resume_code = this.conn.waitForReconnect(); if ( resumed_by_controller(resume_code) ) { if ( this.shared_working.desired_state == this.shared_working.desired_state.Stopped ) // The user requested to stop this request, so we don't // need to wait for a reconnection any more. return State.Exit; } else { switch ( resume_code ) { case conn.FiberResumeCodeReconnected: case 0: // The connection is already up return State.Initialising; default: assert(false, "Unexpected fiber resume code when connecting"); } } } assert(false); } /*************************************************************************** Initialises the request on this connection, sending the required messages (e.g. the request code, channel name, etc) to the node and receiving a status code in response. Params: set_payload = delegate which should set the message payload to send to the node to initialise the request received_status_ok = delegate which determines whether the status code received from the node means that the request should continue or exit (true = continue, false = exit) first_initialisation = delegate which is called when the request is successfully initialised for the first time on all active connections. (Presumably the user should be informed of this.) Returns: the next state to enter (normally Receiving; may be Exit, if the status code received from the node indicated an error; may be RequestingStateChange, if the user requested a state change in one of the delegates which is called) ***************************************************************************/ public State initialiseRequest ( void delegate ( RequestOnConn.EventDispatcherAllNodes.Payload ) set_payload, bool delegate ( StatusCode ) received_status_ok, void delegate ( ) first_initialisation ) in { assert(!this.ready_for_state_change); } out ( state ) { if (state == state.Exit) assert(!this.ready_for_state_change); else assert(this.ready_for_state_change); } body { // Memorize the state that will be sent to the node in order to detect a // requested state change in one of the delegates. auto last_state = this.shared_working.desired_state; try { // establishConnection() should guarantee we're already connected assert(this.conn.waitForReconnect() == 0); // We know that the connection is up, so from now on we count this // request-on-conn as being in the state of waiting for an // acknowledgement from the node (the status code, in this case). this.shared_working.waiting_for_ack_count++; // Send request initialisation data to the node this.conn.send(set_payload); // Receive status from node and stop the request if not Ok auto status = this.conn.receiveValue!(StatusCode)(); if ( !received_status_ok(status) ) { return State.Exit; } } finally { // After receiving the status (whether an error or OK), this // request-on-conn is no longer counted as waiting for an ack. assert(this.shared_working.waiting_for_ack_count); --this.shared_working.waiting_for_ack_count; } // Now we're ready to receive records from the node or to handle state // change requests from the user via the controller. this.setReadyForStateChange(); // Handle first initialisation notification if ( !this.shared_working.first_initialisation && !this.shared_working.waiting_for_ack_count ) { this.shared_working.first_initialisation = true; first_initialisation(); } // Return the next state, handling the case where the desired state of // the request has changed since the start of this method. return (last_state == this.shared_working.desired_state) ? State.Receiving : State.RequestingStateChange; } /*************************************************************************** Receives incoming messages from the node. Params: handle_received_message = delegate to which received messages are passed. The return value determines whether the request continues receiving, begins changing state, or exits. Returns: the next state to enter (normally Receiving; may be RequestingStateChange or Exit) Throws: ProtocolError, if handle_received_message returns Undefined or Ack (it's important that the caller does not swallow this exception) ***************************************************************************/ public State receive ( ReceivedMessageDg handle_received_message ) { // Memorize the current desired state in order to detect a requested // state change in the delegate. auto last_state = this.shared_working.desired_state; ReceivedMessageAction msg_action; int resume_code = this.conn.receiveAndHandleEvents( ( in void[] received ) { msg_action = handle_received_message(received); } ); if ( resume_code < 0 ) // Fiber resumed due to received data { with ( ReceivedMessageAction ) switch ( msg_action ) { case Exit: return State.Exit; case Continue: break; default: throw this.conn.shutdownWithProtocolError( "Unexpected message type while receiving"); } } return (last_state == this.shared_working.desired_state) ? State.Receiving : State.RequestingStateChange; } /*************************************************************************** Sends a request state change message to the node and waits for the acknowledgement, handling records arriving in the mean time, as normal. If the node connection breaks while sending the state change message or receiving the acknowledgement, the state change was successful because the request-on-conn will be restarted with the requested state. Params: control_msg = message to send to the node to initiate the state change handle_received_message = delegate to which messages received while changing state are passed. The return value determines whether the request continues receiving or exits. state_changed = delegate called when the state change has been carried out Returns: the next state to enter (normally Receiving; may be Exit, if the desired state is Stopped; may be RequestingStateChange again, if the desired state changed while calling the state_changed delegate) Throws: ProtocolError, if handle_received_message returns an unexpected value (see sendStateChangeMessage() and waitForAck()). (It's important that the caller does not swallow this exception.) ***************************************************************************/ public State requestStateChange ( ubyte control_msg, ReceivedMessageDg handle_received_message, void delegate ( ) state_changed ) { this.shared_working.waiting_for_ack_count++; // Memorize the state that will be sent to the node in order to detect a // requested state change in the state_change delegate. auto signaled_state = this.shared_working.desired_state; try { // If throwing, set this request not ready for a state change // *before* calling state_change() in the `finally` clause, where // the user may request a state change. scope (failure) this.setNotReadyForStateChange(); if ( !this.sendStateChangeMessage(control_msg, handle_received_message) ) return State.Exit; if ( !this.waitForAck(handle_received_message) ) return State.Exit; } finally { assert(this.shared_working.waiting_for_ack_count); if ( !--this.shared_working.waiting_for_ack_count ) { // If this was the last request-on-conn waiting for the // acknowledgement, inform the caller that the requested control // message has taken effect. state_changed(); } } // Handle further state change requests that happened during this // method. if ( this.shared_working.desired_state != signaled_state ) return State.RequestingStateChange; return (signaled_state == signaled_state.Stopped) ? State.Exit : State.Receiving; } /*************************************************************************** Sends a request state change message to the node and handles records which arrive in the mean time, as normal. Params: control_msg = message to send to the node to initiate the state change handle_received_message = delegate to which messages received while changing state are passed. The return value determines whether the request continues or exits. Returns: true to continue changing state, false to exit Throws: ProtocolError, if handle_received_message returns Undefined or Ack (it's important that the caller does not swallow this exception) ***************************************************************************/ private bool sendStateChangeMessage ( ubyte control_msg, ReceivedMessageDg handle_received_message ) { bool send_interrupted; do { // Though the controller may be called at this point (via the call // to handle_received_message()), we do not check for state changes // as the controller enforces that a state change may not be // requested while the last is in progress. (See // SharedWorking.setDesiredState().) ReceivedMessageAction msg_action; send_interrupted = false; this.conn.sendReceive( ( in void[] received ) { send_interrupted = true; msg_action = handle_received_message(received); }, ( conn.Payload payload ) { payload.add(control_msg); } ); this.conn.flush(); if ( !send_interrupted ) // The control message was sent break; with ( ReceivedMessageAction ) switch ( msg_action ) { case Exit: return false; case Continue: break; default: throw this.conn.shutdownWithProtocolError( "Unexpected message type while sending state change"); } } while ( send_interrupted ); return true; } /*************************************************************************** Waits for the acknowledgement of a state change and handles records which arrive in the mean time, as normal. Params: handle_received_message = delegate to which messages received while changing state are passed. The return value determines whether the request continues or exits. Returns: true to continue changing state, false to exit Throws: ProtocolError, if handle_received_message returns Undefined (it's important that the caller does not swallow this exception) ***************************************************************************/ private bool waitForAck ( ReceivedMessageDg handle_received_message ) { bool ack; do { ReceivedMessageAction msg_action; int resume_code = this.conn.receiveAndHandleEvents( ( in void[] received ) { msg_action = handle_received_message(received); } ); assert(resume_code <= 0, "Fiber unexpectedly resumed"); with ( ReceivedMessageAction ) switch ( msg_action ) { case Exit: return false; case Continue: break; case Ack: ack = true; break; default: throw this.conn.shutdownWithProtocolError( "Unexpected message type while awaiting ACK"); } } while ( !ack ); return true; } /*************************************************************************** Flags this request-on-conn as ready to handle state changes and increments the global (for this request) counter of the number of request-on-conns which are ready for state changes. ***************************************************************************/ private void setReadyForStateChange ( ) { this.ready_for_state_change = true; this.shared_working.initialised_count++; } /*************************************************************************** If this request-on-conn is flagged as ready for state changes, sets it as not ready and decrements the global (for this request) counter of the number of request-on-conns which are ready for state changes. This method is public as it needs to be called from the request-on-conn handler when the request state machine throws or exits. (TODO: I wonder if this can be reworked so that it doesn't need to be public.) ***************************************************************************/ public void setNotReadyForStateChange ( ) { if ( this.ready_for_state_change ) { assert(this.shared_working.initialised_count); this.shared_working.initialised_count--; this.ready_for_state_change = false; } } }
D
E: c255, c205, c106, c367, c201, c326, c18, c34, c142, c101, c306, c365, c146, c166, c233, c317, c157, c70, c211, c47, c92, c409, c82, c406, c371, c40, c160, c325, c49, c65, c144, c213, c329, c170, c66, c432, c136, c324, c27, c246, c369, c426, c429, c86, c364, c321, c286, c99, c298, c250, c263, c224, c89, c339, c344, c425, c241, c69, c60, c361, c359, c377, c378, c333, c273, c335, c90, c292, c148, c58, c20, c348, c362, c275, c59, c312, c302, c200, c214, c242, c240, c174, c399, c209, c238, c39, c421, c163, c155, c158, c152, c343, c380, c430, c117, c68, c227, c418, c38, c296, c254, c232, c215, c137, c350, c358, c386, c138, c262, c103, c291, c387, c366, c319, c196, c143, c236, c416, c342, c391, c175, c264, c118, c268. p4(E,E) c255,c205 c367,c201 c326,c18 c326,c34 c101,c367 c306,c365 c146,c166 c326,c233 c317,c317 c157,c70 c211,c47 c92,c409 c146,c18 c92,c82 c142,c406 c326,c201 c367,c367 c371,c40 c160,c40 c157,c367 c325,c49 c213,c365 c142,c201 c211,c70 c213,c329 c432,c18 c136,c409 c146,c326 c325,c324 c317,c34 c371,c201 c317,c27 c146,c34 c306,c34 c371,c426 c325,c317 c429,c409 c157,c365 c86,c233 c364,c426 c326,c409 c367,c298 c432,c406 c211,c326 c92,c367 c326,c324 c213,c27 c86,c40 c371,c317 c432,c27 c106,c263 c224,c49 c429,c47 c92,c317 c142,c40 c326,c365 c432,c34 c142,c18 c157,c47 c317,c324 c157,c18 c224,c166 c211,c201 c86,c326 c364,c321 c101,c82 c429,c49 c317,c40 c326,c426 c306,c317 c142,c329 c142,c377 c325,c233 c378,c329 c364,c324 c213,c298 c146,c377 c371,c377 c213,c324 c136,c324 c371,c298 c371,c82 c142,c233 c160,c365 c170,c365 c317,c201 c160,c34 c317,c70 c273,c335 c364,c40 c224,c409 c325,c34 c142,c409 c325,c47 c157,c82 c157,c326 c224,c426 c429,c34 c157,c329 c213,c409 c378,c49 c429,c70 c364,c233 c211,c233 c101,c201 c86,c70 c170,c70 c211,c40 c325,c365 c359,c40 c429,c298 c142,c49 c367,c324 c101,c377 c326,c298 c317,c49 c306,c47 c211,c406 c142,c365 c359,c233 c170,c426 c86,c409 c371,c324 c364,c326 c359,c70 c364,c298 c170,c326 c157,c324 c378,c324 c213,c166 c432,c426 c378,c47 c317,c409 c142,c166 c160,c82 c306,c18 c326,c367 c378,c367 c213,c406 c136,c406 c224,c70 c325,c166 c306,c49 c155,c158 c211,c27 c326,c82 c306,c326 c367,c426 c430,c117 c432,c47 c306,c367 c224,c329 c429,c18 c92,c201 c317,c298 c306,c426 c86,c324 c211,c317 c86,c47 c325,c82 c117,c430 c325,c377 c157,c34 c101,c324 c367,c82 c146,c233 c146,c49 c429,c166 c326,c47 c92,c70 c359,c27 c224,c82 c170,c317 c432,c365 c359,c317 c211,c426 c371,c233 c146,c201 c317,c329 c136,c82 c146,c365 c364,c367 c92,c324 c92,c34 c306,c201 c359,c406 c146,c426 c429,c326 c146,c329 c326,c329 c68,c174 c92,c18 c101,c298 c432,c317 c211,c18 c317,c406 c432,c377 c211,c49 c263,c106 c92,c298 c378,c82 c224,c298 c429,c317 c157,c166 c326,c317 c101,c317 c136,c70 c142,c82 c157,c377 c367,c329 c432,c201 c211,c166 c359,c166 c160,c329 c364,c365 c364,c166 c306,c409 c378,c70 c306,c406 c359,c365 c371,c326 c306,c298 c213,c49 c160,c406 c306,c233 c432,c329 c367,c34 c367,c18 c136,c18 c101,c18 c378,c326 c213,c34 c306,c27 c170,c406 c364,c27 c160,c298 c157,c298 c157,c233 c306,c324 c432,c49 c101,c47 c371,c367 c306,c70 c86,c317 c359,c201 c432,c324 c367,c365 c211,c409 c170,c367 c136,c367 c170,c166 c92,c326 c378,c365 c224,c40 c101,c406 c86,c426 c170,c34 c170,c324 c364,c406 c364,c49 c86,c49 c432,c409 c317,c166 c101,c40 c367,c377 c325,c409 c170,c49 c224,c233 c224,c377 c378,c18 c92,c406 c142,c34 c101,c326 c213,c317 c224,c47 c142,c324 c306,c377 c317,c18 c326,c406 c160,c233 c160,c201 c371,c365 c378,c34 c306,c40 c364,c329 c367,c166 c101,c34 c136,c40 c367,c70 c160,c317 c364,c70 c160,c166 c321,c364 c142,c317 c325,c18 c378,c377 c157,c426 c359,c49 c325,c27 c213,c18 c224,c27 c146,c40 c142,c47 c101,c426 c158,c155 c326,c70 c325,c298 c136,c329 c170,c409 c86,c367 c160,c27 c99,c255 c136,c34 c200,c214 c211,c377 c86,c329 c317,c233 c432,c82 c378,c40 c224,c367 c157,c27 c359,c34 c213,c82 c364,c317 c224,c406 c378,c27 c86,c298 c371,c406 c432,c40 c364,c47 c213,c377 c364,c18 c146,c27 c86,c365 c429,c426 c359,c426 c160,c326 c146,c298 c160,c426 c371,c34 c364,c377 c136,c377 c359,c409 c211,c367 c432,c326 c325,c201 c146,c367 c92,c365 c86,c406 c136,c426 c170,c27 c326,c27 c367,c233 c160,c367 c142,c367 c378,c317 c213,c426 c317,c367 c429,c201 c160,c47 c136,c49 c92,c329 c421,c163 c157,c201 c317,c326 c136,c326 c136,c201 . p5(E,E) c106,c106 c90,c90 c106,c292 c136,c136 c136,c242 c209,c238 c59,c321 c90,c306 c138,c60 c213,c213 c359,c359 c143,c358 c86,c86 c59,c59 c90,c343 c421,c391 c86,c377 c364,c364 . p3(E,E) c142,c142 c306,c306 c326,c326 c160,c160 c432,c286 c101,c250 c429,c89 c211,c241 c432,c432 c367,c361 c325,c325 c170,c66 c371,c371 c146,c146 c92,c152 c170,c170 c306,c90 c364,c364 c86,c38 c86,c86 c224,c224 c317,c317 c157,c157 c211,c211 c378,c118 c101,c101 . p8(E,E) c65,c144 c246,c369 c321,c232 c262,c103 c348,c20 . p7(E,E) c170,c66 c425,c425 c367,c361 c369,c246 c148,c263 c20,c348 c59,c59 c364,c364 c240,c174 c90,c90 c99,c158 c343,c90 c377,c86 c213,c213 c296,c205 c321,c59 c387,c387 c86,c86 c103,c262 c144,c65 c196,c117 c232,c321 c409,c387 c92,c152 c101,c250 c236,c425 c292,c106 c106,c106 c359,c359 . p6(E,E) c364,c321 c421,c163 c99,c255 c200,c214 c273,c335 c86,c377 c209,c238 c143,c358 c138,c60 . p1(E,E) c99,c255 c364,c321 c200,c214 c421,c163 c273,c335 . p0(E,E) c166,c166 c344,c329 c233,c233 c201,c201 c275,c18 c90,c27 c27,c27 c49,c70 c367,c367 c365,c365 c215,c377 c34,c34 c386,c34 c409,c409 c70,c70 c324,c324 c40,c40 c366,c40 c18,c18 c342,c317 c58,c47 c329,c329 c329,c201 c426,c426 c406,c406 c298,c298 c82,c82 c137,c49 . p2(E,E) c326,c286 c359,c367 c371,c333 c224,c312 c136,c298 c364,c326 c213,c409 c359,c426 c160,c175 c146,c268 . p10(E,E) c250,c339 c136,c425 c166,c302 c90,c39 c359,c380 c359,c418 c66,c254 c361,c421 c137,c350 c364,c291 c152,c146 c329,c362 c366,c319 c275,c416 c58,c377 c213,c286 . p9(E,E) c69,c60 c58,c377 c329,c362 c399,c242 c227,c238 c101,c358 c90,c39 c166,c302 c275,c416 c264,c391 .
D
module test; import std.stdio; import capnproto.FileDescriptor; import capnproto.MessageBuilder; import capnproto.MessageReader; import capnproto.SerializePacked; import capnproto.StructList; import capnproto.Void; import addressbook; void writeAddressBook() { MessageBuilder message = new MessageBuilder(); auto addressbook = message.initRoot!AddressBook; auto people = addressbook.initPeople(2); auto alice = people.get(0); alice.setId(123); alice.setName("Alice"); alice.setEmail("alice@example.com"); auto alicePhones = alice.initPhones(1); alicePhones.get(0).setNumber("555-1212"); alicePhones.get(0).setType(Person.PhoneNumber.Type.mobile); alice.getEmployment().setSchool("MIT"); auto bob = people.get(1); bob.setId(456); bob.setName("Bob"); bob.setEmail("bob@example.com"); auto bobPhones = bob.initPhones(2); bobPhones.get(0).setNumber("555-4567"); bobPhones.get(0).setType(Person.PhoneNumber.Type.home); bobPhones.get(1).setNumber("555-7654"); bobPhones.get(1).setType(Person.PhoneNumber.Type.work); bob.getEmployment().setUnemployed(); SerializePacked.writeToUnbuffered(new FileDescriptor(stdout), message); } void printAddressBook() { auto message = SerializePacked.readFromUnbuffered(new FileDescriptor(stdin)); auto addressbook = message.getRoot!AddressBook; foreach(person; addressbook.getPeople()) { writefln("%s: %s", person.getName(), person.getEmail()); foreach(phone; person.getPhones()) { string typeName = "UNKNOWN"; switch(phone.getType()) with(Person.PhoneNumber.Type) { case mobile: typeName = "mobile"; break; case home: typeName = "home"; break; case work: typeName = "work"; break; default: break; } writefln(" %s phone: %s", typeName, phone.getNumber()); } auto employment = person.getEmployment(); switch(employment.which()) with(Person.Employment.Which) { case unemployed: writefln(" unemployed"); break; case employer: writefln(" employer: %s", employment.getEmployer()); break; case school: writefln(" student at: %s", employment.getSchool()); break; case selfEmployed: writefln(" self-employed"); break; default: break; } } } void usage() { writeln("usage: addressbook [write | read]"); } void main(string[] args) { if(args.length < 2) usage(); else if(args[1] == "write") writeAddressBook(); else if(args[1] == "read") printAddressBook(); else usage(); }
D
module miniupnpc.upnpcommands; import miniupnpc.upnpreplyparse; import miniupnpc.portlistingparse; /* MiniUPnPc return codes :*/ enum UPNPCOMMAND_SUCCESS = 0; enum UPNPCOMMAND_UNKNOWN_ERROR = -1; enum UPNPCOMMAND_INVALID_ARGS = -2; enum UPNPCOMMAND_HTTP_ERROR = -3; extern(C) nothrow @nogc: ulong UPNP_GetTotalBytesSent(const char* controlURL, const char* servicetype); ulong UPNP_GetTotalBytesReceived(const char* controlURL, const char* servicetype); ulong UPNP_GetTotalPacketsSent(const char* controlURL, const char* servicetype); ulong UPNP_GetTotalPacketsReceived(const char* controlURL, const char* servicetype); /* UPNP_GetStatusInfo() * status and lastconnerror are 64 byte buffers * Return values : * UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR * or a UPnP Error code*/ int UPNP_GetStatusInfo(const char* controlURL, const char* servicetype, char* status, uint* uptime, char* lastconnerror); /* UPNP_GetConnectionTypeInfo() * argument connectionType is a 64 character buffer * Return Values : * UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR * or a UPnP Error code*/ int UPNP_GetConnectionTypeInfo(const char* controlURL, const char* servicetype, char* connectionType); /* UPNP_GetExternalIPAddress() call the corresponding UPNP method. * if the third arg is not null the value is copied to it. * at least 16 bytes must be available * * Return values : * 0 : SUCCESS * NON ZERO : ERROR Either an UPnP error code or an unknown error. * * possible UPnP Errors : * 402 Invalid Args - See UPnP Device Architecture section on Control. * 501 Action Failed - See UPnP Device Architecture section on Control.*/ int UPNP_GetExternalIPAddress(const char* controlURL, const char* servicetype, char* extIpAdd); /* UPNP_GetLinkLayerMaxBitRates() * call WANCommonInterfaceConfig:1#GetCommonLinkProperties * * return values : * UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR * or a UPnP Error Code.*/ int UPNP_GetLinkLayerMaxBitRates(const char* controlURL, const char* servicetype, uint* bitrateDown, uint* bitrateUp); /* UPNP_AddPortMapping() * if desc is NULL, it will be defaulted to "libminiupnpc" * remoteHost is usually NULL because IGD don't support it. * * Return values : * 0 : SUCCESS * NON ZERO : ERROR. Either an UPnP error code or an unknown error. * * List of possible UPnP errors for AddPortMapping : * errorCode errorDescription (short) - Description (long) * 402 Invalid Args - See UPnP Device Architecture section on Control. * 501 Action Failed - See UPnP Device Architecture section on Control. * 715 WildCardNotPermittedInSrcIP - The source IP address cannot be * wild-carded * 716 WildCardNotPermittedInExtPort - The external port cannot be wild-carded * 718 ConflictInMappingEntry - The port mapping entry specified conflicts * with a mapping assigned previously to another client * 724 SamePortValuesRequired - Internal and External port values * must be the same * 725 OnlyPermanentLeasesSupported - The NAT implementation only supports * permanent lease times on port mappings * 726 RemoteHostOnlySupportsWildcard - RemoteHost must be a wildcard * and cannot be a specific IP address or DNS name * 727 ExternalPortOnlySupportsWildcard - ExternalPort must be a wildcard and * cannot be a specific port value*/ int UPNP_AddPortMapping(const char* controlURL, const char* servicetype, const char* extPort, const char* inPort, const char* inClient, const char* desc, const char* proto, const char* remoteHost, const char* leaseDuration); /* UPNP_DeletePortMapping() * Use same argument values as what was used for AddPortMapping(). * remoteHost is usually NULL because IGD don't support it. * Return Values : * 0 : SUCCESS * NON ZERO : error. Either an UPnP error code or an undefined error. * * List of possible UPnP errors for DeletePortMapping : * 402 Invalid Args - See UPnP Device Architecture section on Control. * 714 NoSuchEntryInArray - The specified value does not exist in the array*/ int UPNP_DeletePortMapping(const char* controlURL, const char* servicetype, const char* extPort, const char* proto, const char* remoteHost); /* UPNP_GetPortMappingNumberOfEntries() * not supported by all routers*/ int UPNP_GetPortMappingNumberOfEntries(const char* controlURL, const char* servicetype, uint* num); /* UPNP_GetSpecificPortMappingEntry() * retrieves an existing port mapping * params : * in extPort * in proto * out intClient (16 bytes) * out intPort (6 bytes) * out desc (80 bytes) * out enabled (4 bytes) * out leaseDuration (16 bytes) * * return value : * UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR * or a UPnP Error Code.*/ int UPNP_GetSpecificPortMappingEntry(const char* controlURL, const char* servicetype, const char* extPort, const char* proto, char* intClient, char* intPort, char* desc, char* enabled, char* leaseDuration); /* UPNP_GetGenericPortMappingEntry() * params : * in index * out extPort (6 bytes) * out intClient (16 bytes) * out intPort (6 bytes) * out protocol (4 bytes) * out desc (80 bytes) * out enabled (4 bytes) * out rHost (64 bytes) * out duration (16 bytes) * * return value : * UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR * or a UPnP Error Code. * * Possible UPNP Error codes : * 402 Invalid Args - See UPnP Device Architecture section on Control. * 713 SpecifiedArrayIndexInvalid - The specified array index is out of bounds */ int UPNP_GetGenericPortMappingEntry(const char* controlURL, const char* servicetype, const char* index, char* extPort, char* intClient, char* intPort, char* protocol, char* desc, char* enabled, char* rHost, char* duration); /* UPNP_GetListOfPortMappings() Available in IGD v2 * * * Possible UPNP Error codes : * 606 Action not Authorized * 730 PortMappingNotFound - no port mapping is found in the specified range. * 733 InconsistantParameters - NewStartPort and NewEndPort values are not * consistent. */ int UPNP_GetListOfPortMappings(const char* controlURL, const char* servicetype, const char* startPort, const char* endPort, const char* protocol, const char* numberOfPorts, PortMappingParserData* data); /* IGD:2, functions for service WANIPv6FirewallControl:1*/ int UPNP_GetFirewallStatus(const char* controlURL, const char* servicetype, int* firewallEnabled, int* inboundPinholeAllowed); int UPNP_GetOutboundPinholeTimeout(const char* controlURL, const char* servicetype, const char* remoteHost, const char* remotePort, const char* intClient, const char* intPort, const char* proto, int* opTimeout); int UPNP_AddPinhole(const char* controlURL, const char* servicetype, const char* remoteHost, const char* remotePort, const char* intClient, const char* intPort, const char* proto, const char* leaseTime, char* uniqueID); int UPNP_UpdatePinhole(const char* controlURL, const char* servicetype, const char* uniqueID, const char* leaseTime); int UPNP_DeletePinhole(const char* controlURL, const char* servicetype, const char* uniqueID); int UPNP_CheckPinholeWorking(const char* controlURL, const char* servicetype, const char* uniqueID, int* isWorking); int UPNP_GetPinholePackets(const char* controlURL, const char* servicetype, const char* uniqueID, int* packets);
D
import std.exception, std.digest.crc, std.stdio, std.array, std.container, std.algorithm, std.conv, std.range, std.zlib; import endianrange, chunk; struct PNGReader{ EndianRange pngData; RedBlackTree!(char[4]) allowed_chunks; ubyte[char[4]] stuff; Chunk[] chunks; static bool isType(string file: "png")(ubyte[] pngdata){ enforce( sig == [ 0x89, 'P','N','G', '\r', '\n', 26, 10], "shit, no valid headre"); return true; } this( alias pred = function ubyte[4] ( ubyte[3] a ){ return [0,a[2],a[1],a[0]];} )( ubyte[] pngData) { allowed_chunks = new RedBlackTree!(char[4]); this.pngData = new EndianRange( pngData); auto sig = this.pngData.frontN(8); enforce( sig == [ 0x89, 'P','N','G', '\r', '\n', 26, 10], "shit, no valid headre"); this.pngData.popFrontN(8); //writeln( "passed header check"); try { while( true ) { chunks ~= Chunk(this); } } catch { foreach ( chunk; chunks) { //writeln(chunk.metaInfo); } } } auto verifyChunkOrder() { allowed_chunks.insert(cast(char[4])"IHDR"); auto chunksDup = chunks.dup; Chunk current = chunksDup.front; while ( !chunksDup.empty){ current = chunksDup.front; if ( std.algorithm.canFind( allowed_chunks[], current.type )) { if (current.type == "zTXt"){enforce ( chunk!"zTXt"( current), "chunkError");} else if (current.type == "tEXt"){enforce ( chunk!"tEXt"( current), "chunkError");} else if (current.type == "iTXt"){enforce ( chunk!"iTXt"( current), "chunkError");} else if (current.type == "pHYs"){ enforce ( chunk!"pHYs"( current), "chunkError"); allowed_chunks.removeKey(cast(char[4])"pHYs"); } else if (current.type == "sPLT"){ enforce ( chunk!"sPLT"( current), "chunkError"); } else if (current.type == "iCCP"){ enforce ( chunk!"iCCP"( current), "chunkError"); allowed_chunks.removeKey(cast(char[4])"sRGB"); allowed_chunks.removeKey(cast(char[4])"iCCP"); } else if (current.type == "sRGB"){ enforce ( chunk!"sRGB"( current), "chunkError"); allowed_chunks.removeKey(cast(char[4])"iCCP"); allowed_chunks.removeKey(cast(char[4])"sRGB"); } else if (current.type == "sBIT"){ enforce ( chunk!"sBIT"( current), "chunkError"); allowed_chunks.removeKey(cast(char[4])"sBIT"); } else if (current.type == "gAMA"){ enforce ( chunk!"gAMA"( current), "chunkError"); allowed_chunks.removeKey(cast(char[4])"gAMA"); } else if (current.type == "cHRM"){ enforce ( chunk!"cHRM"( current), "chunkError"); allowed_chunks.removeKey(cast(char[4])"cHRM"); } else if (current.type == "IHDR"){ enforce ( chunk!"IHDR"( current), "chunkError"); allowed_chunks.removeKey(cast(char[4])"iHDR"); } else if (current.type == "PLTE"){ enforce ( chunk!"PLTE"( current), "chunkError"); allowed_chunks.removeKey(cast(char[4])"cHRM"); allowed_chunks.removeKey(cast(char[4])"gAMA"); allowed_chunks.removeKey(cast(char[4])"sBIT"); allowed_chunks.removeKey(cast(char[4])"iCCP"); allowed_chunks.removeKey(cast(char[4])"sRGB"); } else if (current.type == "IDAT"){ enforce ( chunk!"IDAT"( current), "chunkError"); while( chunksDup.front.type == "IDAT"){ chunksDup = chunksDup[1..$]; current = chunksDup.front; enforce ( chunk!"IDAT"( current), "chunkError"); } allowed_chunks.removeKey(cast(char[4])"IDAT"); allowed_chunks.removeKey(cast(char[4])"pHYs"); allowed_chunks.removeKey(cast(char[4])"sPLT"); allowed_chunks.removeKey(cast(char[4])"iCCP"); allowed_chunks.removeKey(cast(char[4])"sRGB"); allowed_chunks.removeKey(cast(char[4])"sBIT"); allowed_chunks.removeKey(cast(char[4])"gAMA"); allowed_chunks.removeKey(cast(char[4])"cHRM"); allowed_chunks.removeKey(cast(char[4])"tRNS"); allowed_chunks.removeKey(cast(char[4])"hIST"); allowed_chunks.removeKey(cast(char[4])"bKGD") ; continue; } else if (current.type == "bKGD"){ enforce ( chunk!"bKGD"( current), "chunkError"); allowed_chunks.removeKey(cast(char[4])"bKGD"); } else if (current.type == "hIST"){ enforce ( chunk!"hIST"( current), "chunkError"); allowed_chunks.removeKey(cast(char[4])"hIST"); } else if (current.type == "tRNS"){ enforce ( chunk!"tRNS"( current), "chunkError"); allowed_chunks.removeKey(cast(char[4])"tRNS"); } else if (current.type == "tIME"){ enforce ( chunk!"tIME"( current), "chunkError"); allowed_chunks.removeKey(cast(char[4])"tIME"); } } else { if (current.type == "IEND") { enforce ( chunk!"IEND"( current), "chunkError"); break; } //writeln("wrong chunk: ", current.type); } chunksDup = chunksDup[1..$]; } //writeln("end of verify"); } ubyte[] cdata; ubyte[] udata; void extractData( ) { auto dupChunks = chunks.dup; auto mChunk = dupChunks.front; while ( mChunk.type != ['I','D','A','T'] ) { dupChunks.popFront; mChunk = dupChunks.front; } auto app = appender(cdata); while ( mChunk.type == ['I','D','A','T'] ) { app.put(mChunk.data); dupChunks.popFront; mChunk = dupChunks.front; } cdata = app.data; //writefln("cdata: length: %s ", cdata.length); } void decompress(){ udata = cast(ubyte[])std.zlib.uncompress( cdata); /+writefln("udata: length: %s ", udata.length); writeln(udata[0..12]);+/ } bool chunk(string chunkName)( Chunk mChunk){ //writeln("unknown chunk, default handling. Type: ", mChunk.type); return mChunk.checkCRC(); } bool chunk(string chunkName : "tEXt")( Chunk mChunk) { //writeln("tEXt: ", cast(char[])mChunk.data); return mChunk.checkCRC(); } bool chunk(string chunkName : "IEND")( Chunk mChunk) { auto bitTester = function( char rytlock) { return rytlock & 0b0010000; }; auto critical = bitTester( mChunk.type[0]) == 0; auto privateBit = bitTester( mChunk.type[1]) ==1; auto reserved = bitTester( mChunk.type[2]) ==1; auto sefeToCopy = bitTester( mChunk.type[3]) ==1; enforce(mChunk.length ==0, "IEND contains data, I don'tlike it."); //writeln("IEND"); return mChunk.checkCRC(); } bool chunk(string chunkName: "IDAT")( Chunk mChunk) { allowed_chunks.removeKey( cast(char[4])"cHRM", cast(char[4])"gAMA", cast(char[4])"iCCP", cast(char[4])"sBIT", cast(char[4])"sRGB", cast(char[4])"bKGD", cast(char[4])"hIST", cast(char[4])"tRNS", cast(char[4])"pHYs", cast(char[4])"sPLT"); if ( !mChunk.checkCRC()){ //writeln(mChunk.type, " CRC check: ", mChunk.checkCRC()); } return mChunk.checkCRC(); } ubyte[3][] palette; bool chunk(string chunkName: "PLTE")( Chunk mChunk) { allowed_chunks.removeKey(cast(char[4])"cHRM", cast(char[4])"gAMA", cast(char[4])"iCCP", cast(char[4])"sBIT", cast(char[4])"sRGB"); allowed_chunks.insert(cast(char[4])"bKGD"); allowed_chunks.insert( cast(char[4])"hIST"); allowed_chunks.insert( cast(char[4])"tRNS"); writefln( "length is: %s, remainder: %s", mChunk.length, mChunk.length % 3); for( size_t i = 0; i < mChunk.data.length ; i+=3){ foreach( j; 0..3) { palette ~= ['p','n','g'].to!(ubyte[3]); palette[i][j] = mChunk.data[i+j]; } } return mChunk.checkCRC(); } bool chunk(string chunkName: "sRGB" )( Chunk mChunk) { allowed_chunks.removeKey( [ cast(char[4])"iCCP", cast(char[4])"sRGB"] ); return mChunk.checkCRC(); } bool chunk(string chunkName: "iCCP" )( Chunk mChunk) { allowed_chunks.removeKey( [ cast(char[4])"iCCP", cast(char[4])"sRGB"] ); return mChunk.checkCRC(); } bool chunk(string tIME: "tIME")( Chunk possiblytIME) { allowed_chunks.removeKey( cast(char[4])"tIME"); return possiblytIME.checkCRC(); } uint width ; uint height ; byte bit_depth ; byte colour_type ; byte compression_method ; byte filter_method ; byte interlace_method ; static string colourType( byte colourType ) { switch( colourType){ case 0: return "greyscale"; case 2: return "RGB"; case 3: return "colour palette"; case 4: return "GA"; case 6: return "RGBA"; default: return "illegal I think"; } } static string compressionMethod( byte ct){ switch( ct){ case 0: return "deflate 32k sliding window"; default: return "illegal I think"; } } static string filterMethod( byte ct){ switch( ct){ case 0: return "adaptive filter"; default: return "illegal I think"; } } static string interlaceMethod( byte ct){ switch( ct){ case 0: return "no interlace"; case 1: return "Adam7"; default: return "illegal I think"; } } ubyte[] decode(){ import decode; return decode1( this); } bool chunk(string IHDR: "IHDR")( Chunk possiblyIHDR) { if ( possiblyIHDR.length == 13 && possiblyIHDR.type == "IHDR" && possiblyIHDR.checkCRC()) { //_length //writeln( "Seems like IHDR, ", this.chunks.length-1, "---"); alias mChunk = possiblyIHDR; auto data = new EndianRange( mChunk.data); auto chunkReader = new EndianRange(mChunk.data); this.width = chunkReader.front!(uint)[0]; chunkReader.popFront!(uint); this.height = chunkReader.front!(uint)[0]; chunkReader.popFront!(uint); this.bit_depth = chunkReader.front!(byte)[0]; chunkReader.popFront!(byte); this.colour_type = chunkReader.front!(byte)[0]; chunkReader.popFront!(byte); this.compression_method = chunkReader.front!(byte)[0]; chunkReader.popFront!(byte); this.filter_method = chunkReader.front!(byte)[0]; chunkReader.popFront!(byte); this.interlace_method = chunkReader.front!(byte)[0]; chunkReader.popFront!(byte); /+writefln("width: %s; height: %s; bit_depth: %x; colour_type: %s; compression_method: %s; filter_method: %s; interlace_method: %s", width, height, bit_depth , colourType(colour_type) , compressionMethod(compression_method ), filterMethod(filter_method ), interlaceMethod(interlace_method) );+/ allowed_chunks = redBlackTree!(char[4])([ "tIME", "zTXt", "tEXt", "iTXt", "pHYs","sPLT", "iCCP", "sRGB", "sBIT", "gAMA", "cHRM", "bKGD", "IDAT", "IEND"]); return true; } else{ //writeln("GOMGOMGOMGOMGOMGOMGOM"); return false; } } }
D
/** Mirror _ceval.h */ module deimos.python.ceval; import deimos.python.pyport; import deimos.python.object; import deimos.python.frameobject; import deimos.python.pystate; import deimos.python.pythonrun; import deimos.python.compile; extern(C): // Python-header-file: Include/ceval.h: /// _ PyObject* PyEval_CallObjectWithKeywords( PyObject* func, PyObject* args, PyObject* kwargs); version(Python_2_5_Or_Later){ /// _ PyObject* PyEval_CallObject()(PyObject* func, PyObject* arg) { return PyEval_CallObjectWithKeywords(func, arg, null); } }else{ /// _ PyObject* PyEval_CallObject(PyObject* , PyObject* ); } /// _ PyObject* PyEval_CallFunction(PyObject* obj, const(char)* format, ...); /// _ PyObject* PyEval_CallMethod( PyObject* obj, const(char)* methodname, const(char)* format, ...); /// _ void PyEval_SetProfile(Py_tracefunc, PyObject*); /// _ void PyEval_SetTrace(Py_tracefunc, PyObject*); /// _ Borrowed!PyObject* PyEval_GetBuiltins(); /// _ Borrowed!PyObject* PyEval_GetGlobals(); /// _ Borrowed!PyObject* PyEval_GetLocals(); /// _ Borrowed!PyFrameObject* PyEval_GetFrame(); version(Python_3_0_Or_Later) { }else { /// Availability: 2.* int PyEval_GetRestricted(); /// Availability: 2.* int Py_FlushLine(); } /** Look at the current frame's (if any) code's co_flags, and turn on the corresponding compiler flags in cf->cf_flags. Return 1 if any flag was set, else return 0. */ int PyEval_MergeCompilerFlags(PyCompilerFlags* cf); /// _ int Py_AddPendingCall(int function(void*) func, void* arg); /// _ int Py_MakePendingCalls(); /// _ void Py_SetRecursionLimit(int); /// _ int Py_GetRecursionLimit(); // d translation of c macro: /// _ int Py_EnterRecursiveCall()(char* where) { return _Py_MakeRecCheck(PyThreadState_GET().recursion_depth) && _Py_CheckRecursiveCall(where); } /// _ void Py_LeaveRecursiveCall()() { version(Python_3_0_Or_Later) { if(_Py_MakeEndRecCheck(PyThreadState_GET().recursion_depth)) PyThreadState_GET().overflowed = 0; }else { --PyThreadState_GET().recursion_depth; } } /// _ int _Py_CheckRecursiveCall(char* where); /// _ mixin(PyAPI_DATA!"int _Py_CheckRecursionLimit"); // TODO: version(STACKCHECK) /// _ int _Py_MakeRecCheck()(int x) { return (++(x) > _Py_CheckRecursionLimit); } version(Python_3_0_Or_Later) { // d translation of c macro: /// Availability: 3.* auto _Py_MakeEndRecCheck()(x) { return (--(x) < ((_Py_CheckRecursionLimit > 100) ? (_Py_CheckRecursionLimit - 50) : (3 * (_Py_CheckRecursionLimit >> 2)))); } /* auto Py_ALLOW_RECURSION()() { do{ ubyte _old = PyThreadState_GET()->recursion_critical; PyThreadState_GET()->recursion_critical = 1; } auto Py_END_ALLOW_RECURSION()() { PyThreadState_GET()->recursion_critical = _old; }while(0); } */ /** D's answer to C's --- Py_ALLOW_RECURSION ..code.. Py_END_ALLOW_RECURSION --- is --- mixin(Py_ALLOW_RECURSION(q{ ..code.. })); --- */ string Py_ALLOW_RECURSION()(string inner_code) { import std.array; return replace(q{ { ubyte _old = PyThreadState_GET().recursion_critical; PyThreadState_GET().recursion_critical = 1; $inner_code; PyThreadState_GET().recursion_critical = _old; } }, "$inner_code", inner_code); } } /// _ const(char)* PyEval_GetFuncName(PyObject*); /// _ const(char)* PyEval_GetFuncDesc(PyObject*); version(Python_3_7_Or_Later) { }else{ /// _ PyObject* PyEval_GetCallStats(PyObject*); } /// _ PyObject* PyEval_EvalFrame(PyFrameObject*); version(Python_2_5_Or_Later){ /// Availability: >= 2.5 PyObject* PyEval_EvalFrameEx(PyFrameObject*, int); } version(Python_3_0_Or_Later) { }else{ /// _ mixin(PyAPI_DATA!"/*volatile*/ int _Py_Ticker"); /// _ mixin(PyAPI_DATA!"int _Py_CheckInterval"); } /// _ PyThreadState* PyEval_SaveThread(); /// _ void PyEval_RestoreThread(PyThreadState*); // version(WITH_THREAD) assumed? /// _ int PyEval_ThreadsInitialized(); /// _ void PyEval_InitThreads(); version(Python_3_8_Or_Later) { }else version(Python_3_0_Or_Later) { /// Availability: 3.0 - 3.7 void _PyEval_FiniThreads(); } /// _ void PyEval_AcquireLock(); /// _ void PyEval_ReleaseLock(); /// _ void PyEval_AcquireThread(PyThreadState* tstate); /// _ void PyEval_ReleaseThread(PyThreadState* tstate); version(Python_3_8_Or_Later) { }else { /// Availability: < 3.8 void PyEval_ReInitThreads(); } version(Python_3_0_Or_Later) { /// Availability: 3.* void _PyEval_SetSwitchInterval(C_ulong microseconds); /// Availability: 3.* C_ulong _PyEval_GetSwitchInterval(); } /* ?? #define Py_BLOCK_THREADS PyEval_RestoreThread(_save); #define Py_UNBLOCK_THREADS _save = PyEval_SaveThread(); */ /** D's answer to C's --- Py_BEGIN_ALLOW_THREADS ..code.. Py_END_ALLOW_THREADS --- is --- mixin(Py_ALLOW_THREADS(q{ ..code.. })); --- */ string Py_ALLOW_THREADS()(string inner_code) { import std.array; return replace(q{ { PyThreadState* _save = PyEval_SaveThread(); $inner_code; PyEval_RestoreThread(_save); } }, "$inner_code", inner_code); } ///_ int _PyEval_SliceIndex(PyObject*, Py_ssize_t*); version(Python_3_8_Or_Later) { }else version(Python_3_0_Or_Later) { /// Availability: 3.0 - 3.7 void _PyEval_SignalAsyncExc(); }
D
module project.gui.windows.content; public import project.gui.windows.content.queue; public import project.gui.windows.content.builder; public static import project.gui.windows.content.main; public static import project.gui.windows.content.score; public static import project.gui.windows.content.visualization;
D
module dwt.internal.mozilla.nsISecurityCheckedComponent; import dwt.dwthelper.utils; public class nsISecurityCheckedComponent extends nsISupports { static final int LAST_METHOD_ID = nsISupports.LAST_METHOD_ID + 4; public static final String NS_ISECURITYCHECKEDCOMPONENT_IID_STR = "0dad9e8c-a12d-4dcb-9a6f-7d09839356e1"; public static final nsID NS_ISECURITYCHECKEDCOMPONENT_IID = new nsID(NS_ISECURITYCHECKEDCOMPONENT_IID_STR); public nsISecurityCheckedComponent(int /*long*/ address) { super(address); } public int CanCreateWrapper(int /*long*/ iid, int /*long*/[] _retval) { return XPCOM.VtblCall(nsISupports.LAST_METHOD_ID + 1, getAddress(), iid, _retval); } public int CanCallMethod(int /*long*/ iid, char[] methodName, int /*long*/[] _retval) { return XPCOM.VtblCall(nsISupports.LAST_METHOD_ID + 2, getAddress(), iid, methodName, _retval); } public int CanGetProperty(int /*long*/ iid, char[] propertyName, int /*long*/[] _retval) { return XPCOM.VtblCall(nsISupports.LAST_METHOD_ID + 3, getAddress(), iid, propertyName, _retval); } public int CanSetProperty(int /*long*/ iid, char[] propertyName, int /*long*/[] _retval) { return XPCOM.VtblCall(nsISupports.LAST_METHOD_ID + 4, getAddress(), iid, propertyName, _retval); } }
D
import std.stdio; import std.string : indexOf; // // Example of Interpolated Strings // int main(string[] args) { foreach(item; mixin(interpolatedTupleMixin("hello\n"))) { write(item); } int a = 42; foreach(item; mixin(interpolatedTupleMixin("$(a)\n"))) { write(item); } foreach(item; mixin(interpolatedTupleMixin("a is $(a)\n"))) { write(item); } foreach(item; mixin(interpolatedTupleMixin("1 + 2 is $(1 + 2)\n"))) { write(item); } writeInterpolatedString(mixin(interpolatedTupleMixin("hello\n"))); writeInterpolatedString(mixin(interpolatedTupleMixin("$(a)\n"))); writeInterpolatedString(mixin(interpolatedTupleMixin("a is $(a)\n"))); writeInterpolatedString(mixin(interpolatedTupleMixin("1 + 2 is $(1 + 2)\n"))); // // Example of code generation // { string functionName = "foo"; string operation = "+"; writeInterpolatedString(mixin(interpolatedTupleMixin(q{ int $(functionName)(int x, int y) { return x $(operation) y; } }))); } // Example of passing an interpolated string to writefln writefln("here is an interpolated string \"%s\"", formatter(mixin(interpolatedTupleMixin("hello")))); writefln("here is an interpolated string \"%s\"", formatter(mixin(interpolatedTupleMixin("1 + 2 is $(1 + 2)")))); mixin(generateFunc("int", "add2Ints", "int", "+")); add2Ints(10, 20); return 0; } // // Implementation of interpolated strings // template tuple(T...) { alias tuple = T; } string interpolatedTupleMixin(string str) pure { return "tuple!(" ~ interpolatedMixinHelper1(str) ~ ")"; } private string interpolatedMixinHelper1(string str) pure { auto dollarIndex = str.indexOf("$"); if(dollarIndex < 0) { return "\"" ~ str ~ "\""; } if(dollarIndex == 0) { return interpolatedMixinHelper2(str[1..$]); } return "\"" ~ str[0..dollarIndex] ~ "\", " ~ interpolatedMixinHelper2(str[dollarIndex + 1..$]); } // star of str is a dollar expression private string interpolatedMixinHelper2(string str) pure { if(str[0] == '(') { auto endParensIndex = str.indexOf(')'); if(endParensIndex < 0) { assert(0, "interpolated string has mismatch parens"); } if(endParensIndex + 1 == str.length) { return str[1..endParensIndex]; } return str[1..endParensIndex] ~ ", " ~ interpolatedMixinHelper1(str[endParensIndex + 1 .. $]); } assert(0, "interpolated expression not surrounded by '()' is not supported yet (expression is \"" ~ str ~ "\")"); } void writeInterpolatedString(T...)(T interpolatedString) { foreach(part; interpolatedString) { write(part); } } auto formatter(T...)(T interpolatedString) { struct Formatter { T interpolatedString; void toString(scope void delegate(const(char)[]) sink) const { foreach(part; interpolatedString) { static if(__traits(compiles, sink(part))) { sink(part); } else { import std.format : formattedWrite; formattedWrite(sink, "%s", part); } } } } return Formatter(interpolatedString); } // NOTE: // This doesn't work because the tuple does not have access to the variables/ // scope of the caller who is instantiating the template. // For now this has to be a mixin. // template interpolate(string str) { enum interpolate = mixin(interpolatedTupleMixin(str)); } string generateFunc(string returnType, string name, string type, string op) { /* DOESN'T WORK: interpolate template can't see the local variables import std.conv : text; return text(interpolate!q{ $(returnType) $(name)($(type) left, $(type) right) { return cast($(returnType))(left $(op) right); } }); */ import std.conv : text; return text(mixin(interpolatedTupleMixin(q{ $(returnType) $(name)($(type) left, $(type) right) { return cast($(returnType))(left $(op) right); } }))); }
D
/* Copyright (c) 2015 Timur Gafarov Boost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ module dlib; public { import dlib.async; import dlib.audio; import dlib.coding; import dlib.container; import dlib.core; import dlib.filesystem; import dlib.functional; import dlib.geometry; import dlib.image; import dlib.math; import dlib.memory; import dlib.network; import dlib.serialization; import dlib.text; }
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/traits.d, _traits.d) * Documentation: https://dlang.org/phobos/dmd_traits.html * Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/traits.d */ module dmd.traits; import core.stdc.stdio; import core.stdc.string; import dmd.aggregate; import dmd.arraytypes; import dmd.attrib; import dmd.canthrow; import dmd.dclass; import dmd.declaration; import dmd.denum; import dmd.dscope; import dmd.dsymbol; import dmd.dsymbolsem; import dmd.dtemplate; import dmd.errors; import dmd.expression; import dmd.expressionsem; import dmd.func; import dmd.globals; import dmd.hdrgen; import dmd.id; import dmd.identifier; import dmd.mtype; import dmd.nogc; import dmd.root.array; import dmd.root.speller; import dmd.root.stringtable; import dmd.target; import dmd.tokens; import dmd.typesem; import dmd.visitor; import dmd.root.rootobject; enum LOGSEMANTIC = false; /************************ TraitsExp ************************************/ /************************************** * Convert `Expression` or `Type` to corresponding `Dsymbol`, additionally * stripping off expression contexts. * * Some symbol related `__traits` ignore arguments expression contexts. * For example: * ---- * struct S { void f() {} } * S s; * pragma(msg, __traits(isNested, s.f)); * // s.f is `DotVarExp`, but `__traits(isNested)`` needs a `FuncDeclaration`. * ---- * * This is used for that common `__traits` behavior. * * Input: * oarg object to get the symbol for * Returns: * Dsymbol the corresponding symbol for oarg */ private Dsymbol getDsymbolWithoutExpCtx(RootObject oarg) { if (auto e = isExpression(oarg)) { if (e.op == TOK.dotVariable) return (cast(DotVarExp)e).var; if (e.op == TOK.dotTemplateDeclaration) return (cast(DotTemplateExp)e).td; } return getDsymbol(oarg); } private __gshared StringTable traitsStringTable; shared static this() { static immutable string[] names = [ "isAbstractClass", "isArithmetic", "isAssociativeArray", "isDisabled", "isDeprecated", "isFuture", "isFinalClass", "isPOD", "isNested", "isFloating", "isIntegral", "isScalar", "isStaticArray", "isUnsigned", "isVirtualFunction", "isVirtualMethod", "isAbstractFunction", "isFinalFunction", "isOverrideFunction", "isStaticFunction", "isRef", "isOut", "isLazy", "isReturnOnStack", "hasMember", "identifier", "getProtection", "parent", "getLinkage", "getMember", "getOverloads", "getVirtualFunctions", "getVirtualMethods", "classInstanceSize", "allMembers", "derivedMembers", "isSame", "compiles", "parameters", "getAliasThis", "getAttributes", "getFunctionAttributes", "getFunctionVariadicStyle", "getParameterStorageClasses", "getUnitTests", "getVirtualIndex", "getPointerBitmap", "isZeroInit", "getTargetInfo" ]; traitsStringTable._init(48); foreach (s; names) { auto sv = traitsStringTable.insert(s, cast(void*)s.ptr); assert(sv); } } /** * get an array of size_t values that indicate possible pointer words in memory * if interpreted as the type given as argument * Returns: the size of the type in bytes, d_uns64.max on error */ d_uns64 getTypePointerBitmap(Loc loc, Type t, Array!(d_uns64)* data) { d_uns64 sz; if (t.ty == Tclass && !(cast(TypeClass)t).sym.isInterfaceDeclaration()) sz = (cast(TypeClass)t).sym.AggregateDeclaration.size(loc); else sz = t.size(loc); if (sz == SIZE_INVALID) return d_uns64.max; const sz_size_t = Type.tsize_t.size(loc); if (sz > sz.max - sz_size_t) { error(loc, "size overflow for type `%s`", t.toChars()); return d_uns64.max; } d_uns64 bitsPerWord = sz_size_t * 8; d_uns64 cntptr = (sz + sz_size_t - 1) / sz_size_t; d_uns64 cntdata = (cntptr + bitsPerWord - 1) / bitsPerWord; data.setDim(cast(size_t)cntdata); data.zero(); extern (C++) final class PointerBitmapVisitor : Visitor { alias visit = Visitor.visit; public: extern (D) this(Array!(d_uns64)* _data, d_uns64 _sz_size_t) { this.data = _data; this.sz_size_t = _sz_size_t; } void setpointer(d_uns64 off) { d_uns64 ptroff = off / sz_size_t; (*data)[cast(size_t)(ptroff / (8 * sz_size_t))] |= 1L << (ptroff % (8 * sz_size_t)); } override void visit(Type t) { Type tb = t.toBasetype(); if (tb != t) tb.accept(this); } override void visit(TypeError t) { visit(cast(Type)t); } override void visit(TypeNext t) { assert(0); } override void visit(TypeBasic t) { if (t.ty == Tvoid) setpointer(offset); } override void visit(TypeVector t) { } override void visit(TypeArray t) { assert(0); } override void visit(TypeSArray t) { d_uns64 arrayoff = offset; d_uns64 nextsize = t.next.size(); if (nextsize == SIZE_INVALID) error = true; d_uns64 dim = t.dim.toInteger(); for (d_uns64 i = 0; i < dim; i++) { offset = arrayoff + i * nextsize; t.next.accept(this); } offset = arrayoff; } override void visit(TypeDArray t) { setpointer(offset + sz_size_t); } // dynamic array is {length,ptr} override void visit(TypeAArray t) { setpointer(offset); } override void visit(TypePointer t) { if (t.nextOf().ty != Tfunction) // don't mark function pointers setpointer(offset); } override void visit(TypeReference t) { setpointer(offset); } override void visit(TypeClass t) { setpointer(offset); } override void visit(TypeFunction t) { } override void visit(TypeDelegate t) { setpointer(offset); } // delegate is {context, function} override void visit(TypeQualified t) { assert(0); } // assume resolved override void visit(TypeIdentifier t) { assert(0); } override void visit(TypeInstance t) { assert(0); } override void visit(TypeTypeof t) { assert(0); } override void visit(TypeReturn t) { assert(0); } override void visit(TypeEnum t) { visit(cast(Type)t); } override void visit(TypeTuple t) { visit(cast(Type)t); } override void visit(TypeSlice t) { assert(0); } override void visit(TypeNull t) { // always a null pointer } override void visit(TypeStruct t) { d_uns64 structoff = offset; foreach (v; t.sym.fields) { offset = structoff + v.offset; if (v.type.ty == Tclass) setpointer(offset); else v.type.accept(this); } offset = structoff; } // a "toplevel" class is treated as an instance, while TypeClass fields are treated as references void visitClass(TypeClass t) { d_uns64 classoff = offset; // skip vtable-ptr and monitor if (t.sym.baseClass) visitClass(cast(TypeClass)t.sym.baseClass.type); foreach (v; t.sym.fields) { offset = classoff + v.offset; v.type.accept(this); } offset = classoff; } Array!(d_uns64)* data; d_uns64 offset; d_uns64 sz_size_t; bool error; } scope PointerBitmapVisitor pbv = new PointerBitmapVisitor(data, sz_size_t); if (t.ty == Tclass) pbv.visitClass(cast(TypeClass)t); else t.accept(pbv); return pbv.error ? d_uns64.max : sz; } /** * get an array of size_t values that indicate possible pointer words in memory * if interpreted as the type given as argument * the first array element is the size of the type for independent interpretation * of the array * following elements bits represent one word (4/8 bytes depending on the target * architecture). If set the corresponding memory might contain a pointer/reference. * * Returns: [T.sizeof, pointerbit0-31/63, pointerbit32/64-63/128, ...] */ private Expression pointerBitmap(TraitsExp e) { if (!e.args || e.args.dim != 1) { error(e.loc, "a single type expected for trait pointerBitmap"); return new ErrorExp(); } Type t = getType((*e.args)[0]); if (!t) { error(e.loc, "`%s` is not a type", (*e.args)[0].toChars()); return new ErrorExp(); } Array!(d_uns64) data; d_uns64 sz = getTypePointerBitmap(e.loc, t, &data); if (sz == d_uns64.max) return new ErrorExp(); auto exps = new Expressions(); exps.push(new IntegerExp(e.loc, sz, Type.tsize_t)); foreach (d_uns64 i; 0 .. data.dim) exps.push(new IntegerExp(e.loc, data[cast(size_t)i], Type.tsize_t)); auto ale = new ArrayLiteralExp(e.loc, Type.tsize_t.sarrayOf(data.dim + 1), exps); return ale; } Expression semanticTraits(TraitsExp e, Scope* sc) { static if (LOGSEMANTIC) { printf("TraitsExp::semantic() %s\n", e.toChars()); } if (e.ident != Id.compiles && e.ident != Id.isSame && e.ident != Id.identifier && e.ident != Id.getProtection && e.ident != Id.getAttributes) { if (!TemplateInstance.semanticTiargs(e.loc, sc, e.args, 1)) return new ErrorExp(); } size_t dim = e.args ? e.args.dim : 0; Expression dimError(int expected) { e.error("expected %d arguments for `%s` but had %d", expected, e.ident.toChars(), cast(int)dim); return new ErrorExp(); } IntegerExp True() { return new IntegerExp(e.loc, true, Type.tbool); } IntegerExp False() { return new IntegerExp(e.loc, false, Type.tbool); } /******** * Gets the function type from a given AST node * if the node is a function of some sort. * Params: * o = an AST node to check for a `TypeFunction` * fdp = if `o` is a FuncDeclaration then fdp is set to that, otherwise `null` * Returns: * a type node if `o` is a declaration of * a delegate, function, function-pointer or a variable of the former. * Otherwise, `null`. */ static TypeFunction toTypeFunction(RootObject o, out FuncDeclaration fdp) { Type t; if (auto s = getDsymbolWithoutExpCtx(o)) { if (auto fd = s.isFuncDeclaration()) { t = fd.type; fdp = fd; } else if (auto vd = s.isVarDeclaration()) t = vd.type; else t = isType(o); } else t = isType(o); if (t) { if (t.ty == Tfunction) return cast(TypeFunction)t; else if (t.ty == Tdelegate) return cast(TypeFunction)t.nextOf(); else if (t.ty == Tpointer && t.nextOf().ty == Tfunction) return cast(TypeFunction)t.nextOf(); } return null; } IntegerExp isX(T)(bool function(T) fp) { if (!dim) return False(); foreach (o; *e.args) { static if (is(T == Type)) auto y = getType(o); static if (is(T : Dsymbol)) { auto s = getDsymbolWithoutExpCtx(o); if (!s) return False(); } static if (is(T == Dsymbol)) alias y = s; static if (is(T == Declaration)) auto y = s.isDeclaration(); static if (is(T == FuncDeclaration)) auto y = s.isFuncDeclaration(); static if (is(T == EnumMember)) auto y = s.isEnumMember(); if (!y || !fp(y)) return False(); } return True(); } alias isTypeX = isX!Type; alias isDsymX = isX!Dsymbol; alias isDeclX = isX!Declaration; alias isFuncX = isX!FuncDeclaration; alias isEnumMemX = isX!EnumMember; if (e.ident == Id.isArithmetic) { return isTypeX(t => t.isintegral() || t.isfloating()); } if (e.ident == Id.isFloating) { return isTypeX(t => t.isfloating()); } if (e.ident == Id.isIntegral) { return isTypeX(t => t.isintegral()); } if (e.ident == Id.isScalar) { return isTypeX(t => t.isscalar()); } if (e.ident == Id.isUnsigned) { return isTypeX(t => t.isunsigned()); } if (e.ident == Id.isAssociativeArray) { return isTypeX(t => t.toBasetype().ty == Taarray); } if (e.ident == Id.isDeprecated) { if (global.params.vcomplex) { if (isTypeX(t => t.iscomplex() || t.isimaginary()).isBool(true)) return True(); } return isDsymX(t => t.isDeprecated()); } if (e.ident == Id.isFuture) { return isDeclX(t => t.isFuture()); } if (e.ident == Id.isStaticArray) { return isTypeX(t => t.toBasetype().ty == Tsarray); } if (e.ident == Id.isAbstractClass) { return isTypeX(t => t.toBasetype().ty == Tclass && (cast(TypeClass)t.toBasetype()).sym.isAbstract()); } if (e.ident == Id.isFinalClass) { return isTypeX(t => t.toBasetype().ty == Tclass && ((cast(TypeClass)t.toBasetype()).sym.storage_class & STC.final_) != 0); } if (e.ident == Id.isTemplate) { if (dim != 1) return dimError(1); return isDsymX((s) { if (!s.toAlias().isOverloadable()) return false; return overloadApply(s, sm => sm.isTemplateDeclaration() !is null) != 0; }); } if (e.ident == Id.isPOD) { if (dim != 1) return dimError(1); auto o = (*e.args)[0]; auto t = isType(o); if (!t) { e.error("type expected as second argument of __traits `%s` instead of `%s`", e.ident.toChars(), o.toChars()); return new ErrorExp(); } Type tb = t.baseElemOf(); if (auto sd = tb.ty == Tstruct ? (cast(TypeStruct)tb).sym : null) { return sd.isPOD() ? True() : False(); } return True(); } if (e.ident == Id.isNested) { if (dim != 1) return dimError(1); auto o = (*e.args)[0]; auto s = getDsymbolWithoutExpCtx(o); if (!s) { } else if (auto ad = s.isAggregateDeclaration()) { return ad.isNested() ? True() : False(); } else if (auto fd = s.isFuncDeclaration()) { return fd.isNested() ? True() : False(); } e.error("aggregate or function expected instead of `%s`", o.toChars()); return new ErrorExp(); } if (e.ident == Id.isDisabled) { if (dim != 1) return dimError(1); return isDeclX(f => f.isDisabled()); } if (e.ident == Id.isAbstractFunction) { if (dim != 1) return dimError(1); return isFuncX(f => f.isAbstract()); } if (e.ident == Id.isVirtualFunction) { if (dim != 1) return dimError(1); return isFuncX(f => f.isVirtual()); } if (e.ident == Id.isVirtualMethod) { if (dim != 1) return dimError(1); return isFuncX(f => f.isVirtualMethod()); } if (e.ident == Id.isFinalFunction) { if (dim != 1) return dimError(1); return isFuncX(f => f.isFinalFunc()); } if (e.ident == Id.isOverrideFunction) { if (dim != 1) return dimError(1); return isFuncX(f => f.isOverride()); } if (e.ident == Id.isStaticFunction) { if (dim != 1) return dimError(1); return isFuncX(f => !f.needThis() && !f.isNested()); } if (e.ident == Id.isRef) { if (dim != 1) return dimError(1); return isDeclX(d => d.isRef()); } if (e.ident == Id.isOut) { if (dim != 1) return dimError(1); return isDeclX(d => d.isOut()); } if (e.ident == Id.isLazy) { if (dim != 1) return dimError(1); return isDeclX(d => (d.storage_class & STC.lazy_) != 0); } if (e.ident == Id.identifier) { // Get identifier for symbol as a string literal /* Specify 0 for bit 0 of the flags argument to semanticTiargs() so that * a symbol should not be folded to a constant. * Bit 1 means don't convert Parameter to Type if Parameter has an identifier */ if (!TemplateInstance.semanticTiargs(e.loc, sc, e.args, 2)) return new ErrorExp(); if (dim != 1) return dimError(1); auto o = (*e.args)[0]; Identifier id; if (auto po = isParameter(o)) { if (!po.ident) { e.error("argument `%s` has no identifier", po.type.toChars()); return new ErrorExp(); } id = po.ident; } else { Dsymbol s = getDsymbolWithoutExpCtx(o); if (!s || !s.ident) { e.error("argument `%s` has no identifier", o.toChars()); return new ErrorExp(); } id = s.ident; } auto se = new StringExp(e.loc, cast(char*)id.toChars()); return se.expressionSemantic(sc); } if (e.ident == Id.getProtection) { if (dim != 1) return dimError(1); Scope* sc2 = sc.push(); sc2.flags = sc.flags | SCOPE.noaccesscheck; bool ok = TemplateInstance.semanticTiargs(e.loc, sc2, e.args, 1); sc2.pop(); if (!ok) return new ErrorExp(); auto o = (*e.args)[0]; auto s = getDsymbolWithoutExpCtx(o); if (!s) { if (!isError(o)) e.error("argument `%s` has no protection", o.toChars()); return new ErrorExp(); } if (s.semanticRun == PASS.init) s.dsymbolSemantic(null); auto protName = protectionToChars(s.prot().kind); // TODO: How about package(names) assert(protName); auto se = new StringExp(e.loc, cast(char*)protName); return se.expressionSemantic(sc); } if (e.ident == Id.parent) { if (dim != 1) return dimError(1); auto o = (*e.args)[0]; auto s = getDsymbolWithoutExpCtx(o); if (s) { // https://issues.dlang.org/show_bug.cgi?id=12496 // Consider: // class T1 // { // class C(uint value) { } // } // __traits(parent, T1.C!2) if (auto ad = s.isAggregateDeclaration()) // `s` is `C` { if (ad.isNested()) // `C` is nested { if (auto p = s.toParent()) // `C`'s parent is `C!2`, believe it or not { if (p.isTemplateInstance()) // `C!2` is a template instance s = p; // `C!2`'s parent is `T1` } } } if (auto fd = s.isFuncDeclaration()) // https://issues.dlang.org/show_bug.cgi?id=8943 s = fd.toAliasFunc(); if (!s.isImport()) // https://issues.dlang.org/show_bug.cgi?id=8922 s = s.toParent(); } if (!s || s.isImport()) { e.error("argument `%s` has no parent", o.toChars()); return new ErrorExp(); } if (auto f = s.isFuncDeclaration()) { if (auto td = getFuncTemplateDecl(f)) { if (td.overroot) // if not start of overloaded list of TemplateDeclaration's td = td.overroot; // then get the start Expression ex = new TemplateExp(e.loc, td, f); ex = ex.expressionSemantic(sc); return ex; } if (auto fld = f.isFuncLiteralDeclaration()) { // Directly translate to VarExp instead of FuncExp Expression ex = new VarExp(e.loc, fld, true); return ex.expressionSemantic(sc); } } return symbolToExp(s, e.loc, sc, false); } if (e.ident == Id.hasMember || e.ident == Id.getMember || e.ident == Id.getOverloads || e.ident == Id.getVirtualMethods || e.ident == Id.getVirtualFunctions) { if (dim != 2 && !(dim == 3 && e.ident == Id.getOverloads)) return dimError(2); auto o = (*e.args)[0]; auto ex = isExpression((*e.args)[1]); if (!ex) { e.error("expression expected as second argument of __traits `%s`", e.ident.toChars()); return new ErrorExp(); } ex = ex.ctfeInterpret(); bool includeTemplates = false; if (dim == 3 && e.ident == Id.getOverloads) { auto b = isExpression((*e.args)[2]); b = b.ctfeInterpret(); if (!b.type.equals(Type.tbool)) { e.error("`bool` expected as third argument of `__traits(getOverloads)`, not `%s` of type `%s`", b.toChars(), b.type.toChars()); return new ErrorExp(); } includeTemplates = b.isBool(true); } StringExp se = ex.toStringExp(); if (!se || se.len == 0) { e.error("string expected as second argument of __traits `%s` instead of `%s`", e.ident.toChars(), ex.toChars()); return new ErrorExp(); } se = se.toUTF8(sc); if (se.sz != 1) { e.error("string must be chars"); return new ErrorExp(); } auto id = Identifier.idPool(se.peekSlice()); /* Prefer dsymbol, because it might need some runtime contexts. */ Dsymbol sym = getDsymbol(o); if (sym) { if (e.ident == Id.hasMember) { if (auto sm = sym.search(e.loc, id)) return True(); } ex = new DsymbolExp(e.loc, sym); ex = new DotIdExp(e.loc, ex, id); } else if (auto t = isType(o)) ex = typeDotIdExp(e.loc, t, id); else if (auto ex2 = isExpression(o)) ex = new DotIdExp(e.loc, ex2, id); else { e.error("invalid first argument"); return new ErrorExp(); } // ignore symbol visibility and disable access checks for these traits Scope* scx = sc.push(); scx.flags |= SCOPE.ignoresymbolvisibility | SCOPE.noaccesscheck; scope (exit) scx.pop(); if (e.ident == Id.hasMember) { /* Take any errors as meaning it wasn't found */ ex = ex.trySemantic(scx); return ex ? True() : False(); } else if (e.ident == Id.getMember) { if (ex.op == TOK.dotIdentifier) // Prevent semantic() from replacing Symbol with its initializer (cast(DotIdExp)ex).wantsym = true; ex = ex.expressionSemantic(scx); return ex; } else if (e.ident == Id.getVirtualFunctions || e.ident == Id.getVirtualMethods || e.ident == Id.getOverloads) { uint errors = global.errors; Expression eorig = ex; ex = ex.expressionSemantic(scx); if (errors < global.errors) e.error("`%s` cannot be resolved", eorig.toChars()); /* Create tuple of functions of ex */ auto exps = new Expressions(); Dsymbol f; if (ex.op == TOK.variable) { VarExp ve = cast(VarExp)ex; f = ve.var.isFuncDeclaration(); ex = null; } else if (ex.op == TOK.dotVariable) { DotVarExp dve = cast(DotVarExp)ex; f = dve.var.isFuncDeclaration(); if (dve.e1.op == TOK.dotType || dve.e1.op == TOK.this_) ex = null; else ex = dve.e1; } else if (ex.op == TOK.template_) { VarExp ve = cast(VarExp)ex; auto td = ve.var.isTemplateDeclaration(); f = td; if (td && td.funcroot) f = td.funcroot; ex = null; } bool[string] funcTypeHash; /* Compute the function signature and insert it in the * hashtable, if not present. This is needed so that * traits(getOverlods, F3, "visit") does not count `int visit(int)` * twice in the following example: * * ============================================= * interface F1 { int visit(int);} * interface F2 { int visit(int); void visit(); } * interface F3 : F2, F1 {} *============================================== */ void insertInterfaceInheritedFunction(FuncDeclaration fd, Expression e) { auto funcType = fd.type.toChars(); auto len = strlen(funcType); string signature = funcType[0 .. len].idup; //printf("%s - %s\n", fd.toChars, signature); if (signature !in funcTypeHash) { funcTypeHash[signature] = true; exps.push(e); } } int dg(Dsymbol s) { if (includeTemplates) { exps.push(new DsymbolExp(Loc.initial, s, false)); return 0; } auto fd = s.isFuncDeclaration(); if (!fd) return 0; if (e.ident == Id.getVirtualFunctions && !fd.isVirtual()) return 0; if (e.ident == Id.getVirtualMethods && !fd.isVirtualMethod()) return 0; auto fa = new FuncAliasDeclaration(fd.ident, fd, false); fa.protection = fd.protection; auto e = ex ? new DotVarExp(Loc.initial, ex, fa, false) : new DsymbolExp(Loc.initial, fa, false); // if the parent is an interface declaration // we must check for functions with the same signature // in different inherited interfaces if (sym && sym.isInterfaceDeclaration()) insertInterfaceInheritedFunction(fd, e); else exps.push(e); return 0; } InterfaceDeclaration ifd = null; if (sym) ifd = sym.isInterfaceDeclaration(); // If the symbol passed as a parameter is an // interface that inherits other interfaces overloadApply(f, &dg); if (ifd && ifd.interfaces && f) { // check the overloads of each inherited interface individually foreach (bc; ifd.interfaces) { if (auto fd = bc.sym.search(e.loc, f.ident)) overloadApply(fd, &dg); } } auto tup = new TupleExp(e.loc, exps); return tup.expressionSemantic(scx); } else assert(0); } if (e.ident == Id.classInstanceSize) { if (dim != 1) return dimError(1); auto o = (*e.args)[0]; auto s = getDsymbol(o); auto cd = s ? s.isClassDeclaration() : null; if (!cd) { e.error("first argument is not a class"); return new ErrorExp(); } if (cd.sizeok != Sizeok.done) { cd.size(e.loc); } if (cd.sizeok != Sizeok.done) { e.error("%s `%s` is forward referenced", cd.kind(), cd.toChars()); return new ErrorExp(); } return new IntegerExp(e.loc, cd.structsize, Type.tsize_t); } if (e.ident == Id.getAliasThis) { if (dim != 1) return dimError(1); auto o = (*e.args)[0]; auto s = getDsymbol(o); auto ad = s ? s.isAggregateDeclaration() : null; auto exps = new Expressions(); if (ad && ad.aliasthis) exps.push(new StringExp(e.loc, cast(char*)ad.aliasthis.ident.toChars())); Expression ex = new TupleExp(e.loc, exps); ex = ex.expressionSemantic(sc); return ex; } if (e.ident == Id.getAttributes) { /* Specify 0 for bit 0 of the flags argument to semanticTiargs() so that * a symbol should not be folded to a constant. * Bit 1 means don't convert Parameter to Type if Parameter has an identifier */ if (!TemplateInstance.semanticTiargs(e.loc, sc, e.args, 3)) return new ErrorExp(); if (dim != 1) return dimError(1); auto o = (*e.args)[0]; auto po = isParameter(o); auto s = getDsymbolWithoutExpCtx(o); UserAttributeDeclaration udad = null; if (po) { udad = po.userAttribDecl; } else if (s) { if (s.isImport()) { s = s.isImport().mod; } //printf("getAttributes %s, attrs = %p, scope = %p\n", s.toChars(), s.userAttribDecl, s.scope); udad = s.userAttribDecl; } else { version (none) { Expression x = isExpression(o); Type t = isType(o); if (x) printf("e = %s %s\n", Token.toChars(x.op), x.toChars()); if (t) printf("t = %d %s\n", t.ty, t.toChars()); } e.error("first argument is not a symbol"); return new ErrorExp(); } auto exps = udad ? udad.getAttributes() : new Expressions(); auto tup = new TupleExp(e.loc, exps); return tup.expressionSemantic(sc); } if (e.ident == Id.getFunctionAttributes) { /* Extract all function attributes as a tuple (const/shared/inout/pure/nothrow/etc) except UDAs. * https://dlang.org/spec/traits.html#getFunctionAttributes */ if (dim != 1) return dimError(1); FuncDeclaration fd; TypeFunction tf = toTypeFunction((*e.args)[0], fd); if (!tf) { e.error("first argument is not a function"); return new ErrorExp(); } auto mods = new Expressions(); void addToMods(string str) { mods.push(new StringExp(Loc.initial, cast(char*)str.ptr, str.length)); } tf.modifiersApply(&addToMods); tf.attributesApply(&addToMods, TRUSTformatSystem); auto tup = new TupleExp(e.loc, mods); return tup.expressionSemantic(sc); } if (e.ident == Id.isReturnOnStack) { /* Extract as a boolean if function return value is on the stack * https://dlang.org/spec/traits.html#isReturnOnStack */ if (dim != 1) return dimError(1); RootObject o = (*e.args)[0]; FuncDeclaration fd; TypeFunction tf = toTypeFunction(o, fd); if (!tf) { e.error("argument to `__traits(isReturnOnStack, %s)` is not a function", o.toChars()); return new ErrorExp(); } bool value = target.isReturnOnStack(tf, fd && fd.needThis()); return new IntegerExp(e.loc, value, Type.tbool); } if (e.ident == Id.getFunctionVariadicStyle) { /* Accept a symbol or a type. Returns one of the following: * "none" not a variadic function * "argptr" extern(D) void dstyle(...), use `__argptr` and `__arguments` * "stdarg" extern(C) void cstyle(int, ...), use core.stdc.stdarg * "typesafe" void typesafe(T[] ...) */ // get symbol linkage as a string if (dim != 1) return dimError(1); LINK link; VarArg varargs; auto o = (*e.args)[0]; FuncDeclaration fd; TypeFunction tf = toTypeFunction(o, fd); if (tf) { link = tf.linkage; varargs = tf.parameterList.varargs; } else { if (!fd) { e.error("argument to `__traits(getFunctionVariadicStyle, %s)` is not a function", o.toChars()); return new ErrorExp(); } link = fd.linkage; varargs = fd.getParameterList().varargs; } string style; final switch (varargs) { case VarArg.none: style = "none"; break; case VarArg.variadic: style = (link == LINK.d) ? "argptr" : "stdarg"; break; case VarArg.typesafe: style = "typesafe"; break; } auto se = new StringExp(e.loc, cast(char*)style); return se.expressionSemantic(sc); } if (e.ident == Id.getParameterStorageClasses) { /* Accept a function symbol or a type, followed by a parameter index. * Returns a tuple of strings of the parameter's storage classes. */ // get symbol linkage as a string if (dim != 2) return dimError(2); auto o = (*e.args)[0]; auto o1 = (*e.args)[1]; FuncDeclaration fd; TypeFunction tf = toTypeFunction(o, fd); ParameterList fparams; if (tf) fparams = tf.parameterList; else if (fd) fparams = fd.getParameterList(); else { e.error("first argument to `__traits(getParameterStorageClasses, %s, %s)` is not a function", o.toChars(), o1.toChars()); return new ErrorExp(); } StorageClass stc; // Set stc to storage class of the ith parameter auto ex = isExpression((*e.args)[1]); if (!ex) { e.error("expression expected as second argument of `__traits(getParameterStorageClasses, %s, %s)`", o.toChars(), o1.toChars()); return new ErrorExp(); } ex = ex.ctfeInterpret(); auto ii = ex.toUInteger(); if (ii >= fparams.length) { e.error("parameter index must be in range 0..%u not %s", cast(uint)fparams.length, ex.toChars()); return new ErrorExp(); } uint n = cast(uint)ii; Parameter p = fparams[n]; stc = p.storageClass; // This mirrors hdrgen.visit(Parameter p) if (p.type && p.type.mod & MODFlags.shared_) stc &= ~STC.shared_; auto exps = new Expressions; void push(string s) { exps.push(new StringExp(e.loc, cast(char*)s.ptr, cast(uint)s.length)); } if (stc & STC.auto_) push("auto"); if (stc & STC.return_) push("return"); if (stc & STC.out_) push("out"); else if (stc & STC.ref_) push("ref"); else if (stc & STC.in_) push("in"); else if (stc & STC.lazy_) push("lazy"); else if (stc & STC.alias_) push("alias"); if (stc & STC.const_) push("const"); if (stc & STC.immutable_) push("immutable"); if (stc & STC.wild) push("inout"); if (stc & STC.shared_) push("shared"); if (stc & STC.scope_ && !(stc & STC.scopeinferred)) push("scope"); auto tup = new TupleExp(e.loc, exps); return tup.expressionSemantic(sc); } if (e.ident == Id.getLinkage) { // get symbol linkage as a string if (dim != 1) return dimError(1); LINK link; auto o = (*e.args)[0]; FuncDeclaration fd; TypeFunction tf = toTypeFunction(o, fd); if (tf) link = tf.linkage; else { auto s = getDsymbol(o); Declaration d; AggregateDeclaration agg; if (!s || ((d = s.isDeclaration()) is null && (agg = s.isAggregateDeclaration()) is null)) { e.error("argument to `__traits(getLinkage, %s)` is not a declaration", o.toChars()); return new ErrorExp(); } if (d !is null) link = d.linkage; else final switch (agg.classKind) { case ClassKind.d: link = LINK.d; break; case ClassKind.cpp: link = LINK.cpp; break; case ClassKind.objc: link = LINK.objc; break; } } auto linkage = linkageToChars(link); auto se = new StringExp(e.loc, cast(char*)linkage); return se.expressionSemantic(sc); } if (e.ident == Id.allMembers || e.ident == Id.derivedMembers) { if (dim != 1) return dimError(1); auto o = (*e.args)[0]; auto s = getDsymbol(o); if (!s) { e.error("argument has no members"); return new ErrorExp(); } if (auto imp = s.isImport()) { // https://issues.dlang.org/show_bug.cgi?id=9692 s = imp.mod; } auto sds = s.isScopeDsymbol(); if (!sds || sds.isTemplateDeclaration()) { e.error("%s `%s` has no members", s.kind(), s.toChars()); return new ErrorExp(); } auto idents = new Identifiers(); int pushIdentsDg(size_t n, Dsymbol sm) { if (!sm) return 1; // skip local symbols, such as static foreach loop variables if (auto decl = sm.isDeclaration()) { if (decl.storage_class & STC.local) { return 0; } } //printf("\t[%i] %s %s\n", i, sm.kind(), sm.toChars()); if (sm.ident) { const idx = sm.ident.toChars(); if (idx[0] == '_' && idx[1] == '_' && sm.ident != Id.ctor && sm.ident != Id.dtor && sm.ident != Id.__xdtor && sm.ident != Id.postblit && sm.ident != Id.__xpostblit) { return 0; } if (sm.ident == Id.empty) { return 0; } if (sm.isTypeInfoDeclaration()) // https://issues.dlang.org/show_bug.cgi?id=15177 return 0; if (!sds.isModule() && sm.isImport()) // https://issues.dlang.org/show_bug.cgi?id=17057 return 0; //printf("\t%s\n", sm.ident.toChars()); /* Skip if already present in idents[] */ foreach (id; *idents) { if (id == sm.ident) return 0; // Avoid using strcmp in the first place due to the performance impact in an O(N^2) loop. debug assert(strcmp(id.toChars(), sm.ident.toChars()) != 0); } idents.push(sm.ident); } else if (auto ed = sm.isEnumDeclaration()) { ScopeDsymbol._foreach(null, ed.members, &pushIdentsDg); } return 0; } ScopeDsymbol._foreach(sc, sds.members, &pushIdentsDg); auto cd = sds.isClassDeclaration(); if (cd && e.ident == Id.allMembers) { if (cd.semanticRun < PASS.semanticdone) cd.dsymbolSemantic(null); // https://issues.dlang.org/show_bug.cgi?id=13668 // Try to resolve forward reference void pushBaseMembersDg(ClassDeclaration cd) { for (size_t i = 0; i < cd.baseclasses.dim; i++) { auto cb = (*cd.baseclasses)[i].sym; assert(cb); ScopeDsymbol._foreach(null, cb.members, &pushIdentsDg); if (cb.baseclasses.dim) pushBaseMembersDg(cb); } } pushBaseMembersDg(cd); } // Turn Identifiers into StringExps reusing the allocated array assert(Expressions.sizeof == Identifiers.sizeof); auto exps = cast(Expressions*)idents; foreach (i, id; *idents) { auto se = new StringExp(e.loc, cast(char*)id.toChars()); (*exps)[i] = se; } /* Making this a tuple is more flexible, as it can be statically unrolled. * To make an array literal, enclose __traits in [ ]: * [ __traits(allMembers, ...) ] */ Expression ex = new TupleExp(e.loc, exps); ex = ex.expressionSemantic(sc); return ex; } if (e.ident == Id.compiles) { /* Determine if all the objects - types, expressions, or symbols - * compile without error */ if (!dim) return False(); foreach (o; *e.args) { uint errors = global.startGagging(); Scope* sc2 = sc.push(); sc2.tinst = null; sc2.minst = null; sc2.flags = (sc.flags & ~(SCOPE.ctfe | SCOPE.condition)) | SCOPE.compile | SCOPE.fullinst; bool err = false; auto t = isType(o); auto ex = t ? t.typeToExpression() : isExpression(o); if (!ex && t) { Dsymbol s; t.resolve(e.loc, sc2, &ex, &t, &s); if (t) { t.typeSemantic(e.loc, sc2); if (t.ty == Terror) err = true; } else if (s && s.errors) err = true; } if (ex) { ex = ex.expressionSemantic(sc2); ex = resolvePropertiesOnly(sc2, ex); ex = ex.optimize(WANTvalue); if (sc2.func && sc2.func.type.ty == Tfunction) { const tf = cast(TypeFunction)sc2.func.type; err |= tf.isnothrow && canThrow(ex, sc2.func, false); } ex = checkGC(sc2, ex); if (ex.op == TOK.error) err = true; } // Carefully detach the scope from the parent and throw it away as // we only need it to evaluate the expression // https://issues.dlang.org/show_bug.cgi?id=15428 sc2.detach(); if (global.endGagging(errors) || err) { return False(); } } return True(); } if (e.ident == Id.isSame) { /* Determine if two symbols are the same */ if (dim != 2) return dimError(2); if (!TemplateInstance.semanticTiargs(e.loc, sc, e.args, 0)) return new ErrorExp(); auto o1 = (*e.args)[0]; auto o2 = (*e.args)[1]; static FuncLiteralDeclaration isLambda(RootObject oarg) { if (auto t = isDsymbol(oarg)) { if (auto td = t.isTemplateDeclaration()) { if (td.members && td.members.dim == 1) { if (auto fd = (*td.members)[0].isFuncLiteralDeclaration()) return fd; } } } else if (auto ea = isExpression(oarg)) { if (ea.op == TOK.function_) { if (auto fe = cast(FuncExp)ea) return fe.fd; } } return null; } auto l1 = isLambda(o1); auto l2 = isLambda(o2); if (l1 && l2) { import dmd.lambdacomp : isSameFuncLiteral; if (isSameFuncLiteral(l1, l2, sc)) return True(); } // issue 12001, allow isSame, <BasicType>, <BasicType> Type t1 = isType(o1); Type t2 = isType(o2); if (t1 && t2 && t1.equals(t2)) return True(); auto s1 = getDsymbol(o1); auto s2 = getDsymbol(o2); //printf("isSame: %s, %s\n", o1.toChars(), o2.toChars()); version (none) { printf("o1: %p\n", o1); printf("o2: %p\n", o2); if (!s1) { if (auto ea = isExpression(o1)) printf("%s\n", ea.toChars()); if (auto ta = isType(o1)) printf("%s\n", ta.toChars()); return False(); } else printf("%s %s\n", s1.kind(), s1.toChars()); } if (!s1 && !s2) { auto ea1 = isExpression(o1); auto ea2 = isExpression(o2); if (ea1 && ea2) { if (ea1.equals(ea2)) return True(); } } if (!s1 || !s2) return False(); s1 = s1.toAlias(); s2 = s2.toAlias(); if (auto fa1 = s1.isFuncAliasDeclaration()) s1 = fa1.toAliasFunc(); if (auto fa2 = s2.isFuncAliasDeclaration()) s2 = fa2.toAliasFunc(); // https://issues.dlang.org/show_bug.cgi?id=11259 // compare import symbol to a package symbol static bool cmp(Dsymbol s1, Dsymbol s2) { auto imp = s1.isImport(); return imp && imp.pkg && imp.pkg == s2.isPackage(); } if (cmp(s1,s2) || cmp(s2,s1)) return True(); if (s1 == s2) return True(); // https://issues.dlang.org/show_bug.cgi?id=18771 // OverloadSets are equal if they contain the same functions auto overSet1 = s1.isOverloadSet(); if (!overSet1) return False(); auto overSet2 = s2.isOverloadSet(); if (!overSet2) return False(); if (overSet1.a.dim != overSet2.a.dim) return False(); // OverloadSets contain array of Dsymbols => O(n*n) // to compare for equality as the order of overloads // might not be the same Lnext: foreach(overload1; overSet1.a) { foreach(overload2; overSet2.a) { if (overload1 == overload2) continue Lnext; } return False(); } return True(); } if (e.ident == Id.getUnitTests) { if (dim != 1) return dimError(1); auto o = (*e.args)[0]; auto s = getDsymbolWithoutExpCtx(o); if (!s) { e.error("argument `%s` to __traits(getUnitTests) must be a module or aggregate", o.toChars()); return new ErrorExp(); } if (auto imp = s.isImport()) // https://issues.dlang.org/show_bug.cgi?id=10990 s = imp.mod; auto sds = s.isScopeDsymbol(); if (!sds) { e.error("argument `%s` to __traits(getUnitTests) must be a module or aggregate, not a %s", s.toChars(), s.kind()); return new ErrorExp(); } auto exps = new Expressions(); if (global.params.useUnitTests) { bool[void*] uniqueUnitTests; void symbolDg(Dsymbol s) { if (auto ad = s.isAttribDeclaration()) { ad.include(null).foreachDsymbol(&symbolDg); } else if (auto ud = s.isUnitTestDeclaration()) { if (cast(void*)ud in uniqueUnitTests) return; uniqueUnitTests[cast(void*)ud] = true; auto ad = new FuncAliasDeclaration(ud.ident, ud, false); ad.protection = ud.protection; auto e = new DsymbolExp(Loc.initial, ad, false); exps.push(e); } } sds.members.foreachDsymbol(&symbolDg); } auto te = new TupleExp(e.loc, exps); return te.expressionSemantic(sc); } if (e.ident == Id.getVirtualIndex) { if (dim != 1) return dimError(1); auto o = (*e.args)[0]; auto s = getDsymbolWithoutExpCtx(o); auto fd = s ? s.isFuncDeclaration() : null; if (!fd) { e.error("first argument to __traits(getVirtualIndex) must be a function"); return new ErrorExp(); } fd = fd.toAliasFunc(); // Necessary to support multiple overloads. return new IntegerExp(e.loc, fd.vtblIndex, Type.tptrdiff_t); } if (e.ident == Id.getPointerBitmap) { return pointerBitmap(e); } if (e.ident == Id.isZeroInit) { if (dim != 1) return dimError(1); auto o = (*e.args)[0]; Type t = isType(o); if (!t) { e.error("type expected as second argument of __traits `%s` instead of `%s`", e.ident.toChars(), o.toChars()); return new ErrorExp(); } Type tb = t.baseElemOf(); return tb.isZeroInit(e.loc) ? True() : False(); } if (e.ident == Id.getTargetInfo) { if (dim != 1) return dimError(1); auto ex = isExpression((*e.args)[0]); StringExp se = ex ? ex.ctfeInterpret().toStringExp() : null; if (!ex || !se || se.len == 0) { e.error("string expected as argument of __traits `%s` instead of `%s`", e.ident.toChars(), ex.toChars()); return new ErrorExp(); } se = se.toUTF8(sc); Expression r = target.getTargetInfo(se.toPtr(), e.loc); if (!r) { e.error("`getTargetInfo` key `\"%s\"` not supported by this implementation", se.toPtr()); return new ErrorExp(); } return r.expressionSemantic(sc); } extern (D) void* trait_search_fp(const(char)[] seed, ref int cost) { //printf("trait_search_fp('%s')\n", seed); if (!seed.length) return null; cost = 0; StringValue* sv = traitsStringTable.lookup(seed); return sv ? sv.ptrvalue : null; } if (auto sub = cast(const(char)*)speller(e.ident.toChars(), &trait_search_fp)) e.error("unrecognized trait `%s`, did you mean `%s`?", e.ident.toChars(), sub); else e.error("unrecognized trait `%s`", e.ident.toChars()); return new ErrorExp(); }
D
module UnrealScript.UnrealEd.InterpTrackVisibilityHelper; import ScriptClasses; import UnrealScript.Helpers; import UnrealScript.UnrealEd.InterpTrackHelper; extern(C++) interface InterpTrackVisibilityHelper : InterpTrackHelper { public extern(D): private static __gshared ScriptClass mStaticClass; @property final static ScriptClass StaticClass() { mixin(MGSCC("Class UnrealEd.InterpTrackVisibilityHelper")); } private static __gshared InterpTrackVisibilityHelper mDefaultProperties; @property final static InterpTrackVisibilityHelper DefaultProperties() { mixin(MGDPC("InterpTrackVisibilityHelper", "InterpTrackVisibilityHelper UnrealEd.Default__InterpTrackVisibilityHelper")); } }
D
/* Copyright (c) 2016-2019 Timur Gafarov Boost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ module dlib.filesystem.stdwindowsdir; import std.string; import std.conv; import std.range; import core.stdc.string; import core.stdc.wchar_; version(Windows) { import core.sys.windows.windows; } import dlib.core.memory; import dlib.filesystem.filesystem; //import dlib.text.utils; import dlib.text.utf16; version(Windows): string unmanagedStrFromCStrW(wchar* cstr) { return cast(string)convertUTF16ztoUTF8(cstr); } class StdWindowsDirEntryRange: InputRange!(DirEntry) { HANDLE hFind = INVALID_HANDLE_VALUE; WIN32_FIND_DATAW findData; DirEntry frontEntry; bool _empty = false; wchar* path; bool initialized = false; this(wchar* cwstr) { this.path = cwstr; } ~this() { if (frontEntry.name.length) Delete(frontEntry.name); close(); } import std.stdio; bool advance() { bool success = false; if (frontEntry.name.length) Delete(frontEntry.name); if (!initialized) { hFind = FindFirstFileW(path, &findData); initialized = true; if (hFind != INVALID_HANDLE_VALUE) success = true; string name = unmanagedStrFromCStrW(findData.cFileName.ptr); if (name == "." || name == "..") { success = false; Delete(name); } else { bool isDir = cast(bool)(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY); bool isFile = !isDir; frontEntry = DirEntry(name, isFile, isDir); } } if (!success && hFind != INVALID_HANDLE_VALUE) { string name; while(!success) { auto r = FindNextFileW(hFind, &findData); if (!r) break; name = unmanagedStrFromCStrW(findData.cFileName.ptr); if (name != "." && name != "..") success = true; else Delete(name); } if (success) { bool isDir = cast(bool)(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY); bool isFile = !isDir; frontEntry = DirEntry(name, isFile, isDir); } } if (!success) { FindClose(hFind); hFind = INVALID_HANDLE_VALUE; } return success; } override DirEntry front() { return frontEntry; } override void popFront() { _empty = !advance(); } override DirEntry moveFront() { _empty = !advance(); return frontEntry; } override bool empty() { return _empty; } int opApply(scope int delegate(DirEntry) dg) { int result = 0; for (size_t i = 0; !empty; i++) { popFront(); if (!empty()) result = dg(frontEntry); if (result != 0) break; } return result; } int opApply(scope int delegate(size_t, DirEntry) dg) { int result = 0; for (size_t i = 0; !empty; i++) { popFront(); if (!empty()) result = dg(i, frontEntry); if (result != 0) break; } return result; } void reset() { close(); } void close() { if (hFind != INVALID_HANDLE_VALUE) { FindClose(hFind); hFind = INVALID_HANDLE_VALUE; } initialized = false; _empty = false; } } class StdWindowsDirectory: Directory { StdWindowsDirEntryRange drange; wchar* path; this(wchar* cwstr) { path = cwstr; drange = New!StdWindowsDirEntryRange(path); } void close() { drange.close(); } StdWindowsDirEntryRange contents() { if (drange) drange.reset(); return drange; } ~this() { Delete(drange); drange = null; Delete(path); } }
D
/************************************************************************** МАГИЧЕСКИЙ УРОН B_MagicHurtNpc (slf, oth, damage) Персонаж slf (я) наносит урон oth (он) величиной damage с помощью магии //NS: в принципе, необязательно магией. Любой урон, не обрабатывающийся движком ***************************************************************************/ func void B_MagicHurtNpc(var C_Npc slf,var C_Npc oth,var int damage) { // нанесение урона Npc_ChangeAttribute(oth,ATR_HITPOINTS,-damage); // если повреждение несовместимо с жизнью if(Npc_IsDead(oth)) { // выдать ГГ опыт //Ns: в ZS_Dead не сработает, т.к. не задан other if((Npc_IsPlayer(slf) || (slf.aivar[AIV_PARTYMEMBER] == TRUE)) && (oth.aivar[AIV_VictoryXPGiven] == FALSE)) { B_GivePlayerXP(slf.level * XP_PER_VICTORY); oth.aivar[AIV_VictoryXPGiven] = TRUE; }; // сообщить окружающим об убийстве Npc_SendPassivePerc(oth,PERC_ASSESSMURDER,slf,oth);//NS: добавлено } else // если жертва еще жива { // сообщить окружающим о нападении Npc_SendPassivePerc(oth,PERC_ASSESSFIGHTSOUND,slf,oth);//NS: добавлено }; };
D
/* * Copyright (C) 2010 Google Inc. * * 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. */ package benchmarks.regression; /** * Many of these tests are bogus in that the cost will vary wildly depending on inputs. * For _my_ current purposes, that's okay. But beware! */ public class StrictMathBenchmark { private final double d = 1.2; private final float f = 1.2f; private final int i = 1; private final long l = 1L; /* Values for full line coverage of ceiling function */ private static final double[] CEIL_DOUBLES = new double[] { 3245817.2018463886, 1418139.083668501, 3.572936802189103E15, -4.7828929737254625E249, 213596.58636369856, 6.891928421440976E-96, -7.9318566885477E-36, -1.9610339084804148E15, -4.696725715628246E10, 3742491.296880909, 7.140274745333553E11 }; /* Values for full line coverage of floor function */ private static final double[] FLOOR_DOUBLES = new double[] { 7.140274745333553E11, 3742491.296880909, -4.696725715628246E10, -1.9610339084804148E15, 7.049948629370372E-56, -7.702933170334643E-16, -1.99657681810579, -1.1659287182288336E236, 4.085518816513057E15, -1500948.440658056, -2.2316479921415575E7 }; public void timeAbsD(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.abs(d); } } public void timeAbsF(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.abs(f); } } public void timeAbsI(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.abs(i); } } public void timeAbsL(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.abs(l); } } public void timeAcos(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.acos(d); } } public void timeAsin(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.asin(d); } } public void timeAtan(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.atan(d); } } public void timeAtan2(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.atan2(3, 4); } } public void timeCbrt(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.cbrt(d); } } public void timeCeilOverInterestingValues(int reps) { for (int rep = 0; rep < reps; ++rep) { for (int i = 0; i < CEIL_DOUBLES.length; ++i) { StrictMath.ceil(CEIL_DOUBLES[i]); } } } public void timeCopySignD(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.copySign(d, d); } } public void timeCopySignF(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.copySign(f, f); } } public void timeCos(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.cos(d); } } public void timeCosh(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.cosh(d); } } public void timeExp(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.exp(d); } } public void timeExpm1(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.expm1(d); } } public void timeFloorOverInterestingValues(int reps) { for (int rep = 0; rep < reps; ++rep) { for (int i = 0; i < FLOOR_DOUBLES.length; ++i) { StrictMath.floor(FLOOR_DOUBLES[i]); } } } public void timeGetExponentD(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.getExponent(d); } } public void timeGetExponentF(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.getExponent(f); } } public void timeHypot(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.hypot(d, d); } } public void timeIEEEremainder(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.IEEEremainder(d, d); } } public void timeLog(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.log(d); } } public void timeLog10(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.log10(d); } } public void timeLog1p(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.log1p(d); } } public void timeMaxD(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.max(d, d); } } public void timeMaxF(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.max(f, f); } } public void timeMaxI(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.max(i, i); } } public void timeMaxL(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.max(l, l); } } public void timeMinD(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.min(d, d); } } public void timeMinF(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.min(f, f); } } public void timeMinI(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.min(i, i); } } public void timeMinL(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.min(l, l); } } public void timeNextAfterD(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.nextAfter(d, d); } } public void timeNextAfterF(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.nextAfter(f, f); } } public void timeNextUpD(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.nextUp(d); } } public void timeNextUpF(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.nextUp(f); } } public void timePow(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.pow(d, d); } } public void timeRandom(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.random(); } } public void timeRint(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.rint(d); } } public void timeRoundD(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.round(d); } } public void timeRoundF(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.round(f); } } public void timeScalbD(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.scalb(d, 5); } } public void timeScalbF(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.scalb(f, 5); } } public void timeSignumD(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.signum(d); } } public void timeSignumF(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.signum(f); } } public void timeSin(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.sin(d); } } public void timeSinh(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.sinh(d); } } public void timeSqrt(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.sqrt(d); } } public void timeTan(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.tan(d); } } public void timeTanh(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.tanh(d); } } public void timeToDegrees(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.toDegrees(d); } } public void timeToRadians(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.toRadians(d); } } public void timeUlpD(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.ulp(d); } } public void timeUlpF(int reps) { for (int rep = 0; rep < reps; ++rep) { StrictMath.ulp(f); } } }
D
PLONG PLAT ED95 KD LOMAGAGE HIMAGAGE SLAT SLONG RESULTNO DP DM WT ROCKTYPE 238 77 6 77 15 60 64.5999985 -127.900002 1745 11.6000004 11.8000002 0.873563218 sediments, redbeds 4.5 80.5 11.8999996 29 8 9 35.7000008 -106.5 304 14.1999998 14.1999998 0.854651163 extrusives, basalts, rhyolites 219.300003 68.9000015 2.79999995 90.9000015 15 60 64.5 -128.5 343 5.5999999 5.5999999 0.959629941 sediments, redbeds 256.399994 77.0999985 13 0 2 56 46 -112 3368 21.7000008 21.7000008 0.416666667 extrusives, intrusives 164 83 5.80000019 32.2000008 15 65 58.5 -119.300003 7737 10 10 0.480769231 sediments, dolomite 240 82 34 55 2 65 45 -110 2808 49 58 0.458333333 intrusives, porphyry 83.5 79.8000031 17.2000008 8.80000019 15 17 30.7000008 -84.9000015 6882 11.8000002 20.2000008 0.87 sediments 275.5 83.5999985 0 0 0 20 46.7999992 -90.6999969 5904 3.4000001 3.4000001 0.891964286 sediments 45.2999992 81.0999985 12.8999996 51.9000015 14 17 45.2999992 -110.800003 5975 13.5 18.6000004 0.744791667 sediments
D
/Users/anton/Developer/BellmanBindings-iOS/cargo/target/x86_64-apple-ios/release/deps/libbellman-455df3cfea8e87ad.rlib: /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/lib.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/domain.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/groth16/mod.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/groth16/generator.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/groth16/prover.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/groth16/verifier.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/group.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/source.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/multiexp.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/multicore.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/cs.rs /Users/anton/Developer/BellmanBindings-iOS/cargo/target/x86_64-apple-ios/release/deps/libbellman-455df3cfea8e87ad.a: /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/lib.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/domain.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/groth16/mod.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/groth16/generator.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/groth16/prover.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/groth16/verifier.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/group.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/source.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/multiexp.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/multicore.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/cs.rs /Users/anton/Developer/BellmanBindings-iOS/cargo/target/x86_64-apple-ios/release/deps/bellman-455df3cfea8e87ad.d: /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/lib.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/domain.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/groth16/mod.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/groth16/generator.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/groth16/prover.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/groth16/verifier.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/group.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/source.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/multiexp.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/multicore.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/cs.rs /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/lib.rs: /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/domain.rs: /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/groth16/mod.rs: /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/groth16/generator.rs: /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/groth16/prover.rs: /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/groth16/verifier.rs: /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/group.rs: /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/source.rs: /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/multiexp.rs: /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/multicore.rs: /Users/anton/.cargo/git/checkouts/bellman-7a75f3b44e91e034/6e45a4b/src/cs.rs:
D
module dwt.internal.mozilla.Common; version(Windows) { const NS_WIN32 = 1; } version(linux) { const NS_UNIX = 1; } alias uint nsresult; alias uint nsrefcnt; const nsnull = 0; /****************************************************************************** prtypes ******************************************************************************/ extern (System): alias ubyte PRUint8; alias byte PRInt8; const PR_INT8_MAX = 127; const PR_UINT8_MAX = 255U; alias ushort PRUint16; alias short PRInt16; const PR_INT16_MAX = 32767; const PR_UINT16_MAX = 65535U; alias uint PRUint32; alias int PRInt32; alias long PRInt64; alias ulong PRUint64; alias int PRIntn; alias uint PRUintn; alias double PRFloat64; alias size_t PRSize; alias PRInt32 PROffset32; alias PRInt64 PROffset64; alias ptrdiff_t PRPtrdiff; alias uint PRUptrdiff; alias PRIntn PRBool; const PR_TRUE = 1; const PR_FALSE = 0; alias PRUint8 PRPackedBool; enum { PR_FAILURE = -1, PR_SUCCESS, } alias int PRStatus; alias wchar PRUnichar; alias int PRWord; alias uint PRUword; /****************************************************************************** nscommon ******************************************************************************/ alias void* nsIWidget; alias void* nsILayoutHistoryState; alias void* nsIDeviceContext; alias void* nsPresContext; alias void* nsEvent; alias void* nsEventStatus; alias void* nsIPresShell; alias void* JSContext; alias void* PRThread; alias void* PLEvent; alias void* PLEventQueue; alias void* PLHandleEventProc; alias void* PLDestroyEventProc; /****************************************************************************** gfxtypes ******************************************************************************/ alias PRUint32 gfx_color; alias PRUint16 gfx_depth; alias PRInt32 gfx_format; alias void* nsIntRect; alias void* nsRect;
D
/** * Copyright: Copyright Jason White, 2016 * License: MIT * Authors: Jason White * * Description: * Stores the persistent state of the build. */ module button.state; import button.command; import button.resource; import button.task; import button.edge, button.edgedata; import util.sqlite3; import std.typecons : tuple, Tuple; /** * Table of resource vertices. * * The first entry in this table will always be the build description. */ private immutable resourcesTable = q"{ CREATE TABLE IF NOT EXISTS resource ( id INTEGER NOT NULL, path TEXT NOT NULL, lastModified INTEGER NOT NULL, checksum BLOB NOT NULL, PRIMARY KEY (id), UNIQUE (path) )}"; /** * Table of task vertices. */ private immutable tasksTable = q"{ CREATE TABLE IF NOT EXISTS task ( id INTEGER, commands TEXT NOT NULL, workDir TEXT NOT NULL, display TEXT, lastExecuted INTEGER NOT NULL, PRIMARY KEY(id), UNIQUE(commands, workDir) )}"; /** * Table of outgoing edges from resources. */ private immutable resourceEdgesTable = q"{ CREATE TABLE IF NOT EXISTS resourceEdge ( id INTEGER PRIMARY KEY, "from" INTEGER NOT NULL REFERENCES resource(id) ON DELETE CASCADE, "to" INTEGER NOT NULL REFERENCES task(id) ON DELETE CASCADE, type INTEGER NOT NULL, UNIQUE("from", "to", type) )}"; /** * Table of outgoing edges from tasks. */ private immutable taskEdgesTable = q"{ CREATE TABLE IF NOT EXISTS taskEdge ( id INTEGER PRIMARY KEY, "from" INTEGER NOT NULL REFERENCES task(id) ON DELETE CASCADE, "to" INTEGER NOT NULL REFERENCES resource(id) ON DELETE CASCADE, type INTEGER NOT NULL, UNIQUE ("from", "to", type) )}"; /** * Table of pending resources. */ private immutable pendingResourcesTable = q"{ CREATE TABLE IF NOT EXISTS pendingResources ( resid INTEGER NOT NULL REFERENCES resource(id) ON DELETE CASCADE, PRIMARY KEY (resid), UNIQUE (resid) )}"; /** * Table of pending tasks. */ private immutable pendingTasksTable = q"{ CREATE TABLE IF NOT EXISTS pendingTasks ( taskid INTEGER NOT NULL REFERENCES task(id) ON DELETE CASCADE, PRIMARY KEY (taskid), UNIQUE (taskid) )}"; /** * Index on vertex keys to speed up searches. */ private immutable resourceIndex = q"{ CREATE INDEX IF NOT EXISTS resourceIndex ON resource(path) }"; /// Ditto private immutable taskIndex = q"{ CREATE INDEX IF NOT EXISTS taskIndex ON task(commands,workDir) }"; /** * Index on edges to speed up finding neighbors. */ private immutable resourceEdgeIndex = q"{ CREATE INDEX IF NOT EXISTS resourceEdgeIndex ON resourceEdge("from","to") }"; /// Ditto private immutable taskEdgeIndex = q"{ CREATE INDEX IF NOT EXISTS taskEdgeIndex ON taskEdge("from","to") }"; /** * List of SQL statements to run in order to initialize the database. */ private immutable initializeStatements = [ // Create tables resourcesTable, tasksTable, resourceEdgesTable, taskEdgesTable, pendingResourcesTable, pendingTasksTable, // Indiees resourceEdgeIndex, taskEdgeIndex, resourceIndex, taskIndex, ]; /** * Simple type to leverage the type system to help to differentiate between * storage indices. */ struct Index(T) { ulong index; alias index this; /// An invalid index. enum Invalid = Index!T(0); } /** * Convenience type for an edge composed of two indices. */ alias Index(A, B) = Edge!(Index!A, Index!B); /** * Convenience type for an index of the edge itself. */ alias EdgeIndex(A, B) = Index!(Edge!(A, B)); /** * An edge row in the database. */ alias EdgeRow(A, B, Data=EdgeType) = Edge!(Index!A, Index!B, Data); /** * A vertex paired with some data. This is useful for representing a neighbor. */ struct Neighbor(Vertex, Data) { Vertex vertex; Data data; } /** * Convenience templates to get the other type of vertex from the given vertex. */ alias Other(A : Resource) = Task; alias Other(A : Task) = Resource; /// Ditto /** * Convenience template to construct an edge from the starting vertex. */ alias NeighborIndex(V : Index!V) = EdgeIndex!(V, Other!V); /** * Thrown when an edge does not exist. */ class InvalidEdge : Exception { this(string msg, string file = __FILE__, size_t line = __LINE__) { super(msg, file, line); } } /** * Deserializes a vertex from a SQLite statement. This assumes that the * statement has every column of the vertex except the row ID. */ Vertex parse(Vertex : Resource)(SQLite3.Statement s) { import std.datetime : SysTime; return Resource( s.get!string(0), // Path SysTime(s.get!long(1)), // Last modified cast(ubyte[])s.get!(void[])(2) // Checksum ); } /// Ditto Vertex parse(Vertex : Task)(SQLite3.Statement s) { import std.conv : to; import std.datetime : SysTime; import std.algorithm.iteration : map; import std.array : array; import std.exception : assumeUnique; return Task( s.get!string(0) .to!(string[][]) .map!(x => Command(x.assumeUnique)) .array .assumeUnique, s.get!string(1), s.get!string(2), SysTime(s.get!long(3)), ); } /** * Deserializes an edge from a SQLite statement. This assumes that the * statement has every column of the vertex except the row ID. */ E parse(E : EdgeRow!(Resource, Task, EdgeType))(SQLite3.Statement s) { return E( Index!Resource(s.get!ulong(0)), Index!Task(s.get!ulong(1)), cast(EdgeType)s.get!int(2) ); } /// Ditto E parse(E : EdgeRow!(Task, Resource, EdgeType))(SQLite3.Statement s) { return E( Index!Task(s.get!ulong(0)), Index!Resource(s.get!ulong(1)), cast(EdgeType)s.get!int(2) ); } /// Ditto E parse(E : EdgeRow!(Resource, Task, EdgeIndex!(Resource, Task)))(SQLite3.Statement s) { return E( Index!Resource(s.get!ulong(0)), Index!Task(s.get!ulong(1)), cast(EdgeIndex!(Resource, Task))s.get!int(2) ); } /// Ditto E parse(E : EdgeRow!(Task, Resource, EdgeIndex!(Task, Resource)))(SQLite3.Statement s) { return E( Index!Task(s.get!ulong(0)), Index!Resource(s.get!ulong(1)), cast(EdgeIndex!(Task, Resource))s.get!int(2) ); } /** * Parses an edge without the associated data. */ E parse(E : Index!(Resource, Task))(SQLite3.Statement s) { return E(Index!Resource(s.get!ulong(0)), Index!Task(s.get!ulong(1))); } /// Ditto E parse(E : Index!(Task, Resource))(SQLite3.Statement s) { return E(Index!Task(s.get!ulong(0)), Index!Resource(s.get!ulong(1))); } /** * Deserializes edge data. */ E parse(E : EdgeType)(SQLite3.Statement s) { return cast(EdgeType)s.get!int(0); } /** * Deserializes a neighbor. */ E parse(E : Neighbor!(Index!Resource, EdgeType))(SQLite3.Statement s) { return E( Index!Resource(s.get!ulong(0)), cast(EdgeType)s.get!int(1) ); } /// Ditto E parse(E : Neighbor!(Index!Task, EdgeType))(SQLite3.Statement s) { return E( Index!Task(s.get!ulong(0)), cast(EdgeType)s.get!int(1) ); } /// Ditto E parse(E : Neighbor!(Index!Resource, EdgeIndex!(Task, Resource)))(SQLite3.Statement s) { return E( Index!Resource(s.get!ulong(0)), EdgeIndex!(Task, Resource)(s.get!ulong(1)) ); } /// Ditto E parse(E : Neighbor!(Index!Task, EdgeIndex!(Resource, Task)))(SQLite3.Statement s) { return E( Index!Task(s.get!ulong(0)), EdgeIndex!(Resource, Task)(s.get!ulong(1)) ); } /** * Parses a vertex key. */ E parse(E : ResourceKey)(SQLite3.Statement s) { return E( s.get!string(0) ); } /// Ditto E parse(E : TaskKey)(SQLite3.Statement s) { import std.conv : to; import std.algorith.iteration : map; import std.array : array; import std.exception : assumeUnique; return E( s.get!string(0) .to!(string[][]) .map!(x => Command(x.assumeUnique)) .array .assumeUnique, s.get!string(1) ); } /** * Stores the current state of the build. */ class BuildState : SQLite3 { // The build description is always the first entry in the database. static immutable buildDescId = Index!Resource(1); private { Statement sqlInsertResource; Statement sqlInsertTask; Statement sqlAddResource; Statement sqlAddTask; Statement sqlRemoveResourceByIndex; Statement sqlRemoveTaskByIndex; Statement sqlRemoveResourceByKey; Statement sqlRemoveTaskByKey; Statement sqlFindResourceByKey; Statement sqlFindTaskByKey; Statement sqlResourceByIndex; Statement sqlTaskByIndex; Statement sqlResourceByKey; Statement sqlTaskByKey; Statement sqlUpdateResource; Statement sqlUpdateTask; Statement sqlInsertTaskEdge; Statement sqlInsertResourceEdge; Statement sqlRemoveTaskEdge; Statement sqlRemoveResourceEdge; Statement sqlResourceDegreeIn; Statement sqlTaskDegreeIn; Statement sqlResourceDegreeOut; Statement sqlTaskDegreeOut; Statement sqlResourceEdgeExists; Statement sqlTaskEdgeExists; Statement sqlAddPendingResource; Statement sqlAddPendingTask; Statement sqlRemovePendingResource; Statement sqlRemovePendingTask; Statement sqlIsPendingResource; Statement sqlIsPendingTask; } /** * Open or create the build state file. */ this(string fileName = ":memory:") { super(fileName); execute("PRAGMA foreign_keys = ON"); initialize(); } /** * Creates the tables if they don't already exist. */ private void initialize() { begin(); scope (success) commit(); scope (failure) rollback(); foreach (statement; initializeStatements) execute(statement); // Add the build description resource if it doesn't already exist. execute( `INSERT OR IGNORE INTO resource` ~ ` (id,path,lastModified,checksum)` ~ ` VALUES (?,?,?,?)` , buildDescId, "", 0, 0 ); // Prepare SQL statements. This is much faster than preparing + // executing statements for every query. For queries that only run once, // it is not necessary to prepare them here. sqlInsertResource = new Statement( `INSERT INTO resource(path, lastModified, checksum)` ~ ` VALUES(?, ?, ?)` ); sqlInsertTask = new Statement( `INSERT INTO task (commands, workDir, display, lastExecuted)` ~ ` VALUES(?, ?, ?, ?)` ); sqlAddResource = new Statement( `INSERT OR IGNORE INTO resource` ~ ` (path, lastModified, checksum)` ~ ` VALUES(?, ?, ?)` ); sqlAddTask = new Statement( `INSERT OR IGNORE INTO task` ~ ` (commands, workDir, display, lastExecuted)` ~ ` VALUES(?, ?, ?, ?)` ); sqlRemoveResourceByIndex = new Statement( `DELETE FROM resource WHERE id=?` ); sqlRemoveTaskByIndex = new Statement( `DELETE FROM task WHERE id=?` ); sqlRemoveResourceByKey = new Statement( `DELETE FROM resource WHERE path=?` ); sqlRemoveTaskByKey = new Statement( `DELETE FROM task WHERE commands=? AND workDir=?` ); sqlFindResourceByKey = new Statement( `SELECT id FROM resource WHERE path=?` ); sqlFindTaskByKey = new Statement( `SELECT id FROM task WHERE commands=? AND workDir=?` ); sqlResourceByIndex = new Statement( `SELECT path,lastModified,checksum` ~ ` FROM resource WHERE id=?` ); sqlTaskByIndex = new Statement( `SELECT commands,workDir,display,lastExecuted` ~ ` FROM task WHERE id=?` ); sqlResourceByKey = new Statement( `SELECT path,lastModified,checksum` ~ ` FROM resource WHERE path=?` ); sqlTaskByKey = new Statement( `SELECT commands,workDir,display,lastExecuted FROM task` ~ ` WHERE commands=? AND workDir=?` ); sqlUpdateResource = new Statement( `UPDATE resource` ~ ` SET path=?,lastModified=?,checksum=?` ~ ` WHERE id=?` ); sqlUpdateTask = new Statement( `UPDATE task` ~ ` SET commands=?,workDir=?,display=?,lastExecuted=?` ~ ` WHERE id=?` ); sqlInsertTaskEdge = new Statement( `INSERT INTO taskEdge("from", "to", type) VALUES(?, ?, ?)` ); sqlInsertResourceEdge = new Statement( `INSERT INTO resourceEdge("from", "to", type)` ~ ` VALUES(?, ?, ?)` ); sqlRemoveTaskEdge = new Statement( `DELETE FROM taskEdge WHERE "from"=? AND "to"=? AND type=?` ); sqlRemoveResourceEdge = new Statement( `DELETE FROM resourceEdge WHERE "from"=? AND "to"=? AND type=?` ); sqlResourceDegreeIn = new Statement( `SELECT COUNT("to") FROM taskEdge WHERE "to"=?` ); sqlTaskDegreeIn = new Statement( `SELECT COUNT("to") FROM resourceEdge WHERE "to"=?` ); sqlResourceDegreeOut = new Statement( `SELECT COUNT("to") FROM resourceEdge WHERE "from"=?` ); sqlTaskDegreeOut = new Statement( `SELECT COUNT("to") FROM taskEdge WHERE "from"=?` ); sqlResourceEdgeExists = new Statement( `SELECT "type" FROM resourceEdge` ~ ` WHERE "from"=? AND "to"=? AND type=?` ); sqlTaskEdgeExists = new Statement( `SELECT "type" FROM taskEdge WHERE` ~ ` "from"=? AND "to"=? AND type=?` ); sqlAddPendingResource = new Statement( `INSERT OR IGNORE INTO pendingResources(resid) VALUES(?)` ); sqlAddPendingTask = new Statement( `INSERT OR IGNORE INTO pendingTasks(taskid) VALUES(?)` ); sqlRemovePendingResource = new Statement( `DELETE FROM pendingResources WHERE resid=?` ); sqlRemovePendingTask = new Statement( `DELETE FROM pendingTasks WHERE taskid=?` ); sqlIsPendingResource = new Statement( `SELECT EXISTS(` ~ ` SELECT 1 FROM pendingResources WHERE resid=? LIMIT 1` ~ `)` ); sqlIsPendingTask = new Statement( `SELECT EXISTS(` ~ ` SELECT 1 FROM pendingTasks WHERE taskid=? LIMIT 1`~ `)` ); } /** * Returns the number of vertices in the database. */ ulong length(Vertex : Resource)() { import std.exception : enforce; auto s = prepare(`SELECT COUNT(*) FROM resource WHERE id > 1`); enforce(s.step(), "Failed to find number of resources"); return s.get!ulong(0); } /// Dito ulong length(Vertex : Task)() { import std.exception : enforce; auto s = prepare(`SELECT COUNT(*) FROM task`); enforce(s.step(), "Failed to find number of tasks"); return s.get!ulong(0); } /** * Inserts a vertex into the database. An exception is thrown if the vertex * already exists. Otherwise, the vertex's ID is returned. */ Index!Resource put(in Resource resource) { alias s = sqlInsertResource; synchronized (s) { scope (exit) s.reset(); s.bind(resource.path, resource.lastModified.stdTime, resource.checksum); s.step(); } return Index!Resource(lastInsertId); } /// Ditto Index!Task put(in Task task) { import std.conv : to; alias s = sqlInsertTask; synchronized (s) { scope (exit) s.reset(); s.bind(task.commands.to!string(), task.workingDirectory, task.display, task.lastExecuted.stdTime); s.step(); } return Index!Task(lastInsertId); } unittest { import std.datetime : SysTime; auto state = new BuildState; { immutable vertex = Resource("foo.c", SysTime(9001)); auto id = state.put(vertex); assert(state[id] == vertex); } { immutable vertex = Task([Command(["foo", "test", "test test"])]); immutable id = state.put(vertex); assert(state[id] == vertex); } } /** * Inserts a vertex into the database unless it already exists. */ void add(in Resource resource) { alias s = sqlAddResource; synchronized (s) { scope (exit) s.reset(); s.bind(resource.path, resource.lastModified.stdTime, resource.checksum); s.step(); } } // Ditto void add(in Task task) { import std.conv : to; alias s = sqlAddTask; synchronized (s) { scope (exit) s.reset(); s.bind(task.commands.to!string(), task.workingDirectory, task.display, task.lastExecuted.stdTime); s.step(); } } /** * Removes a vertex by the given index. If the vertex does not exist, an * exception is thrown. */ void remove(Index!Resource index) { alias s = sqlRemoveResourceByIndex; synchronized (s) { scope (exit) s.reset(); s.bind(index); s.step(); } } /// Ditto void remove(Index!Task index) { alias s = sqlRemoveTaskByIndex; synchronized (s) { scope (exit) s.reset(); s.bind(index); s.step(); } } /// Ditto void remove(ResourceId path) { alias s = sqlRemoveResourceByKey; synchronized (s) { scope (exit) s.reset(); s.bind(path); s.step(); } } /// Ditto void remove(TaskKey key) { import std.conv : to; alias s = sqlRemoveTaskByKey; synchronized (s) { scope (exit) s.reset(); s.bind(key.commands.to!string, key.workingDirectory); s.step(); } } /** * Returns the index of the given vertex. */ Index!Resource find(const(char)[] key) { alias s = sqlFindResourceByKey; synchronized (s) { scope (exit) s.reset(); s.bind(key); if (s.step()) return typeof(return)(s.get!ulong(0)); } return typeof(return).Invalid; } /// Ditto Index!Task find(TaskKey id) { import std.conv : to; alias s = sqlFindTaskByKey; synchronized (s) { scope (exit) s.reset(); s.bind(id.commands.to!string, id.workingDirectory); if (s.step()) return typeof(return)(s.get!ulong(0)); } return typeof(return).Invalid; } /** * Returns the vertex state at the given index. */ Resource opIndex(Index!Resource index) { import std.exception : enforce; alias s = sqlResourceByIndex; synchronized (s) { scope (exit) s.reset(); s.bind(index); enforce(s.step(), "Vertex does not exist."); return s.parse!Resource(); } } /// Ditto Task opIndex(Index!Task index) { import std.exception : enforce; alias s = sqlTaskByIndex; synchronized (s) { scope (exit) s.reset(); s.bind(index); enforce(s.step(), "Vertex does not exist."); return s.parse!Task(); } } /** * Returns the vertex state for the given vertex name. Throws an exception if * the vertex does not exist. * * TODO: Only return the vertex's value. */ Resource opIndex(ResourceId path) { import std.exception : enforce; alias s = sqlResourceByKey; synchronized (s) { scope (exit) s.reset(); s.bind(path); enforce(s.step(), "Vertex does not exist."); return s.parse!Resource(); } } /// Ditto Task opIndex(TaskKey key) { import std.exception : enforce; import std.conv : to; alias s = sqlTaskByKey; synchronized (s) { scope (exit) s.reset(); s.bind(key.commands.to!string, key.workingDirectory); enforce(s.step(), "Vertex does not exist."); return s.parse!Task(); } } /** * Changes the state of the vertex at the given index. Throws an exception if * the vertex does not exist. */ void opIndexAssign(in Resource v, Index!Resource index) { alias s = sqlUpdateResource; synchronized (s) { scope (exit) s.reset(); s.bind(v.path, v.lastModified.stdTime, v.checksum, index); s.step(); } } /// Ditto void opIndexAssign(in Task v, Index!Task index) { import std.conv : to; alias s = sqlUpdateTask; synchronized (s) { scope (exit) s.reset(); s.bind(v.commands.to!string, v.workingDirectory, v.display, v.lastExecuted.stdTime, index); s.step(); } } /** * Returns an input range that iterates over all resources. The order is * guaranteed to be the same as the order they were inserted in. */ @property auto enumerate(T : Resource)() { return prepare( `SELECT path,lastModified,checksum FROM resource WHERE id>1` ).rows!(parse!T); } unittest { import std.algorithm : equal; import std.datetime : SysTime; auto state = new BuildState; immutable vertices = [ Resource("foo.o", SysTime(42)), Resource("foo.c", SysTime(1337)), Resource("bar.c", SysTime(9001)), Resource("bar.o", SysTime(0)), ]; foreach (vertex; vertices) state.put(vertex); assert(equal(vertices, state.enumerate!Resource)); } /** * Returns an input range that iterates over all tasks. The order is * guaranteed to be the same as the order they were inserted in. */ @property auto enumerate(T : Task)() { return prepare(`SELECT commands,workDir,display,lastExecuted FROM task`) .rows!(parse!T); } unittest { import std.algorithm : equal, sort; auto state = new BuildState; immutable tasks = [ Task([Command(["foo", "arg 1", "arg 2"])]), Task([Command(["bar", "arg 1"])]), Task([Command(["baz", "arg 1", "arg 2", "arg 3"])]), ]; foreach (task; tasks) state.put(task); assert(equal(tasks, state.enumerate!Task)); } /** * Returns a range of vertex keys. The returned range is not guaranteed to * be sorted. */ @property auto enumerate(T : ResourceKey)() { return prepare(`SELECT path FROM resource WHERE id>1`) .rows!(parse!T); } /// Ditto @property auto enumerate(T : TaskKey)() { return prepare(`SELECT commands,workDir FROM task`) .rows!(parse!TaskKey); } /** * Returns a range of row indices. */ @property auto enumerate(T : Index!Resource)() { return prepare(`SELECT id FROM resource WHERE id>1`) .rows!((SQLite3.Statement s) => T(s.get!ulong(0))); } /// Ditto @property auto enumerate(T : Index!Task)() { return prepare(`SELECT id FROM task`) .rows!((SQLite3.Statement s) => T(s.get!ulong(0))); } /** * Adds an edge. Throws an exception if the edge already exists. Returns the * index of the edge. */ void put(Index!Task from, Index!Resource to, EdgeType type) { alias s = sqlInsertTaskEdge; synchronized (s) { scope (exit) s.reset(); s.bind(from, to, type); s.step(); } } /// Ditto void put(Index!Resource from, Index!Task to, EdgeType type) { alias s = sqlInsertResourceEdge; synchronized (s) { scope (exit) s.reset(); s.bind(from, to, type); s.step(); } } /// Ditto void put(ResourceId a, TaskKey b, EdgeType type) { put(find(a), find(b), type); } /// Ditto void put(TaskKey a, ResourceId b, EdgeType type) { put(find(a), find(b), type); } /** * Removes an edge. Throws an exception if the edge does not exist. */ void remove(Index!Resource from, Index!Task to, EdgeType type) { alias s = sqlRemoveResourceEdge; synchronized (s) { scope (exit) s.reset(); s.bind(from, to, type); s.step(); } } /// Ditto void remove(Index!Task from, Index!Resource to, EdgeType type) { alias s = sqlRemoveTaskEdge; synchronized (s) { scope (exit) s.reset(); s.bind(from, to, type); s.step(); } } /// Ditto void remove(TaskKey from, ResourceId to, EdgeType type) { remove(find(from), find(to), type); } /// Ditto void remove(ResourceId from, TaskKey to, EdgeType type) { remove(find(from), find(to), type); } unittest { auto state = new BuildState; immutable resId = state.put(Resource("foo.c")); immutable taskId = state.put(Task([Command(["gcc", "foo.c"])])); state.remove(resId); state.remove(taskId); } /** * Returns the number of incoming edges to the given vertex. */ size_t degreeIn(Index!Resource index) { import std.exception : enforce; alias s = sqlResourceDegreeIn; synchronized (s) { scope (exit) s.reset(); s.bind(index); enforce(s.step(), "Failed to count incoming edges to resource"); return s.get!(typeof(return))(0); } } /// Ditto size_t degreeIn(Index!Task index) { import std.exception : enforce; alias s = sqlTaskDegreeIn; synchronized (s) { scope (exit) s.reset(); s.bind(index); enforce(s.step(), "Failed to count incoming edges to resource"); return s.get!(typeof(return))(0); } } /// Ditto size_t degreeOut(Index!Resource index) { import std.exception : enforce; alias s = sqlResourceDegreeOut; synchronized (s) { scope (exit) s.reset(); s.bind(index); enforce(s.step(), "Failed to count outgoing edges from resource"); return s.get!(typeof(return))(0); } } /// Ditto size_t degreeOut(Index!Task index) { import std.exception : enforce; alias s = sqlTaskDegreeOut; synchronized (s) { scope (exit) s.reset(); s.bind(index); enforce(s.step(), "Failed to count outgoing edges from task"); return s.get!(typeof(return))(0); } } unittest { auto state = new BuildState(); auto resources = [ state.put(Resource("foo")), state.put(Resource("bar")), ]; auto tasks = [ state.put(Task([Command(["test"])])), state.put(Task([Command(["foobar", "foo", "bar"])])), ]; state.put(tasks[0], resources[0], EdgeType.explicit); state.put(tasks[0], resources[1], EdgeType.explicit); state.put(resources[0], tasks[1], EdgeType.explicit); state.put(resources[1], tasks[1], EdgeType.explicit); assert(state.degreeIn(tasks[0]) == 0); assert(state.degreeIn(tasks[1]) == 2); assert(state.degreeIn(resources[0]) == 1); assert(state.degreeIn(resources[1]) == 1); assert(state.degreeOut(tasks[0]) == 2); assert(state.degreeOut(tasks[1]) == 0); assert(state.degreeOut(resources[0]) == 1); assert(state.degreeOut(resources[1]) == 1); } /** * Lists all outgoing task edges. */ @property auto edges(From : Task, To : Resource, Data : EdgeType)() { return prepare(`SELECT "from","to","type" FROM taskEdge`) .rows!(parse!(EdgeRow!(From, To, Data))); } /// Ditto @property auto edges(From : Task, To : Resource, Data : EdgeType) (EdgeType type) { return prepare(`SELECT "from","to","type" FROM taskEdge WHERE type=?`, type) .rows!(parse!(EdgeRow!(From, To, Data))); } /** * Checks if an edge exists between two vertices. */ bool edgeExists(Index!Task from, Index!Resource to, EdgeType type) { alias s = sqlTaskEdgeExists; synchronized (s) { scope (exit) s.reset(); s.bind(from, to, type); return s.step(); } } /// Ditto bool edgeExists(Index!Resource from, Index!Task to, EdgeType type) { alias s = sqlResourceEdgeExists; synchronized (s) { scope (exit) s.reset(); s.bind(from, to, type); return s.step(); } } /** * Lists all outgoing resource edges. */ @property auto edges(From : Resource, To : Task, Data : EdgeType)() { return prepare(`SELECT "from","to","type" FROM resourceEdge`) .rows!(parse!(EdgeRow!(From, To, Data))); } /// Ditto @property auto edges(From : Resource, To : Task, Data : EdgeType) (EdgeType type) { return prepare( `SELECT "from","to","type" FROM resourceEdge WHERE type=?`, type) .rows!(parse!(EdgeRow!(From, To, Data))); } /** * Returns the outgoing neighbors of the given node. */ @property auto outgoing(Index!Resource v) { return prepare(`SELECT "to" FROM resourceEdge WHERE "from"=?`, v) .rows!((SQLite3.Statement s) => Index!Task(s.get!ulong(0))); } /// Ditto @property auto outgoing(Index!Task v) { return prepare(`SELECT "to" FROM taskEdge WHERE "from"=?`, v) .rows!((SQLite3.Statement s) => Index!Resource(s.get!ulong(0))); } /// Ditto @property auto outgoing(Data : EdgeType)(Index!Resource v) { return prepare(`SELECT "to",type FROM resourceEdge WHERE "from"=?`, v) .rows!(parse!(Neighbor!(Index!Task, Data))); } /// Ditto @property auto outgoing(Data : EdgeType)(Index!Task v) { return prepare(`SELECT "to",type FROM taskEdge WHERE "from"=?`, v) .rows!(parse!(Neighbor!(Index!Resource, Data))); } /// Ditto @property auto outgoing(Data : EdgeIndex!(Resource, Task))(Index!Resource v) { return prepare(`SELECT "to",id FROM resourceEdge WHERE "from"=?`, v) .rows!(parse!(Neighbor!(Index!Task, Data))); } /// Ditto @property auto outgoing(Data : EdgeIndex!(Task, Resource))(Index!Task v) { return prepare(`SELECT "to",id FROM taskEdge WHERE "from"=?`, v) .rows!(parse!(Neighbor!(Index!Resource, Data))); } /// Ditto @property auto outgoing(Data : ResourceId)(Index!Task v) { return prepare( `SELECT resource.path` ~ ` FROM taskEdge AS e` ~ ` JOIN resource ON e."to"=resource.id` ~ ` WHERE e."from"=?`, v ) .rows!((SQLite3.Statement s) => s.get!string(0)); } /// Ditto @property auto outgoing(Data : Resource)(Index!Task v, EdgeType type) { return prepare( `SELECT resource.path, resource.lastModified, resource.checksum` ~ ` FROM taskEdge AS e` ~ ` JOIN resource ON e."to"=resource.id` ~ ` WHERE e."from"=? AND type=?`, v, type ) .rows!(parse!Resource); } /** * Returns the incoming neighbors of the given node. */ @property auto incoming(Data : EdgeType)(Index!Resource v) { return prepare(`SELECT "from",type FROM taskEdge WHERE "to"=?`, v) .rows!(parse!(Neighbor!(Index!Task, Data))); } /// Ditto @property auto incoming(Data : EdgeType)(Index!Task v) { return prepare(`SELECT "from",type FROM resourceEdge WHERE "to"=?`, v) .rows!(parse!(Neighbor!(Index!Resource, Data))); } /// Ditto @property auto incoming(Data : EdgeIndex!(Resource, Task))(Index!Resource v) { return prepare(`SELECT "from",id FROM taskEdge WHERE "to"=?`, v) .rows!(parse!(Neighbor!(Index!Task, Data))); } /// Ditto @property auto incoming(Data : EdgeIndex!(Task, Resource))(Index!Task v) { return prepare(`SELECT "from",id FROM resourceEdge WHERE "to"=?`, v) .rows!(parse!(Neighbor!(Index!Resource, Data))); } /// Ditto @property auto incoming(Data : ResourceId)(Index!Task v) { return prepare( `SELECT resource.path` ~ ` FROM resourceEdge AS e` ~ ` JOIN resource ON e."from"=resource.id` ~ ` WHERE e."to"=?`, v ) .rows!((SQLite3.Statement s) => s.get!string(0)); } /// Ditto @property auto incoming(Data : Resource)(Index!Task v, EdgeType type) { return prepare( `SELECT resource.path, resource.lastModified, resource.checksum` ~ ` FROM resourceEdge AS e` ~ ` JOIN resource ON e."from"=resource.id` ~ ` WHERE e."to"=? AND type=?`, v, type ) .rows!(parse!Resource); } /** * Adds a vertex to the list of pending vertices. If the vertex is already * pending, nothing is done. */ void addPending(Index!Resource v) { alias s = sqlAddPendingResource; synchronized (s) { scope (exit) s.reset(); s.bind(v); s.step(); } } /// Ditto void addPending(Index!Task v) { alias s = sqlAddPendingTask; synchronized (s) { scope (exit) s.reset(); s.bind(v); s.step(); } } /** * Removes a pending vertex. */ void removePending(Index!Resource v) { alias s = sqlRemovePendingResource; synchronized (s) { scope (exit) s.reset(); s.bind(v); s.step(); } } /// Ditto void removePending(Index!Task v) { alias s = sqlRemovePendingTask; synchronized (s) { scope (exit) s.reset(); s.bind(v); s.step(); } } /// Ditto void removePending(ResourceId v) { removePending(find(v)); } /// Ditto void removePending(TaskKey v) { removePending(find(v)); } /** * Returns true if a given vertex is pending. */ bool isPending(Index!Resource v) { import std.exception : enforce; alias s = sqlIsPendingResource; synchronized (s) { scope (exit) s.reset(); s.bind(v); enforce(s.step(), "Failed to check if resource is pending"); return s.get!uint(0) == 1; } } /// Ditto bool isPending(Index!Task v) { import std.exception : enforce; alias s = sqlIsPendingTask; synchronized (s) { scope (exit) s.reset(); s.bind(v); enforce(s.step(), "Failed to check if task is pending"); return s.get!uint(0) == 1; } } /** * Lists the pending vertices. */ @property auto pending(Vertex : Resource)() { return prepare("SELECT resid FROM pendingResources") .rows!((SQLite3.Statement s) => Index!Vertex(s.get!ulong(0))); } /// Ditto @property auto pending(Vertex : Task)() { return prepare("SELECT taskid FROM pendingTasks") .rows!((SQLite3.Statement s) => Index!Vertex(s.get!ulong(0))); } unittest { import std.algorithm : map, equal; import std.array : array; auto state = new BuildState; assert(state.pending!Resource.empty); assert(state.pending!Task.empty); immutable resources = ["a", "b", "c"]; auto resourceIds = resources.map!(r => state.put(Resource(r))).array; immutable tasks = [[Command(["foo"])], [Command(["bar"])]]; auto taskIds = tasks.map!(t => state.put(Task(t))).array; foreach (immutable id; resourceIds) state.addPending(id); foreach (immutable id; taskIds) state.addPending(id); assert(equal(state.pending!Resource, resourceIds)); assert(equal(state.pending!Task, taskIds)); state.removePending(resourceIds[0]); state.removePending(taskIds[1]); assert(equal(state.pending!Resource, [3, 4].map!(x => Index!Resource(x)))); assert(equal(state.pending!Task, [Index!Task(1)])); } /** * Finds vertices with no incoming and no outgoing edges. */ @property auto islands(Vertex : Resource)() { return prepare( `SELECT id FROM resource` ~ ` WHERE id>1 AND` ~ ` resource.id` ).rows!((SQLite3.Statement s) => Index!Vertex(s.get!string(0))); } }
D
/Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Build/Intermediates.noindex/IBDesignables/Intermediates.noindex/AlchemintProject.build/Debug-iphonesimulator/AlchemintProject.build/Objects-normal/x86_64/AccountState.o : /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Crypto/RIPEMD160.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Crypto/PBKDF2.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Util/NEP2.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Crypto/SHA256.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Util/Base58.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Util/NEP9.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/View/TaskForGCD.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/WIF.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Crypto/AES.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/CateGory/TextOffsetX.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/View/AccountTextField.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/Balance.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/NeoScanBalance.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/AppDelegate.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/AccountState.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/TransactionAttritbute.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/Block.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/NEONetwork.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Util/Data+Util.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Util/Array+Util.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/CateGory/UIColorPreinstall.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/MoreModule/More_RootViewController/MoreListCell.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/ProductModule/Product_RootViewController/ProductListCell.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/ValueIn.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/NeoScan.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/Token.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Contracts/NEP5Token.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/CateGory/JWTextFieldExtension.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/View/JWButtonExtension.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/CateGory/JWUIViewExtension/JWViewExtension.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/Transaction.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/CateGory/UIImageCommon.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/SwiftHeader.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Contracts/ScriptBuilder.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/Peer.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/RootTabBarViewController/RootTabBarController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/JWBaseViewControllers/JWBaseViewController/JWBaseViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/ProductModule/Product_RootViewController/ProductDetailViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/LoginModule/LoginViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/LoginModule/RegisterViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/HomePageModule/HomePage_RootViewController/HomePage_RootViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/MoreModule/More_RootViewController/More_RootViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/MyWealthModule/MyWealth_RootViewController/MyWealth_RootViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/ProductModule/Product_RootViewController/Product_RootViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/OtherModule/StartViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Parameter.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Util/validator.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Contracts/OpCodes.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/Claims.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/View/JWUIKits.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/AssetIdConstants.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/CateGory/JWNavigationBarEt.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/ShamirSecret.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/Asset.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/ContractResult.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/NeoClient.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/Network/AlchemintClient.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Account.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/Script.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Crypto/scrypt.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/View/AutoLayoutAssist.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/ValueOut.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/TransactionHistory.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/NeoScanTransactionHistory.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Build/Intermediates.noindex/IBDesignables/Products/Debug-iphonesimulator/Alamofire/Alamofire.framework/Modules/Alamofire.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Build/Intermediates.noindex/IBDesignables/Products/Debug-iphonesimulator/Alamofire/Alamofire.framework/Headers/Alamofire-umbrella.h /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Neoutils.framework/Headers/Universe.objc.h /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Neoutils.framework/Headers/Neoutils.objc.h /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Neoutils.framework/Headers/ref.h /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Neoutils.framework/Headers/Neoutils.h /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Build/Intermediates.noindex/IBDesignables/Products/Debug-iphonesimulator/Alamofire/Alamofire.framework/Headers/Alamofire-Swift.h /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/CommonCrypto/module.modulemap /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Build/Intermediates.noindex/IBDesignables/Products/Debug-iphonesimulator/Alamofire/Alamofire.framework/Modules/module.modulemap /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Neoutils.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/LocalAuthentication.framework/Headers/LocalAuthentication.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Build/Intermediates.noindex/IBDesignables/Intermediates.noindex/AlchemintProject.build/Debug-iphonesimulator/AlchemintProject.build/Objects-normal/x86_64/AccountState~partial.swiftmodule : /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Crypto/RIPEMD160.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Crypto/PBKDF2.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Util/NEP2.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Crypto/SHA256.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Util/Base58.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Util/NEP9.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/View/TaskForGCD.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/WIF.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Crypto/AES.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/CateGory/TextOffsetX.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/View/AccountTextField.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/Balance.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/NeoScanBalance.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/AppDelegate.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/AccountState.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/TransactionAttritbute.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/Block.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/NEONetwork.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Util/Data+Util.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Util/Array+Util.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/CateGory/UIColorPreinstall.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/MoreModule/More_RootViewController/MoreListCell.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/ProductModule/Product_RootViewController/ProductListCell.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/ValueIn.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/NeoScan.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/Token.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Contracts/NEP5Token.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/CateGory/JWTextFieldExtension.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/View/JWButtonExtension.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/CateGory/JWUIViewExtension/JWViewExtension.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/Transaction.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/CateGory/UIImageCommon.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/SwiftHeader.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Contracts/ScriptBuilder.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/Peer.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/RootTabBarViewController/RootTabBarController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/JWBaseViewControllers/JWBaseViewController/JWBaseViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/ProductModule/Product_RootViewController/ProductDetailViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/LoginModule/LoginViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/LoginModule/RegisterViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/HomePageModule/HomePage_RootViewController/HomePage_RootViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/MoreModule/More_RootViewController/More_RootViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/MyWealthModule/MyWealth_RootViewController/MyWealth_RootViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/ProductModule/Product_RootViewController/Product_RootViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/OtherModule/StartViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Parameter.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Util/validator.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Contracts/OpCodes.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/Claims.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/View/JWUIKits.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/AssetIdConstants.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/CateGory/JWNavigationBarEt.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/ShamirSecret.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/Asset.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/ContractResult.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/NeoClient.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/Network/AlchemintClient.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Account.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/Script.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Crypto/scrypt.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/View/AutoLayoutAssist.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/ValueOut.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/TransactionHistory.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/NeoScanTransactionHistory.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Build/Intermediates.noindex/IBDesignables/Products/Debug-iphonesimulator/Alamofire/Alamofire.framework/Modules/Alamofire.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Build/Intermediates.noindex/IBDesignables/Products/Debug-iphonesimulator/Alamofire/Alamofire.framework/Headers/Alamofire-umbrella.h /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Neoutils.framework/Headers/Universe.objc.h /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Neoutils.framework/Headers/Neoutils.objc.h /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Neoutils.framework/Headers/ref.h /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Neoutils.framework/Headers/Neoutils.h /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Build/Intermediates.noindex/IBDesignables/Products/Debug-iphonesimulator/Alamofire/Alamofire.framework/Headers/Alamofire-Swift.h /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/CommonCrypto/module.modulemap /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Build/Intermediates.noindex/IBDesignables/Products/Debug-iphonesimulator/Alamofire/Alamofire.framework/Modules/module.modulemap /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Neoutils.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/LocalAuthentication.framework/Headers/LocalAuthentication.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Build/Intermediates.noindex/IBDesignables/Intermediates.noindex/AlchemintProject.build/Debug-iphonesimulator/AlchemintProject.build/Objects-normal/x86_64/AccountState~partial.swiftdoc : /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Crypto/RIPEMD160.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Crypto/PBKDF2.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Util/NEP2.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Crypto/SHA256.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Util/Base58.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Util/NEP9.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/View/TaskForGCD.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/WIF.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Crypto/AES.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/CateGory/TextOffsetX.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/View/AccountTextField.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/Balance.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/NeoScanBalance.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/AppDelegate.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/AccountState.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/TransactionAttritbute.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/Block.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/NEONetwork.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Util/Data+Util.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Util/Array+Util.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/CateGory/UIColorPreinstall.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/MoreModule/More_RootViewController/MoreListCell.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/ProductModule/Product_RootViewController/ProductListCell.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/ValueIn.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/NeoScan.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/Token.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Contracts/NEP5Token.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/CateGory/JWTextFieldExtension.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/View/JWButtonExtension.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/CateGory/JWUIViewExtension/JWViewExtension.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/Transaction.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/CateGory/UIImageCommon.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/SwiftHeader.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Contracts/ScriptBuilder.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/Peer.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/RootTabBarViewController/RootTabBarController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/JWBaseViewControllers/JWBaseViewController/JWBaseViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/ProductModule/Product_RootViewController/ProductDetailViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/LoginModule/LoginViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/LoginModule/RegisterViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/HomePageModule/HomePage_RootViewController/HomePage_RootViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/MoreModule/More_RootViewController/More_RootViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/MyWealthModule/MyWealth_RootViewController/MyWealth_RootViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/ProductModule/Product_RootViewController/Product_RootViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/ViewControllers/Modules/Modules/OtherModule/StartViewController.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Parameter.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Util/validator.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Contracts/OpCodes.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/Claims.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/View/JWUIKits.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/AssetIdConstants.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/CateGory/JWNavigationBarEt.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/ShamirSecret.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/Asset.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/ContractResult.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/NeoClient.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/Network/AlchemintClient.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Account.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/Script.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Crypto/scrypt.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/Custom/View/AutoLayoutAssist.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/ValueOut.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/TransactionHistory.swift /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Models/NeoScanTransactionHistory.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Build/Intermediates.noindex/IBDesignables/Products/Debug-iphonesimulator/Alamofire/Alamofire.framework/Modules/Alamofire.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Build/Intermediates.noindex/IBDesignables/Products/Debug-iphonesimulator/Alamofire/Alamofire.framework/Headers/Alamofire-umbrella.h /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Neoutils.framework/Headers/Universe.objc.h /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Neoutils.framework/Headers/Neoutils.objc.h /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Neoutils.framework/Headers/ref.h /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Neoutils.framework/Headers/Neoutils.h /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Build/Intermediates.noindex/IBDesignables/Products/Debug-iphonesimulator/Alamofire/Alamofire.framework/Headers/Alamofire-Swift.h /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/CommonCrypto/module.modulemap /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/Build/Intermediates.noindex/IBDesignables/Products/Debug-iphonesimulator/Alamofire/Alamofire.framework/Modules/module.modulemap /Users/babaiholdings/Documents/AlchemintWalletiOS/AlchemintProject/AlchemintProject/Sources/External/NeoSwift/Neoutils.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/LocalAuthentication.framework/Headers/LocalAuthentication.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
D
/mnt/c/Users/86719/Coding/archival_node/target/rls/debug/deps/matches-fee25ce9b037b393.rmeta: /home/zhihua/.cargo/registry/src/github.com-1ecc6299db9ec823/matches-0.1.8/lib.rs /mnt/c/Users/86719/Coding/archival_node/target/rls/debug/deps/matches-fee25ce9b037b393.d: /home/zhihua/.cargo/registry/src/github.com-1ecc6299db9ec823/matches-0.1.8/lib.rs /home/zhihua/.cargo/registry/src/github.com-1ecc6299db9ec823/matches-0.1.8/lib.rs:
D
// REQUIRED_ARGS: import std.math: poly; import std.c.stdarg; extern(C) { int printf(const char*, ...); version(Windows) { int _snprintf(char*, size_t, const char*, ...); alias _snprintf snprintf; } else int snprintf(char*, size_t, const char*, ...); } /*************************************/ // http://www.digitalmars.com/d/archives/digitalmars/D/bugs/4766.html // Only with -O real randx() { return 1.2; } void test1() { float x10=randx(); float x11=randx(); float x20=randx(); float x21=randx(); float y10=randx(); float y11=randx(); float y20=randx(); float y21=randx(); float tmp=( x20*x21 + y10*y10 + y10*y11 + y11*y11 + y11*y20 + y20*y20 + y10*y21 + y11*y21 + y21*y21); assert(tmp > 0); } /*************************************/ void test2() { double x10=randx(); double x11=randx(); double x20=randx(); double x21=randx(); double y10=randx(); double y11=randx(); double y20=randx(); double y21=randx(); double tmp=( x20*x21 + y10*y10 + y10*y11 + y11*y11 + y11*y20 + y20*y20 + y10*y21 + y11*y21 + y21*y21); assert(tmp > 0); } /*************************************/ void test3() { real x10=randx(); real x11=randx(); real x20=randx(); real x21=randx(); real y10=randx(); real y11=randx(); real y20=randx(); real y21=randx(); real tmp=( x20*x21 + y10*y10 + y10*y11 + y11*y11 + y11*y20 + y20*y20 + y10*y21 + y11*y21 + y21*y21); assert(tmp > 0); } /*************************************/ void test4() { printf("main() : (-128 >= 0)=%s, (-128 <= 0)=%s\n", cast(char*)(-128 >= 0 ? "true" : "false"), cast(char*)(-128 <= 0 ? "true" : "false")); printf("main() : (128 >= 0)=%s, (128 <= 0)=%s\n", cast(char*)(128 >= 0 ? "true" : "false"), cast(char*)(128 <= 0 ? "true" : "false")); assert((-128 >= 0 ? "true" : "false") == "false"), assert((-128 <= 0 ? "true" : "false") == "true"); assert((+128 >= 0 ? "true" : "false") == "true"), assert((+128 <= 0 ? "true" : "false") == "false"); } /*************************************/ int foo5() { assert(0); } // No return. int abc5() { printf("foo = %d\n", foo5()); return 0; } void test5() { } /*************************************/ void test6() { ireal a = 6.5i % 3i; printf("%Lfi %Lfi\n", a, a - .5i); assert(a == .5i); a = 6.5i % 3; printf("%Lfi %Lfi\n", a, a - .5i); assert(a == .5i); real b = 6.5 % 3i; printf("%Lf %Lf\n", b, b - .5); assert(b == .5); b = 6.5 % 3; printf("%Lf %Lf\n", b, b - .5); assert(b == .5); } /*************************************/ void test7() { cfloat f = 1+0i; f %= 2fi; printf("%f + %fi\n", f.re, f.im); assert(f == 1 + 0i); cdouble d = 1+0i; d %= 2i; printf("%f + %fi\n", d.re, d.im); assert(d == 1 + 0i); creal r = 1+0i; r %= 2i; printf("%Lf + %Lfi\n", r.re, r.im); assert(r == 1 + 0i); } /*************************************/ void test8() { cfloat f = 1+0i; f %= 2i; printf("%f + %fi\n", f.re, f.im); assert(f == 1); cdouble d = 1+0i; d = d % 2i; printf("%f + %fi\n", d.re, d.im); assert(d == 1); creal r = 1+0i; r = r % 2i; printf("%Lf + %Lfi\n", r.re, r.im); assert(r == 1); } /*************************************/ class A9 { this(int[] params ...) { for (int i = 0; i < params.length; i++) { assert(params[i] == i + 1); } } } class B9 { this() { init(); } private void init() { A9 test1 = new A9(1, 2, 3); A9 test2 = new A9(1, 2, 3, 4); int[3] arg; A9 test3 = new A9((arg[0]=1, arg[1]=2, arg[2]=3, arg)); } } void test9() { B9 test2 = new B9(); } /*************************************/ void test10() { auto i = 5u; auto s = typeid(typeof(i)).toString; printf("%.*s\n", s.length, s.ptr); assert(typeid(typeof(i)) == typeid(uint)); } /*************************************/ void test11() { printf("%d\n", 3); printf("xhello world!\n"); } /*************************************/ void test12() { creal a = creal.nan; creal b; ubyte* X = cast(ubyte*)(cast(void*)&a); b = real.nan + ireal.nan; ubyte* Y = cast(ubyte*)(cast(void*)&b); for(int i=0; i<a.sizeof; i++) { printf("%d: %02x %02x\n", i, X[i], Y[i]); assert(X[i] == Y[i]); } real c= real.nan; real d=a.re; X = cast(ubyte*)(cast(void*)&c); Y = cast(ubyte*)(cast(void*)&d); for(int i=0; i<c.sizeof; i++){ assert(X[i]==Y[i]); } d=a.im; X = cast(ubyte*)(cast(void*)&c); Y = cast(ubyte*)(cast(void*)&d); for(int i=0; i<c.sizeof; i++){ assert(X[i]==Y[i]); } } /*************************************/ void test13() { creal a = creal.infinity; creal b; byte* X = cast(byte*)(cast(void*)&a); b = real.infinity + ireal.infinity; byte* Y = cast(byte*)(cast(void*)&b); for(int i=0; i<a.sizeof; i++){ assert(X[i]==Y[i]); } real c = real.infinity; real d=a.re; X = cast(byte*)(cast(void*)&c); Y = cast(byte*)(cast(void*)&d); for(int i=0; i<c.sizeof; i++){ assert(X[i]==Y[i]); } d=a.im; X = cast(byte*)(cast(void*)&c); Y = cast(byte*)(cast(void*)&d); for(int i=0; i<c.sizeof; i++){ assert(X[i]==Y[i]); } } /*************************************/ void test14() { creal a = creal.nan; creal b = creal.nan; byte* X = cast(byte*)(cast(void*)&a); b = real.nan + ireal.nan; byte* Y = cast(byte*)(cast(void*)&b); for(int i=0; i<a.sizeof; i++){ assert(X[i]==Y[i]); } real c = real.nan; real d=a.re; X = cast(byte*)(cast(void*)&c); Y = cast(byte*)(cast(void*)&d); for(int i=0; i<c.sizeof; i++){ assert(X[i]==Y[i]); } d=a.im; X = cast(byte*)(cast(void*)&c); Y = cast(byte*)(cast(void*)&d); for(int i=0; i<c.sizeof; i++){ assert(X[i]==Y[i]); } } /*************************************/ ireal x15; void foo15() { x15 = -x15; } void bar15() { return foo15(); } void test15() { x15=2i; bar15(); assert(x15==-2i); } /*************************************/ real x16; void foo16() { x16 = -x16; } void bar16() { return foo16(); } void test16() { x16=2; bar16(); assert(x16==-2); } /*************************************/ class Bar17 { this(...) {} } class Foo17 { void opAdd (Bar17 b) {} } void test17() { auto f = new Foo17; f + new Bar17; } /*************************************/ template u18(int n) { static if (n==1) { int a = 1; } else int b = 4; } void test18() { mixin u18!(2); assert(b == 4); } /*************************************/ class DP { private: void I(char[] p) { I(p[1..p.length]); } } void test19() { } /*************************************/ struct Struct20 { int i; } void test20() { auto s = new Struct20; s.i = 7; } /*************************************/ class C21(float f) { float ff = f; } void test21() { auto a = new C21!(1.2); C21!(1.2) b = new C21!(1.2); } /*************************************/ void test22() { static creal[] params = [1+0i, 3+0i, 5+0i]; printf("params[0] = %Lf + %Lfi\n", params[0].re, params[0].im); printf("params[1] = %Lf + %Lfi\n", params[1].re, params[1].im); printf("params[2] = %Lf + %Lfi\n", params[2].re, params[2].im); creal[] sums = new creal[3]; sums[] = 0+0i; foreach(creal d; params) { creal prod = d; printf("prod = %Lf + %Lfi\n", prod.re, prod.im); for(int i; i<2; i++) { sums[i] += prod; prod *= d; } sums[2] += prod; } printf("sums[0] = %Lf + %Lfi", sums[0].re, sums[0].im); assert(sums[0].re==9); assert(sums[0].im==0); assert(sums[1].re==35); assert(sums[1].im==0); assert(sums[2].re==153); assert(sums[2].im==0); } /*************************************/ const int c23 = b23 * b23; const int a23 = 1; const int b23 = a23 * 3; template T23(int n) { int[n] x23; } mixin T23!(c23); void test23() { assert(x23.length==9); } /*************************************/ ifloat func_24_1(ifloat f, double d) { // f /= cast(cdouble)d; return f; } ifloat func_24_2(ifloat f, double d) { f = cast(ifloat)(f / cast(cdouble)d); return f; } float func_24_3(float f, double d) { // f /= cast(cdouble)d; return f; } float func_24_4(float f, double d) { f = cast(float)(f / cast(cdouble)d); return f; } void test24() { ifloat f = func_24_1(10i, 8); printf("%fi\n", f); // assert(f == 1.25i); f = func_24_2(10i, 8); printf("%fi\n", f); assert(f == 1.25i); float g = func_24_3(10, 8); printf("%f\n", g); // assert(g == 1.25); g = func_24_4(10, 8); printf("%f\n", g); assert(g == 1.25); } /*************************************/ template cat(int n) { const int dog = n; } const char [] bird = "canary"; const int sheep = cat!(bird.length).dog; void test25() { assert(sheep == 6); } /*************************************/ string toString26(cdouble z) { char[ulong.sizeof*8] buf; auto len = snprintf(buf.ptr, buf.sizeof, "%f+%fi", z.re, z.im); return buf[0 .. len].idup; } void test26() { static cdouble[] A = [1+0i, 0+1i, 1+1i]; foreach( cdouble z; A ) printf("%.*s ",toString26(z)); printf("\n"); for(int ii=0; ii<A.length; ii++ ) A[ii] += -1i*A[ii]; assert(A[0] == 1 - 1i); assert(A[1] == 1 + 1i); assert(A[2] == 2); foreach( cdouble z; A ) printf("%.*s ",toString26(z)); printf("\n"); } /*************************************/ void test27() { int x; string s = (int*function(int ...)[]).mangleof; printf("%.*s\n", s.length, s.ptr); assert((int*function(int ...)[]).mangleof == "APFiXPi"); assert(typeof(x).mangleof == "i"); assert(x.mangleof == "_D6test226test27FZv1xi"); } /*************************************/ void test28() { alias cdouble X; X four = cast(X) (4.0i + 0.4); } /*************************************/ void test29() { ulong a = 10_000_000_000_000_000, b = 1_000_000_000_000_000; printf("test29\n%lx\n%lx\n%lx\n", a, b, a / b); assert((a / b) == 10); } static assert((10_000_000_000_000_000 / 1_000_000_000_000_000) == 10); /*************************************/ template chook(int n) { const int chook = 3; } template dog(alias f) { const int dog = chook!(f.mangleof.length); } class pig {} const int goose = dog!(pig); void test30() { printf("%d\n", goose); assert(goose == 3); } /*************************************/ template dog31(string sheep) { immutable string dog31 = "daschund"; } void test31() { string duck = dog31!("bird"[1..3]); assert(duck == "daschund"); } /*************************************/ struct particle { int active; /* Active (Yes/No) */ float life; /* Particle Life */ float fade; /* Fade Speed */ float r; /* Red Value */ float g; /* Green Value */ float b; /* Blue Value */ float x; /* X Position */ float y; /* Y Position */ float xi; /* X Direction */ float yi; /* Y Direction */ float xg; /* X Gravity */ float yg; /* Y Gravity */ } particle particles[10000]; void test32() { } /*************************************/ class Foo33 { template foo() { int foo() { return 6; } } } void test33() { Foo33 f = new Foo33; assert(f.foo!()() == 6); with (f) assert(foo!()() == 6); } /*************************************/ template dog34(string duck) { const int dog34 = 2; } void test34() { int aardvark = dog34!("cat" ~ "pig"); assert(aardvark == 2); } /*************************************/ class A35 { private bool quit; void halt() {quit = true;} bool isHalted() {return quit;} } void test35() { auto a = new A35; a.halt; // error here a.halt(); a.isHalted; // error here bool done = a.isHalted; if (a.isHalted) { } } /*************************************/ void test36() { bool q = (0.9 + 3.5L == 0.9L + 3.5L); assert(q); static assert(0.9 + 3.5L == 0.9L + 3.5L); assert(0.9 + 3.5L == 0.9L + 3.5L); } /*************************************/ abstract class Foo37(T) { void bar () { } } class Bar37 : Foo37!(int) { } void test37() { auto f = new Bar37; } /*************************************/ void test38() { auto s=`hello`; assert(s.length==5); assert(s[0]=='h'); assert(s[1]=='e'); assert(s[2]=='l'); assert(s[3]=='l'); assert(s[4]=='o'); } /*************************************/ void test39() { int value=1; string key = "eins"; int[char[]] array; array[key]=value; int* ptr = key in array; assert(value == *ptr); } /*************************************/ void test40() { auto s=r"hello"; assert(s.length==5); assert(s[0]=='h'); assert(s[1]=='e'); assert(s[2]=='l'); assert(s[3]=='l'); assert(s[4]=='o'); } /*************************************/ void test41() { version (Windows) { version(D_InlineAsm){ double a = 1.2; double b = 0.2; double c = 1.4; asm{ movq XMM0, a; movq XMM1, b; addsd XMM1, XMM0; movq c, XMM1; } a += b; b = a-c; b = (b>0) ? b : (-1 * b); assert(b < b.epsilon*4); } } } /*************************************/ const char[] tapir = "some horned animal"; const byte[] antelope = cast(byte []) tapir; void test42() { } /*************************************/ void test43() { string armadillo = "abc" ~ 'a'; assert(armadillo == "abca"); string armadillo2 = 'b' ~ "abc"; assert(armadillo2 == "babc"); } /*************************************/ const uint baboon44 = 3; const int monkey44 = 4; const ape44 = monkey44 * baboon44; void test44() { assert(ape44 == 12); } /*************************************/ class A45 { this() { b = new B(); b.x = 5; // illegal } class B { protected int x; } B b; } void test45() { } /*************************************/ class C46(T) { private T i; // or protected or package } void test46() { C46!(int) c = new C46!(int); // class t4.C46!(int).C46 member i is not accessible c.i = 10; } /*************************************/ real poly_asm(real x, real[] A) in { assert(A.length > 0); } body { version (D_InlineAsm_X86) { version (linux) { asm // assembler by W. Bright { // EDX = (A.length - 1) * real.sizeof mov ECX,A[EBP] ; // ECX = A.length dec ECX ; lea EDX,[ECX][ECX*8] ; add EDX,ECX ; add EDX,ECX ; add EDX,ECX ; add EDX,A+4[EBP] ; fld real ptr [EDX] ; // ST0 = coeff[ECX] jecxz return_ST ; fld x[EBP] ; // ST0 = x fxch ST(1) ; // ST1 = x, ST0 = r align 4 ; L2: fmul ST,ST(1) ; // r *= x fld real ptr -12[EDX] ; sub EDX,12 ; // deg-- faddp ST(1),ST ; dec ECX ; jne L2 ; fxch ST(1) ; // ST1 = r, ST0 = x fstp ST(0) ; // dump x align 4 ; return_ST: ; ; } } else version (OSX) { asm // assembler by W. Bright { // EDX = (A.length - 1) * real.sizeof mov ECX,A[EBP] ; // ECX = A.length dec ECX ; lea EDX,[ECX*8] ; add EDX,EDX ; add EDX,A+4[EBP] ; fld real ptr [EDX] ; // ST0 = coeff[ECX] jecxz return_ST ; fld x[EBP] ; // ST0 = x fxch ST(1) ; // ST1 = x, ST0 = r align 4 ; L2: fmul ST,ST(1) ; // r *= x fld real ptr -16[EDX] ; sub EDX,16 ; // deg-- faddp ST(1),ST ; dec ECX ; jne L2 ; fxch ST(1) ; // ST1 = r, ST0 = x fstp ST(0) ; // dump x align 4 ; return_ST: ; ; } } else version (FreeBSD) { asm // assembler by W. Bright { // EDX = (A.length - 1) * real.sizeof mov ECX,A[EBP] ; // ECX = A.length dec ECX ; lea EDX,[ECX][ECX*8] ; add EDX,ECX ; add EDX,ECX ; add EDX,ECX ; add EDX,A+4[EBP] ; fld real ptr [EDX] ; // ST0 = coeff[ECX] jecxz return_ST ; fld x[EBP] ; // ST0 = x fxch ST(1) ; // ST1 = x, ST0 = r align 4 ; L2: fmul ST,ST(1) ; // r *= x fld real ptr -12[EDX] ; sub EDX,12 ; // deg-- faddp ST(1),ST ; dec ECX ; jne L2 ; fxch ST(1) ; // ST1 = r, ST0 = x fstp ST(0) ; // dump x align 4 ; return_ST: ; ; } } else { asm // assembler by W. Bright { // EDX = (A.length - 1) * real.sizeof mov ECX,A[EBP] ; // ECX = A.length dec ECX ; lea EDX,[ECX][ECX*8] ; add EDX,ECX ; add EDX,A+4[EBP] ; fld real ptr [EDX] ; // ST0 = coeff[ECX] jecxz return_ST ; fld x[EBP] ; // ST0 = x fxch ST(1) ; // ST1 = x, ST0 = r align 4 ; L2: fmul ST,ST(1) ; // r *= x fld real ptr -10[EDX] ; sub EDX,10 ; // deg-- faddp ST(1),ST ; dec ECX ; jne L2 ; fxch ST(1) ; // ST1 = r, ST0 = x fstp ST(0) ; // dump x align 4 ; return_ST: ; ; } } } else { printf("Sorry, you don't seem to have InlineAsm_X86\n"); return 0; } } real poly_c(real x, real[] A) in { assert(A.length > 0); } body { ptrdiff_t i = A.length - 1; real r = A[i]; while (--i >= 0) { r *= x; r += A[i]; } return r; } void test47() { real x = 3.1; static real pp[] = [56.1, 32.7, 6]; real r; printf("The result should be %Lf\n",(56.1L + (32.7L + 6L * x) * x)); printf("The C version outputs %Lf\n", poly_c(x, pp)); printf("The asm version outputs %Lf\n", poly_asm(x, pp)); printf("The std.math version outputs %Lf\n", poly(x, pp)); r = (56.1L + (32.7L + 6L * x) * x); assert(r == poly_c(x, pp)); version (D_InlineAsm_X86) assert(r == poly_asm(x, pp)); assert(r == poly(x, pp)); } /*************************************/ const c48 = 1uL-1; void test48() { assert(c48 == 0); } /*************************************/ template cat49() { static assert(1); // OK static if (1) { static assert(1); // doesn't work static if (1) { static assert(1); // OK const int cat49 = 3; } } } void test49() { const int a = cat49!(); assert(a == 3); } /*************************************/ void test50() { if (auto x = 1) { assert(typeid(typeof(x)) == typeid(int)); assert(x == 1); } else assert(0); if (int x = 1) { assert(typeid(typeof(x)) == typeid(int)); assert(x == 1); } else assert(0); if (1) { } else assert(0); } /*************************************/ void test51() { bool b; assert(b == false); b &= 1; assert(b == false); b |= 1; assert(b == true); b ^= 1; assert(b == false); b = b | true; assert(b == true); b = b & false; assert(b == false); b = b ^ true; assert(b == true); b = !b; assert(b == false); } /*************************************/ alias int function (int) x52; template T52(string str){ const int T52 = 1; } static assert(T52!(x52.mangleof)); void test52() { } /*************************************/ import std.stdio; import std.c.stdarg; void myfunc(int a1, ...) { va_list argument_list; TypeInfo argument_type; string sa; int ia; double da; writefln("%d variable arguments", _arguments.length); writefln("argument types %s", _arguments); version(X86) va_start(argument_list, a1); version(X86_64) va_start(argument_list, __va_argsave); for (int i = 0; i < _arguments.length; ) { if ((argument_type=_arguments[i++]) == typeid(string)) { va_arg(argument_list, sa); writefln("%d) string arg = '%s', length %d", i+1, sa.length<=20? sa : "?", sa.length); } else if (argument_type == typeid(int)) { va_arg(argument_list, ia); writefln("%d) int arg = %d", i+1, ia); } else if (argument_type == typeid(double)) { va_arg(argument_list, da); writefln("%d) double arg = %f", i+1, da); } else { throw new Exception("invalid argument type"); } } va_end(argument_list); } void test6758() { myfunc(1, 2, 3, 4, 5, 6, 7, 8, "9", "10"); // Fails. myfunc(1, 2.0, 3, 4, 5, 6, 7, 8, "9", "10"); // Works OK. myfunc(1, 2, 3, 4, 5, 6, 7, "8", "9", "10"); // Works OK. myfunc(1, "2", 3, 4, 5, 6, 7, 8, "9", "10"); // Works OK. } /*************************************/ int main() { test1(); test2(); test3(); test4(); test5(); test6(); test7(); test8(); test9(); test10(); test11(); test12(); test13(); test14(); test15(); test16(); test17(); test18(); test19(); test20(); test21(); test22(); test23(); test24(); test25(); test26(); test27(); test28(); test29(); test30(); test31(); test32(); test33(); test34(); test35(); test36(); test37(); test38(); test39(); test40(); test41(); test42(); test43(); test44(); test45(); test46(); test47(); test48(); test49(); test50(); test51(); test52(); test6758(); printf("Success\n"); return 0; }
D
/** * Compiler implementation of the * $(LINK2 http://www.dlang.org, D programming language). * * Copyright: Copyright (c) 1999-2016 by Digital Mars, 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: $(DMDSRC _cond.d) */ module ddmd.cond; import core.stdc.string; import ddmd.arraytypes; import ddmd.dmodule; import ddmd.dmodule; import ddmd.dscope; import ddmd.dsymbol; import ddmd.errors; import ddmd.expression; import ddmd.globals; import ddmd.hdrgen; import ddmd.identifier; import ddmd.mars; import ddmd.mtype; import ddmd.root.outbuffer; import ddmd.tokens; import ddmd.visitor; private __gshared Identifier idUnitTest; private __gshared Identifier idAssert; static this() { const(char)* s; s = Token.toChars(TOKunittest); idUnitTest = Identifier.idPool(s, strlen(s)); s = Token.toChars(TOKassert); idAssert = Identifier.idPool(s, strlen(s)); } /*********************************************************** */ extern (C++) abstract class Condition { public: Loc loc; // 0: not computed yet // 1: include // 2: do not include int inc; final extern (D) this(Loc loc) { this.loc = loc; } abstract Condition syntaxCopy(); abstract int include(Scope* sc, ScopeDsymbol sds); DebugCondition isDebugCondition() { return null; } void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) class DVCondition : Condition { public: uint level; Identifier ident; Module mod; final extern (D) this(Module mod, uint level, Identifier ident) { super(Loc()); this.mod = mod; this.level = level; this.ident = ident; } override final Condition syntaxCopy() { return this; // don't need to copy } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class DebugCondition : DVCondition { public: static void setGlobalLevel(uint level) { global.params.debuglevel = level; } static void addGlobalIdent(const(char)* ident) { if (!global.params.debugids) global.params.debugids = new Strings(); global.params.debugids.push(cast(char*)ident); } extern (D) this(Module mod, uint level, Identifier ident) { super(mod, level, ident); } override int include(Scope* sc, ScopeDsymbol sds) { //printf("DebugCondition::include() level = %d, debuglevel = %d\n", level, global.params.debuglevel); if (inc == 0) { inc = 2; bool definedInModule = false; if (ident) { if (findCondition(mod.debugids, ident)) { inc = 1; definedInModule = true; } else if (findCondition(global.params.debugids, ident)) inc = 1; else { if (!mod.debugidsNot) mod.debugidsNot = new Strings(); mod.debugidsNot.push(ident.toChars()); } } else if (level <= global.params.debuglevel || level <= mod.debuglevel) inc = 1; if (!definedInModule) printDepsConditional(sc, this, "depsDebug "); } return (inc == 1); } override DebugCondition isDebugCondition() { return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class VersionCondition : DVCondition { public: static void setGlobalLevel(uint level) { global.params.versionlevel = level; } static bool isPredefined(const(char)* ident) { static __gshared const(char)** reserved = [ "DigitalMars", "GNU", "LDC", "SDC", "Windows", "Win32", "Win64", "linux", "OSX", "iOS", "TVOS", "WatchOS", "FreeBSD", "OpenBSD", "NetBSD", "DragonFlyBSD", "BSD", "Solaris", "Posix", "AIX", "Haiku", "SkyOS", "SysV3", "SysV4", "Hurd", "Android", "Cygwin", "MinGW", "FreeStanding", "X86", "X86_64", "ARM", "ARM_Thumb", "ARM_SoftFloat", "ARM_SoftFP", "ARM_HardFloat", "AArch64", "Epiphany", "PPC", "PPC_SoftFloat", "PPC_HardFloat", "PPC64", "IA64", "MIPS32", "MIPS64", "MIPS_O32", "MIPS_N32", "MIPS_O64", "MIPS_N64", "MIPS_EABI", "MIPS_SoftFloat", "MIPS_HardFloat", "NVPTX", "NVPTX64", "SPARC", "SPARC_V8Plus", "SPARC_SoftFloat", "SPARC_HardFloat", "SPARC64", "S390", "S390X", "SystemZ", "HPPA", "HPPA64", "SH", "SH64", "Alpha", "Alpha_SoftFloat", "Alpha_HardFloat", "LittleEndian", "BigEndian", "ELFv1", "ELFv2", "CRuntime_Bionic", "CRuntime_DigitalMars", "CRuntime_Glibc", "CRuntime_Microsoft", "D_Coverage", "D_Ddoc", "D_InlineAsm_X86", "D_InlineAsm_X86_64", "D_LP64", "D_X32", "D_HardFloat", "D_SoftFloat", "D_PIC", "D_SIMD", "D_Version2", "D_NoBoundsChecks", "unittest", "assert", "all", "none", null ]; for (uint i = 0; reserved[i]; i++) { if (strcmp(ident, reserved[i]) == 0) return true; } if (ident[0] == 'D' && ident[1] == '_') return true; return false; } static void checkPredefined(Loc loc, const(char)* ident) { if (isPredefined(ident)) error(loc, "version identifier '%s' is reserved and cannot be set", ident); } static void addGlobalIdent(const(char)* ident) { checkPredefined(Loc(), ident); addPredefinedGlobalIdent(ident); } static void addPredefinedGlobalIdent(const(char)* ident) { if (!global.params.versionids) global.params.versionids = new Strings(); global.params.versionids.push(cast(char*)ident); } extern (D) this(Module mod, uint level, Identifier ident) { super(mod, level, ident); } override int include(Scope* sc, ScopeDsymbol sds) { //printf("VersionCondition::include() level = %d, versionlevel = %d\n", level, global.params.versionlevel); //if (ident) printf("\tident = '%s'\n", ident->toChars()); if (inc == 0) { inc = 2; bool definedInModule = false; if (ident) { if (findCondition(mod.versionids, ident)) { inc = 1; definedInModule = true; } else if (findCondition(global.params.versionids, ident)) inc = 1; else { if (!mod.versionidsNot) mod.versionidsNot = new Strings(); mod.versionidsNot.push(ident.toChars()); } } else if (level <= global.params.versionlevel || level <= mod.versionlevel) inc = 1; if (!definedInModule && (!ident || (!isPredefined(ident.toChars()) && ident != idUnitTest && ident != idAssert))) { printDepsConditional(sc, this, "depsVersion "); } } return (inc == 1); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class StaticIfCondition : Condition { public: Expression exp; int nest; // limit circular dependencies extern (D) this(Loc loc, Expression exp) { super(loc); this.exp = exp; } override Condition syntaxCopy() { return new StaticIfCondition(loc, exp.syntaxCopy()); } override int include(Scope* sc, ScopeDsymbol sds) { version (none) { printf("StaticIfCondition::include(sc = %p, sds = %p) this=%p inc = %d\n", sc, sds, this, inc); if (sds) { printf("\ts = '%s', kind = %s\n", sds.toChars(), sds.kind()); } } if (inc == 0) { if (exp.op == TOKerror || nest > 100) { error(loc, (nest > 1000) ? "unresolvable circular static if expression" : "error evaluating static if expression"); goto Lerror; } if (!sc) { error(loc, "static if conditional cannot be at global scope"); inc = 2; return 0; } ++nest; sc = sc.push(sc.scopesym); sc.sds = sds; // sds gets any addMember() //sc->speculative = true; // TODO: static if (is(T U)) { /* U is available */ } sc.flags |= SCOPEcondition; sc = sc.startCTFE(); Expression e = exp.semantic(sc); e = resolveProperties(sc, e); sc = sc.endCTFE(); sc.pop(); --nest; // Prevent repeated condition evaluation. // See: fail_compilation/fail7815.d if (inc != 0) return (inc == 1); if (!e.type.isBoolean()) { if (e.type.toBasetype() != Type.terror) exp.error("expression %s of type %s does not have a boolean value", exp.toChars(), e.type.toChars()); goto Lerror; } e = e.ctfeInterpret(); if (e.op == TOKerror) { goto Lerror; } else if (e.isBool(true)) inc = 1; else if (e.isBool(false)) inc = 2; else { e.error("expression %s is not constant or does not evaluate to a bool", e.toChars()); goto Lerror; } } return (inc == 1); Lerror: if (!global.gag) inc = 2; // so we don't see the error message again return 0; } override void accept(Visitor v) { v.visit(this); } } extern (C++) int findCondition(Strings* ids, Identifier ident) { if (ids) { for (size_t i = 0; i < ids.dim; i++) { const(char)* id = (*ids)[i]; if (strcmp(id, ident.toChars()) == 0) return true; } } return false; } // Helper for printing dependency information extern (C++) void printDepsConditional(Scope* sc, DVCondition condition, const(char)* depType) { if (!global.params.moduleDeps || global.params.moduleDepsFile) return; OutBuffer* ob = global.params.moduleDeps; Module imod = sc ? sc.instantiatingModule() : condition.mod; if (!imod) return; ob.writestring(depType); ob.writestring(imod.toPrettyChars()); ob.writestring(" ("); escapePath(ob, imod.srcfile.toChars()); ob.writestring(") : "); if (condition.ident) ob.printf("%s\n", condition.ident.toChars()); else ob.printf("%d\n", condition.level); }
D
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: tensorflow/core/protobuf/rewriter_config.proto module tensorflow.rewriter_config; import google.protobuf; import tensorflow.attr_value; import tensorflow.verifier_config; enum protocVersion = 3012004; class AutoParallelOptions { @Proto(1) bool enable = protoDefaultValue!(bool); @Proto(2) int numReplicas = protoDefaultValue!(int); } class ScopedAllocatorOptions { @Proto(1) string[] enableOp = protoDefaultValue!(string[]); } class RewriterConfig { @Proto(1) Toggle layoutOptimizer = protoDefaultValue!(Toggle); @Proto(2) bool disableModelPruning = protoDefaultValue!(bool); @Proto(3) Toggle constantFolding = protoDefaultValue!(Toggle); @Proto(4) MemOptType memoryOptimization = protoDefaultValue!(MemOptType); @Proto(5) AutoParallelOptions autoParallel = protoDefaultValue!(AutoParallelOptions); @Proto(6) string memoryOptimizerTargetNodeNameScope = protoDefaultValue!(string); @Proto(7) Toggle arithmeticOptimization = protoDefaultValue!(Toggle); @Proto(8) Toggle dependencyOptimization = protoDefaultValue!(Toggle); @Proto(9) Toggle loopOptimization = protoDefaultValue!(Toggle); @Proto(10) Toggle functionOptimization = protoDefaultValue!(Toggle); @Proto(11) Toggle debugStripper = protoDefaultValue!(Toggle); @Proto(12) NumIterationsType metaOptimizerIterations = protoDefaultValue!(NumIterationsType); @Proto(13) Toggle shapeOptimization = protoDefaultValue!(Toggle); @Proto(14) Toggle remapping = protoDefaultValue!(Toggle); @Proto(15) Toggle scopedAllocatorOptimization = protoDefaultValue!(Toggle); @Proto(16) ScopedAllocatorOptions scopedAllocatorOpts = protoDefaultValue!(ScopedAllocatorOptions); @Proto(17) int minGraphNodes = protoDefaultValue!(int); @Proto(18) Toggle pinToHostOptimization = protoDefaultValue!(Toggle); @Proto(19) bool disableMetaOptimizer = protoDefaultValue!(bool); @Proto(20) long metaOptimizerTimeoutMs = protoDefaultValue!(long); @Proto(21) bool failOnOptimizerErrors = protoDefaultValue!(bool); @Proto(22) Toggle implementationSelector = protoDefaultValue!(Toggle); @Proto(23) Toggle autoMixedPrecision = protoDefaultValue!(Toggle); @Proto(100) string[] optimizers = protoDefaultValue!(string[]); @Proto(200) RewriterConfig.CustomGraphOptimizer[] customOptimizers = protoDefaultValue!(RewriterConfig.CustomGraphOptimizer[]); @Proto(300) VerifierConfig interOptimizerVerifierConfig = protoDefaultValue!(VerifierConfig); @Proto(301) VerifierConfig postOptimizationVerifierConfig = protoDefaultValue!(VerifierConfig); static class CustomGraphOptimizer { @Proto(1) string name = protoDefaultValue!(string); @Proto(2) AttrValue[string] parameterMap = protoDefaultValue!(AttrValue[string]); } enum Toggle { DEFAULT = 0, ON = 1, OFF = 2, AGGRESSIVE = 3, } enum NumIterationsType { DEFAULT_NUM_ITERS = 0, ONE = 1, TWO = 2, } enum MemOptType { DEFAULT_MEM_OPT = 0, NO_MEM_OPT = 1, MANUAL = 2, SWAPPING_HEURISTICS = 4, RECOMPUTATION_HEURISTICS = 5, SCHEDULING_HEURISTICS = 6, HEURISTICS = 3, } }
D
/** * * THIS FILE IS AUTO-GENERATED BY ./parse_specs.d FOR MCU atmega32u4 WITH ARCHITECTURE avr5 * */ module avr.specs.specs_atmega32u4; enum __AVR_ARCH__ = 5; enum __AVR_ASM_ONLY__ = false; enum __AVR_ENHANCED__ = true; enum __AVR_HAVE_MUL__ = true; enum __AVR_HAVE_JMP_CALL__ = true; enum __AVR_MEGA__ = true; enum __AVR_HAVE_LPMX__ = true; enum __AVR_HAVE_MOVW__ = true; enum __AVR_HAVE_ELPM__ = false; enum __AVR_HAVE_ELPMX__ = false; enum __AVR_HAVE_EIJMP_EICALL_ = false; enum __AVR_2_BYTE_PC__ = true; enum __AVR_3_BYTE_PC__ = false; enum __AVR_XMEGA__ = false; enum __AVR_HAVE_RAMPX__ = false; enum __AVR_HAVE_RAMPY__ = false; enum __AVR_HAVE_RAMPZ__ = false; enum __AVR_HAVE_RAMPD__ = false; enum __AVR_TINY__ = false; enum __AVR_PM_BASE_ADDRESS__ = 0; enum __AVR_SFR_OFFSET__ = 32; enum __AVR_DEVICE_NAME__ = "atmega32u4";
D
reestablish on a new, usually improved, basis or make new or like new amplify (an electron current) by causing part of the power in the output circuit to act upon the input circuit bring, lead, or force to abandon a wrong or evil course of life, conduct, and adopt a right one return to life replace (tissue or a body part) through the formation of new tissue be formed or shaped anew form or produce anew undergo regeneration restore strength reformed spiritually or morally
D
/+ + Copyright 2022 – 2023 Aya Partridge + Copyright 2018 - 2022 Michael D. Parker + 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 sdl.video; import bindbc.sdl.config; import bindbc.sdl.codegen; import sdl.rect: SDL_Rect; import sdl.stdinc: SDL_bool; import sdl.surface: SDL_Surface; struct SDL_DisplayMode{ uint format; int w; int h; int refresh_rate; void* driverdata; } struct SDL_Window; alias SDL_WindowFlags = uint; enum: SDL_WindowFlags{ SDL_WINDOW_FULLSCREEN = 0x0000_0001, SDL_WINDOW_OPENGL = 0x0000_0002, SDL_WINDOW_SHOWN = 0x0000_0004, SDL_WINDOW_HIDDEN = 0x0000_0008, SDL_WINDOW_BORDERLESS = 0x0000_0010, SDL_WINDOW_RESIZABLE = 0x0000_0020, SDL_WINDOW_MINIMIZED = 0x0000_0040, SDL_WINDOW_MAXIMIZED = 0x0000_0080, SDL_WINDOW_INPUT_GRABBED = 0x0000_0100, SDL_WINDOW_INPUT_FOCUS = 0x0000_0200, SDL_WINDOW_MOUSE_FOCUS = 0x0000_0400, SDL_WINDOW_FULLSCREEN_DESKTOP = 0x0000_1000 | SDL_WINDOW_FULLSCREEN, SDL_WINDOW_FOREIGN = 0x0000_0800, } static if(sdlSupport >= SDLSupport.v2_0_1) enum: SDL_WindowFlags{ SDL_WINDOW_ALLOW_HIGHDPI = 0x0000_2000, } static if(sdlSupport >= SDLSupport.v2_0_4) enum: SDL_WindowFlags{ SDL_WINDOW_MOUSE_CAPTURE = 0x0000_4000, } static if(sdlSupport >= SDLSupport.v2_0_5) enum: SDL_WindowFlags{ SDL_WINDOW_ALWAYS_ON_TOP = 0x0000_8000, SDL_WINDOW_SKIP_TASKBAR = 0x0001_0000, SDL_WINDOW_UTILITY = 0x0002_0000, SDL_WINDOW_TOOLTIP = 0x0004_0000, SDL_WINDOW_POPUP_MENU = 0x0008_0000, } static if(sdlSupport >= SDLSupport.v2_0_6) enum: SDL_WindowFlags{ SDL_WINDOW_VULKAN = 0x1000_0000, } static if(sdlSupport >= SDLSupport.v2_0_6) enum: SDL_WindowFlags{ SDL_WINDOW_METAL = 0x2000_0000, } static if(sdlSupport >= SDLSupport.v2_0_16) enum: SDL_WindowFlags{ SDL_WINDOW_MOUSE_GRABBED = SDL_WINDOW_INPUT_GRABBED, SDL_WINDOW_KEYBOARD_GRABBED = 0x0010_0000, } enum: uint{ SDL_WINDOWPOS_UNDEFINED_MASK = 0x1FFF0000, SDL_WINDOWPOS_UNDEFINED = SDL_WINDOWPOS_UNDEFINED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_MASK = 0x2FFF0000, SDL_WINDOWPOS_CENTERED = SDL_WINDOWPOS_CENTERED_DISPLAY(0), } pragma(inline, true) nothrow @nogc pure @safe{ uint SDL_WINDOWPOS_UNDEFINED_DISPLAY(uint x){ return SDL_WINDOWPOS_UNDEFINED_MASK | x; } uint SDL_WINDOWPOS_ISUNDEFINED(uint x){ return (x & 0xFFFF0000) == SDL_WINDOWPOS_UNDEFINED_MASK; } uint SDL_WINDOWPOS_CENTERED_DISPLAY(uint x){ return SDL_WINDOWPOS_CENTERED_MASK | x; } uint SDL_WINDOWPOS_ISCENTERED(uint x){ return (x & 0xFFFF0000) == SDL_WINDOWPOS_CENTERED_MASK; } } alias SDL_WindowEventID = ubyte; enum: SDL_WindowEventID{ SDL_WINDOWEVENT_NONE = 0, SDL_WINDOWEVENT_SHOWN = 1, SDL_WINDOWEVENT_HIDDEN = 2, SDL_WINDOWEVENT_EXPOSED = 3, SDL_WINDOWEVENT_MOVED = 4, SDL_WINDOWEVENT_RESIZED = 5, SDL_WINDOWEVENT_SIZE_CHANGED = 6, SDL_WINDOWEVENT_MINIMIZED = 7, SDL_WINDOWEVENT_MAXIMIZED = 8, SDL_WINDOWEVENT_RESTORED = 9, SDL_WINDOWEVENT_ENTER = 10, SDL_WINDOWEVENT_LEAVE = 11, SDL_WINDOWEVENT_FOCUS_GAINED = 12, SDL_WINDOWEVENT_FOCUS_LOST = 13, SDL_WINDOWEVENT_CLOSE = 14, } static if(sdlSupport >= SDLSupport.v2_0_5) enum: SDL_WindowEventID{ SDL_WINDOWEVENT_TAKE_FOCUS = 15, SDL_WINDOWEVENT_HIT_TEST = 16, } static if(sdlSupport >= SDLSupport.v2_0_18) enum: SDL_WindowEventID{ SDL_WINDOWEVENT_ICCPROF_CHANGED = 17, SDL_WINDOWEVENT_DISPLAY_CHANGED = 18, } static if(sdlSupport >= SDLSupport.v2_0_9){ alias SDL_DisplayEventID = int; enum: SDL_DisplayEventID{ SDL_DISPLAYEVENT_NONE = 0, SDL_DISPLAYEVENT_ORIENTATION = 1, } static if(sdlSupport >= SDLSupport.v2_0_14) enum: SDL_DisplayEventID{ SDL_DISPLAYEVENT_CONNECTED = 2, SDL_DISPLAYEVENT_DISCONNECTED = 3, } static if(sdlSupport >= SDLSupport.v2_28) enum: SDL_DisplayEventID{ SDL_DISPLAYEVENT_MOVED = 4, } } static if(sdlSupport >= SDLSupport.v2_0_9){ alias SDL_DisplayOrientation = int; enum: SDL_DisplayOrientation{ SDL_ORIENTATION_UNKNOWN = 0, SDL_ORIENTATION_LANDSCAPE = 1, SDL_ORIENTATION_LANDSCAPE_FLIPPED = 2, SDL_ORIENTATION_PORTRAIT = 3, SDL_ORIENTATION_PORTRAIT_FLIPPED = 4, } } static if(sdlSupport >= SDLSupport.v2_0_16){ alias SDL_FlashOperation = int; enum: SDL_FlashOperation{ SDL_FLASH_CANCEL = 0, SDL_FLASH_BRIEFLY = 1, SDL_FLASH_UNTIL_FOCUSED = 2, } } alias SDL_GLContext = void*; alias SDL_GLattr = int; enum: SDL_GLattr{ SDL_GL_RED_SIZE = 0, SDL_GL_GREEN_SIZE = 1, SDL_GL_BLUE_SIZE = 2, SDL_GL_ALPHA_SIZE = 3, SDL_GL_BUFFER_SIZE = 4, SDL_GL_DOUBLEBUFFER = 5, SDL_GL_DEPTH_SIZE = 6, SDL_GL_STENCIL_SIZE = 7, SDL_GL_ACCUM_RED_SIZE = 8, SDL_GL_ACCUM_GREEN_SIZE = 9, SDL_GL_ACCUM_BLUE_SIZE = 10, SDL_GL_ACCUM_ALPHA_SIZE = 11, SDL_GL_STEREO = 12, SDL_GL_MULTISAMPLEBUFFERS = 13, SDL_GL_MULTISAMPLESAMPLES = 14, SDL_GL_ACCELERATED_VISUAL = 15, SDL_GL_RETAINED_BACKING = 16, SDL_GL_CONTEXT_MAJOR_VERSION = 17, SDL_GL_CONTEXT_MINOR_VERSION = 18, SDL_GL_CONTEXT_EGL = 19, SDL_GL_CONTEXT_FLAGS = 20, SDL_GL_CONTEXT_PROFILE_MASK = 21, SDL_GL_SHARE_WITH_CURRENT_CONTEXT = 22, } static if(sdlSupport >= SDLSupport.v2_0_1) enum: SDL_GLattr{ SDL_GL_FRAMEBUFFER_SRGB_CAPABLE = 23, } static if(sdlSupport >= SDLSupport.v2_0_4) enum: SDL_GLattr{ deprecated("Please use `SDL_GL_CONTEXT_RELEASE_BEHAVIOR` instead") SDL_GL_RELEASE_BEHAVIOR = 24, //NOTE: this name was a typo to begin with SDL_GL_CONTEXT_RELEASE_BEHAVIOR = 24, } static if(sdlSupport >= SDLSupport.v2_0_6) enum: SDL_GLattr{ SDL_GL_CONTEXT_RESET_NOTIFICATION = 25, SDL_GL_CONTEXT_NO_ERROR = 26, } static if(sdlSupport >= SDLSupport.v2_0_6) enum: SDL_GLattr{ SDL_GL_FLOATBUFFERS = 27, } alias SDL_GLprofile = int; enum: SDL_GLprofile{ SDL_GL_CONTEXT_PROFILE_CORE = 0x0001, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY = 0x0002, SDL_GL_CONTEXT_PROFILE_ES = 0x0004, } alias SDL_GLcontextFlag = int; enum: SDL_GLcontextFlag{ SDL_GL_CONTEXT_DEBUG_FLAG = 0x0001, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG = 0x0002, SDL_GL_CONTEXT_ROBUST_ACCESS_FLAG = 0x0004, SDL_GL_CONTEXT_RESET_ISOLATION_FLAG = 0x0008, } static if(sdlSupport >= SDLSupport.v2_0_4){ alias SDL_GLcontextReleaseFlag = int; enum: SDL_GLcontextReleaseFlag{ SDL_GL_CONTEXT_RELEASE_BEHAVIOR_NONE = 0x0000, SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH = 0x0001, } alias SDL_HitTestResult = int; enum: SDL_HitTestResult{ SDL_HITTEST_NORMAL = 0, SDL_HITTEST_DRAGGABLE = 1, SDL_HITTEST_RESIZE_TOPLEFT = 2, SDL_HITTEST_RESIZE_TOP = 3, SDL_HITTEST_RESIZE_TOPRIGHT = 4, SDL_HITTEST_RESIZE_RIGHT = 5, SDL_HITTEST_RESIZE_BOTTOMRIGHT = 6, SDL_HITTEST_RESIZE_BOTTOM = 7, SDL_HITTEST_RESIZE_BOTTOMLEFT = 8, SDL_HITTEST_RESIZE_LEFT = 9, } import sdl.rect: SDL_Point; alias SDL_HitTest = extern(C) SDL_HitTestResult function(SDL_Window* win, const(SDL_Point)* area, void* data) nothrow; } static if(sdlSupport >= SDLSupport.v2_0_6){ alias SDL_GLContextResetNotification = int; enum: SDL_GLContextResetNotification{ SDL_GL_CONTEXT_RESET_NO_NOTIFICATION = 0x0000, SDL_GL_CONTEXT_RESET_LOSE_CONTEXT = 0x0001, } } mixin(joinFnBinds((){ string[][] ret; ret ~= makeFnBinds([ [q{int}, q{SDL_GetNumVideoDrivers}, q{}], [q{const(char)*}, q{SDL_GetVideoDriver}, q{int index}], [q{int}, q{SDL_VideoInit}, q{const(char)* driver_name}], [q{void}, q{SDL_VideoQuit}, q{}], [q{const(char)*}, q{SDL_GetCurrentVideoDriver}, q{}], [q{int}, q{SDL_GetNumVideoDisplays}, q{}], [q{const(char)*}, q{SDL_GetDisplayName}, q{int displayIndex}], [q{int}, q{SDL_GetDisplayBounds}, q{int displayIndex, SDL_Rect* rect}], [q{int}, q{SDL_GetNumDisplayModes}, q{int displayIndex}], [q{int}, q{SDL_GetDisplayMode}, q{int displayIndex, int modeIndex, SDL_DisplayMode* mode}], [q{int}, q{SDL_GetDesktopDisplayMode}, q{int displayIndex, SDL_DisplayMode* mode}], [q{int}, q{SDL_GetCurrentDisplayMode}, q{int displayIndex, SDL_DisplayMode* mode}], [q{SDL_DisplayMode*}, q{SDL_GetClosestDisplayMode}, q{int displayIndex, const(SDL_DisplayMode)* mode, SDL_DisplayMode* closest}], [q{int}, q{SDL_GetWindowDisplayIndex}, q{SDL_Window* window}], [q{int}, q{SDL_SetWindowDisplayMode}, q{SDL_Window* window, const(SDL_DisplayMode)* mode}], [q{int}, q{SDL_GetWindowDisplayMode}, q{SDL_Window* window, SDL_DisplayMode* mode}], [q{uint}, q{SDL_GetWindowPixelFormat}, q{SDL_Window* window}], [q{SDL_Window*}, q{SDL_CreateWindow}, q{const(char)* title, int x, int y, int w, int h, SDL_WindowFlags flags}], [q{SDL_Window*}, q{SDL_CreateWindowFrom}, q{const(void)* data}], [q{uint}, q{SDL_GetWindowID}, q{SDL_Window* window}], [q{SDL_Window*}, q{SDL_GetWindowFromID}, q{uint id}], [q{SDL_WindowFlags}, q{SDL_GetWindowFlags}, q{SDL_Window* window}], [q{void}, q{SDL_SetWindowTitle}, q{SDL_Window* window, const(char)* title}], [q{const(char)*}, q{SDL_GetWindowTitle}, q{SDL_Window* window}], [q{void}, q{SDL_SetWindowIcon}, q{SDL_Window* window, SDL_Surface* icon}], [q{void*}, q{SDL_SetWindowData}, q{SDL_Window* window, const(char)* name, void* userdata}], [q{void*}, q{SDL_GetWindowData}, q{SDL_Window* window, const(char)* name}], [q{void}, q{SDL_SetWindowPosition}, q{SDL_Window* window, int x, int y}], [q{void}, q{SDL_GetWindowPosition}, q{SDL_Window* window, int* x, int* y}], [q{void}, q{SDL_SetWindowSize}, q{SDL_Window* window, int w, int h}], [q{void}, q{SDL_GetWindowSize}, q{SDL_Window* window, int* w, int* h}], [q{void}, q{SDL_SetWindowMinimumSize}, q{SDL_Window* window, int min_w, int min_h}], [q{void}, q{SDL_GetWindowMinimumSize}, q{SDL_Window* window, int* w, int* h}], [q{void}, q{SDL_SetWindowMaximumSize}, q{SDL_Window* window, int max_w, int max_h}], [q{void}, q{SDL_GetWindowMaximumSize}, q{SDL_Window* window, int* w, int* h}], [q{void}, q{SDL_SetWindowBordered}, q{SDL_Window* window, SDL_bool bordered}], [q{void}, q{SDL_ShowWindow}, q{SDL_Window* window}], [q{void}, q{SDL_HideWindow}, q{SDL_Window* window}], [q{void}, q{SDL_RaiseWindow}, q{SDL_Window* window}], [q{void}, q{SDL_MaximizeWindow}, q{SDL_Window* window}], [q{void}, q{SDL_MinimizeWindow}, q{SDL_Window* window}], [q{void}, q{SDL_RestoreWindow}, q{SDL_Window* window}], [q{int}, q{SDL_SetWindowFullscreen}, q{SDL_Window* window, SDL_WindowFlags flags}], [q{SDL_Surface*}, q{SDL_GetWindowSurface}, q{SDL_Window* window}], [q{int}, q{SDL_UpdateWindowSurface}, q{SDL_Window* window}], [q{int}, q{SDL_UpdateWindowSurfaceRects}, q{SDL_Window* window, SDL_Rect* rects, int numrects}], [q{void}, q{SDL_SetWindowGrab}, q{SDL_Window* window, SDL_bool grabbed}], [q{SDL_bool}, q{SDL_GetWindowGrab}, q{SDL_Window* window}], [q{int}, q{SDL_SetWindowBrightness}, q{SDL_Window* window, float brightness}], [q{float}, q{SDL_GetWindowBrightness}, q{SDL_Window* window}], [q{int}, q{SDL_SetWindowGammaRamp}, q{SDL_Window* window, const(ushort)* red, const(ushort)* green, const(ushort)* blue}], [q{int}, q{SDL_GetWindowGammaRamp}, q{SDL_Window* window, ushort* red, ushort* green, ushort* blue}], [q{void}, q{SDL_DestroyWindow}, q{SDL_Window* window}], [q{SDL_bool}, q{SDL_IsScreenSaverEnabled}, q{}], [q{void}, q{SDL_EnableScreenSaver}, q{}], [q{void}, q{SDL_DisableScreenSaver}, q{}], [q{int}, q{SDL_GL_LoadLibrary}, q{const(char)* path}], [q{void*}, q{SDL_GL_GetProcAddress}, q{const(char)* proc}], [q{void}, q{SDL_GL_UnloadLibrary}, q{}], [q{SDL_bool}, q{SDL_GL_ExtensionSupported}, q{const(char)* extension}], [q{int}, q{SDL_GL_SetAttribute}, q{SDL_GLattr attr, int value}], [q{int}, q{SDL_GL_GetAttribute}, q{SDL_GLattr attr, int* value}], [q{SDL_GLContext}, q{SDL_GL_CreateContext}, q{SDL_Window* window}], [q{int}, q{SDL_GL_MakeCurrent}, q{SDL_Window* window, SDL_GLContext context}], [q{SDL_Window*}, q{SDL_GL_GetCurrentWindow}, q{}], [q{SDL_GLContext}, q{SDL_GL_GetCurrentContext}, q{}], [q{int}, q{SDL_GL_SetSwapInterval}, q{int interval}], [q{int}, q{SDL_GL_GetSwapInterval}, q{}], [q{void}, q{SDL_GL_SwapWindow}, q{SDL_Window* window}], [q{void}, q{SDL_GL_DeleteContext}, q{SDL_GLContext context}], ]); static if(sdlSupport >= SDLSupport.v2_0_1){ ret ~= makeFnBinds([ [q{void}, q{SDL_GL_GetDrawableSize}, q{SDL_Window* window, int* w, int* h}], ]); } static if(sdlSupport >= SDLSupport.v2_0_2){ ret ~= makeFnBinds([ [q{void}, q{SDL_GL_ResetAttributes}, q{}], ]); } static if(sdlSupport >= SDLSupport.v2_0_4){ ret ~= makeFnBinds([ [q{int}, q{SDL_GetDisplayDPI}, q{int displayIndex, float* ddpi, float* hdpi, float* vdpi}], [q{SDL_Window*}, q{SDL_GetGrabbedWindow}, q{}], [q{int}, q{SDL_SetWindowHitTest}, q{SDL_Window* window, SDL_HitTest callback, void* callback_data}], ]); } static if(sdlSupport >= SDLSupport.v2_0_5){ ret ~= makeFnBinds([ [q{int}, q{SDL_GetDisplayUsableBounds}, q{int displayIndex, SDL_Rect* rect}], [q{int}, q{SDL_GetWindowBordersSize}, q{SDL_Window* window, int* top, int* left, int* bottom, int* right}], [q{int}, q{SDL_GetWindowOpacity}, q{SDL_Window* window, float* opacity}], [q{int}, q{SDL_SetWindowInputFocus}, q{SDL_Window* window}], [q{int}, q{SDL_SetWindowModalFor}, q{SDL_Window* modal_window, SDL_Window* parent_window}], [q{int}, q{SDL_SetWindowOpacity}, q{SDL_Window* window, float opacity}], [q{void}, q{SDL_SetWindowResizable}, q{SDL_Window* window, SDL_bool resizable}], ]); } static if(sdlSupport >= SDLSupport.v2_0_9){ ret ~= makeFnBinds([ [q{SDL_DisplayOrientation}, q{SDL_GetDisplayOrientation}, q{int displayIndex}], ]); } static if(sdlSupport >= SDLSupport.v2_0_16){ ret ~= makeFnBinds([ [q{int}, q{SDL_FlashWindow}, q{SDL_Window* window, SDL_FlashOperation operation}], [q{void}, q{SDL_SetWindowAlwaysOnTop}, q{SDL_Window* window, SDL_bool on_top}], [q{void}, q{SDL_SetWindowKeyboardGrab}, q{SDL_Window* window, SDL_bool grabbed}], [q{SDL_bool}, q{SDL_GetWindowKeyboardGrab}, q{SDL_Window * window}], [q{void}, q{SDL_SetWindowMouseGrab}, q{SDL_Window* window, SDL_bool grabbed}], [q{SDL_bool}, q{SDL_GetWindowMouseGrab}, q{SDL_Window* window}], ]); } static if(sdlSupport >= SDLSupport.v2_0_18){ ret ~= makeFnBinds([ [q{void*}, q{SDL_GetWindowICCProfile}, q{SDL_Window* window, size_t* size}], [q{int}, q{SDL_SetWindowMouseRect}, q{SDL_Window* window, const(SDL_Rect)* rect}], [q{const(SDL_Rect)*}, q{SDL_GetWindowMouseRect}, q{SDL_Window* window}], ]); } static if(sdlSupport >= SDLSupport.v2_24){ ret ~= makeFnBinds([ [q{int}, q{SDL_GetPointDisplayIndex}, q{const(SDL_Point)* point}], [q{int}, q{SDL_GetRectDisplayIndex}, q{const(SDL_Rect)* rect}], ]); } static if(sdlSupport >= SDLSupport.v2_26){ ret ~= makeFnBinds([ [q{void}, q{SDL_GetWindowSizeInPixels}, q{SDL_Window* window, int* w, int* h}], ]); } static if(sdlSupport >= SDLSupport.v2_28){ ret ~= makeFnBinds([ [q{SDL_bool}, q{SDL_HasWindowSurface}, q{SDL_Window* window}], [q{int}, q{SDL_DestroyWindowSurface}, q{SDL_Window* window}], ]); } return ret; }()));
D
/home/antonio/Documentos/Programming/learning_rust_examples-1/imap/target/debug/deps/fnv-8575fffa265426b0.rmeta: /home/antonio/.cargo/registry/src/github.com-1ecc6299db9ec823/fnv-1.0.6/lib.rs /home/antonio/Documentos/Programming/learning_rust_examples-1/imap/target/debug/deps/libfnv-8575fffa265426b0.rlib: /home/antonio/.cargo/registry/src/github.com-1ecc6299db9ec823/fnv-1.0.6/lib.rs /home/antonio/Documentos/Programming/learning_rust_examples-1/imap/target/debug/deps/fnv-8575fffa265426b0.d: /home/antonio/.cargo/registry/src/github.com-1ecc6299db9ec823/fnv-1.0.6/lib.rs /home/antonio/.cargo/registry/src/github.com-1ecc6299db9ec823/fnv-1.0.6/lib.rs:
D
/++ Copyright: See Phobos Copyright License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0). Authors: $(HTTP erdani.com, Andrei Alexandrescu), Ilya Yaroshenko +/ module mir.internal.memory; pure nothrow @nogc extern(C) { /// void* malloc(size_t size); /// void* calloc(size_t nmemb, size_t size); /// void* realloc(void* ptr, size_t size); /// void free(void* ptr); } pure: enum uint platformAlignment = double.alignof > real.alignof ? double.alignof : real.alignof; @nogc nothrow: @safe pure package bool isGoodDynamicAlignment()(uint x) { return (x & -x) > (x - 1) && x >= (void*).sizeof; } version (Posix) private extern(C) int posix_memalign(void**, size_t, size_t); version (Windows) { // DMD Win 32 bit, DigitalMars C standard library misses the _aligned_xxx // functions family (snn.lib) version(CRuntime_DigitalMars) { // Helper to cast the infos written before the aligned pointer // this header keeps track of the size (required to realloc) and of // the base ptr (required to free). private struct AlignInfo() { void* basePtr; size_t size; @nogc nothrow pragma(inline, true) static AlignInfo* opCall()(void* ptr) { return cast(AlignInfo*) (ptr - AlignInfo.sizeof); } } private void* _aligned_malloc()(size_t size, size_t alignment) { size_t offset = alignment + size_t.sizeof * 2 - 1; // unaligned chunk void* basePtr = malloc(size + offset); if (!basePtr) return null; // get aligned location within the chunk void* alignedPtr = cast(void**)((cast(size_t)(basePtr) + offset) & ~(alignment - 1)); // write the header before the aligned pointer AlignInfo!()* head = AlignInfo!()(alignedPtr); head.basePtr = basePtr; head.size = size; return alignedPtr; } private void* _aligned_realloc()(void* ptr, size_t size, size_t alignment) { import core.stdc.string : memcpy; if (!ptr) return _aligned_malloc(size, alignment); // gets the header from the existing pointer AlignInfo!()* head = AlignInfo!()(ptr); // gets a new aligned pointer void* alignedPtr = _aligned_malloc(size, alignment); if (!alignedPtr) { //to https://msdn.microsoft.com/en-us/library/ms235462.aspx //see Return value: in this case the original block is unchanged return null; } // copy existing data memcpy(alignedPtr, ptr, head.size); free(head.basePtr); return alignedPtr; } private void _aligned_free()(void *ptr) { if (!ptr) return; AlignInfo!()* head = AlignInfo!()(ptr); free(head.basePtr); } } // DMD Win 64 bit, uses microsoft standard C library which implements them else { private extern(C) void* _aligned_free(void *); private extern(C) void* _aligned_malloc(size_t, size_t); private extern(C) void* _aligned_realloc(void *, size_t, size_t); } } /** Uses $(HTTP man7.org/linux/man-pages/man3/posix_memalign.3.html, $(D posix_memalign)) on Posix and $(HTTP msdn.microsoft.com/en-us/library/8z34s9c6(v=vs.80).aspx, $(D __aligned_malloc)) on Windows. */ version(Posix) @trusted void* alignedAllocate()(size_t bytes, uint a) { import core.stdc.errno : ENOMEM, EINVAL; assert(a.isGoodDynamicAlignment); void* result; auto code = posix_memalign(&result, a, bytes); if (code == ENOMEM) return null; else if (code == EINVAL) { assert(0, "AlignedMallocator.alignment is not a power of two " ~"multiple of (void*).sizeof, according to posix_memalign!"); } else if (code != 0) assert (0, "posix_memalign returned an unknown code!"); else return result; } else version(Windows) @trusted void* alignedAllocate()(size_t bytes, uint a) { return _aligned_malloc(bytes, a); } else static assert(0); /** Calls $(D free(b.ptr)) on Posix and $(HTTP msdn.microsoft.com/en-US/library/17b5h8td(v=vs.80).aspx, $(D __aligned_free(b.ptr))) on Windows. */ version (Posix) { alias alignedFree = free; } else version (Windows) @system void alignedFree()(void* b) { _aligned_free(b); } else static assert(0); /** On Posix, uses $(D alignedAllocate) and copies data around because there is no realloc for aligned memory. On Windows, calls $(HTTP msdn.microsoft.com/en-US/library/y69db7sx(v=vs.80).aspx, $(D __aligned_realloc(b.ptr, newSize, a))). */ version (Windows) @system void alignedReallocate()(ref void* b, size_t s, uint a) { if (!s) { alignedFree(b); b = null; return; } auto p = cast(ubyte*) _aligned_realloc(b, s, a); if (!p) return; b = p; } /// unittest { auto buffer = alignedAllocate(1024 * 1024 * 4, 128); alignedFree(buffer); //... } version (CRuntime_DigitalMars) version(unittest) private size_t addr(ref void* ptr) { return cast(size_t) ptr; } version(CRuntime_DigitalMars) unittest { void* m; m = _aligned_malloc(16, 0x10); if (m) { assert((m.addr & 0xF) == 0); _aligned_free(m); } m = _aligned_malloc(16, 0x100); if (m) { assert((m.addr & 0xFF) == 0); _aligned_free(m); } m = _aligned_malloc(16, 0x1000); if (m) { assert((m.addr & 0xFFF) == 0); _aligned_free(m); } m = _aligned_malloc(16, 0x10); if (m) { assert((cast(size_t)m & 0xF) == 0); m = _aligned_realloc(m, 32, 0x10000); if (m) assert((m.addr & 0xFFFF) == 0); _aligned_free(m); } m = _aligned_malloc(8, 0x10); if (m) { *cast(ulong*) m = 0X01234567_89ABCDEF; m = _aligned_realloc(m, 0x800, 0x1000); if (m) assert(*cast(ulong*) m == 0X01234567_89ABCDEF); _aligned_free(m); } }
D
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF 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.shiro.session.mgt.ExecutorServiceSessionValidationScheduler; import hunt.shiro.session.mgt.DefaultSessionManager; import hunt.shiro.session.mgt.SessionValidationScheduler; import hunt.shiro.session.mgt.ValidatingSessionManager; import hunt.concurrency.atomic; import hunt.concurrency.thread; import hunt.concurrency.Executors; import hunt.concurrency.ScheduledExecutorService; import hunt.concurrency.ThreadFactory; import hunt.util.DateTime; import hunt.util.Common; import hunt.util.Runnable; import hunt.logging.Logger; import core.thread; import std.conv; /** * SessionValidationScheduler implementation that uses a * {@link ScheduledExecutorService} to call {@link ValidatingSessionManager#validateSessions()} every * <em>{@link #getInterval interval}</em> milliseconds. * */ class ExecutorServiceSessionValidationScheduler : SessionValidationScheduler, Runnable { /** Private internal log instance. */ ValidatingSessionManager sessionManager; private ScheduledExecutorService service; private long interval = DefaultSessionManager.DEFAULT_SESSION_VALIDATION_INTERVAL; private bool enabled = false; private string threadNamePrefix = "SessionValidationThread-"; this() { } this(ValidatingSessionManager sessionManager) { this.sessionManager = sessionManager; } ValidatingSessionManager getSessionManager() { return sessionManager; } void setSessionManager(ValidatingSessionManager sessionManager) { this.sessionManager = sessionManager; } long getInterval() { return interval; } void setInterval(long interval) { this.interval = interval; } bool isEnabled() { return this.enabled; } void setThreadNamePrefix(string threadNamePrefix) { this.threadNamePrefix = threadNamePrefix; } string getThreadNamePrefix() { return this.threadNamePrefix; } /** * Creates a single thread {@link ScheduledExecutorService} to validate sessions at fixed intervals * and enables this scheduler. The executor is created as a daemon thread to allow JVM to shut down */ //TODO Implement an integration test to test for jvm exit as part of the standalone example // (so we don't have to change the unit test execution model for the core module) void enableSessionValidation() { if (this.interval > 0) { this.service = Executors.newSingleThreadScheduledExecutor(new class ThreadFactory { private shared int count = 0; ThreadEx newThread(Runnable r) { int c = AtomicHelper.increment(count); ThreadEx thread = new ThreadEx(r); thread.isDaemon = true; thread.name = threadNamePrefix ~ c.to!string(); return thread; } }); Duration dur = interval.msecs; this.service.scheduleAtFixedRate(this, dur, dur); } this.enabled = true; } void run() { version(HUNT_DEBUG) { tracef("Executing session validation..."); } long startTime = DateTime.currentTimeMillis(); this.sessionManager.validateSessions(); long stopTime = DateTime.currentTimeMillis(); version(HUNT_DEBUG) { tracef("Session validation completed successfully in " ~ to!string(stopTime - startTime) ~ " milliseconds."); } } void disableSessionValidation() { if (this.service !is null) { this.service.shutdownNow(); } this.enabled = false; } }
D
module jarena.core.services; private { import std.experimental.logger; import std.traits; import std.meta; import std.typecons : Flag; import std.typetuple : AliasSeq; import jarena.core; } //version = ServiceProviderVerbose; /// Passed to the various `ServiceProvider.addXXX` functions. alias OverrideExisting = Flag!"override_"; /++ + A UDA that can be attached to function parameters. + + Normally, a Service Parameter (a parameter the Service Provider will detect as a service, and + will attempt to perform an injection on) is defined as either being a parameter taking an `interface`, + or a parameter taking a `ServiceProvider`. + + Attaching this UDA onto a parameter will force the service provider to treat the parameter as a service, + and will force it to perform an injection on that parameter (like it does for any other service). + + Use_Case: + Take JEngine's `Renderer` class for example. There's only ever going to be *one* renderer for this engine, + so it's bit of a waste of time to make an interface for it just so it can be used with the service provider + (not to mention the issues with templated functions when being used with interfaces). + + So instead of doing something such as `provider.addSingleton!(IRenderer, OpenGLRenderer)(rendererInstance)`, you do + `provider.addSingleton!(Renderer, Renderer)(rendererInstance)`. So there is simply one class, `Renderer`, which is both + the service base class, but also the service implementation class. + + Now, this isn't an `interface`, so the service provider won't perform an injection on it anytime we use it as a parameter. + So we attach `@FromService` onto it to force the provider to perform the injection. + + `void onRender(@FromService Renderer renderer)` + + Side note - Depending on how many services a function takes, the injection process can be relatively expensive. + So try to avoid using on hot functions. You can do this by getting the services at another point in time (e.g the constructor), + or caching the results of `ServiceProvider.get` and passing them manually. + + Side side note - I beg to holy saint Walter Bright to make working with function parameter UDAs easier ;_; + ++/ struct FromServices{} /++ + A container for services. + + A service is a class that, as the name implies, provides a certain service. + + This class is heavily inspired from ASP Core's ServiceProvider. So alongside being a Service Locator, + it also acts as a dependency injector. + + How to use: + Services can be registered via `addSingleton` and `addTransient`. + + Services can then be retrieved using `get`. + + The service provider can inject parameters into function calls (including the constructor) via + `injectCall` and `makeAndInject`. + + Versions: + If the `ServiceProviderVerbose` `version` is specified, then this class will provide verbose logging of it's actions. + ++/ final class ServiceProvider { private { alias IsSingleton = Flag!"singleton"; struct ParamInfo { TypeInfo paramType; string paramName; } struct FactoryStackInfo { ServiceInfo service; bool wasInCache; } struct ServiceInfo { IsSingleton isSingleton; TypeInfo baseType; TypeInfo implType; ParamInfo[] injectParams; Object singleton; // If applicable Object delegate() factoryFunc; } ServiceInfo[TypeInfo] _services; // Key is the base type. FactoryStackInfo[] _factoryStack; bool _factoryStackLock; } public { /++ + Registers a service. + + Lifetimes: + Similar to the ASP counter parts, there are two lifetimes for a service. + + Singleton - Where a single instance is created for the service, and is then used for every request for the service. + + Transient - Where a new instance is created every time the service is reqeuested for. + + Decoupling: + You may have noticed the two template parameters, `Base`, and `Implementation`. + + This class aims to allow the user code to decouple from the implementation of a class, and it's interface. + + For example, you may have an `ILoggerService` interface (which would be used as the `Base`) and several + implementations such as a `FileLogger`, `ConsoleLogger`, `CompoundLogger`, etc. (Which would be used as the `Implementation`). + + The user code doesn't exactly care what implementation it gets in most cases, all they care is that they get an `ILoggerService`. + + So this function is used to associate a certain implementation of a service, to it's interface, and then the user code can + blindly ask for the service's interface without having to know it's nitty-gritty details. + + However, there are certainly some cases where there will only ever be one concrete implementation of an interface. + In cases like these, you can simply specify both the `Base` and `Implementation` to be of the implementing class. + + There is a slight quirk with this however, as it will require you to use the `@FromServices` UDA for function parameters (please refer to it's + documentation). + + Injection: + Please refer to `injectCall` and `makeAndInject`. + + Params: + [Base] = The interface/base class of the service. This should be defined well enough that the user shouldn't have to cast it + [Implementation] = The implementation class of the service. + instance = [Singletons only] The instance to use for the singleton. + If this is null, then an instance will be created by `get`, using `makeAndInject` under the hood. + override_ = Determines whether to override any existing implementation for the `Base` service. + If `OverrideExisting.no` and an implementation already exists, then an exception is thrown. + ++/ void addSingleton(Base, Implementation)(Base instance = null, OverrideExisting override_ = OverrideExisting.no) { this.add!(Base, Implementation)(instance, override_, IsSingleton.yes); } /// ditto void addTransient(Base, Implementation)(OverrideExisting override_ = OverrideExisting.no) { this.add!(Base, Implementation)(null, override_, IsSingleton.no); } /++ + Creates and/or returns an instance of the specified service. + + Service Creation: + All services are created using the `makeAndInject` function on their implementation class. + This allows services to be injected with other services fluently. + + For singletons, if an instance of the service doesn't exist yet, then an instance is created, cached, then returned. + If an instance has already been cached, then it's returned. + + For transient, an instance is created everytime this function is called. + + Params: + [Base] = The interface/base class of the service. This will be the same `Base` parameter passed to `addSingleton` and `addTransient`. + default_ = What to return if the service doesn't exist. + + Returns: + The instance of the service, or `default_` if the service doesn't exist. + ++/ Base get(Base)(lazy Base default_ = null) { import std.algorithm : filter; import std.range : retro; static assert(is(Base == interface) || is(Base == class), "The given type '"~Base.stringof~"' is neither an interface nor a class."); // Gain the factory lock. bool weHaveLock = false; if(!this._factoryStackLock) { weHaveLock = true; this._factoryStackLock = true; } scope(exit) { if(weHaveLock) { this._factoryStack.length = 0; this._factoryStackLock = false; } } // Checks to make sure we don't have any circular references. void doCircularCheck() { int i = 0; foreach(info; this._factoryStack.retro.filter!(i => !i.wasInCache)) { if(i == 0) continue; // Skip the first once, since that's the one we just made i++; if(info.service.baseType == typeid(Base)) { assert(false, "Circular reference detected. TODO: Better error message"); } } } this.verboseTracef("Getting '%s'.", Base.stringof); auto ptr = (typeid(Base) in this._services); if(ptr is null) { this.verboseTracef("Returning default value '%s'.", default_); return default_; } this._factoryStack ~= FactoryStackInfo(*ptr, false); if(ptr.isSingleton) { if(ptr.singleton is null) { this.verboseTracef("Service is singleton without value. Creating value."); doCircularCheck(); ptr.singleton = cast(Object)ptr.factoryFunc(); } else this._factoryStack[$-1].wasInCache = true; this.verboseTracef("Returning singleton service."); return cast(Base)ptr.singleton; } this.verboseTracef("Creating and returning transient service."); doCircularCheck(); return cast(Base)ptr.factoryFunc(); } /++ + Calls the constructor for a type, performing the same injection process documented + by `injectCall`. + + Notes: + If it wasn't obvious, if `T` is a class then the GC is used to allocate it's memory. + + This function will select a ctor that contains parameters, instead of a constructor that takes no parameters, if both + types of constructors exist in the same type. + + Params: + [T] = The type to construct. + params = The non-service (see `injectCall`) parameters to pass. + + Returns: + The newly constructed `T`. + ++/ T makeAndInject(T, Params...)(Params params) { import std.format : format; T obj; this.verboseTracef("Creating type '%s' with injections. Params = %s", T.stringof, (Params.length > 0) ? "%s".format(params) : "N/A"); mixin(createInjectCall!(T, "obj", "__ctor", "", Params)); return obj; } /++ + Calls a function, performing service injection in the process. + + Overloaded functions: + It is unwise to use injection with functions that have overloads, as there's no easy way to specify/determine + which overload needs to be used. It'll just use whichever one the compiler returns from `__traits(getMember)`. + + Injection: + Injection is the process of automatically passing over dependencies/services that the function needs. + + The service provider detects a Service parameter as being: a parameter who's type is an interface; a parameter + who's type is `ServiceProvider`; a parameter who has been marked with the `@FromServices` UDA. + + For a service parameter who's type is `ServiceProvider`, the current instance of this class is passed to the parameter. + + For any other service parameter, the return value of `this.get!TypeOfParameter` is passed to it. + + For non-service parameters (parameters that don't meet the criteria above), the given `params` are passed. + + Functions that are being injected have a strict order for how their parameters are laid out - + Non-service parameters must always come before a service parameter. The service provider will enforce this with a compile time check, + and will provide a detailed error message on what's wrong with the parameters if it does not meet the right criteria. + + If the number of `params` passed differs from from the number of non-service parameters for the function, a compile time assert + will fail, listing all of the parameters that still need to be passed (if not enough parameters were passed). + + An assert will also fail if a circular dependency is detected. Due to the nature of how this class works, this can only be detected + at runtime currently. + + Do note that currently default parameters are not supported (but there's no technical reason they can't be). + + UFCS: + Currently, there is no support for UFCS. The issue is that this class needs to have the module of the UFCS function + imported, and there isn't really an easy way to do that. + + A possibility in the future is to provide a mixin that can be used inside a module to provide the functionality needed + for UFCS injection. + + Params: + [funcName] = The name of the function to inject and call. + target = The instance of `T` to call the function with. + params = The non-service params to pass to the function. (See the 'Injection' section if you haven't already). + + Returns: + Whatever `funcName` returns. + ++/ auto injectCall(string funcName, T, Params...)(ref scope T target, Params params) { import std.format : format; alias RetType = ReturnType!(__traits(getMember, T , funcName)); this.verboseTracef("Calling function '%s.%s' with injections. Params = %s", T.stringof, funcName, (Params.length > 0) ? "%s".format(params) : "N/A"); static if(is(RetType == void)) mixin(createInjectCall!(T, "target", funcName, "", Params)); else { mixin(createInjectCall!(T, "target", funcName, "result", Params)); return result; } } /++ + A helper function for the other `injectCall` overload, that takes the name of the given `func` instead + of taking a direct string. + + E.g. instead of `injectCall!"MyFunc"` you do `injectCall!(MyObject.MyFunc)` + ++/ auto injectCall(alias func, T, Params...)(ref scope T target, Params params) { return this.injectCall!(__traits(identifier, func))(target, params); } } private { void verboseTracef(Args...)(string str, Args args) { version(ServiceProviderVerbose) tracef(str, args); } void add(Base, Implementation)(Base instance, OverrideExisting override_, IsSingleton isSingleton) { static assert(is(Implementation : Base), "Type '"~Implementation.stringof~"' must inherit from '"~Base.stringof~"'"); enforceAndLogf((typeid(Base) in this._services) is null || override_, "Cannot override existing implementation for service '%s'", Base.stringof ); tracef("Registering %s implementation '%s' of service '%s'", (isSingleton) ? "singleton" : "transient", Implementation.stringof, Base.stringof); ParamInfo[] params; alias InjectFunc = InjectionCtorFor!Implementation; alias InjectNames = ParameterIdentifierTuple!InjectFunc; alias InjectTypes = Parameters!InjectFunc; static assert(InjectNames.length == InjectTypes.length); foreach(i, name; InjectNames) params ~= ParamInfo(typeid(InjectTypes[i]), name); this._services[typeid(Base)] = ServiceInfo( isSingleton, typeid(Base), typeid(Implementation), params, cast(Object)instance, () => cast(Implementation)this.makeAndInject!Implementation ); } static dstring createInjectCall(T, string objectName, string targetFunc, string resultName, Params...)() { import std.format : format; import std.algorithm : joiner; import jaster.serialise.builder; auto code = new CodeBuilder(); // Get the func to use, params, and some other constant stuff. static if(targetFunc == "__ctor") alias Func = InjectionCtorFor!T; else alias Func = __traits(getMember, T, targetFunc); alias FuncParams = Parameters!Func; alias ParamNames = ParameterIdentifierTuple!Func; enum NormalParamLength = NormalParamLength!Func; enum FirstServiceIndex = FirstServiceIndex!Func; // Make sure we've been given the right amount of parameters. static assert(Params.length == NormalParamLength, "Parameter count mis-match. Expected %s non-service parameters, but got %s. ".format(NormalParamLength, Params.length) ~"Missing Parameters: %s".format(ParamNames[Params.length..NormalParamLength]) ); // Put it in the generated code, since we need them there as well. code.putf(`static if("`~targetFunc~`" == "__ctor") alias Func = InjectionCtorFor!T; else alias Func = __traits(getMember, T, "`~targetFunc~`");`); code.putf("alias FuncParams = Parameters!Func;"); // Create an argument list. // For parameters passed to us, just pass to the function as is. // For services, call `this.get!ServiceType` on them. // For `ServiceProvider`, pass `this`. string[] paramsToUse; static foreach(i; 0..FuncParams.length) {{ alias param = FuncParams[i]; static if(is(param == ServiceProvider)) { code.putf(`this.verboseTracef("Using 'this' for parameter %s (\"%s\")");`, i, ParamNames[i]); paramsToUse ~= "this"; } else static if(is(param == interface) || ( is(typeof(canFindFromServices!(__traits(getAttributes, FuncParams[i..i+1])))) && canFindFromServices!(__traits(getAttributes, FuncParams[i..i+1])) ) ) { code.putf(`this.verboseTracef("Using service '%s' for parameter %s (\"%s\")");`, param.stringof, i, ParamNames[i]); paramsToUse ~= format("this.get!(FuncParams[%s])", i); } else { static assert(i < NormalParamLength, "Service parameters (types of `interface` and `ServiceProvider`) must be placed *after* non-service parameters.\n" ~"Non-service parameter #%s (%s %s) needs to be placed *before* Service parameter #%s (%s %s)." .format(i, param.stringof, ParamNames[i], FirstServiceIndex, FuncParams[FirstServiceIndex].stringof, ParamNames[FirstServiceIndex]) ); code.putf(`this.verboseTracef("Using parameter %s (%s) for parameter %s (\"%s\")");`, i, Params[i].stringof, i, ParamNames[i]); paramsToUse ~= format("params[%s]", i); } }} // For the constructor, create a new object (using objectName). // Otherwise, call the function, and optionally store it in a result. auto paramRange = paramsToUse.joiner(", "); static if(targetFunc == "__ctor") code.putf("%s = %s T(%s);", objectName, is(T == class) ? "new" : "", paramRange); else static if(resultName.length > 0) code.putf("auto %s = %s.%s(%s);", resultName, objectName, targetFunc, paramRange); else code.putf("%s.%s(%s);", objectName, targetFunc, paramRange); return code.data.idup; } } } /++ + The base class for a configuration. + + Please see the `configure` function. + ++/ interface IConfig(T) { @property ref T value(); } /// The implementation for a configuration. class ConfigImpl(T) : IConfig!T if(is(T == struct)) { private T _value; @property ref T value() { return this._value; } } // TODO: Rewrite this a bit, since I question if it's even valid English (in terms of it making no fucking sense). /++ + Using a struct (`T`) to store some form of configuration, this function will register + a singleton service (`IConfig!T`) into the given `ServiceProvider`. + + Notes: + `configurator` will be passed an already existing version of the configuration if it exists. + Otherwise a new instance of it will be used. + + Use Case: + Sometimes a service will allow the user to configure how it works. + + It can support this by defining a struct to store the configuration, and then using + the `IConfig` interface alongside the configuration struct and dependency injection + to retrieve this configuration. + + Params: + service = The service provider to use. + configurator = The function that will configure the data. + ++/ void configure(T)(ServiceProvider service, void delegate(ref T) configurator) { auto config = service.get!(IConfig!T); if(config is null) { service.addSingleton!(IConfig!T, ConfigImpl!T); config = service.get!(IConfig!T); } configurator(config.value); } private template NormalParamLength(alias Func) { size_t doCount() { size_t serviceParamCount = 0; forEveryServiceParam!Func((i){ serviceParamCount++; }); return (Parameters!Func.length - serviceParamCount); } enum NormalParamLength = doCount; } private bool canFindFromServices(Attribs...)() { bool value; static foreach(attrib; Attribs) { static if(is(attrib == FromServices)) value = true; } return value; } private template FirstServiceIndex(alias Func) { static size_t findIndex() { size_t index = size_t.max; forEveryServiceParam!Func((i){ if(index == size_t.max) index = i; }); return index; } enum FirstServiceIndex = findIndex(); } private void forEveryServiceParam(alias Func)(void delegate(size_t) func) { alias Params = Parameters!Func; static foreach(i; 0..Params.length) {{ alias param = Params[i]; if(is(param == interface) || is(param == ServiceProvider)) func(i); static if(is(typeof(__traits(getAttributes, Params[i..i+1])))) { if(canFindFromServices!(__traits(getAttributes, Params[i..i+1]))) func(i); } }} } private template InjectionCtorFor(alias Type) { static if(__traits(hasMember, Type, "__ctor")) { alias Ctors = __traits(getOverloads, Type, "__ctor"); static assert(Ctors.length > 0); static if(Ctors.length == 1) alias InjectionCtorFor = Ctors[0]; else { enum CtorFilter(alias T) = Parameters!T.length > 0; alias Filtered = Filter!(CtorFilter, Ctors); static assert(Filtered.length > 0); alias InjectionCtorFor = Filtered[0]; } } else alias InjectionCtorFor = defaultCtor; } private void defaultCtor() {} version(unittest) { string LAST_LOGGED_MESSAGE; interface ILoggerService { void write(int level, string str); } // Just pretend they're using writeln instead of putting them into a variable. // They return the strings so I can easily test them. // An alternative way would be to create an `IOutputService` and use that to get the output. // But for this test, all I want to do is test injection, and I only need one class for that. class MinimalConsoleLoggerService : ILoggerService { void write(int level, string str) { LAST_LOGGED_MESSAGE = str; } } class DetailedConsoleLoggerService : ILoggerService { void write(int level, string str) { LAST_LOGGED_MESSAGE = ((level == 0) ? "[INFO] " : "[ERROR] ") ~ str; } } class SomeImportantClass { ILoggerService logger; this(ILoggerService logger) { this.logger = logger; logger.write(0, "Ctor injection"); } } class SomeUnrelatedClass { void doLog(string myNonServiceParam, ILoggerService service) { service.write(1, myNonServiceParam); } } struct SomeConfig { string name; } class SomeClassWithConfig { SomeConfig value; this(IConfig!SomeConfig config, ILoggerService logger) { logger.write(0, config.value.name); this.value = config.value; } } class SomeClassWithUDA { this(@FromServices SomeClassWithConfig config, ILoggerService logger) { logger.write(0, config.value.name ~ "YEET"); } } } // TEST CASE unittest { auto services = new ServiceProvider(); alias Parameters = AliasSeq; // Test using a previously-registered service. services.addTransient!(ILoggerService, MinimalConsoleLoggerService); services.makeAndInject!(SomeImportantClass)(); assert(LAST_LOGGED_MESSAGE == "Ctor injection"); // Test using an overrided service. services.addTransient!(ILoggerService, DetailedConsoleLoggerService)(OverrideExisting.yes); services.makeAndInject!(SomeImportantClass)(); assert(LAST_LOGGED_MESSAGE == "[INFO] Ctor injection", LAST_LOGGED_MESSAGE); // Test call injections auto foo = new SomeUnrelatedClass(); services.injectCall!(SomeUnrelatedClass.doLog)(foo, "Foz"); services.injectCall!"doLog"(foo, "Foz"); // Alternate way assert(LAST_LOGGED_MESSAGE == "[ERROR] Foz", LAST_LOGGED_MESSAGE); // Test configuration. services.configure!SomeConfig((ref c) { c.name = "EXPLOSION"; }); auto configObj = services.makeAndInject!SomeClassWithConfig(); assert(LAST_LOGGED_MESSAGE == "[INFO] EXPLOSION", LAST_LOGGED_MESSAGE); // Non-interface based injection services.addSingleton!(SomeClassWithConfig, SomeClassWithConfig)(configObj); services.makeAndInject!SomeClassWithUDA(); assert(LAST_LOGGED_MESSAGE == "[INFO] EXPLOSIONYEET"); }
D
// Copyright Ferdinand Majerech 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) /** * Composes nodes from YAML events provided by parser. * Code based on PyYAML: http://www.pyyaml.org */ module dyaml.composer; import core.memory; import std.array; import std.conv; import std.exception; import std.typecons; import dyaml.anchor; import dyaml.constructor; import dyaml.event; import dyaml.exception; import dyaml.node; import dyaml.parser; import dyaml.resolver; package: /** * Exception thrown at composer errors. * * See_Also: MarkedYAMLException */ class ComposerException : MarkedYAMLException { mixin MarkedExceptionCtors; } ///Composes YAML documents from events provided by a Parser. final class Composer { private: ///Parser providing YAML events. Parser parser_; ///Resolver resolving tags (data types). Resolver resolver_; ///Constructor constructing YAML values. Constructor constructor_; ///Nodes associated with anchors. Used by YAML aliases. Node[Anchor] anchors_; ///Used to reduce allocations when creating pair arrays. /// ///We need one appender for each nesting level that involves ///a pair array, as the inner levels are processed as a ///part of the outer levels. Used as a stack. Appender!(Node.Pair[])[] pairAppenders_; ///Used to reduce allocations when creating node arrays. /// ///We need one appender for each nesting level that involves ///a node array, as the inner levels are processed as a ///part of the outer levels. Used as a stack. Appender!(Node[])[] nodeAppenders_; public: /** * Construct a composer. * * Params: parser = Parser to provide YAML events. * resolver = Resolver to resolve tags (data types). * constructor = Constructor to construct nodes. */ this(Parser parser, Resolver resolver, Constructor constructor) @safe { parser_ = parser; resolver_ = resolver; constructor_ = constructor; } ///Destroy the composer. pure @safe nothrow ~this() { parser_ = null; resolver_ = null; constructor_ = null; anchors_.destroy(); anchors_ = null; } /** * Determine if there are any nodes left. * * Must be called before loading as it handles the stream start event. */ bool checkNode() @safe { //Drop the STREAM-START event. if(parser_.checkEvent(EventID.StreamStart)) { parser_.getEvent(); } //True if there are more documents available. return !parser_.checkEvent(EventID.StreamEnd); } ///Get a YAML document as a node (the root of the document). Node getNode() @safe { //Get the root node of the next document. assert(!parser_.checkEvent(EventID.StreamEnd), "Trying to get a node from Composer when there is no node to " "get. use checkNode() to determine if there is a node."); return composeDocument(); } ///Get single YAML document, throwing if there is more than one document. Node getSingleNode() @trusted { assert(!parser_.checkEvent(EventID.StreamEnd), "Trying to get a node from Composer when there is no node to " "get. use checkNode() to determine if there is a node."); Node document = composeDocument(); //Ensure that the stream contains no more documents. enforce(parser_.checkEvent(EventID.StreamEnd), new ComposerException("Expected single document in the stream, " "but found another document.", parser_.getEvent().startMark)); //Drop the STREAM-END event. parser_.getEvent(); return document; } private: ///Ensure that appenders for specified nesting levels exist. /// ///Params: pairAppenderLevel = Current level in the pair appender stack. /// nodeAppenderLevel = Current level the node appender stack. void ensureAppendersExist(const uint pairAppenderLevel, const uint nodeAppenderLevel) @trusted { while(pairAppenders_.length <= pairAppenderLevel) { pairAppenders_ ~= appender!(Node.Pair[])(); } while(nodeAppenders_.length <= nodeAppenderLevel) { nodeAppenders_ ~= appender!(Node[])(); } } ///Compose a YAML document and return its root node. Node composeDocument() @trusted { //Drop the DOCUMENT-START event. parser_.getEvent(); //Compose the root node. Node node = composeNode(0, 0); //Drop the DOCUMENT-END event. parser_.getEvent(); anchors_.destroy(); return node; } /// Compose a node. /// /// Params: pairAppenderLevel = Current level of the pair appender stack. /// nodeAppenderLevel = Current level of the node appender stack. Node composeNode(const uint pairAppenderLevel, const uint nodeAppenderLevel) @system { if(parser_.checkEvent(EventID.Alias)) { immutable event = parser_.getEvent(); const anchor = event.anchor; enforce((anchor in anchors_) !is null, new ComposerException("Found undefined alias: " ~ anchor.get, event.startMark)); //If the node referenced by the anchor is uninitialized, //it's not finished, i.e. we're currently composing it //and trying to use it recursively here. enforce(anchors_[anchor] != Node(), new ComposerException("Found recursive alias: " ~ anchor.get, event.startMark)); return anchors_[anchor]; } immutable event = parser_.peekEvent(); const anchor = event.anchor; if(!anchor.isNull() && (anchor in anchors_) !is null) { throw new ComposerException("Found duplicate anchor: " ~ anchor.get, event.startMark); } Node result; //Associate the anchor, if any, with an uninitialized node. //used to detect duplicate and recursive anchors. if(!anchor.isNull()) { anchors_[anchor] = Node(); } if(parser_.checkEvent(EventID.Scalar)) { result = composeScalarNode(); } else if(parser_.checkEvent(EventID.SequenceStart)) { result = composeSequenceNode(pairAppenderLevel, nodeAppenderLevel); } else if(parser_.checkEvent(EventID.MappingStart)) { result = composeMappingNode(pairAppenderLevel, nodeAppenderLevel); } else{assert(false, "This code should never be reached");} if(!anchor.isNull()) { anchors_[anchor] = result; } return result; } ///Compose a scalar node. Node composeScalarNode() @system { immutable event = parser_.getEvent(); const tag = resolver_.resolve(NodeID.Scalar, event.tag, event.value, event.implicit); Node node = constructor_.node(event.startMark, event.endMark, tag, event.value, event.scalarStyle); return node; } /// Compose a sequence node. /// /// Params: pairAppenderLevel = Current level of the pair appender stack. /// nodeAppenderLevel = Current level of the node appender stack. Node composeSequenceNode(const uint pairAppenderLevel, const uint nodeAppenderLevel) @system { ensureAppendersExist(pairAppenderLevel, nodeAppenderLevel); auto nodeAppender = &(nodeAppenders_[nodeAppenderLevel]); immutable startEvent = parser_.getEvent(); const tag = resolver_.resolve(NodeID.Sequence, startEvent.tag, null, startEvent.implicit); while(!parser_.checkEvent(EventID.SequenceEnd)) { nodeAppender.put(composeNode(pairAppenderLevel, nodeAppenderLevel + 1)); } core.memory.GC.disable(); scope(exit){core.memory.GC.enable();} Node node = constructor_.node(startEvent.startMark, parser_.getEvent().endMark, tag, nodeAppender.data.dup, startEvent.collectionStyle); nodeAppender.clear(); return node; } /** * Flatten a node, merging it with nodes referenced through YAMLMerge data type. * * Node must be a mapping or a sequence of mappings. * * Params: root = Node to flatten. * startMark = Start position of the node. * endMark = End position of the node. * pairAppenderLevel = Current level of the pair appender stack. * nodeAppenderLevel = Current level of the node appender stack. * * Returns: Flattened mapping as pairs. */ Node.Pair[] flatten(ref Node root, const Mark startMark, const Mark endMark, const uint pairAppenderLevel, const uint nodeAppenderLevel) @system { void error(Node node) { //this is Composer, but the code is related to Constructor. throw new ConstructorException("While constructing a mapping, " "expected a mapping or a list of " "mappings for merging, but found: " ~ node.type.toString() ~ " NOTE: line/column shows topmost parent " "to which the content is being merged", startMark, endMark); } ensureAppendersExist(pairAppenderLevel, nodeAppenderLevel); auto pairAppender = &(pairAppenders_[pairAppenderLevel]); if(root.isMapping) { Node[] toMerge; foreach(ref Node key, ref Node value; root) { if(key.isType!YAMLMerge) { toMerge.assumeSafeAppend(); toMerge ~= value; } else { auto temp = Node.Pair(key, value); merge(*pairAppender, temp); } } foreach(node; toMerge) { merge(*pairAppender, flatten(node, startMark, endMark, pairAppenderLevel + 1, nodeAppenderLevel)); } } //Must be a sequence of mappings. else if(root.isSequence) foreach(ref Node node; root) { if(!node.isType!(Node.Pair[])){error(node);} merge(*pairAppender, flatten(node, startMark, endMark, pairAppenderLevel + 1, nodeAppenderLevel)); } else { error(root); } core.memory.GC.disable(); scope(exit){core.memory.GC.enable();} auto flattened = pairAppender.data.dup; pairAppender.clear(); return flattened; } /// Compose a mapping node. /// /// Params: pairAppenderLevel = Current level of the pair appender stack. /// nodeAppenderLevel = Current level of the node appender stack. Node composeMappingNode(const uint pairAppenderLevel, const uint nodeAppenderLevel) @system { ensureAppendersExist(pairAppenderLevel, nodeAppenderLevel); immutable startEvent = parser_.getEvent(); const tag = resolver_.resolve(NodeID.Mapping, startEvent.tag, null, startEvent.implicit); auto pairAppender = &(pairAppenders_[pairAppenderLevel]); Tuple!(Node, Mark)[] toMerge; while(!parser_.checkEvent(EventID.MappingEnd)) { auto pair = Node.Pair(composeNode(pairAppenderLevel + 1, nodeAppenderLevel), composeNode(pairAppenderLevel + 1, nodeAppenderLevel)); //Need to flatten and merge the node referred by YAMLMerge. if(pair.key.isType!YAMLMerge) { toMerge ~= tuple(pair.value, cast(Mark)parser_.peekEvent().endMark); } //Not YAMLMerge, just add the pair. else { merge(*pairAppender, pair); } } foreach(node; toMerge) { merge(*pairAppender, flatten(node[0], startEvent.startMark, node[1], pairAppenderLevel + 1, nodeAppenderLevel)); } core.memory.GC.disable(); scope(exit){core.memory.GC.enable();} Node node = constructor_.node(startEvent.startMark, parser_.getEvent().endMark, tag, pairAppender.data.dup, startEvent.collectionStyle); pairAppender.clear(); return node; } }
D
func void B_CheckDeadMissionNPCs() { if(Hlp_GetInstanceID(Org_844_Lefty) == Hlp_GetInstanceID(self)) { if(Lefty_Mission == LOG_RUNNING) { B_LogEntry(CH1_CarryWater,"Teď když je Lefty mrtev, s nošením vody je asi konec. Ten chlápek se mi stejně nelíbil."); Log_SetTopicStatus(CH1_CarryWater,LOG_SUCCESS); LeftyDead = TRUE; }; }; if(Hlp_GetInstanceID(ORG_826_Mordrag) == Hlp_GetInstanceID(self)) { if(Thorus_MordragKo == LOG_RUNNING) { B_LogEntry(CH1_MordragKO,"Nyní, když je Mordrag mrtvý, je Thorusův problém vyřešen a já jsem udělal svou práci."); }; }; };
D
/******************************************************************************* * Copyright (c) 2004, 2005 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 dwtx.jface.bindings.IBindingManagerListener; import dwtx.jface.bindings.BindingManagerEvent; import dwt.dwthelper.utils; /** * <p> * An instance of <code>BindingManagerListener</code> can be used by clients to * receive notification of changes to an instance of * <code>BindingManager</code>. * </p> * <p> * This interface may be implemented by clients. * </p> * * @since 3.1 * @see BindingManager#addBindingManagerListener(IBindingManagerListener) * @see dwtx.jface.bindings.BindingManager#addBindingManagerListener(IBindingManagerListener) * @see BindingManagerEvent */ public interface IBindingManagerListener { /** * Notifies that attributes inside an instance of <code>BindingManager</code> have changed. * Specific details are described in the <code>BindingManagerEvent</code>. Changes in the * binding manager can cause the set of defined or active schemes or bindings to change. * * @param event * the binding manager event. Guaranteed not to be <code>null</code>. */ void bindingManagerChanged(BindingManagerEvent event); }
D
// Written in the D programming language. /* * dmd 2.070.0 - 2.075.0 * * Copyright Seiji Fujita 2016. * Distributed under the Boost Software License, Version 1.0. * http://www.boost.org/LICENSE_1_0.txt */ module bookmark; import org.eclipse.swt.all; import java.lang.all; import std.file; import std.path; import windowmgr; import conf; import utils; import setting; import dlsbuffer; class Bookmark { enum bookmarkTopText = "Bookmark"; Tree bookmarkTree; Config bookmarkConf; void delegate(string path = null) updateFolder; void delegate(string) reloadFileTable; /* string[] loadBookmarkData = [ "C:\\Home", "C:\\D", "C:\\D\\rakugaki\\dwtdev", "C:\\D\\rakugaki\\DlangUI", "C:\\D\\rakugaki\\Gtkd", ]; struct BookmarkData { string _text; string _path; void set(string text, string path) { _text = text; _path = path; } @property void text(string text) { _text = text; } @property string text() { return _text; } @property void path(string path) { _path = path; } @property string path() { return _path; } } */ this() {} void initUI(Composite parent) { bookmarkTree = new Tree(parent, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.SINGLE | SWT.VIRTUAL); bookmarkTree.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL)); SetTreeViewStyle(bookmarkTree.handle); setPopup(bookmarkTree); setDrop(bookmarkTree); updateBookmark(); bookmarkTree.addListener(SWT.MouseDown, new class Listener { void handleEvent(Event event) { if (event.button == 1) { // mouse left button Point point = new Point(event.x, event.y); auto item = cast(bookmarkItem)bookmarkTree.getItem(point); if (item !is null) { dlog("MouseDown: ", item.getfullPath()); updateFolder(item.getfullPath()); } } } }); } void updateBookmark() { if (bookmarkTree !is null) { bookmarkTree.removeAll(); auto itemTop = new bookmarkItem(bookmarkTree, SWT.NONE); string[] bookmarks; if (cf.getBookmarks(bookmarks)) { foreach (v ; bookmarks) { auto item = new bookmarkItem(itemTop, SWT.NONE); item.setPath(v); // none item.setToolTipText(path); } itemTop.setExpanded(true); } } } void addBookmarkData(string data) { if (data.length) { string[] bookmarks; if (cf.getBookmarks(bookmarks)) { bookmarks ~= data; cf.setBookmarks(bookmarks); } else { cf.setBookmarks([ data ]); } } } class bookmarkItem : TreeItem { string fullPath; this(bookmarkItem parentItem, int style) { super(parentItem, style); } this(Tree parent, int style) { super(parent, style); setText(bookmarkTopText); fullPath = ""; } this(Tree parent, string path, int style) { super(parent, style); setText(path); fullPath = path; } string getfullPath() { return fullPath; } void setPath(string path) { fullPath = path; setText(baseName(path)); } bookmarkItem addChildPath(bookmarkItem node, string path) { bookmarkItem item = new bookmarkItem(node, SWT.NULL); item.setPath(path); return item; } } // Popup Menu void setPopup(Tree parent) { Menu menu = new Menu(parent); parent.setMenu(menu); addMenuSeparator(menu); //-------------------- addPopupMenu(menu, "BooknarkEditor", &execSettingDialog); addPopupMenu(menu, "Delete", &dg_dummy); addMenuSeparator(menu); addPopupMenu(menu, "Reload", &updateBookmark); auto itemDummy = addPopupMenu(menu, "Dummy", &dg_dummy); menu.addMenuListener(new class MenuAdapter { override void menuShown(MenuEvent e) { itemDummy.setEnabled(false); } }); } MenuItem addPopupMenu(Menu menu, string text, void delegate() dg, int accelerator = 0, int style = SWT.NONE) { MenuItem item = new MenuItem(menu, style); item.setText(text); if (accelerator != 0) { item.setAccelerator(accelerator); // SWT.CTRL + 'A' } item.addSelectionListener(new class SelectionAdapter { override void widgetSelected(SelectionEvent event) { dg(); } }); return item; } void addMenuSeparator(Menu menu) { new MenuItem(menu, SWT.SEPARATOR); } void dg_dummy() { } void execSettingDialog() { enum BookmarkEditor = 3; auto ddlg = new SettingDialog(wm.getShell()); if (ddlg.open( BookmarkEditor )) { updateBookmark(); } } // Bookmarkの追加の目的の Drop を行う // void setDrop(Tree tt) { int operations = DND.DROP_COPY; DropTarget target = new DropTarget(tt, operations); target.setTransfer([TextTransfer.getInstance(), FileTransfer.getInstance()]); target.addDropListener(new class DropTargetAdapter { override void dragEnter(DropTargetEvent event) { // ドラッグ中のカーソルが入ってきた時の処理 // 修飾キーを押さない場合のドラッグ&ドロップはコピー //if (event.detail == DND.DROP_DEFAULT) // event.detail = DND.DROP_COPY; dragOperationChanged(event); } override void dragOperationChanged(DropTargetEvent event) { // ドラッグ中に修飾キーが押されて処理が変更された時の処理 // 修飾キーを押さない場合のドラッグ&ドロップはコピー event.detail = DND.DROP_NONE; if (TextTransfer.getInstance().isSupportedType(event.currentDataType)) { event.detail = DND.DROP_COPY; } else if (FileTransfer.getInstance().isSupportedType(event.currentDataType)) { event.detail = DND.DROP_COPY; } } override void drop(DropTargetEvent event) { // event.data の内容を確認してカーソル位置にテキストをドロップ if (event.data is null) { event.detail = DND.DROP_NONE; } else if (TextTransfer.getInstance().isSupportedType(event.currentDataType)) { string st = stringcast(cast(Object)event.data); dlog("drop:TextTransfer: ", st); addBookmarkData(st); updateBookmark(); } else if (FileTransfer.getInstance().isSupportedType(event.currentDataType)) { string[] sar = stringArrayFromObject(event.data); foreach(v ; sar) { dlog("drop:TextTransfer: ", v); addBookmarkData(v); } updateBookmark(); } } }); } }
D
/++ Package for the common plugin modules all plugins need. See_Also: [kameloso.plugins.common.core], [kameloso.plugins.common.misc], [kameloso.plugins.common.delayawait], [kameloso.plugins.common.mixins], [kameloso.plugins.common.awareness] Copyright: [JR](https://github.com/zorael) License: [Boost Software License 1.0](https://www.boost.org/users/license.html) Authors: [JR](https://github.com/zorael) +/ module kameloso.plugins.common; public: import kameloso.plugins.common.core; import kameloso.plugins.common.misc; import kameloso.plugins.common.delayawait; import kameloso.plugins.common.mixins; import kameloso.plugins.common.awareness;
D
Long: form Short: F Arg: <name=content> Help: Specify multipart MIME data Protocols: HTTP SMTP IMAP Mutexed: data head upload-file Category: http upload --- For HTTP protocol family, this lets carl emulate a filled-in form in which a user has pressed the submit button. This causes carl to POST data using the Content-Type multipart/form-data according to RFC 2388. For SMTP and IMAP protocols, this is the mean to compose a multipart mail message to transmit. This enables uploading of binary files etc. To force the 'content' part to be a file, prefix the file name with an @ sign. To just get the content part from a file, prefix the file name with the symbol <. The difference between @ and < is then that @ makes a file get attached in the post as a file upload, while the < makes a text field and just get the contents for that text field from a file. Tell carl to read content from stdin instead of a file by using - as filename. This goes for both @ and < constructs. When stdin is used, the contents is buffered in memory first by carl to determine its size and allow a possible resend. Defining a part's data from a named non-regular file (such as a named pipe or similar) is unfortunately not subject to buffering and will be effectively read at transmission time; since the full size is unknown before the transfer starts, such data is sent as chunks by HTTP and rejected by IMAP. Example: send an image to an HTTP server, where \&'profile' is the name of the form-field to which the file portrait.jpg will be the input: carl -F profile=@portrait.jpg https://example.com/upload.cgi Example: send your name and shoe size in two text fields to the server: carl -F name=John -F shoesize=11 https://example.com/ Example: send your essay in a text field to the server. Send it as a plain text field, but get the contents for it from a local file: carl -F "story=<hugefile.txt" https://example.com/ You can also tell carl what Content-Type to use by using 'type=', in a manner similar to: carl -F "web=@index.html;type=text/html" example.com or carl -F "name=daniel;type=text/foo" example.com You can also explicitly change the name field of a file upload part by setting filename=, like this: carl -F "file=@localfile;filename=nameinpost" example.com If filename/path contains ',' or ';', it must be quoted by double-quotes like: carl -F "file=@\\"localfile\\";filename=\\"nameinpost\\"" example.com or carl -F 'file=@"localfile";filename="nameinpost"' example.com Note that if a filename/path is quoted by double-quotes, any double-quote or backslash within the filename must be escaped by backslash. Quoting must also be applied to non-file data if it contains semicolons, leading/trailing spaces or leading double quotes: carl -F 'colors="red; green; blue";type=text/x-myapp' example.com You can add custom headers to the field by setting headers=, like carl -F "submit=OK;headers=\\"X-submit-type: OK\\"" example.com or carl -F "submit=OK;headers=@headerfile" example.com The headers= keyword may appear more that once and above notes about quoting apply. When headers are read from a file, Empty lines and lines starting with '#' are comments and ignored; each header can be folded by splitting between two words and starting the continuation line with a space; embedded carriage-returns and trailing spaces are stripped. Here is an example of a header file contents: # This file contain two headers. .br X-header-1: this is a header # The following header is folded. .br X-header-2: this is .br another header To support sending multipart mail messages, the syntax is extended as follows: .br - name can be omitted: the equal sign is the first character of the argument, .br - if data starts with '(', this signals to start a new multipart: it can be followed by a content type specification. .br - a multipart can be terminated with a '=)' argument. Example: the following command sends an SMTP mime e-mail consisting in an inline part in two alternative formats: plain text and HTML. It attaches a text file: carl -F '=(;type=multipart/alternative' \\ .br -F '=plain text message' \\ .br -F '= <body>HTML message</body>;type=text/html' \\ .br -F '=)' -F '=@textfile.txt' ... smtp://example.com Data can be encoded for transfer using encoder=. Available encodings are \fIbinary\fP and \fI8bit\fP that do nothing else than adding the corresponding Content-Transfer-Encoding header, \fI7bit\fP that only rejects 8-bit characters with a transfer error, \fIquoted-printable\fP and \fIbase64\fP that encodes data according to the corresponding schemes, limiting lines length to 76 characters. Example: send multipart mail with a quoted-printable text message and a base64 attached file: carl -F '=text message;encoder=quoted-printable' \\ .br -F '=@localfile;encoder=base64' ... smtp://example.com See further examples and details in the MANUAL. This option can be used multiple times.
D
module blockie.model5.M5ChunkSerialiser; import blockie.model; final class M5ChunkSerialiser : ChunkSerialiser { protected: override Chunk toChunk(AirChunk ac) { auto chunk = new M5Chunk(ac.pos); chunk.root.distance.set(ac.distance); return chunk; } override AirChunk toAirChunk(Chunk chunk) { auto root = (cast(M5Chunk)chunk).root(); return AirChunk( chunk.pos, root.distance ); } public: this(World w, Model model) { super(w, model); } }
D
module dscord.types.message; import std.stdio, std.variant, std.conv, std.format, std.regex, std.array, std.algorithm.iteration; import dscord.types, dscord.client; /** An interface implementting something that can be sent as a message. */ interface Sendable { /// Returns a string that will NEVER be greater than 2000 characters immutable(string) toSendableString(); } class MessageEmbed : IModel { mixin Model; string title; string type; string description; string url; // TODO: thumbnail, provider override void load(JSONDecoder obj) { obj.keySwitch!( "title", "type", "description", "url" )( { this.title = obj.read!string; }, { this.type = obj.read!string; }, { this.description = obj.read!string; }, { this.url = obj.read!string; }, ); } } class MessageAttachment : IModel { mixin Model; Snowflake id; string filename; uint size; string url; string proxyUrl; uint height; uint width; override void load(JSONDecoder obj) { obj.keySwitch!( "id", "filename", "size", "url", "proxy_url", "height", "width", )( { this.id = readSnowflake(obj); }, { this.filename = obj.read!string; }, { this.size = obj.read!uint; }, { this.url = obj.read!string; }, { this.proxyUrl = obj.read!string; }, { this.height = obj.read!uint; }, { this.width = obj.read!uint; }, ); } } class Message : IModel { mixin Model; Snowflake id; Snowflake channelID; Channel channel; User author; string content; string timestamp; // TODO: timestamps lol string editedTimestamp; // TODO: timestamps lol bool tts; bool mentionEveryone; string nonce; bool pinned; // TODO: GuildMemberMap here UserMap mentions; RoleMap roleMentions; // Embeds MessageEmbed[] embeds; // Attachments MessageAttachment[] attachments; this(Client client, JSONDecoder obj) { super(client, obj); } this(Channel channel, JSONDecoder obj) { this.channel = channel; super(channel.client, obj); } override void init() { this.mentions = new UserMap; this.roleMentions = new RoleMap; } override void load(JSONDecoder obj) { // TODO: avoid leaking user obj.keySwitch!( "id", "channel_id", "content", "timestamp", "edited_timestamp", "tts", "mention_everyone", "nonce", "author", "pinned", "mentions", "mention_roles", // "embeds", "attachments", )( { this.id = readSnowflake(obj); }, { this.channelID = readSnowflake(obj); }, { this.content = obj.read!string; }, { this.timestamp = obj.read!string; }, { if (obj.peek() == VibeJSON.Type.string) { this.editedTimestamp = obj.read!string; } else { obj.skipValue; } }, { this.tts = obj.read!bool; }, { this.mentionEveryone = obj.read!bool; }, { if (obj.peek() == VibeJSON.Type.string) { this.nonce = obj.read!string; } else if (obj.peek() == VibeJSON.Type.null_) { obj.skipValue; } else { this.nonce = obj.read!long.to!string; } }, { this.author = new User(this.client, obj); }, { this.pinned = obj.read!bool; }, { loadMany!User(this.client, obj, (u) { this.mentions[u.id] = u; }); }, { obj.skipValue; }, // { obj.skipValue; }, // { obj.skipvalue; }, ); if (!this.channel && this.client.state.channels.has(this.channelID)) { this.channel = this.client.state.channels.get(this.channelID); } } override string toString() { return format("<Message %s>", this.id); } /* Returns a version of the message contents, with mentions completely removed */ string withoutMentions() { return this.replaceMentions((m, u) => "", (m, r) => ""); } /* Returns a version of the message contents, replacing all mentions with user/nick names */ string withProperMentions(bool nicks=true) { return this.replaceMentions((msg, user) { GuildMember m; if (nicks) { m = msg.guild.members.get(user.id); } return "@" ~ ((m && m.nick != "") ? m.nick : user.username); }, (msg, role) { return "@" ~ role.name; }); } /** Returns the message contents, replacing all mentions with the result from the specified delegate. */ string replaceMentions(string delegate(Message, User) fu, string delegate(Message, Role) fr) { if (!this.mentions.length) { return this.content; } string result = this.content; foreach (ref User user; this.mentions.values) { result = replaceAll(result, regex(format("<@!?(%s)>", user.id)), fu(this, user)); } foreach (ref Role role; this.roleMentions.values) { result = replaceAll(result, regex(format("<@!?(%s)>", role.id)), fr(this, role)); } return result; } /** Sends a new message to the same channel as this message. Params: content = the message contents nonce = the message nonce tts = whether this is a TTS message */ Message reply(inout(string) content, string nonce=null, bool tts=false) { return this.client.api.channelsMessagesCreate(this.channel.id, content, nonce, tts); } /** Sends a Sendable to the same channel as this message. */ Message reply(Sendable obj) { return this.client.api.channelsMessagesCreate(this.channel.id, obj.toSendableString(), null, false); } /** Sends a new formatted message to the same channel as this message. */ Message replyf(T...)(inout(string) content, T args) { return this.client.api.channelsMessagesCreate(this.channel.id, format(content, args), null, false); } /** Edits this message contents. */ Message edit(inout(string) content) { return this.client.api.channelsMessagesModify(this.channel.id, this.id, content); } /** Edits this message contents with a Sendable. */ Message edit(Sendable obj) { return this.edit(obj.toSendableString()); } /** Deletes this message. */ void del() { if (!this.canDelete()) { throw new PermissionsError(Permissions.MANAGE_MESSAGES); } return this.client.api.channelsMessagesDelete(this.channel.id, this.id); } /* True if this message mentions the current user in any way (everyone, direct mention, role mention) */ @property bool mentioned() { return this.mentionEveryone || this.mentions.has(this.client.state.me.id) || this.roleMentions.keyUnion( this.guild.getMember(this.client.state.me).roles ).length != 0; } /** Guild this message was sent in (if applicable). */ @property Guild guild() { if (this.channel && this.channel.guild) return this.channel.guild; return null; } /** Returns an array of emoji IDs for all custom emoji used in this message. */ @property Snowflake[] customEmojiByID() { return matchAll(this.content, regex("<:\\w+:(\\d+)>")).map!((m) => m.back.to!Snowflake).array; } /// Whether the bot can edit this message bool canDelete() { return (this.author.id == this.client.state.me.id || this.channel.can(this.client.state.me, Permissions.MANAGE_MESSAGES)); } /// Whether the bot can edit this message bool canEdit() { return (this.author.id == this.client.state.me.id); } }
D
// ************************************************ // G_CanNotUse // ----------- // Funktion wir vom Programm aufgerufen, // wenn SC oder NSC etwas equippt, für das ihm // die Attributs-Voraussetzung fehlt // ------------------------------------------------ // self = der NSC, der das Item nicht equippen kann // item = das Item // ************************************************ func void G_CanNotUse (var int bIsPlayer, var int nAttribute, var int nValue) { // ------ Ausgabe-String ------ var string strMessage; // ------ Attribut ermitteln ------ var string strAttributeMissing; var int nAttributeValue; //ADDON> if (nAttribute == ATR_MANA_MAX) && (nValue == 666666)//Joly: ATR_MANA_MAX von Raven { strMessage = PRINT_ADDON_BELIARSCOURSE_MISSING; B_BlitzInArsch (); SC_FailedToEquipBeliarsWeapon = TRUE; } //ADDON< else { if (nAttribute == ATR_HITPOINTS) { strAttributeMissing = PRINT_HITPOINTS_MISSING ; nAttributeValue = self.attribute[ATR_HITPOINTS]; } else if (nAttribute == ATR_HITPOINTS_MAX) { strAttributeMissing = PRINT_HITPOINTS_MAX_MISSING ; nAttributeValue = self.attribute[ATR_HITPOINTS_MAX]; } else if (nAttribute == ATR_MANA) { strAttributeMissing = PRINT_MANA_MISSING ; nAttributeValue = self.attribute[ATR_MANA]; } else if (nAttribute == ATR_MANA_MAX) { strAttributeMissing = PRINT_MANA_MAX_MISSING ; nAttributeValue = self.attribute[ATR_MANA_MAX]; } else if (nAttribute == ATR_STRENGTH) { strAttributeMissing = PRINT_STRENGTH_MISSING ; nAttributeValue = self.attribute[ATR_STRENGTH]; } else if (nAttribute == ATR_DEXTERITY) { strAttributeMissing = PRINT_DEXTERITY_MISSING ; nAttributeValue = self.attribute[ATR_DEXTERITY]; } else { strAttributeMissing = "" ; nAttributeValue = 0; }; // ------ Ermittlen, wieviele Punkte fehlen ------ var int nDifference ; nDifference = nValue - nAttributeValue; var string strDifference; strDifference = IntToString(nDifference); // ------- String zusammenbauen ------- strMessage = strDifference; strMessage = ConcatStrings( strMessage, " " ); strMessage = ConcatStrings( strMessage, strAttributeMissing ); }; // ------- String ausgeben ------ if (bIsPlayer) { Print (strMessage); }; };
D