code
stringlengths
3
10M
language
stringclasses
31 values
instance GRD_262_Aaron_Exit(C_Info) { npc = GRD_262_Aaron; nr = 999; condition = GRD_262_Aaron_Exit_Condition; information = GRD_262_Aaron_Exit_Info; important = 0; permanent = 1; description = DIALOG_ENDE; }; func int GRD_262_Aaron_Exit_Condition() { return 1; }; func void GRD_262_Aaron_Exit_Info() { AI_StopProcessInfos(self); }; instance GRD_262_Aaron_CHEST(C_Info) { npc = GRD_262_Aaron; condition = GRD_262_Aaron_CHEST_Condition; information = GRD_262_Aaron_CHEST_Info; important = 0; permanent = 1; description = "Czym się tutaj zajmujesz?"; }; func int GRD_262_Aaron_CHEST_Condition() { if((Npc_GetDistToWP(self,"OM_CAVE1_34") < 400) && !Npc_KnowsInfo(hero,GRD_262_Aaron_BLUFF)) { return 1; }; }; func void GRD_262_Aaron_CHEST_Info() { AI_Output(other,self,"GRD_262_Aaron_CHEST_Info_15_01"); //Czym się tutaj zajmujesz? AI_Output(self,other,"GRD_262_Aaron_CHEST_Info_09_02"); //Pilnuję, żeby Kopacze, tacy jak nasz drogi Snipes, trzymali łapy z dala od mojej skrzyni. }; instance GRD_262_Aaron_BLUFF(C_Info) { npc = GRD_262_Aaron; condition = GRD_262_Aaron_BLUFF_Condition; information = GRD_262_Aaron_BLUFF_Info; important = 0; permanent = 1; description = "(odciągnij Aarona)"; }; func int GRD_262_Aaron_BLUFF_Condition() { if(Npc_KnowsInfo(hero,VLK_584_Snipes_DEAL) && (Aaron_lock != LOG_RUNNING) && (Aaron_lock != LOG_SUCCESS)) { return 1; }; }; func void GRD_262_Aaron_BLUFF_Info() { Info_ClearChoices(GRD_262_Aaron_BLUFF); Info_AddChoice(GRD_262_Aaron_BLUFF,DIALOG_BACK,GRD_262_Aaron_BLUFF_BACK); Info_AddChoice(GRD_262_Aaron_BLUFF,"Przysyła mnie Ian. Masz się do niego natychmiast zgłosić!",GRD_262_Aaron_BLUFF_IAN); Info_AddChoice(GRD_262_Aaron_BLUFF,"Podobno w waszej kopalni są jacyś rabusie.",GRD_262_Aaron_BLUFF_BANDIT); Info_AddChoice(GRD_262_Aaron_BLUFF,"Kopacze znaleźli ogromną bryłę rudy!",GRD_262_Aaron_BLUFF_ORE); }; func void GRD_262_Aaron_BLUFF_ORE() { AI_Output(other,self,"GRD_262_Aaron_BLUFF_ORE_15_01"); //Kopacze znaleźli ogromną bryłę rudy! AI_Output(self,other,"GRD_262_Aaron_BLUFF_ORE_09_02"); //I co z tego? AI_Output(other,self,"GRD_262_Aaron_BLUFF_ORE_15_03"); //Powinieneś na nią rzucić okiem. AI_Output(self,other,"GRD_262_Aaron_BLUFF_ORE_09_04"); //Nie ma mowy. }; func void GRD_262_Aaron_BLUFF_BANDIT() { AI_Output(other,self,"GRD_262_Aaron_BLUFF_BANDIT_15_01"); //Podobno w waszej kopalni są jacyś rabusie. Zamierzają ukraść ładunek rudy! AI_Output(self,other,"GRD_262_Aaron_BLUFF_BANDIT_09_02"); //Masz mnie za głupca? Nie odważyliby się na coś takiego! }; func void GRD_262_Aaron_BLUFF_IAN() { AI_Output(other,self,"GRD_262_Aaron_BLUFF_IAN_15_01"); //Przysyła mnie Ian. Masz się do niego natychmiast zgłosić! AI_Output(self,other,"GRD_262_Aaron_BLUFF_IAN_09_02"); //A czego ode mnie chce? Info_ClearChoices(GRD_262_Aaron_BLUFF); Info_AddChoice(GRD_262_Aaron_BLUFF,"Nie wiem.",GRD_262_Aaron_BLUFF_UGLY); Info_AddChoice(GRD_262_Aaron_BLUFF,"Ma już dość twojego lenistwa.",GRD_262_Aaron_BLUFF_BAD); Info_AddChoice(GRD_262_Aaron_BLUFF,"Ma ci wręczyć nagrodę za przykładną pracę.",GRD_262_Aaron_BLUFF_GOOD); }; func void GRD_262_Aaron_BLUFF_GOOD() { AI_Output(other,self,"GRD_262_Aaron_BLUFF_GOOD_15_01"); //Ma ci wręczyć nagrodę za przykładną pracę. AI_Output(self,other,"GRD_262_Aaron_BLUFF_GOOD_09_02"); //Czyżby? Wiesz co? Lepiej już stąd idź. Npc_SetTempAttitude(self,ATT_ANGRY); AI_StopProcessInfos(self); }; func void GRD_262_Aaron_BLUFF_BAD() { AI_Output(other,self,"GRD_262_Aaron_BLUFF_BAD_15_01"); //Ma już dość twojego lenistwa. AI_Output(self,other,"GRD_262_Aaron_BLUFF_BAD_09_02"); //Phi. To nic nowego. Spadaj! AI_StopProcessInfos(self); }; func void GRD_262_Aaron_BLUFF_UGLY() { AI_Output(other,self,"GRD_262_Aaron_BLUFF_UGLY_15_01"); //Nie wiem. Pewnie sam ci to powie. Inaczej po co by cię wzywał? AI_Output(self,other,"GRD_262_Aaron_BLUFF_UGLY_09_02"); //Ach, trudno. W takim razie zajrzę do niego. AI_StopProcessInfos(self); Npc_ExchangeRoutine(self,"trick"); Aaron_lock = LOG_RUNNING; Snipes_deal = LOG_SUCCESS; GRD_262_Aaron_BLUFF.permanent = 0; B_LogEntry(CH2_SnipesDeal,"Odciągnąłem Aarona od skrzyni pod pretekstem spotkania z Ianem. Mam nadzieję, że się na mnie nie wścieknie."); }; func void GRD_262_Aaron_BLUFF_BACK() { Info_ClearChoices(GRD_262_Aaron_BLUFF); }; instance GRD_262_Aaron_PISSED(C_Info) { npc = GRD_262_Aaron; condition = GRD_262_Aaron_PISSED_Condition; information = GRD_262_Aaron_PISSED_Info; important = 1; permanent = 0; }; func int GRD_262_Aaron_PISSED_Condition() { if((Aaron_lock == LOG_RUNNING) && (Npc_GetDistToWP(hero,"OM_CAVE1_47") < 1000)) { return TRUE; }; }; func void GRD_262_Aaron_PISSED_Info() { AI_DrawWeapon(self); AI_Output(self,other,"Info_Aaron_PISSED_09_01"); //HEJ, TY! Jeśli jeszcze raz spróbujesz wystrychnąć mnie na dudka, pogadamy inaczej. Zrozumiano?! AI_RemoveWeapon(self); Npc_ExchangeRoutine(self,"start"); Aaron_lock = LOG_SUCCESS; B_LogEntry(CH2_SnipesDeal,"Spotkałem Aarona. Jednak się na mnie wściekł!"); }; instance GRD_262_Aaron_SELL(C_Info) { npc = GRD_262_Aaron; condition = GRD_262_Aaron_SELL_Condition; information = GRD_262_Aaron_SELL_Info; important = 0; permanent = 0; description = "Nie zgubiłeś przypadkiem klucza do swojej skrzyni?"; }; func int GRD_262_Aaron_SELL_Condition() { if(Npc_KnowsInfo(hero,VLK_584_Snipes_DEAL_RUN)) { return 1; }; }; func void GRD_262_Aaron_SELL_Info() { AI_Output(other,self,"Info_Aaron_SELL_15_01"); //Nie zgubiłeś przypadkiem klucza do swojej skrzyni? AI_Output(self,other,"Info_Aaron_SELL_09_02"); //W rzeczy samej. Nawet nie chcę wiedzieć skąd wiesz o jego istnieniu. AI_Output(self,other,"Info_Aaron_SELL_09_03"); //Ale dam ci 20 bryłek rudy, jeśli mi go oddasz. B_LogEntry(CH2_SnipesDeal,"Aaron zaoferował mi 20 bryłek rudy, jeśli zdobędę dla niego klucze od skrzyni."); }; instance GRD_262_Aaron_SELLNOW(C_Info) { npc = GRD_262_Aaron; condition = GRD_262_Aaron_SELLNOW_Condition; information = GRD_262_Aaron_SELLNOW_Info; important = 0; permanent = 0; description = "(sprzedaj klucz)"; }; func int GRD_262_Aaron_SELLNOW_Condition() { if(Npc_KnowsInfo(hero,GRD_262_Aaron_SELL) && Npc_HasItems(hero,ItKe_OM_02)) { return 1; }; }; func void GRD_262_Aaron_SELLNOW_Info() { AI_Output(other,self,"Info_Aaron_SELLNOW_15_01"); //Oto twój klucz. AI_Output(self,other,"Info_Aaron_SELLNOW_09_02"); //Tak, to ten. Masz tu swoje 20 bryłek, zgodnie z umową. AI_Output(self,other,"Info_Aaron_SELLNOW_09_03"); //Ale w przyszłości radzę ci uważać! Od tej pory będę cię miał na oku! CreateInvItems(self,ItMiNugget,20); B_GiveInvItems(self,other,ItMiNugget,20); B_GiveInvItems(hero,self,ItKe_OM_02,1); B_GiveXP(XP_SellKeyToAaron); B_LogEntry(CH2_SnipesDeal,"Sprzedałem Aaronowi jego własny klucz. Nieźle mi się to opłaciło!"); Log_SetTopicStatus(CH2_SnipesDeal,LOG_SUCCESS); };
D
/home/ubuntu/substrate-node-template/target/debug/build/rand_pcg-2d818fb632897b98/build_script_build-2d818fb632897b98: /home/ubuntu/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_pcg-0.1.2/build.rs /home/ubuntu/substrate-node-template/target/debug/build/rand_pcg-2d818fb632897b98/build_script_build-2d818fb632897b98.d: /home/ubuntu/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_pcg-0.1.2/build.rs /home/ubuntu/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_pcg-0.1.2/build.rs:
D
/* Copyright (c) 2013 Andrey Penechko 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 anchovy.graphics.windows.glfwwindow; private { import std.conv : to; import std.stdio; import std.string; import anchovy.core.interfaces.iwindow; } public { import derelict.glfw3.glfw3; import derelict.opengl3.gl3; import anchovy.utils.string; } class GlfwWindow : IWindow { public: override void init(uvec2 size, in string caption) { if (!glfwInited) { initGlfw(); } scope(failure) glfwTerminate(); _size = size; //BUG: sometimes fails in Windows 8. Maybe because of old drivers. _window = glfwCreateWindow(_size.x, _size.y, toStringz(caption), null, null); if (_window is null) { throw new Error("Error creating GLFW3 window"); } glfwMakeContextCurrent(_window); glfwSwapInterval(0); glClearColor(1.0, 1.0, 1.0, 1.0); glViewport(0, 0, _size.x, _size.y); DerelictGL3.reload(); glfwSetWindowUserPointer(_window, cast(void*)this); glfwSetWindowPosCallback(_window, &windowposfun); glfwSetFramebufferSizeCallback(_window, &windowsizefun); glfwSetWindowCloseCallback(_window, &windowclosefun); //glfwSetWindowRefreshCallback(_window, &windowrefreshfun); glfwSetWindowFocusCallback(_window, &windowfocusfun); glfwSetWindowIconifyCallback(_window, &windowiconifyfun); glfwSetMouseButtonCallback(_window, &mousebuttonfun); glfwSetCursorPosCallback(_window, &cursorposfun); glfwSetScrollCallback(_window, &scrollfun); glfwSetKeyCallback(_window, &keyfun); glfwSetCharCallback(_window, &charfun); //glfwSetCursorEnterCallback(window, GLFWcursorenterfun cbfun); } override void processEvents() { glfwPollEvents(); } override double elapsedTime() @property //in seconds { return glfwGetTime(); } override void reshape(uvec2 viewportSize) { glViewport(0, 0, cast(int)viewportSize.x, cast(int)viewportSize.y); } override void releaseWindow() { glfwDestroyWindow(_window); glfwTerminate(); } override void mousePosition(ivec2 newPosition) @property { glfwSetCursorPos(_window, newPosition.x, newPosition.y); } override ivec2 mousePosition() @property { double x, y; glfwGetCursorPos(_window, &x, &y); return ivec2(cast(int)x, cast(int)y); } override void swapBuffers() { glfwSwapBuffers(_window); } override void grabMouse(){} override void releaseMouse(){} override void size(uvec2 newSize) @property { glfwSetWindowSize(_window, cast(int)newSize.x, cast(int)newSize.y); } override uvec2 size() @property { int width, height; glfwGetWindowSize(_window, &width, &height); return uvec2(cast(uint)width, cast(uint)height); } override string clipboardString() @property { const(char*) data = glfwGetClipboardString(_window); if (data is null) return ""; return ZToString(data); } override void clipboardString(string newClipboardString) @property { glfwSetClipboardString(_window, toStringz(newClipboardString)); } override bool isKeyPressed(uint key) { return glfwGetKey(_window, key) == GLFW_PRESS; } protected: static void initGlfw() { glfwSetErrorCallback(&errorfun); if (glfwInit() == 0) { throw new Error("Error initializing GLFW3"); //TODO: add proper error handling } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwInited = true; } private: GLFWwindow* _window; uvec2 _size; bool _mouseGrabbed = false; static bool glfwInited = false; } static GlfwWindow getWinFromUP(GLFWwindow* w) nothrow { GlfwWindow win; win = cast(GlfwWindow) glfwGetWindowUserPointer(w); return win; } extern(C) { static void errorfun(int errorCode, const(char)* msg) nothrow { throw new Error("GLFW error ocured ["~to!string(errorCode)~"] : "~ZToString(msg)); } static void windowposfun(GLFWwindow* w, int nx, int ny) nothrow { try { getWinFromUP(w).windowMoved.emit(ivec2(nx, ny)); } catch(Exception e) { throw new Error(to!string(e)); } } static void windowsizefun(GLFWwindow* w, int newWidth, int newHeight) nothrow { try { getWinFromUP(w).windowResized.emit(uvec2(cast(uint)newWidth, cast(uint)newHeight)); } catch(Exception e) { throw new Error(to!string(e)); } } static void windowclosefun(GLFWwindow* w) nothrow { try { getWinFromUP(w).closePressed.emit();//------------------ } catch(Exception e) { throw new Error(to!string(e)); } } static void windowrefreshfun(GLFWwindow* w) nothrow { } static void windowfocusfun(GLFWwindow* w, int focus) nothrow { try { getWinFromUP(w).focusChanged.emit(cast(bool)focus); } catch(Exception e) { throw new Error(to!string(e)); } } static void windowiconifyfun(GLFWwindow* w, int iconified) nothrow { try { getWinFromUP(w).windowIconified.emit(cast(bool)iconified); } catch(Exception e) { throw new Error(to!string(e)); } } static void mousebuttonfun(GLFWwindow* w, int mouseButton, int action, int) nothrow { try { if(action == GLFW_RELEASE) { getWinFromUP(w).mouseReleased.emit(mouseButton); } else { getWinFromUP(w).mousePressed.emit(mouseButton); } } catch(Exception e) { throw new Error(to!string(e)); } } static void cursorposfun(GLFWwindow* w, double nx, double ny) nothrow { try { getWinFromUP(w).mouseMoved.emit(ivec2(cast(int)nx, cast(int)ny)); } catch(Exception e) { throw new Error(to!string(e)); } } static void scrollfun(GLFWwindow* w, double x, double y) nothrow { try { getWinFromUP(w).wheelScrolled.emit(dvec2(x, y)); } catch(Exception e) { throw new Error(to!string(e)); } } static void cursorenterfun(GLFWwindow* w, int) nothrow { } static void keyfun(GLFWwindow* w, int key, int, int action, int) nothrow { try { if (action == GLFW_RELEASE) { getWinFromUP(w).keyReleased.emit(key); } else { getWinFromUP(w).keyPressed.emit(key); } } catch(Exception e) { throw new Error(to!string(e)); } } static void charfun(GLFWwindow* w, uint unicode) nothrow { try { getWinFromUP(w).charEntered.emit(cast(dchar)unicode); } catch(Exception e) { throw new Error(to!string(e)); } } }
D
// Written in D programming language /** * Copyright: © 2014 Anton Gushcha * License: Subject to the terms of the MIT license, as written in the included LICENSE file. * Authors: NCrashed <ncrashed@gmail.com> * * Describes java parser. */ module parser.java; import pegged.grammar; import pegged.tester.grammartester; mixin(grammar(` Java: # Spacing and Comments #============================================================ Spacing <- :(' ' / '\t' / '\r' / '\n' / '\r\n' / Comment)* Comment <- BlockComment / LineComment BlockComment <~ :'/*' (!'*/' .)* :'*/' LineComment <~ :'//' (!endOfLine .)* :endOfLine # Identifiers #============================================================ Identifier <~ !Keyword [a-zA-Z_] [a-zA-Z0-9_]* Keyword < "abstract" / "continue" / "for" / "new" / "switch" / "assert" / "default" / "if" / "package" / "synchronized" / "boolean" / "do" / "goto" / "private" / "this" / "break" / "double" / "implements" / "protected" / "throw" / "byte" / "else" / "import" / "public" / "throws" / "case" / "enum" / "instanceof" / "return" / "transient" / "catch" / "extends" / "int" / "short" / "try" / "char" / "final" / "interface" / "static" / "void" / "class" / "finally" / "long" / "strictfp" / "volatile" / "const" / "float" / "native" / "super" / "while" QualifiedIdentifier < Identifier ('.' Identifier)* QualifiedIdentifierList < QualifiedIdentifier (',' QualifiedIdentifier)* # Literals #============================================================ Literal <- FloatingPointLiteral / IntegerLiteral / BooleanLiteral / CharacterLiteral / StringLiteral / NullLiteral Underscores <~ '_'+ # Integer literals IntegerLiteral <- HexIntegerLiteral / OctalIntegerLiteral / BinaryIntegerLiteral / DecimalIntegerLiteral DecimalIntegerLiteral <- DecimalNumeral IntegerTypeSuffix? HexIntegerLiteral <- HexNumeral IntegerTypeSuffix? OctalIntegerLiteral <- OctalNumeral IntegerTypeSuffix? BinaryIntegerLiteral <- BinaryNumeral IntegerTypeSuffix? IntegerTypeSuffix <- 'l' / 'L' DecimalNumeral <~ '0' / (NonZeroDigit Digits?) / (NonZeroDigit Underscores Digits) Digits <~ digit (digit / '_')* NonZeroDigit <- [1-9] HexNumeral <~ ("0x" / "0X") HexDigits HexDigits <~ HexDigit (HexDigit / '_')* HexDigit <~ [0-9a-fA-F] OctalNumeral <~ '0' OctalDigits / '0' Underscores OctalDigits OctalDigits <~ OctalDigit (OctalDigit / '_')* OctalDigit <~ [0-7] BinaryNumeral <~ ("0b"/ "0B") BinaryDigits BinaryDigits <~ BinaryDigit (BinaryDigit / '_')* BinaryDigit <~ [01] # Floating point literals FloatingPointLiteral < DecimalFloatingPointLiteral / HexadecimalFloatingPointLiteral DecimalFloatingPointLiteral <~ Digits '.' Digits? ExponentPart? FloatTypeSuffix? / '.' Digits ExponentPart? FloatTypeSuffix? / Digits ExponentPart FloatTypeSuffix? / Digits ExponentPart? FloatTypeSuffix ExponentPart <~ ExponentIndicator SignedInteger ExponentIndicator <~ [eE] SignedInteger <~ Sign? Digits Sign <~ '+' / '-' FloatTypeSuffix <~ [fFdD] HexadecimalFloatingPointLiteral <~ HexSignificand BinaryExponent FloatTypeSuffix? HexSignificand <~ HexNumeral '.'? / ("0x" / "0X") HexDigits? '.' HexDigits BinaryExponent <~ BinaryExponentIndicator SignedInteger BinaryExponentIndicator <~ [pP] # Boolean literal BooleanLiteral <~ "true" / "false" # Character literal CharacterLiteral <~ quote (!quote (EscapeSequence / .)) quote # String literal StringLiteral <~ doublequote (JChar)* doublequote JChar <- EscapeSequence / !doublequote . EscapeSequence <- backslash ( quote / doublequote / backslash / [bfnrtv] / 'u'+ HexDigit HexDigit HexDigit HexDigit / OctalEscape ) OctalEscape <~ [0-3] OctalDigit OctalDigit / OctalDigit OctalDigit / OctalDigit # Null literal NullLiteral <~ "null" # Compilation Unit #============================================================ CompilationUnit < (Annotations? "package" QualifiedIdentifier ';')? ImportDeclaration* TypeDeclaration* ImportDeclaration < "import" StaticImport? Identifier ('.' Identifier)* ImportAll? ';' StaticImport <~ "static" ImportAll <~ ".*" # Annotations #============================================================ Annotations < Annotation (Annotation)* Annotation < '@' QualifiedIdentifier ('(' AnnotationElement* ')')? AnnotationElement < ElementValuePairs / ElementValue ElementValuePairs < ElementValuePair (',' ElementValuePair)* ElementValuePair < Identifier '=' ElementValue ElementValue < Annotation / Expression1 / ElementValueArrayInitializer ElementValueArrayInitializer < (ElementValues? ','?)* ElementValues < ElementValue (',' ElementValue)* AnnotationTypeBody < '{' AnnotationTypeElementDeclaration* '}' AnnotationTypeElementDeclaration < Modifier* AnnotationTypeElementRest AnnotationTypeElementRest < / Type Identifier AnnotationMethodOrConstantRest ';' / ClassDeclaration / InterfaceDeclaration / EnumDeclaration / AnnotationTypeDeclaration AnnotationMethodOrConstantRest < / AnnotationMethodRest / ConstantDeclaratorsRest AnnotationMethodRest < '(' ')' SquareParens? ("default" ElementValue)? # Types #============================================================ TypeDeclaration < ClassOrInterfaceDeclaration / ';' ClassOrInterfaceDeclaration < Modifier* (ClassDeclaration / InterfaceDeclaration) Type < BasicType SquareParens* / ReferenceType SquareParens* SquareParens < '[' ']' BasicType <- "byte" / "short" / "char" / "int" / "long" / "float" / "double" / "boolean" ReferenceType < Identifier TypeArguments? ('.' Identifier TypeArguments?)* TypeArguments < '<' TypeArgument (',' TypeArgument)* '>' TypeArgument < ReferenceType / '?' (("extends" / "super") ReferenceType)? NonWildcardTypeArguments < '<' TypeList '>' TypeList < ReferenceType (',' ReferenceType)* TypeArgumentsOrDiamond < '<' '>' / TypeArguments NonWildcardTypeArgumentsOrDiamond < '<' '>' / NonWildcardTypeArguments TypeParameters < '<' TypeParameter (',' TypeParameter)* '>' TypeParameter < Identifier ("extends" Bound)? Bound < ReferenceType ('&' ReferenceType)? Modifier <- / Annotation / "public" / "protected" / "private" / "static" / "abstract" / "final" / "native" / "synchronized" / "trasient" / "volatile" / "strictfp" # Classes #============================================================ ClassDeclaration < NormalClassDeclaration / EnumDeclaration NormalClassDeclaration < "class" Identifier TypeParameters? ExtendBody? ImplementBody? ClassBody ExtendBody < "extends" Type ImplementBody < "implements" TypeList ClassBody < '{' ClassBodyDeclaration* '}' ClassBodyDeclaration < ';' / Modifier* MemberDecl / "static"? Block MemberDecl < / MethodOrFieldDecl / "void" Identifier VoidMethodDeclaratorRest / Identifier ConstructorDeclaratorRest / GenericMethodOrConstructorDecl / ClassDeclaration / InterfaceDeclaration MethodOrFieldDecl < Type Identifier MethodOrFieldRest MethodOrFieldRest < FieldDeclaratorsRest ';' / MethodDeclaratorRest FieldDeclaratorsRest < VariableDeclaratorRest (',' VariableDeclarator)* MethodDeclaratorRest < FormalParameters SquareParens* ("throws" QualifiedIdentifierList)? (Block / ';') VoidMethodDeclaratorRest < FormalParameters ("throws" QualifiedIdentifierList)? (Block / ';') ConstructorDeclaratorRest < FormalParameters ("throws" QualifiedIdentifierList)? Block GenericMethodOrConstructorDecl < TypeParameters GenericMethodOrConstructorRest GenericMethodOrConstructorRest < / (Type / "void") Identifier MethodDeclaratorRest / Identifier ConstructorDeclaratorRest # Enums #============================================================ EnumDeclaration < "enum" Identifier ("implements" TypeList)? EnumBody EnumBody < '{' EnumConstants? ','? EnumBodyDeclarations? '}' EnumConstants < EnumConstant (',' EnumConstant)* EnumConstant < Annotations? Identifier Arguments? ClassBody? EnumBodyDeclarations < ';' ClassBodyDeclaration* # Interfaces #============================================================ InterfaceDeclaration < NormalInterfaceDeclaration / AnnotationTypeDeclaration NormalInterfaceDeclaration < "interface" Identifier TypeParameters? ("extends" TypeList)? InterfaceBody AnnotationTypeDeclaration < '@' "interface" Identifier AnnotationTypeBody InterfaceBody < '{' InterfaceBodyDeclaration* '}' InterfaceBodyDeclaration < Modifier* InterfaceMemberDecl / ';' InterfaceMemberDecl < / InterfaceMethodOrFieldDecl / "void" Identifier VoidInterfaceMethodDeclaratorRest / InterfaceGenericMethodDecl / ClassDeclaration / InterfaceDeclaration InterfaceMethodOrFieldDecl < Type Identifier InterfaceMethodOrFieldRest InterfaceMethodOrFieldRest < ConstantDeclaratorsRest ';' / InterfaceMethodDeclaratorRest ConstantDeclaratorsRest < ConstantDeclaratorRest (',' ConstantDeclarator)* ConstantDeclaratorRest < SquareParens* '=' VariableInitializer ConstantDeclarator < Identifier ConstantDeclaratorRest InterfaceMethodDeclaratorRest < FormalParameters SquareParens* ("throws" QualifiedIdentifierList)? ';' VoidInterfaceMethodDeclaratorRest < FormalParameters ("throws" QualifiedIdentifierList)? ';' InterfaceGenericMethodDecl < TypeParameters (Type / "void") Identifier InterfaceMethodDeclaratorRest # Variables and parameters #============================================================ FormalParameters < '(' FormalParameterDecls? ')' FormalParameterDecls < VariableModifier* Type FormalParameterDeclsRest VariableModifier <- "final" / Annotation FormalParameterDeclsRest < VariableDeclaratorId (',' FormalParameterDecls)? / "..." VariableDeclaratorId VariableDeclaratorId < Identifier SquareParens* VariableDeclarators < VariableDeclarator (',' VariableDeclarator)* VariableDeclarator < Identifier VariableDeclaratorRest VariableDeclaratorRest < SquareParens* ('=' VariableInitializer)? VariableInitializer <- Expression / ArrayInitializer ArrayInitializer < ('[' VariableInitializer (',' VariableInitializer)* ','? ']')* # Expression #============================================================ Expression1 < eps Expression < eps Arguments < '(' ( Expression ( ',' Expression )* )? ')' # Block #============================================================ Block < eps `)); version(unittest) { import std.algorithm; import std.functional; import std.exception; import std.typecons; import std.range; import std.stdio; import std.traits; alias Test = Tuple!(string, "tcase", string, "result", bool, "positive"); void evaluate(R)(R range) if(isInputRange!R && isCallable!(ForeachType!R)) { foreach(elem; range) { elem(); } } auto test(T...)(GrammarTester!T tester, auto const ref Test test) { return { if(test.positive) tester.assertSimilar(test.tcase, test.result); else tester.assertSimilar(test.tcase, test.result).assertThrown!Error; }; } void runTests(string startSymbol)(Test[] tests) { auto tester = new GrammarTester!(Java, startSymbol); tests.map!(curry!(test, tester)).evaluate; } } unittest { [ Test(`foo123`, `QualifiedIdentifier -> Identifier`, true), Test(`1foo123`, `QualifiedIdentifier -> Identifier`, false), Test(`abstract`, `QualifiedIdentifier -> Identifier`, false), Test(`foo123.ahola`, `QualifiedIdentifier -> { Identifier Identifier }`, true), ].runTests!"QualifiedIdentifier"; [ Test(`foo123.ahola, foo.boo`, ` QualifiedIdentifierList -> { QualifiedIdentifier -> { Identifier Identifier } QualifiedIdentifier -> { Identifier Identifier } }` , true) ].runTests!"QualifiedIdentifierList"; [ Test(q{ /** * My awesome package */ package net.mypackage; // imports import com.google.common.base.Stopwatch; import com.google.common.collect.Queues; import com.google.common.collect.Sets; /* I like comments */ import static java.lang.Math.*; }, ` CompilationUnit -> { QualifiedIdentifier -> { Identifier Identifier } ImportDeclaration -> {Identifier Identifier Identifier Identifier Identifier} ImportDeclaration -> {Identifier Identifier Identifier Identifier Identifier} ImportDeclaration -> {Identifier Identifier Identifier Identifier Identifier} ImportDeclaration -> {StaticImport Identifier Identifier Identifier ImportAll} } `, true) ].runTests!"CompilationUnit"; [ Test(q{@StartObject}, `Annotation -> QualifiedIdentifier -> Identifier`, true), Test(q{@StartObject()}, `Annotation -> QualifiedIdentifier -> Identifier`, true), ].runTests!"Annotation"; // lets test literals [ // integer Test(`0`, `Literal -> IntegerLiteral -> DecimalIntegerLiteral -> DecimalNumeral`, true), Test(`0x7fff_ffff`, `Literal -> IntegerLiteral -> HexIntegerLiteral -> HexNumeral`, true), Test(`0177_7777_7777`, `Literal -> IntegerLiteral -> OctalIntegerLiteral -> OctalNumeral`, true), Test(`0b0111_1111_1111_1111_1111_1111_1111_1111`, `Literal -> IntegerLiteral -> BinaryIntegerLiteral -> BinaryNumeral`, true), Test(`0x8000_0000`, `Literal -> IntegerLiteral -> HexIntegerLiteral -> HexNumeral`, true), Test(`0200_0000_0000`, `Literal -> IntegerLiteral -> OctalIntegerLiteral -> OctalNumeral`, true), Test(`0b1000_0000_0000_0000_0000_0000_0000_0000`, `Literal -> IntegerLiteral -> BinaryIntegerLiteral -> BinaryNumeral`, true), Test(`0xffff_ffff`, `Literal -> IntegerLiteral -> HexIntegerLiteral -> HexNumeral`, true), Test(`0377_7777_7777`, `Literal -> IntegerLiteral -> OctalIntegerLiteral -> OctalNumeral`, true), Test(`0b1111_1111_1111_1111_1111_1111_1111_1111`, `Literal -> IntegerLiteral -> BinaryIntegerLiteral -> BinaryNumeral`, true), Test(`9223372036854775808L`, `Literal -> IntegerLiteral -> DecimalIntegerLiteral -> { DecimalNumeral IntegerTypeSuffix }`, true), Test(`0l`, `Literal -> IntegerLiteral -> DecimalIntegerLiteral -> { DecimalNumeral IntegerTypeSuffix }`, true), Test(`0b111`, `Literal -> IntegerLiteral -> BinaryIntegerLiteral -> BinaryNumeral`, true), Test(`0b111l`, `Literal -> IntegerLiteral -> BinaryIntegerLiteral -> { BinaryNumeral IntegerTypeSuffix }`, true), Test(`123`, `Literal -> IntegerLiteral -> DecimalIntegerLiteral -> DecimalNumeral`, true), Test(`0123`, `Literal -> IntegerLiteral -> OctalIntegerLiteral -> OctalNumeral`, true), Test(`0123L`, `Literal -> IntegerLiteral -> OctalIntegerLiteral -> { OctalNumeral IntegerTypeSuffix }`, true), Test(`0X123`, `Literal -> IntegerLiteral -> HexIntegerLiteral -> HexNumeral`, true), Test(`0X123l`, `Literal -> IntegerLiteral -> HexIntegerLiteral -> { HexNumeral IntegerTypeSuffix }`, true), // floating point Test(`1e1f`, `Literal -> FloatingPointLiteral -> DecimalFloatingPointLiteral`, true), Test(`2.f`, `Literal -> FloatingPointLiteral -> DecimalFloatingPointLiteral`, true), Test(`.3f`, `Literal -> FloatingPointLiteral -> DecimalFloatingPointLiteral`, true), Test(`0f`, `Literal -> FloatingPointLiteral -> DecimalFloatingPointLiteral`, true), Test(`3.14f`, `Literal -> FloatingPointLiteral -> DecimalFloatingPointLiteral`, true), Test(`6.022137e+23f`, `Literal -> FloatingPointLiteral -> DecimalFloatingPointLiteral`, true), Test(`1e1`, `Literal -> FloatingPointLiteral -> DecimalFloatingPointLiteral`, true), Test(`2.`, `Literal -> FloatingPointLiteral -> DecimalFloatingPointLiteral`, true), Test(`.3`, `Literal -> FloatingPointLiteral -> DecimalFloatingPointLiteral`, true), Test(`0.0`, `Literal -> FloatingPointLiteral -> DecimalFloatingPointLiteral`, true), Test(`3.14`, `Literal -> FloatingPointLiteral -> DecimalFloatingPointLiteral`, true), Test(`1e-9d`, `Literal -> FloatingPointLiteral -> DecimalFloatingPointLiteral`, true), Test(`1e137`, `Literal -> FloatingPointLiteral -> DecimalFloatingPointLiteral`, true), Test(`3.4028235e38f`, `Literal -> FloatingPointLiteral -> DecimalFloatingPointLiteral`, true), Test(`1.40e-45f`, `Literal -> FloatingPointLiteral -> DecimalFloatingPointLiteral`, true), Test(`1.7976931348623157e308`, `Literal -> FloatingPointLiteral -> DecimalFloatingPointLiteral`, true), Test(`4.9e-324`, `Literal -> FloatingPointLiteral -> DecimalFloatingPointLiteral`, true), // boolean Test(`true`, `Literal -> BooleanLiteral`, true), Test(`false`, `Literal -> BooleanLiteral`, true), // character Test(q{'a'}, `Literal -> CharacterLiteral`, true), Test(q{'%'}, `Literal -> CharacterLiteral`, true), Test(q{'\t'}, `Literal -> CharacterLiteral`, true), Test(q{'\\'}, `Literal -> CharacterLiteral`, true), Test(q{'\''}, `Literal -> CharacterLiteral`, true), Test(q{'\u03a9'}, `Literal -> CharacterLiteral`, true), Test(`'\uFFFF'`, `Literal -> CharacterLiteral`, true), Test(q{'\177'}, `Literal -> CharacterLiteral`, true), // Test(q{'Я'}, `Literal -> CharacterLiteral`, true), // Test(q{'Ω'}, `Literal -> CharacterLiteral`, true), uncomment when pegged starts supporting dstrings // string Test(q{""}, `Literal -> StringLiteral`, true), Test(q{"Hello"}, `Literal -> StringLiteral`, true), Test(q{"\t\n"}, `Literal -> StringLiteral`, true), Test(q{"Привет"}, `Literal -> StringLiteral`, true), // null Test("null", `Literal -> NullLiteral`, true), ].runTests!"Literal"; // classes [ Test(q{class A {}}, ` ClassDeclaration -> NormalClassDeclaration -> { Identifier ClassBody } `, true), Test(q{class B <T> extends A implements C {}}, ` ClassDeclaration -> NormalClassDeclaration -> { Identifier TypeParameters -> TypeParameter -> Identifier ExtendBody -> Type -> ReferenceType -> Identifier ImplementBody -> TypeList -> ReferenceType -> Identifier ClassBody } `, true), Test(q{ class A { String field1; } }, ` ClassDeclaration -> NormalClassDeclaration -> { Identifier ClassBody -> ClassBodyDeclaration -> MemberDecl -> MethodOrFieldDecl -> { Type -> ReferenceType -> Identifier Identifier MethodOrFieldRest } } `, true), Test(q{ class A { int foo(boolean param) } }, ` ClassDeclaration -> NormalClassDeclaration -> { Identifier ClassBody -> ClassBodyDeclaration -> MemberDecl -> MethodOrFieldDecl -> { Type -> BasicType Identifier MethodOrFieldRest -> MethodDeclaratorRest -> { FormalParameters -> FormalParameterDecls -> { Type -> BasicType FormalParameterDeclsRest -> VariableDeclaratorId -> Identifier } Block } } } `, true), Test(q{ class A { A(boolean param) } }, ` ClassDeclaration -> NormalClassDeclaration -> { Identifier ClassBody -> ClassBodyDeclaration -> MemberDecl -> { Identifier ConstructorDeclaratorRest -> { FormalParameters -> FormalParameterDecls -> { Type -> BasicType FormalParameterDeclsRest -> VariableDeclaratorId -> Identifier } Block } } } `, true), Test(q{ class A { <T> A(boolean param) } }, ` ClassDeclaration -> NormalClassDeclaration -> { Identifier ClassBody -> ClassBodyDeclaration -> MemberDecl -> { GenericMethodOrConstructorDecl -> { TypeParameters -> TypeParameter -> Identifier GenericMethodOrConstructorRest -> { Identifier ConstructorDeclaratorRest -> { FormalParameters -> FormalParameterDecls -> { Type -> BasicType FormalParameterDeclsRest -> VariableDeclaratorId -> Identifier } Block } } } } } `, true), Test(q{ class A { <T extends C & I> int foo(boolean param) } }, ` ClassDeclaration -> NormalClassDeclaration -> { Identifier ClassBody -> ClassBodyDeclaration -> MemberDecl -> GenericMethodOrConstructorDecl -> { TypeParameters -> TypeParameter -> { Identifier Bound -> { ReferenceType -> Identifier ReferenceType -> Identifier } } GenericMethodOrConstructorRest -> { Type -> BasicType Identifier MethodDeclaratorRest-> { FormalParameters -> FormalParameterDecls -> { Type -> BasicType FormalParameterDeclsRest -> VariableDeclaratorId -> Identifier } Block } } } } `, true), ].runTests!"ClassDeclaration"; // interfaces [ Test(q{interface A {}}, ` InterfaceDeclaration -> NormalInterfaceDeclaration -> { Identifier InterfaceBody } `, true), Test(q{interface B <T> extends A {}}, ` InterfaceDeclaration -> NormalInterfaceDeclaration -> { Identifier TypeParameters -> TypeParameter -> Identifier TypeList -> ReferenceType -> Identifier InterfaceBody } `, true), Test(q{ interface A { String field1 = ; } }, ` InterfaceDeclaration -> NormalInterfaceDeclaration -> { Identifier InterfaceBody -> InterfaceBodyDeclaration -> InterfaceMemberDecl -> InterfaceMethodOrFieldDecl -> { Type -> ReferenceType -> Identifier Identifier InterfaceMethodOrFieldRest -> ConstantDeclaratorsRest -> ConstantDeclaratorRest -> VariableInitializer -> Expression } } `, true), Test(q{ interface A { int foo(boolean param); } }, ` InterfaceDeclaration -> NormalInterfaceDeclaration -> { Identifier InterfaceBody -> InterfaceBodyDeclaration -> InterfaceMemberDecl -> InterfaceMethodOrFieldDecl -> { Type -> BasicType Identifier InterfaceMethodOrFieldRest -> InterfaceMethodDeclaratorRest -> { FormalParameters -> FormalParameterDecls -> { Type -> BasicType FormalParameterDeclsRest -> VariableDeclaratorId -> Identifier } } } } `, true), Test(q{ interface A { <T extends C & I> int foo(boolean param); } }, ` InterfaceDeclaration -> NormalInterfaceDeclaration -> { Identifier InterfaceBody -> InterfaceBodyDeclaration -> InterfaceMemberDecl -> InterfaceGenericMethodDecl -> { TypeParameters -> TypeParameter -> { Identifier Bound -> { ReferenceType -> Identifier ReferenceType -> Identifier } } Type -> BasicType Identifier InterfaceMethodDeclaratorRest-> { FormalParameters -> FormalParameterDecls -> { Type -> BasicType FormalParameterDeclsRest -> VariableDeclaratorId -> Identifier } } } } `, true), ].runTests!"InterfaceDeclaration"; // annotation declaration [ Test(q{ package test; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; //@Retention(RetentionPolicy.RUNTIME) //@Target(ElementType.METHOD) //can use in method only. public @interface Test { public boolean enabled() default /*true*/; } }, ` CompilationUnit -> { QualifiedIdentifier -> Identifier ImportDeclaration -> { Identifier Identifier Identifier Identifier } ImportDeclaration -> { Identifier Identifier Identifier Identifier } ImportDeclaration -> { Identifier Identifier Identifier Identifier } ImportDeclaration -> { Identifier Identifier Identifier Identifier } TypeDeclaration -> ClassOrInterfaceDeclaration -> { Modifier InterfaceDeclaration -> AnnotationTypeDeclaration -> { Identifier AnnotationTypeBody -> AnnotationTypeElementDeclaration -> { Modifier AnnotationTypeElementRest -> { Type -> BasicType Identifier AnnotationMethodOrConstantRest -> AnnotationMethodRest -> ElementValue -> Expression1 } } } } } `, true), ].runTests!"CompilationUnit"; // enum declaration [ Test(q{ enum Season { WINTER, SPRING, SUMMER, AUTUMN } }, ` EnumDeclaration -> { Identifier EnumBody -> EnumConstants -> { EnumConstant -> Identifier EnumConstant -> Identifier EnumConstant -> Identifier EnumConstant -> Identifier } } `, true), Test(q{ enum Direction implements IDirection { UP, DOWN; public Direction opposite() /*{ return this == UP ? DOWN : UP; }*/ } }, ` EnumDeclaration -> { Identifier TypeList -> ReferenceType -> Identifier EnumBody -> { EnumConstants -> { EnumConstant -> Identifier EnumConstant -> Identifier } EnumBodyDeclarations -> ClassBodyDeclaration -> { Modifier MemberDecl -> MethodOrFieldDecl -> { Type -> ReferenceType -> Identifier Identifier MethodOrFieldRest -> MethodDeclaratorRest -> { FormalParameters Block } } } } } `, true), Test(q{ enum Direction implements IDirection { UP { public Direction opposite() /*{ return DOWN; }*/ }, DOWN { public Direction opposite() /*{ return UP; }*/ }; public abstract Direction opposite()/*;*/ } }, ` EnumDeclaration -> { Identifier TypeList -> ReferenceType -> Identifier EnumBody -> { EnumConstants -> { EnumConstant -> { Identifier ClassBody -> ClassBodyDeclaration -> { Modifier MemberDecl -> MethodOrFieldDecl -> { Type -> ReferenceType -> Identifier Identifier MethodOrFieldRest -> MethodDeclaratorRest -> { FormalParameters Block } } } } EnumConstant -> { Identifier ClassBody -> ClassBodyDeclaration -> { Modifier MemberDecl -> MethodOrFieldDecl -> { Type -> ReferenceType -> Identifier Identifier MethodOrFieldRest -> MethodDeclaratorRest -> { FormalParameters Block } } } } } EnumBodyDeclarations -> ClassBodyDeclaration -> { Modifier Modifier MemberDecl -> MethodOrFieldDecl -> { Type -> ReferenceType -> Identifier Identifier MethodOrFieldRest -> MethodDeclaratorRest -> { FormalParameters Block } } } } } `, true), ].runTests!"EnumDeclaration"; }
D
// Written in the D programming language /* Copyright (C) 2004-2011 Christopher E. Miller 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. socket.d 1.4 Jan 2011 Thanks to Benjamin Herr for his assistance. */ /** * Socket primitives. * Example: See $(SAMPLESRC listener.d) and $(SAMPLESRC htmlget.d) * License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0). * Authors: Christopher E. Miller, $(HTTP klickverbot.at, David Nadlinger), * $(HTTP thecybershadow.net, Vladimir Panteleev) * Source: $(PHOBOSSRC std/_socket.d) */ module std.socket; import core.stdc.stdint, core.stdc.stdlib, core.stdc.string, std.conv, std.string; import core.stdc.config; import core.time : dur, Duration; import std.exception; import std.internal.cstring; @safe: version(Windows) { pragma (lib, "ws2_32.lib"); pragma (lib, "wsock32.lib"); import core.sys.windows.windows, std.windows.syserror; public import core.sys.windows.winsock2; private alias _ctimeval = core.sys.windows.winsock2.timeval; private alias _clinger = core.sys.windows.winsock2.linger; enum socket_t : SOCKET { INVALID_SOCKET } private const int _SOCKET_ERROR = SOCKET_ERROR; private int _lasterr() nothrow @nogc { return WSAGetLastError(); } } else version(Posix) { version(linux) { enum : int { TCP_KEEPIDLE = 4, TCP_KEEPINTVL = 5 } } public import core.sys.posix.netinet.in_; import core.sys.posix.arpa.inet; import core.sys.posix.fcntl; import core.sys.posix.netdb; import core.sys.posix.netinet.tcp; import core.sys.posix.sys.select; import core.sys.posix.sys.socket; import core.sys.posix.sys.time; import core.sys.posix.sys.un : sockaddr_un; import core.sys.posix.unistd; private alias _ctimeval = core.sys.posix.sys.time.timeval; private alias _clinger = core.sys.posix.sys.socket.linger; import core.stdc.errno; enum socket_t : int32_t { init = -1 } private const int _SOCKET_ERROR = -1; private enum : int { SD_RECEIVE = SHUT_RD, SD_SEND = SHUT_WR, SD_BOTH = SHUT_RDWR } private int _lasterr() nothrow @nogc { return errno; } } else { static assert(0); // No socket support yet. } version(unittest) { // Print a message on exception instead of failing the unittest. private void softUnittest(void delegate() @safe test, int line = __LINE__) @trusted { import std.stdio : writefln; try test(); catch (Throwable e) { writefln(" --- std.socket(%d) test fails depending on environment ---", line); writefln(" (%s)", e); } } } /// Base exception thrown by `std.socket`. class SocketException: Exception { mixin basicExceptionCtors; } version (CRuntime_Glibc) version = GNU_STRERROR; version (CRuntime_UClibc) version = GNU_STRERROR; /* * Needs to be public so that SocketOSException can be thrown outside of * std.socket (since it uses it as a default argument), but it probably doesn't * need to actually show up in the docs, since there's not really any public * need for it outside of being a default argument. */ string formatSocketError(int err) @trusted { version(Posix) { char[80] buf; const(char)* cs; version (GNU_STRERROR) { cs = strerror_r(err, buf.ptr, buf.length); } else { auto errs = strerror_r(err, buf.ptr, buf.length); if (errs == 0) cs = buf.ptr; else return "Socket error " ~ to!string(err); } auto len = strlen(cs); if (cs[len - 1] == '\n') len--; if (cs[len - 1] == '\r') len--; return cs[0 .. len].idup; } else version(Windows) { return sysErrorString(err); } else return "Socket error " ~ to!string(err); } /// Retrieve the error message for the most recently encountered network error. @property string lastSocketError() { return formatSocketError(_lasterr()); } /** * Socket exceptions representing network errors reported by the operating * system. */ class SocketOSException: SocketException { int errorCode; /// Platform-specific error code. /// this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null, int err = _lasterr(), string function(int) @trusted errorFormatter = &formatSocketError) { errorCode = err; if (msg.length) super(msg ~ ": " ~ errorFormatter(err), file, line, next); else super(errorFormatter(err), file, line, next); } /// this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__, int err = _lasterr(), string function(int) @trusted errorFormatter = &formatSocketError) { this(msg, file, line, next, err, errorFormatter); } /// this(string msg, int err, string function(int) @trusted errorFormatter = &formatSocketError, string file = __FILE__, size_t line = __LINE__, Throwable next = null) { this(msg, file, line, next, err, errorFormatter); } } /// Socket exceptions representing invalid parameters specified by user code. class SocketParameterException: SocketException { mixin basicExceptionCtors; } /** * Socket exceptions representing attempts to use network capabilities not * available on the current system. */ class SocketFeatureException: SocketException { mixin basicExceptionCtors; } /** * Returns: * `true` if the last socket operation failed because the socket * was in non-blocking mode and the operation would have blocked. */ bool wouldHaveBlocked() nothrow @nogc { version(Windows) return _lasterr() == WSAEWOULDBLOCK; else version(Posix) return _lasterr() == EAGAIN; else static assert(0); } private immutable { typeof(&getnameinfo) getnameinfoPointer; typeof(&getaddrinfo) getaddrinfoPointer; typeof(&freeaddrinfo) freeaddrinfoPointer; } shared static this() @system { version(Windows) { WSADATA wd; // Winsock will still load if an older version is present. // The version is just a request. int val; val = WSAStartup(0x2020, &wd); if (val) // Request Winsock 2.2 for IPv6. throw new SocketOSException("Unable to initialize socket library", val); // These functions may not be present on older Windows versions. // See the comment in InternetAddress.toHostNameString() for details. auto ws2Lib = GetModuleHandleA("ws2_32.dll"); if (ws2Lib) { getnameinfoPointer = cast(typeof(getnameinfoPointer)) GetProcAddress(ws2Lib, "getnameinfo"); getaddrinfoPointer = cast(typeof(getaddrinfoPointer)) GetProcAddress(ws2Lib, "getaddrinfo"); freeaddrinfoPointer = cast(typeof(freeaddrinfoPointer)) GetProcAddress(ws2Lib, "freeaddrinfo"); } } else version(Posix) { getnameinfoPointer = &getnameinfo; getaddrinfoPointer = &getaddrinfo; freeaddrinfoPointer = &freeaddrinfo; } } shared static ~this() @system nothrow @nogc { version(Windows) { WSACleanup(); } } /** * The communication domain used to resolve an address. */ enum AddressFamily: int { UNSPEC = AF_UNSPEC, /// Unspecified address family UNIX = AF_UNIX, /// Local communication INET = AF_INET, /// Internet Protocol version 4 IPX = AF_IPX, /// Novell IPX APPLETALK = AF_APPLETALK, /// AppleTalk INET6 = AF_INET6, /// Internet Protocol version 6 } /** * Communication semantics */ enum SocketType: int { STREAM = SOCK_STREAM, /// Sequenced, reliable, two-way communication-based byte streams DGRAM = SOCK_DGRAM, /// Connectionless, unreliable datagrams with a fixed maximum length; data may be lost or arrive out of order RAW = SOCK_RAW, /// Raw protocol access RDM = SOCK_RDM, /// Reliably-delivered message datagrams SEQPACKET = SOCK_SEQPACKET, /// Sequenced, reliable, two-way connection-based datagrams with a fixed maximum length } /** * Protocol */ enum ProtocolType: int { IP = IPPROTO_IP, /// Internet Protocol version 4 ICMP = IPPROTO_ICMP, /// Internet Control Message Protocol IGMP = IPPROTO_IGMP, /// Internet Group Management Protocol GGP = IPPROTO_GGP, /// Gateway to Gateway Protocol TCP = IPPROTO_TCP, /// Transmission Control Protocol PUP = IPPROTO_PUP, /// PARC Universal Packet Protocol UDP = IPPROTO_UDP, /// User Datagram Protocol IDP = IPPROTO_IDP, /// Xerox NS protocol RAW = IPPROTO_RAW, /// Raw IP packets IPV6 = IPPROTO_IPV6, /// Internet Protocol version 6 } /** * `Protocol` is a class for retrieving protocol information. * * Example: * --- * auto proto = new Protocol; * writeln("About protocol TCP:"); * if (proto.getProtocolByType(ProtocolType.TCP)) * { * writefln(" Name: %s", proto.name); * foreach (string s; proto.aliases) * writefln(" Alias: %s", s); * } * else * writeln(" No information found"); * --- */ class Protocol { /// These members are populated when one of the following functions are called successfully: ProtocolType type; string name; /// ditto string[] aliases; /// ditto void populate(protoent* proto) @system pure nothrow { type = cast(ProtocolType) proto.p_proto; name = to!string(proto.p_name); int i; for (i = 0;; i++) { if (!proto.p_aliases[i]) break; } if (i) { aliases = new string[i]; for (i = 0; i != aliases.length; i++) { aliases[i] = to!string(proto.p_aliases[i]); } } else { aliases = null; } } /** Returns: false on failure */ bool getProtocolByName(in char[] name) @trusted nothrow { protoent* proto; proto = getprotobyname(name.tempCString()); if (!proto) return false; populate(proto); return true; } /** Returns: false on failure */ // Same as getprotobynumber(). bool getProtocolByType(ProtocolType type) @trusted nothrow { protoent* proto; proto = getprotobynumber(type); if (!proto) return false; populate(proto); return true; } } // Skip this test on Android because getprotobyname/number are // unimplemented in bionic. version(CRuntime_Bionic) {} else @safe unittest { // import std.stdio : writefln; softUnittest({ Protocol proto = new Protocol; assert(proto.getProtocolByType(ProtocolType.TCP)); //writeln("About protocol TCP:"); //writefln("\tName: %s", proto.name); // foreach (string s; proto.aliases) // { // writefln("\tAlias: %s", s); // } assert(proto.name == "tcp"); assert(proto.aliases.length == 1 && proto.aliases[0] == "TCP"); }); } /** * `Service` is a class for retrieving service information. * * Example: * --- * auto serv = new Service; * writeln("About service epmap:"); * if (serv.getServiceByName("epmap", "tcp")) * { * writefln(" Service: %s", serv.name); * writefln(" Port: %d", serv.port); * writefln(" Protocol: %s", serv.protocolName); * foreach (string s; serv.aliases) * writefln(" Alias: %s", s); * } * else * writefln(" No service for epmap."); * --- */ class Service { /// These members are populated when one of the following functions are called successfully: string name; string[] aliases; /// ditto ushort port; /// ditto string protocolName; /// ditto void populate(servent* serv) @system pure nothrow { name = to!string(serv.s_name); port = ntohs(cast(ushort) serv.s_port); protocolName = to!string(serv.s_proto); int i; for (i = 0;; i++) { if (!serv.s_aliases[i]) break; } if (i) { aliases = new string[i]; for (i = 0; i != aliases.length; i++) { aliases[i] = to!string(serv.s_aliases[i]); } } else { aliases = null; } } /** * If a protocol name is omitted, any protocol will be matched. * Returns: false on failure. */ bool getServiceByName(in char[] name, in char[] protocolName = null) @trusted nothrow { servent* serv; serv = getservbyname(name.tempCString(), protocolName.tempCString()); if (!serv) return false; populate(serv); return true; } /// ditto bool getServiceByPort(ushort port, in char[] protocolName = null) @trusted nothrow { servent* serv; serv = getservbyport(port, protocolName.tempCString()); if (!serv) return false; populate(serv); return true; } } @safe unittest { import std.stdio : writefln; softUnittest({ Service serv = new Service; if (serv.getServiceByName("epmap", "tcp")) { // writefln("About service epmap:"); // writefln("\tService: %s", serv.name); // writefln("\tPort: %d", serv.port); // writefln("\tProtocol: %s", serv.protocolName); // foreach (string s; serv.aliases) // { // writefln("\tAlias: %s", s); // } // For reasons unknown this is loc-srv on Wine and epmap on Windows assert(serv.name == "loc-srv" || serv.name == "epmap", serv.name); assert(serv.port == 135); assert(serv.protocolName == "tcp"); } else { writefln("No service for epmap."); } }); } private mixin template socketOSExceptionCtors() { /// this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null, int err = _lasterr()) { super(msg, file, line, next, err); } /// this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__, int err = _lasterr()) { super(msg, next, file, line, err); } /// this(string msg, int err, string file = __FILE__, size_t line = __LINE__, Throwable next = null) { super(msg, next, file, line, err); } } /** * Class for exceptions thrown from an `InternetHost`. */ class HostException: SocketOSException { mixin socketOSExceptionCtors; } /** * `InternetHost` is a class for resolving IPv4 addresses. * * Consider using `getAddress`, `parseAddress` and `Address` methods * instead of using this class directly. */ class InternetHost { /// These members are populated when one of the following functions are called successfully: string name; string[] aliases; /// ditto uint[] addrList; /// ditto void validHostent(in hostent* he) { if (he.h_addrtype != cast(int) AddressFamily.INET || he.h_length != 4) throw new HostException("Address family mismatch"); } void populate(hostent* he) @system pure nothrow { int i; char* p; name = to!string(he.h_name); for (i = 0;; i++) { p = he.h_aliases[i]; if (!p) break; } if (i) { aliases = new string[i]; for (i = 0; i != aliases.length; i++) { aliases[i] = to!string(he.h_aliases[i]); } } else { aliases = null; } for (i = 0;; i++) { p = he.h_addr_list[i]; if (!p) break; } if (i) { addrList = new uint[i]; for (i = 0; i != addrList.length; i++) { addrList[i] = ntohl(*(cast(uint*) he.h_addr_list[i])); } } else { addrList = null; } } private bool getHostNoSync(string opMixin, T)(T param) @system { mixin(opMixin); if (!he) return false; validHostent(he); populate(he); return true; } version(Windows) alias getHost = getHostNoSync; else { // posix systems use global state for return value, so we // must synchronize across all threads private bool getHost(string opMixin, T)(T param) @system { synchronized(this.classinfo) return getHostNoSync!(opMixin, T)(param); } } /** * Resolve host name. * Returns: false if unable to resolve. */ bool getHostByName(in char[] name) @trusted { static if (is(typeof(gethostbyname_r))) { return getHostNoSync!q{ hostent he_v; hostent* he; ubyte[256] buffer_v = void; auto buffer = buffer_v[]; auto param_zTmp = param.tempCString(); while (true) { he = &he_v; int errno; if (gethostbyname_r(param_zTmp, he, buffer.ptr, buffer.length, &he, &errno) == ERANGE) buffer.length = buffer.length * 2; else break; } }(name); } else { return getHost!q{ auto he = gethostbyname(param.tempCString()); }(name); } } /** * Resolve IPv4 address number. * * Params: * addr = The IPv4 address to resolve, in host byte order. * Returns: * false if unable to resolve. */ bool getHostByAddr(uint addr) @trusted { return getHost!q{ auto x = htonl(param); auto he = gethostbyaddr(&x, 4, cast(int) AddressFamily.INET); }(addr); } /** * Same as previous, but addr is an IPv4 address string in the * dotted-decimal form $(I a.b.c.d). * Returns: false if unable to resolve. */ bool getHostByAddr(in char[] addr) @trusted { return getHost!q{ auto x = inet_addr(param.tempCString()); enforce(x != INADDR_NONE, new SocketParameterException("Invalid IPv4 address")); auto he = gethostbyaddr(&x, 4, cast(int) AddressFamily.INET); }(addr); } } /// @safe unittest { InternetHost ih = new InternetHost; ih.getHostByAddr(0x7F_00_00_01); assert(ih.addrList[0] == 0x7F_00_00_01); ih.getHostByAddr("127.0.0.1"); assert(ih.addrList[0] == 0x7F_00_00_01); if (!ih.getHostByName("www.digitalmars.com")) return; // don't fail if not connected to internet assert(ih.addrList.length); InternetAddress ia = new InternetAddress(ih.addrList[0], InternetAddress.PORT_ANY); assert(ih.name == "www.digitalmars.com" || ih.name == "digitalmars.com", ih.name); assert(ih.getHostByAddr(ih.addrList[0])); string getHostNameFromInt = ih.name.dup; assert(ih.getHostByAddr(ia.toAddrString())); string getHostNameFromStr = ih.name.dup; assert(getHostNameFromInt == getHostNameFromStr); } /// Holds information about a socket _address retrieved by `getAddressInfo`. struct AddressInfo { AddressFamily family; /// Address _family SocketType type; /// Socket _type ProtocolType protocol; /// Protocol Address address; /// Socket _address string canonicalName; /// Canonical name, when `AddressInfoFlags.CANONNAME` is used. } /** * A subset of flags supported on all platforms with getaddrinfo. * Specifies option flags for `getAddressInfo`. */ enum AddressInfoFlags: int { /// The resulting addresses will be used in a call to `Socket.bind`. PASSIVE = AI_PASSIVE, /// The canonical name is returned in `canonicalName` member in the first `AddressInfo`. CANONNAME = AI_CANONNAME, /** * The `node` parameter passed to `getAddressInfo` must be a numeric string. * This will suppress any potentially lengthy network host address lookups. */ NUMERICHOST = AI_NUMERICHOST, } /** * On POSIX, getaddrinfo uses its own error codes, and thus has its own * formatting function. */ private string formatGaiError(int err) @trusted { version(Windows) { return sysErrorString(err); } else { synchronized return to!string(gai_strerror(err)); } } /** * Provides _protocol-independent translation from host names to socket * addresses. If advanced functionality is not required, consider using * `getAddress` for compatibility with older systems. * * Returns: Array with one `AddressInfo` per socket address. * * Throws: `SocketOSException` on failure, or `SocketFeatureException` * if this functionality is not available on the current system. * * Params: * node = string containing host name or numeric address * options = optional additional parameters, identified by type: * $(UL $(LI `string` - service name or port number) * $(LI `AddressInfoFlags` - option flags) * $(LI `AddressFamily` - address family to filter by) * $(LI `SocketType` - socket type to filter by) * $(LI `ProtocolType` - protocol to filter by)) * * Example: * --- * // Roundtrip DNS resolution * auto results = getAddressInfo("www.digitalmars.com"); * assert(results[0].address.toHostNameString() == * "digitalmars.com"); * * // Canonical name * results = getAddressInfo("www.digitalmars.com", * AddressInfoFlags.CANONNAME); * assert(results[0].canonicalName == "digitalmars.com"); * * // IPv6 resolution * results = getAddressInfo("ipv6.google.com"); * assert(results[0].family == AddressFamily.INET6); * * // Multihomed resolution * results = getAddressInfo("google.com"); * assert(results.length > 1); * * // Parsing IPv4 * results = getAddressInfo("127.0.0.1", * AddressInfoFlags.NUMERICHOST); * assert(results.length && results[0].family == * AddressFamily.INET); * * // Parsing IPv6 * results = getAddressInfo("::1", * AddressInfoFlags.NUMERICHOST); * assert(results.length && results[0].family == * AddressFamily.INET6); * --- */ AddressInfo[] getAddressInfo(T...)(in char[] node, T options) { const(char)[] service = null; addrinfo hints; hints.ai_family = AF_UNSPEC; foreach (option; options) { static if (is(typeof(option) : const(char)[])) service = option; else static if (is(typeof(option) == AddressInfoFlags)) hints.ai_flags |= option; else static if (is(typeof(option) == AddressFamily)) hints.ai_family = option; else static if (is(typeof(option) == SocketType)) hints.ai_socktype = option; else static if (is(typeof(option) == ProtocolType)) hints.ai_protocol = option; else static assert(0, "Unknown getAddressInfo option type: " ~ typeof(option).stringof); } return () @trusted { return getAddressInfoImpl(node, service, &hints); }(); } @system unittest { struct Oops { const(char[]) breakSafety() { *cast(int*) 0xcafebabe = 0xdeadbeef; return null; } alias breakSafety this; } assert(!__traits(compiles, () { getAddressInfo("", Oops.init); }), "getAddressInfo breaks @safe"); } private AddressInfo[] getAddressInfoImpl(in char[] node, in char[] service, addrinfo* hints) @system { import std.array : appender; if (getaddrinfoPointer && freeaddrinfoPointer) { addrinfo* ai_res; int ret = getaddrinfoPointer( node.tempCString(), service.tempCString(), hints, &ai_res); enforce(ret == 0, new SocketOSException("getaddrinfo error", ret, &formatGaiError)); scope(exit) freeaddrinfoPointer(ai_res); auto result = appender!(AddressInfo[])(); // Use const to force UnknownAddressReference to copy the sockaddr. for (const(addrinfo)* ai = ai_res; ai; ai = ai.ai_next) result ~= AddressInfo( cast(AddressFamily) ai.ai_family, cast(SocketType ) ai.ai_socktype, cast(ProtocolType ) ai.ai_protocol, new UnknownAddressReference(ai.ai_addr, cast(socklen_t) ai.ai_addrlen), ai.ai_canonname ? to!string(ai.ai_canonname) : null); assert(result.data.length > 0); return result.data; } throw new SocketFeatureException("Address info lookup is not available " ~ "on this system."); } @safe unittest { softUnittest({ if (getaddrinfoPointer) { // Roundtrip DNS resolution auto results = getAddressInfo("www.digitalmars.com"); assert(results[0].address.toHostNameString() == "digitalmars.com"); // Canonical name results = getAddressInfo("www.digitalmars.com", AddressInfoFlags.CANONNAME); assert(results[0].canonicalName == "digitalmars.com"); // IPv6 resolution //results = getAddressInfo("ipv6.google.com"); //assert(results[0].family == AddressFamily.INET6); // Multihomed resolution //results = getAddressInfo("google.com"); //assert(results.length > 1); // Parsing IPv4 results = getAddressInfo("127.0.0.1", AddressInfoFlags.NUMERICHOST); assert(results.length && results[0].family == AddressFamily.INET); // Parsing IPv6 results = getAddressInfo("::1", AddressInfoFlags.NUMERICHOST); assert(results.length && results[0].family == AddressFamily.INET6); } }); if (getaddrinfoPointer) { auto results = getAddressInfo(null, "1234", AddressInfoFlags.PASSIVE, SocketType.STREAM, ProtocolType.TCP, AddressFamily.INET); assert(results.length == 1 && results[0].address.toString() == "0.0.0.0:1234"); } } private ushort serviceToPort(in char[] service) { if (service == "") return InternetAddress.PORT_ANY; else if (isNumeric(service)) return to!ushort(service); else { auto s = new Service(); s.getServiceByName(service); return s.port; } } /** * Provides _protocol-independent translation from host names to socket * addresses. Uses `getAddressInfo` if the current system supports it, * and `InternetHost` otherwise. * * Returns: Array with one `Address` instance per socket address. * * Throws: `SocketOSException` on failure. * * Example: * --- * writeln("Resolving www.digitalmars.com:"); * try * { * auto addresses = getAddress("www.digitalmars.com"); * foreach (address; addresses) * writefln(" IP: %s", address.toAddrString()); * } * catch (SocketException e) * writefln(" Lookup failed: %s", e.msg); * --- */ Address[] getAddress(in char[] hostname, in char[] service = null) { if (getaddrinfoPointer && freeaddrinfoPointer) { // use getAddressInfo auto infos = getAddressInfo(hostname, service); Address[] results; results.length = infos.length; foreach (i, ref result; results) result = infos[i].address; return results; } else return getAddress(hostname, serviceToPort(service)); } /// ditto Address[] getAddress(in char[] hostname, ushort port) { if (getaddrinfoPointer && freeaddrinfoPointer) return getAddress(hostname, to!string(port)); else { // use getHostByName auto ih = new InternetHost; if (!ih.getHostByName(hostname)) throw new AddressException( text("Unable to resolve host '", hostname, "'")); Address[] results; foreach (uint addr; ih.addrList) results ~= new InternetAddress(addr, port); return results; } } @safe unittest { softUnittest({ auto addresses = getAddress("63.105.9.61"); assert(addresses.length && addresses[0].toAddrString() == "63.105.9.61"); if (getaddrinfoPointer) { // test via gethostbyname auto getaddrinfoPointerBackup = getaddrinfoPointer; cast() getaddrinfoPointer = null; scope(exit) cast() getaddrinfoPointer = getaddrinfoPointerBackup; addresses = getAddress("63.105.9.61"); assert(addresses.length && addresses[0].toAddrString() == "63.105.9.61"); } }); } /** * Provides _protocol-independent parsing of network addresses. Does not * attempt name resolution. Uses `getAddressInfo` with * `AddressInfoFlags.NUMERICHOST` if the current system supports it, and * `InternetAddress` otherwise. * * Returns: An `Address` instance representing specified address. * * Throws: `SocketException` on failure. * * Example: * --- * writeln("Enter IP address:"); * string ip = readln().chomp(); * try * { * Address address = parseAddress(ip); * writefln("Looking up reverse of %s:", * address.toAddrString()); * try * { * string reverse = address.toHostNameString(); * if (reverse) * writefln(" Reverse name: %s", reverse); * else * writeln(" Reverse hostname not found."); * } * catch (SocketException e) * writefln(" Lookup error: %s", e.msg); * } * catch (SocketException e) * { * writefln(" %s is not a valid IP address: %s", * ip, e.msg); * } * --- */ Address parseAddress(in char[] hostaddr, in char[] service = null) { if (getaddrinfoPointer && freeaddrinfoPointer) return getAddressInfo(hostaddr, service, AddressInfoFlags.NUMERICHOST)[0].address; else return parseAddress(hostaddr, serviceToPort(service)); } /// ditto Address parseAddress(in char[] hostaddr, ushort port) { if (getaddrinfoPointer && freeaddrinfoPointer) return parseAddress(hostaddr, to!string(port)); else { auto in4_addr = InternetAddress.parse(hostaddr); enforce(in4_addr != InternetAddress.ADDR_NONE, new SocketParameterException("Invalid IP address")); return new InternetAddress(in4_addr, port); } } @safe unittest { softUnittest({ auto address = parseAddress("63.105.9.61"); assert(address.toAddrString() == "63.105.9.61"); if (getaddrinfoPointer) { // test via inet_addr auto getaddrinfoPointerBackup = getaddrinfoPointer; cast() getaddrinfoPointer = null; scope(exit) cast() getaddrinfoPointer = getaddrinfoPointerBackup; address = parseAddress("63.105.9.61"); assert(address.toAddrString() == "63.105.9.61"); } assert(collectException!SocketException(parseAddress("Invalid IP address"))); }); } /** * Class for exceptions thrown from an `Address`. */ class AddressException: SocketOSException { mixin socketOSExceptionCtors; } /** * `Address` is an abstract class for representing a socket addresses. * * Example: * --- * writeln("About www.google.com port 80:"); * try * { * Address[] addresses = getAddress("www.google.com", 80); * writefln(" %d addresses found.", addresses.length); * foreach (int i, Address a; addresses) * { * writefln(" Address %d:", i+1); * writefln(" IP address: %s", a.toAddrString()); * writefln(" Hostname: %s", a.toHostNameString()); * writefln(" Port: %s", a.toPortString()); * writefln(" Service name: %s", * a.toServiceNameString()); * } * } * catch (SocketException e) * writefln(" Lookup error: %s", e.msg); * --- */ abstract class Address { /// Returns pointer to underlying `sockaddr` structure. abstract @property sockaddr* name() pure nothrow @nogc; abstract @property const(sockaddr)* name() const pure nothrow @nogc; /// ditto /// Returns actual size of underlying `sockaddr` structure. abstract @property socklen_t nameLen() const pure nothrow @nogc; // Socket.remoteAddress, Socket.localAddress, and Socket.receiveFrom // use setNameLen to set the actual size of the address as returned by // getsockname, getpeername, and recvfrom, respectively. // The following implementation is sufficient for fixed-length addresses, // and ensures that the length is not changed. // Must be overridden for variable-length addresses. protected void setNameLen(socklen_t len) { if (len != this.nameLen) throw new AddressException( format("%s expects address of length %d, not %d", typeid(this), this.nameLen, len), 0); } /// Family of this address. @property AddressFamily addressFamily() const pure nothrow @nogc { return cast(AddressFamily) name.sa_family; } // Common code for toAddrString and toHostNameString private string toHostString(bool numeric) @trusted const { // getnameinfo() is the recommended way to perform a reverse (name) // lookup on both Posix and Windows. However, it is only available // on Windows XP and above, and not included with the WinSock import // libraries shipped with DMD. Thus, we check for getnameinfo at // runtime in the shared module constructor, and use it if it's // available in the base class method. Classes for specific network // families (e.g. InternetHost) override this method and use a // deprecated, albeit commonly-available method when getnameinfo() // is not available. // http://technet.microsoft.com/en-us/library/aa450403.aspx if (getnameinfoPointer) { auto buf = new char[NI_MAXHOST]; auto ret = getnameinfoPointer( name, nameLen, buf.ptr, cast(uint) buf.length, null, 0, numeric ? NI_NUMERICHOST : NI_NAMEREQD); if (!numeric) { if (ret == EAI_NONAME) return null; version(Windows) if (ret == WSANO_DATA) return null; } enforce(ret == 0, new AddressException("Could not get " ~ (numeric ? "host address" : "host name"))); return assumeUnique(buf[0 .. strlen(buf.ptr)]); } throw new SocketFeatureException((numeric ? "Host address" : "Host name") ~ " lookup for this address family is not available on this system."); } // Common code for toPortString and toServiceNameString private string toServiceString(bool numeric) @trusted const { // See toHostNameString() for details about getnameinfo(). if (getnameinfoPointer) { auto buf = new char[NI_MAXSERV]; enforce(getnameinfoPointer( name, nameLen, null, 0, buf.ptr, cast(uint) buf.length, numeric ? NI_NUMERICSERV : NI_NAMEREQD ) == 0, new AddressException("Could not get " ~ (numeric ? "port number" : "service name"))); return assumeUnique(buf[0 .. strlen(buf.ptr)]); } throw new SocketFeatureException((numeric ? "Port number" : "Service name") ~ " lookup for this address family is not available on this system."); } /** * Attempts to retrieve the host address as a human-readable string. * * Throws: `AddressException` on failure, or `SocketFeatureException` * if address retrieval for this address family is not available on the * current system. */ string toAddrString() const { return toHostString(true); } /** * Attempts to retrieve the host name as a fully qualified domain name. * * Returns: The FQDN corresponding to this `Address`, or `null` if * the host name did not resolve. * * Throws: `AddressException` on error, or `SocketFeatureException` * if host name lookup for this address family is not available on the * current system. */ string toHostNameString() const { return toHostString(false); } /** * Attempts to retrieve the numeric port number as a string. * * Throws: `AddressException` on failure, or `SocketFeatureException` * if port number retrieval for this address family is not available on the * current system. */ string toPortString() const { return toServiceString(true); } /** * Attempts to retrieve the service name as a string. * * Throws: `AddressException` on failure, or `SocketFeatureException` * if service name lookup for this address family is not available on the * current system. */ string toServiceNameString() const { return toServiceString(false); } /// Human readable string representing this address. override string toString() const { try { string host = toAddrString(); string port = toPortString(); if (host.indexOf(':') >= 0) return "[" ~ host ~ "]:" ~ port; else return host ~ ":" ~ port; } catch (SocketException) return "Unknown"; } } /** * `UnknownAddress` encapsulates an unknown socket address. */ class UnknownAddress: Address { protected: sockaddr sa; public: override @property sockaddr* name() { return &sa; } override @property const(sockaddr)* name() const { return &sa; } override @property socklen_t nameLen() const { return cast(socklen_t) sa.sizeof; } } /** * `UnknownAddressReference` encapsulates a reference to an arbitrary * socket address. */ class UnknownAddressReference: Address { protected: sockaddr* sa; socklen_t len; public: /// Constructs an `Address` with a reference to the specified `sockaddr`. this(sockaddr* sa, socklen_t len) pure nothrow @nogc { this.sa = sa; this.len = len; } /// Constructs an `Address` with a copy of the specified `sockaddr`. this(const(sockaddr)* sa, socklen_t len) @system pure nothrow { this.sa = cast(sockaddr*) (cast(ubyte*) sa)[0 .. len].dup.ptr; this.len = len; } override @property sockaddr* name() { return sa; } override @property const(sockaddr)* name() const { return sa; } override @property socklen_t nameLen() const { return cast(socklen_t) len; } } /** * `InternetAddress` encapsulates an IPv4 (Internet Protocol version 4) * socket address. * * Consider using `getAddress`, `parseAddress` and `Address` methods * instead of using this class directly. */ class InternetAddress: Address { protected: sockaddr_in sin; this() pure nothrow @nogc { } public: override @property sockaddr* name() { return cast(sockaddr*)&sin; } override @property const(sockaddr)* name() const { return cast(const(sockaddr)*)&sin; } override @property socklen_t nameLen() const { return cast(socklen_t) sin.sizeof; } enum uint ADDR_ANY = INADDR_ANY; /// Any IPv4 host address. enum uint ADDR_NONE = INADDR_NONE; /// An invalid IPv4 host address. enum ushort PORT_ANY = 0; /// Any IPv4 port number. /// Returns the IPv4 _port number (in host byte order). @property ushort port() const pure nothrow @nogc { return ntohs(sin.sin_port); } /// Returns the IPv4 address number (in host byte order). @property uint addr() const pure nothrow @nogc { return ntohl(sin.sin_addr.s_addr); } /** * Construct a new `InternetAddress`. * Params: * addr = an IPv4 address string in the dotted-decimal form a.b.c.d, * or a host name which will be resolved using an `InternetHost` * object. * port = port number, may be `PORT_ANY`. */ this(in char[] addr, ushort port) { uint uiaddr = parse(addr); if (ADDR_NONE == uiaddr) { InternetHost ih = new InternetHost; if (!ih.getHostByName(addr)) //throw new AddressException("Invalid internet address"); throw new AddressException( text("Unable to resolve host '", addr, "'")); uiaddr = ih.addrList[0]; } sin.sin_family = AddressFamily.INET; sin.sin_addr.s_addr = htonl(uiaddr); sin.sin_port = htons(port); } /** * Construct a new `InternetAddress`. * Params: * addr = (optional) an IPv4 address in host byte order, may be `ADDR_ANY`. * port = port number, may be `PORT_ANY`. */ this(uint addr, ushort port) pure nothrow @nogc { sin.sin_family = AddressFamily.INET; sin.sin_addr.s_addr = htonl(addr); sin.sin_port = htons(port); } /// ditto this(ushort port) pure nothrow @nogc { sin.sin_family = AddressFamily.INET; sin.sin_addr.s_addr = ADDR_ANY; sin.sin_port = htons(port); } /** * Construct a new `InternetAddress`. * Params: * addr = A sockaddr_in as obtained from lower-level API calls such as getifaddrs. */ this(sockaddr_in addr) pure nothrow @nogc { assert(addr.sin_family == AddressFamily.INET); sin = addr; } /// Human readable string representing the IPv4 address in dotted-decimal form. override string toAddrString() @trusted const { return to!string(inet_ntoa(sin.sin_addr)); } /// Human readable string representing the IPv4 port. override string toPortString() const { return std.conv.to!string(port); } /** * Attempts to retrieve the host name as a fully qualified domain name. * * Returns: The FQDN corresponding to this `InternetAddress`, or * `null` if the host name did not resolve. * * Throws: `AddressException` on error. */ override string toHostNameString() const { // getnameinfo() is the recommended way to perform a reverse (name) // lookup on both Posix and Windows. However, it is only available // on Windows XP and above, and not included with the WinSock import // libraries shipped with DMD. Thus, we check for getnameinfo at // runtime in the shared module constructor, and fall back to the // deprecated getHostByAddr() if it could not be found. See also: // http://technet.microsoft.com/en-us/library/aa450403.aspx if (getnameinfoPointer) return super.toHostNameString(); else { auto host = new InternetHost(); if (!host.getHostByAddr(ntohl(sin.sin_addr.s_addr))) return null; return host.name; } } /** * Compares with another InternetAddress of same type for equality * Returns: true if the InternetAddresses share the same address and * port number. */ override bool opEquals(Object o) const { auto other = cast(InternetAddress) o; return other && this.sin.sin_addr.s_addr == other.sin.sin_addr.s_addr && this.sin.sin_port == other.sin.sin_port; } /// @system unittest { auto addr1 = new InternetAddress("127.0.0.1", 80); auto addr2 = new InternetAddress("127.0.0.2", 80); assert(addr1 == addr1); assert(addr1 != addr2); } /** * Parse an IPv4 address string in the dotted-decimal form $(I a.b.c.d) * and return the number. * Returns: If the string is not a legitimate IPv4 address, * `ADDR_NONE` is returned. */ static uint parse(in char[] addr) @trusted nothrow { return ntohl(inet_addr(addr.tempCString())); } /** * Convert an IPv4 address number in host byte order to a human readable * string representing the IPv4 address in dotted-decimal form. */ static string addrToString(uint addr) @trusted nothrow { in_addr sin_addr; sin_addr.s_addr = htonl(addr); return to!string(inet_ntoa(sin_addr)); } } @safe unittest { softUnittest({ const InternetAddress ia = new InternetAddress("63.105.9.61", 80); assert(ia.toString() == "63.105.9.61:80"); }); softUnittest({ // test construction from a sockaddr_in sockaddr_in sin; sin.sin_addr.s_addr = htonl(0x7F_00_00_01); // 127.0.0.1 sin.sin_family = AddressFamily.INET; sin.sin_port = htons(80); const InternetAddress ia = new InternetAddress(sin); assert(ia.toString() == "127.0.0.1:80"); }); softUnittest({ // test reverse lookup auto ih = new InternetHost; if (ih.getHostByName("digitalmars.com")) { const ia = new InternetAddress(ih.addrList[0], 80); assert(ia.toHostNameString() == "digitalmars.com"); if (getnameinfoPointer) { // test reverse lookup, via gethostbyaddr auto getnameinfoPointerBackup = getnameinfoPointer; cast() getnameinfoPointer = null; scope(exit) cast() getnameinfoPointer = getnameinfoPointerBackup; assert(ia.toHostNameString() == "digitalmars.com"); } } }); version (SlowTests) softUnittest({ // test failing reverse lookup const InternetAddress ia = new InternetAddress("127.114.111.120", 80); assert(ia.toHostNameString() is null); if (getnameinfoPointer) { // test failing reverse lookup, via gethostbyaddr auto getnameinfoPointerBackup = getnameinfoPointer; getnameinfoPointer = null; scope(exit) getnameinfoPointer = getnameinfoPointerBackup; assert(ia.toHostNameString() is null); } }); } /** * `Internet6Address` encapsulates an IPv6 (Internet Protocol version 6) * socket address. * * Consider using `getAddress`, `parseAddress` and `Address` methods * instead of using this class directly. */ class Internet6Address: Address { protected: sockaddr_in6 sin6; this() pure nothrow @nogc { } public: override @property sockaddr* name() { return cast(sockaddr*)&sin6; } override @property const(sockaddr)* name() const { return cast(const(sockaddr)*)&sin6; } override @property socklen_t nameLen() const { return cast(socklen_t) sin6.sizeof; } /// Any IPv6 host address. static @property ref const(ubyte)[16] ADDR_ANY() pure nothrow @nogc { const(ubyte)[16]* addr; static if (is(typeof(IN6ADDR_ANY))) { addr = &IN6ADDR_ANY.s6_addr; return *addr; } else static if (is(typeof(in6addr_any))) { addr = &in6addr_any.s6_addr; return *addr; } else static assert(0); } /// Any IPv6 port number. enum ushort PORT_ANY = 0; /// Returns the IPv6 port number. @property ushort port() const pure nothrow @nogc { return ntohs(sin6.sin6_port); } /// Returns the IPv6 address. @property ubyte[16] addr() const pure nothrow @nogc { return sin6.sin6_addr.s6_addr; } /** * Construct a new `Internet6Address`. * Params: * addr = an IPv6 host address string in the form described in RFC 2373, * or a host name which will be resolved using `getAddressInfo`. * service = (optional) service name. */ this(in char[] addr, in char[] service = null) @trusted { auto results = getAddressInfo(addr, service, AddressFamily.INET6); assert(results.length && results[0].family == AddressFamily.INET6); sin6 = *cast(sockaddr_in6*) results[0].address.name; } /** * Construct a new `Internet6Address`. * Params: * addr = an IPv6 host address string in the form described in RFC 2373, * or a host name which will be resolved using `getAddressInfo`. * port = port number, may be `PORT_ANY`. */ this(in char[] addr, ushort port) { if (port == PORT_ANY) this(addr); else this(addr, to!string(port)); } /** * Construct a new `Internet6Address`. * Params: * addr = (optional) an IPv6 host address in host byte order, or * `ADDR_ANY`. * port = port number, may be `PORT_ANY`. */ this(ubyte[16] addr, ushort port) pure nothrow @nogc { sin6.sin6_family = AddressFamily.INET6; sin6.sin6_addr.s6_addr = addr; sin6.sin6_port = htons(port); } /// ditto this(ushort port) pure nothrow @nogc { sin6.sin6_family = AddressFamily.INET6; sin6.sin6_addr.s6_addr = ADDR_ANY; sin6.sin6_port = htons(port); } /** * Construct a new `Internet6Address`. * Params: * addr = A sockaddr_in6 as obtained from lower-level API calls such as getifaddrs. */ this(sockaddr_in6 addr) pure nothrow @nogc { assert(addr.sin6_family == AddressFamily.INET6); sin6 = addr; } /** * Parse an IPv6 host address string as described in RFC 2373, and return the * address. * Throws: `SocketException` on error. */ static ubyte[16] parse(in char[] addr) @trusted { // Although we could use inet_pton here, it's only available on Windows // versions starting with Vista, so use getAddressInfo with NUMERICHOST // instead. auto results = getAddressInfo(addr, AddressInfoFlags.NUMERICHOST); if (results.length && results[0].family == AddressFamily.INET6) return (cast(sockaddr_in6*) results[0].address.name).sin6_addr.s6_addr; throw new AddressException("Not an IPv6 address", 0); } } @safe unittest { softUnittest({ const Internet6Address ia = new Internet6Address("::1", 80); assert(ia.toString() == "[::1]:80"); }); softUnittest({ // test construction from a sockaddr_in6 sockaddr_in6 sin; sin.sin6_addr.s6_addr = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]; // [::1] sin.sin6_family = AddressFamily.INET6; sin.sin6_port = htons(80); const Internet6Address ia = new Internet6Address(sin); assert(ia.toString() == "[::1]:80"); }); } version(StdDdoc) { static if (!is(sockaddr_un)) { // This exists only to allow the constructor taking // a sockaddr_un to be compilable for documentation // on platforms that don't supply a sockaddr_un. struct sockaddr_un { } } /** * `UnixAddress` encapsulates an address for a Unix domain socket * (`AF_UNIX`), i.e. a socket bound to a path name in the file system. * Available only on supported systems. * * Linux also supports an abstract address namespace, in which addresses * are independent of the file system. A socket address is abstract * iff `path` starts with a _null byte (`'\0'`). Null bytes in other * positions of an abstract address are allowed and have no special * meaning. * * Example: * --- * auto addr = new UnixAddress("/var/run/dbus/system_bus_socket"); * auto abstractAddr = new UnixAddress("\0/tmp/dbus-OtHLWmCLPR"); * --- * * See_Also: $(HTTP http://man7.org/linux/man-pages/man7/unix.7.html, UNIX(7)) */ class UnixAddress: Address { private this() pure nothrow @nogc {} /// Construct a new `UnixAddress` from the specified path. this(in char[] path) { } /** * Construct a new `UnixAddress`. * Params: * addr = A sockaddr_un as obtained from lower-level API calls. */ this(sockaddr_un addr) pure nothrow @nogc { } /// Get the underlying _path. @property string path() const { return null; } /// ditto override string toString() const { return null; } override @property sockaddr* name() { return null; } override @property const(sockaddr)* name() const { return null; } override @property socklen_t nameLen() const { return 0; } } } else static if (is(sockaddr_un)) { class UnixAddress: Address { protected: socklen_t _nameLen; struct { align (1): sockaddr_un sun; char unused = '\0'; // placeholder for a terminating '\0' } this() pure nothrow @nogc { sun.sun_family = AddressFamily.UNIX; sun.sun_path = '?'; _nameLen = sun.sizeof; } override void setNameLen(socklen_t len) @trusted { if (len > sun.sizeof) throw new SocketParameterException("Not enough socket address storage"); _nameLen = len; } public: override @property sockaddr* name() { return cast(sockaddr*)&sun; } override @property const(sockaddr)* name() const { return cast(const(sockaddr)*)&sun; } override @property socklen_t nameLen() @trusted const { return _nameLen; } this(in char[] path) @trusted pure { enforce(path.length <= sun.sun_path.sizeof, new SocketParameterException("Path too long")); sun.sun_family = AddressFamily.UNIX; sun.sun_path.ptr[0 .. path.length] = (cast(byte[]) path)[]; _nameLen = cast(socklen_t) { auto len = sockaddr_un.init.sun_path.offsetof + path.length; // Pathname socket address must be terminated with '\0' // which must be included in the address length. if (sun.sun_path.ptr[0]) { sun.sun_path.ptr[path.length] = 0; ++len; } return len; }(); } this(sockaddr_un addr) pure nothrow @nogc { assert(addr.sun_family == AddressFamily.UNIX); sun = addr; } @property string path() @trusted const pure { auto len = _nameLen - sockaddr_un.init.sun_path.offsetof; // For pathname socket address we need to strip off the terminating '\0' if (sun.sun_path.ptr[0]) --len; return (cast(const(char)*) sun.sun_path.ptr)[0 .. len].idup; } override string toString() const pure { return path; } } @safe unittest { import core.stdc.stdio : remove; import std.file : deleteme; immutable ubyte[] data = [1, 2, 3, 4]; Socket[2] pair; auto names = [ deleteme ~ "-unix-socket" ]; version (linux) names ~= "\0" ~ deleteme ~ "-abstract\0unix\0socket"; foreach (name; names) { auto address = new UnixAddress(name); auto listener = new Socket(AddressFamily.UNIX, SocketType.STREAM); scope(exit) listener.close(); listener.bind(address); scope(exit) () @trusted { if (name[0]) remove(name.tempCString()); } (); assert(listener.localAddress.toString == name); listener.listen(1); pair[0] = new Socket(AddressFamily.UNIX, SocketType.STREAM); scope(exit) listener.close(); pair[0].connect(address); scope(exit) pair[0].close(); pair[1] = listener.accept(); scope(exit) pair[1].close(); pair[0].send(data); auto buf = new ubyte[data.length]; pair[1].receive(buf); assert(buf == data); } } } /** * Class for exceptions thrown by `Socket.accept`. */ class SocketAcceptException: SocketOSException { mixin socketOSExceptionCtors; } /// How a socket is shutdown: enum SocketShutdown: int { RECEIVE = SD_RECEIVE, /// socket receives are disallowed SEND = SD_SEND, /// socket sends are disallowed BOTH = SD_BOTH, /// both RECEIVE and SEND } /// Flags may be OR'ed together: enum SocketFlags: int { NONE = 0, /// no flags specified OOB = MSG_OOB, /// out-of-band stream data PEEK = MSG_PEEK, /// peek at incoming data without removing it from the queue, only for receiving DONTROUTE = MSG_DONTROUTE, /// data should not be subject to routing; this flag may be ignored. Only for sending } private mixin template FieldProxy(string target, string field) { mixin(` @property typeof(`~target~`) `~field~`() const pure nothrow @nogc { return `~target~`; } /// ditto @property typeof(`~target~`) `~field~`(typeof(`~target~`) value) pure nothrow @nogc { return `~target~` = value; } `); } /// Duration timeout value. struct TimeVal { _ctimeval ctimeval; alias tv_sec_t = typeof(ctimeval.tv_sec); alias tv_usec_t = typeof(ctimeval.tv_usec); version (StdDdoc) // no DDoc for string mixins, can't forward individual fields { tv_sec_t seconds; /// Number of _seconds. tv_usec_t microseconds; /// Number of additional _microseconds. } else { // D interface mixin FieldProxy!(`ctimeval.tv_sec`, `seconds`); mixin FieldProxy!(`ctimeval.tv_usec`, `microseconds`); } } /** * A collection of sockets for use with `Socket.select`. * * `SocketSet` wraps the platform `fd_set` type. However, unlike * `fd_set`, `SocketSet` is not statically limited to `FD_SETSIZE` * or any other limit, and grows as needed. */ class SocketSet { private: version (Windows) { // On Windows, fd_set is an array of socket handles, // following a word containing the fd_set instance size. // We use one dynamic array for everything, and use its first // element(s) for the count. alias fd_set_count_type = typeof(fd_set.init.fd_count); alias fd_set_type = typeof(fd_set.init.fd_array[0]); static assert(fd_set_type.sizeof == socket_t.sizeof); // Number of fd_set_type elements at the start of our array that are // used for the socket count and alignment enum FD_SET_OFFSET = fd_set.fd_array.offsetof / fd_set_type.sizeof; static assert(FD_SET_OFFSET); static assert(fd_set.fd_count.offsetof % fd_set_type.sizeof == 0); fd_set_type[] set; void resize(size_t size) pure nothrow { set.length = FD_SET_OFFSET + size; } ref inout(fd_set_count_type) count() @trusted @property inout pure nothrow @nogc { assert(set.length); return *cast(inout(fd_set_count_type)*)set.ptr; } size_t capacity() @property const pure nothrow @nogc { return set.length - FD_SET_OFFSET; } inout(socket_t)[] fds() @trusted inout @property pure nothrow @nogc { return cast(inout(socket_t)[])set[FD_SET_OFFSET .. FD_SET_OFFSET+count]; } } else version (Posix) { // On Posix, fd_set is a bit array. We assume that the fd_set // type (declared in core.sys.posix.sys.select) is a structure // containing a single field, a static array. static assert(fd_set.tupleof.length == 1); // This is the type used in the fd_set array. // Using the type of the correct size is important for big-endian // architectures. alias fd_set_type = typeof(fd_set.init.tupleof[0][0]); // Number of file descriptors represented by one fd_set_type enum FD_NFDBITS = 8 * fd_set_type.sizeof; static fd_set_type mask(uint n) pure nothrow @nogc { return (cast(fd_set_type) 1) << (n % FD_NFDBITS); } // Array size to fit that many sockets static size_t lengthFor(size_t size) pure nothrow @nogc { return (size + (FD_NFDBITS-1)) / FD_NFDBITS; } fd_set_type[] set; void resize(size_t size) pure nothrow { set.length = lengthFor(size); } // Make sure we can fit that many sockets void setMinCapacity(size_t size) pure nothrow { auto length = lengthFor(size); if (set.length < length) set.length = length; } size_t capacity() @property const pure nothrow @nogc { return set.length * FD_NFDBITS; } int maxfd; } else static assert(false, "Unknown platform"); public: /** * Create a SocketSet with a specific initial capacity (defaults to * `FD_SETSIZE`, the system's default capacity). */ this(size_t size = FD_SETSIZE) pure nothrow { resize(size); reset(); } /// Reset the `SocketSet` so that there are 0 `Socket`s in the collection. void reset() pure nothrow @nogc { version (Windows) count = 0; else { set[] = 0; maxfd = -1; } } void add(socket_t s) @trusted pure nothrow { version (Windows) { if (count == capacity) { set.length *= 2; set.length = set.capacity; } ++count; fds[$-1] = s; } else { auto index = s / FD_NFDBITS; auto length = set.length; if (index >= length) { while (index >= length) length *= 2; set.length = length; set.length = set.capacity; } set[index] |= mask(s); if (maxfd < s) maxfd = s; } } /** * Add a `Socket` to the collection. * The socket must not already be in the collection. */ void add(Socket s) pure nothrow { add(s.sock); } void remove(socket_t s) pure nothrow { version (Windows) { import std.algorithm.searching : countUntil; auto fds = fds; auto p = fds.countUntil(s); if (p >= 0) fds[p] = fds[--count]; } else { auto index = s / FD_NFDBITS; if (index >= set.length) return; set[index] &= ~mask(s); // note: adjusting maxfd would require scanning the set, not worth it } } /** * Remove this `Socket` from the collection. * Does nothing if the socket is not in the collection already. */ void remove(Socket s) pure nothrow { remove(s.sock); } int isSet(socket_t s) const pure nothrow @nogc { version (Windows) { import std.algorithm.searching : canFind; return fds.canFind(s) ? 1 : 0; } else { if (s > maxfd) return 0; auto index = s / FD_NFDBITS; return (set[index] & mask(s)) ? 1 : 0; } } /// Return nonzero if this `Socket` is in the collection. int isSet(Socket s) const pure nothrow @nogc { return isSet(s.sock); } /** * Returns: * The current capacity of this `SocketSet`. The exact * meaning of the return value varies from platform to platform. * * Note: * Since D 2.065, this value does not indicate a * restriction, and `SocketSet` will grow its capacity as * needed automatically. */ @property uint max() const pure nothrow @nogc { return cast(uint) capacity; } fd_set* toFd_set() @trusted pure nothrow @nogc { return cast(fd_set*) set.ptr; } int selectn() const pure nothrow @nogc { version (Windows) { return count; } else version (Posix) { return maxfd + 1; } } } @safe unittest { auto fds = cast(socket_t[]) [cast(socket_t) 1, 2, 0, 1024, 17, 42, 1234, 77, 77+32, 77+64]; auto set = new SocketSet(); foreach (fd; fds) assert(!set.isSet(fd)); foreach (fd; fds) set.add(fd); foreach (fd; fds) assert(set.isSet(fd)); // Make sure SocketSet reimplements fd_set correctly auto fdset = set.toFd_set(); foreach (fd; fds[0]..cast(socket_t)(fds[$-1]+1)) assert(cast(bool) set.isSet(fd) == cast(bool)(() @trusted => FD_ISSET(fd, fdset))()); foreach (fd; fds) { assert(set.isSet(fd)); set.remove(fd); assert(!set.isSet(fd)); } } @safe unittest { softUnittest({ enum PAIRS = 768; version(Posix) () @trusted { enum LIMIT = 2048; static assert(LIMIT > PAIRS*2); import core.sys.posix.sys.resource; rlimit fileLimit; getrlimit(RLIMIT_NOFILE, &fileLimit); assert(fileLimit.rlim_max > LIMIT, "Open file hard limit too low"); fileLimit.rlim_cur = LIMIT; setrlimit(RLIMIT_NOFILE, &fileLimit); } (); Socket[2][PAIRS] pairs; foreach (ref pair; pairs) pair = socketPair(); scope(exit) { foreach (pair; pairs) { pair[0].close(); pair[1].close(); } } import std.random; auto rng = Xorshift(42); pairs[].randomShuffle(rng); auto readSet = new SocketSet(); auto writeSet = new SocketSet(); auto errorSet = new SocketSet(); foreach (testPair; pairs) { void fillSets() { readSet.reset(); writeSet.reset(); errorSet.reset(); foreach (ref pair; pairs) foreach (s; pair[]) { readSet.add(s); writeSet.add(s); errorSet.add(s); } } fillSets(); auto n = Socket.select(readSet, writeSet, errorSet); assert(n == PAIRS*2); // All in writeSet assert(writeSet.isSet(testPair[0])); assert(writeSet.isSet(testPair[1])); assert(!readSet.isSet(testPair[0])); assert(!readSet.isSet(testPair[1])); assert(!errorSet.isSet(testPair[0])); assert(!errorSet.isSet(testPair[1])); ubyte[1] b; // Socket.send can't be marked with `scope` // -> @safe DIP1000 code can't use it - see https://github.com/dlang/phobos/pull/6204 () @trusted { testPair[0].send(b[]); }(); fillSets(); n = Socket.select(readSet, null, null); assert(n == 1); // testPair[1] assert(readSet.isSet(testPair[1])); assert(!readSet.isSet(testPair[0])); // Socket.receive can't be marked with `scope` // -> @safe DIP1000 code can't use it - see https://github.com/dlang/phobos/pull/6204 () @trusted { testPair[1].receive(b[]); }(); } }); } @safe unittest // Issue 14012, 14013 { auto set = new SocketSet(1); assert(set.max >= 0); enum LIMIT = 4096; foreach (n; 0 .. LIMIT) set.add(cast(socket_t) n); assert(set.max >= LIMIT); } /// The level at which a socket option is defined: enum SocketOptionLevel: int { SOCKET = SOL_SOCKET, /// Socket level IP = ProtocolType.IP, /// Internet Protocol version 4 level ICMP = ProtocolType.ICMP, /// Internet Control Message Protocol level IGMP = ProtocolType.IGMP, /// Internet Group Management Protocol level GGP = ProtocolType.GGP, /// Gateway to Gateway Protocol level TCP = ProtocolType.TCP, /// Transmission Control Protocol level PUP = ProtocolType.PUP, /// PARC Universal Packet Protocol level UDP = ProtocolType.UDP, /// User Datagram Protocol level IDP = ProtocolType.IDP, /// Xerox NS protocol level RAW = ProtocolType.RAW, /// Raw IP packet level IPV6 = ProtocolType.IPV6, /// Internet Protocol version 6 level } /// _Linger information for use with SocketOption.LINGER. struct Linger { _clinger clinger; version (StdDdoc) // no DDoc for string mixins, can't forward individual fields { private alias l_onoff_t = typeof(_clinger.init.l_onoff ); private alias l_linger_t = typeof(_clinger.init.l_linger); l_onoff_t on; /// Nonzero for _on. l_linger_t time; /// Linger _time. } else { // D interface mixin FieldProxy!(`clinger.l_onoff`, `on`); mixin FieldProxy!(`clinger.l_linger`, `time`); } } /// Specifies a socket option: enum SocketOption: int { DEBUG = SO_DEBUG, /// Record debugging information BROADCAST = SO_BROADCAST, /// Allow transmission of broadcast messages REUSEADDR = SO_REUSEADDR, /// Allow local reuse of address LINGER = SO_LINGER, /// Linger on close if unsent data is present OOBINLINE = SO_OOBINLINE, /// Receive out-of-band data in band SNDBUF = SO_SNDBUF, /// Send buffer size RCVBUF = SO_RCVBUF, /// Receive buffer size DONTROUTE = SO_DONTROUTE, /// Do not route SNDTIMEO = SO_SNDTIMEO, /// Send timeout RCVTIMEO = SO_RCVTIMEO, /// Receive timeout ERROR = SO_ERROR, /// Retrieve and clear error status KEEPALIVE = SO_KEEPALIVE, /// Enable keep-alive packets ACCEPTCONN = SO_ACCEPTCONN, /// Listen RCVLOWAT = SO_RCVLOWAT, /// Minimum number of input bytes to process SNDLOWAT = SO_SNDLOWAT, /// Minimum number of output bytes to process TYPE = SO_TYPE, /// Socket type // SocketOptionLevel.TCP: TCP_NODELAY = .TCP_NODELAY, /// Disable the Nagle algorithm for send coalescing // SocketOptionLevel.IPV6: IPV6_UNICAST_HOPS = .IPV6_UNICAST_HOPS, /// IP unicast hop limit IPV6_MULTICAST_IF = .IPV6_MULTICAST_IF, /// IP multicast interface IPV6_MULTICAST_LOOP = .IPV6_MULTICAST_LOOP, /// IP multicast loopback IPV6_MULTICAST_HOPS = .IPV6_MULTICAST_HOPS, /// IP multicast hops IPV6_JOIN_GROUP = .IPV6_JOIN_GROUP, /// Add an IP group membership IPV6_LEAVE_GROUP = .IPV6_LEAVE_GROUP, /// Drop an IP group membership IPV6_V6ONLY = .IPV6_V6ONLY, /// Treat wildcard bind as AF_INET6-only } /** * `Socket` is a class that creates a network communication endpoint using * the Berkeley sockets interface. */ class Socket { private: socket_t sock; AddressFamily _family; version(Windows) bool _blocking = false; /// Property to get or set whether the socket is blocking or nonblocking. // The WinSock timeouts seem to be effectively skewed by a constant // offset of about half a second (value in milliseconds). This has // been confirmed on updated (as of Jun 2011) Windows XP, Windows 7 // and Windows Server 2008 R2 boxes. The unittest below tests this // behavior. enum WINSOCK_TIMEOUT_SKEW = 500; @safe unittest { version(SlowTests) softUnittest({ import std.datetime.stopwatch; import std.typecons; enum msecs = 1000; auto pair = socketPair(); auto sock = pair[0]; sock.setOption(SocketOptionLevel.SOCKET, SocketOption.RCVTIMEO, dur!"msecs"(msecs)); auto sw = StopWatch(Yes.autoStart); ubyte[1] buf; sock.receive(buf); sw.stop(); Duration readBack = void; sock.getOption(SocketOptionLevel.SOCKET, SocketOption.RCVTIMEO, readBack); assert(readBack.total!"msecs" == msecs); assert(sw.peek().total!"msecs" > msecs - 100 && sw.peek().total!"msecs" < msecs + 100); }); } void setSock(socket_t handle) { assert(handle != socket_t.init); sock = handle; // Set the option to disable SIGPIPE on send() if the platform // has it (e.g. on OS X). static if (is(typeof(SO_NOSIGPIPE))) { setOption(SocketOptionLevel.SOCKET, cast(SocketOption) SO_NOSIGPIPE, true); } } // For use with accepting(). protected this() pure nothrow @nogc { } public: /** * Create a blocking socket. If a single protocol type exists to support * this socket type within the address family, the `ProtocolType` may be * omitted. */ this(AddressFamily af, SocketType type, ProtocolType protocol) @trusted { _family = af; auto handle = cast(socket_t) socket(af, type, protocol); if (handle == socket_t.init) throw new SocketOSException("Unable to create socket"); setSock(handle); } /// ditto this(AddressFamily af, SocketType type) { /* A single protocol exists to support this socket type within the * protocol family, so the ProtocolType is assumed. */ this(af, type, cast(ProtocolType) 0); // Pseudo protocol number. } /// ditto this(AddressFamily af, SocketType type, in char[] protocolName) @trusted { protoent* proto; proto = getprotobyname(protocolName.tempCString()); if (!proto) throw new SocketOSException("Unable to find the protocol"); this(af, type, cast(ProtocolType) proto.p_proto); } /** * Create a blocking socket using the parameters from the specified * `AddressInfo` structure. */ this(in AddressInfo info) { this(info.family, info.type, info.protocol); } /// Use an existing socket handle. this(socket_t sock, AddressFamily af) pure nothrow @nogc { assert(sock != socket_t.init); this.sock = sock; this._family = af; } ~this() nothrow @nogc { close(); } /// Get underlying socket handle. @property socket_t handle() const pure nothrow @nogc { return sock; } /** * Get/set socket's blocking flag. * * When a socket is blocking, calls to receive(), accept(), and send() * will block and wait for data/action. * A non-blocking socket will immediately return instead of blocking. */ @property bool blocking() @trusted const nothrow @nogc { version(Windows) { return _blocking; } else version(Posix) { return !(fcntl(handle, F_GETFL, 0) & O_NONBLOCK); } } /// ditto @property void blocking(bool byes) @trusted { version(Windows) { uint num = !byes; if (_SOCKET_ERROR == ioctlsocket(sock, FIONBIO, &num)) goto err; _blocking = byes; } else version(Posix) { int x = fcntl(sock, F_GETFL, 0); if (-1 == x) goto err; if (byes) x &= ~O_NONBLOCK; else x |= O_NONBLOCK; if (-1 == fcntl(sock, F_SETFL, x)) goto err; } return; // Success. err: throw new SocketOSException("Unable to set socket blocking"); } /// Get the socket's address family. @property AddressFamily addressFamily() { return _family; } /// Property that indicates if this is a valid, alive socket. @property bool isAlive() @trusted const { int type; socklen_t typesize = cast(socklen_t) type.sizeof; return !getsockopt(sock, SOL_SOCKET, SO_TYPE, cast(char*)&type, &typesize); } /// Associate a local address with this socket. void bind(Address addr) @trusted { if (_SOCKET_ERROR == .bind(sock, addr.name, addr.nameLen)) throw new SocketOSException("Unable to bind socket"); } /** * Establish a connection. If the socket is blocking, connect waits for * the connection to be made. If the socket is nonblocking, connect * returns immediately and the connection attempt is still in progress. */ void connect(Address to) @trusted { if (_SOCKET_ERROR == .connect(sock, to.name, to.nameLen)) { int err; err = _lasterr(); if (!blocking) { version(Windows) { if (WSAEWOULDBLOCK == err) return; } else version(Posix) { if (EINPROGRESS == err) return; } else { static assert(0); } } throw new SocketOSException("Unable to connect socket", err); } } /** * Listen for an incoming connection. `bind` must be called before you * can `listen`. The `backlog` is a request of how many pending * incoming connections are queued until `accept`ed. */ void listen(int backlog) @trusted { if (_SOCKET_ERROR == .listen(sock, backlog)) throw new SocketOSException("Unable to listen on socket"); } /** * Called by `accept` when a new `Socket` must be created for a new * connection. To use a derived class, override this method and return an * instance of your class. The returned `Socket`'s handle must not be * set; `Socket` has a protected constructor `this()` to use in this * situation. * * Override to use a derived class. * The returned socket's handle must not be set. */ protected Socket accepting() pure nothrow { return new Socket; } /** * Accept an incoming connection. If the socket is blocking, `accept` * waits for a connection request. Throws `SocketAcceptException` if * unable to _accept. See `accepting` for use with derived classes. */ Socket accept() @trusted { auto newsock = cast(socket_t).accept(sock, null, null); if (socket_t.init == newsock) throw new SocketAcceptException("Unable to accept socket connection"); Socket newSocket; try { newSocket = accepting(); assert(newSocket.sock == socket_t.init); newSocket.setSock(newsock); version(Windows) newSocket._blocking = _blocking; //inherits blocking mode newSocket._family = _family; //same family } catch (Throwable o) { _close(newsock); throw o; } return newSocket; } /// Disables sends and/or receives. void shutdown(SocketShutdown how) @trusted nothrow @nogc { .shutdown(sock, cast(int) how); } private static void _close(socket_t sock) @system nothrow @nogc { version(Windows) { .closesocket(sock); } else version(Posix) { .close(sock); } } /** * Immediately drop any connections and release socket resources. * Calling `shutdown` before `close` is recommended for * connection-oriented sockets. The `Socket` object is no longer * usable after `close`. * Calling shutdown() before this is recommended * for connection-oriented sockets. */ void close() @trusted nothrow @nogc { _close(sock); sock = socket_t.init; } /** * Returns: the local machine's host name */ static @property string hostName() @trusted // getter { char[256] result; // Host names are limited to 255 chars. if (_SOCKET_ERROR == .gethostname(result.ptr, result.length)) throw new SocketOSException("Unable to obtain host name"); return to!string(result.ptr); } /// Remote endpoint `Address`. @property Address remoteAddress() @trusted { Address addr = createAddress(); socklen_t nameLen = addr.nameLen; if (_SOCKET_ERROR == .getpeername(sock, addr.name, &nameLen)) throw new SocketOSException("Unable to obtain remote socket address"); addr.setNameLen(nameLen); assert(addr.addressFamily == _family); return addr; } /// Local endpoint `Address`. @property Address localAddress() @trusted { Address addr = createAddress(); socklen_t nameLen = addr.nameLen; if (_SOCKET_ERROR == .getsockname(sock, addr.name, &nameLen)) throw new SocketOSException("Unable to obtain local socket address"); addr.setNameLen(nameLen); assert(addr.addressFamily == _family); return addr; } /** * Send or receive error code. See `wouldHaveBlocked`, * `lastSocketError` and `Socket.getErrorText` for obtaining more * information about the error. */ enum int ERROR = _SOCKET_ERROR; private static int capToInt(size_t size) nothrow @nogc { // Windows uses int instead of size_t for length arguments. // Luckily, the send/recv functions make no guarantee that // all the data is sent, so we use that to send at most // int.max bytes. return size > size_t(int.max) ? int.max : cast(int) size; } /** * Send data on the connection. If the socket is blocking and there is no * buffer space left, `send` waits. * Returns: The number of bytes actually sent, or `Socket.ERROR` on * failure. */ ptrdiff_t send(const(void)[] buf, SocketFlags flags) @trusted { static if (is(typeof(MSG_NOSIGNAL))) { flags = cast(SocketFlags)(flags | MSG_NOSIGNAL); } version( Windows ) auto sent = .send(sock, buf.ptr, capToInt(buf.length), cast(int) flags); else auto sent = .send(sock, buf.ptr, buf.length, cast(int) flags); return sent; } /// ditto ptrdiff_t send(const(void)[] buf) { return send(buf, SocketFlags.NONE); } /** * Send data to a specific destination Address. If the destination address is * not specified, a connection must have been made and that address is used. * If the socket is blocking and there is no buffer space left, `sendTo` waits. * Returns: The number of bytes actually sent, or `Socket.ERROR` on * failure. */ ptrdiff_t sendTo(const(void)[] buf, SocketFlags flags, Address to) @trusted { static if (is(typeof(MSG_NOSIGNAL))) { flags = cast(SocketFlags)(flags | MSG_NOSIGNAL); } version( Windows ) return .sendto( sock, buf.ptr, capToInt(buf.length), cast(int) flags, to.name, to.nameLen ); else return .sendto(sock, buf.ptr, buf.length, cast(int) flags, to.name, to.nameLen); } /// ditto ptrdiff_t sendTo(const(void)[] buf, Address to) { return sendTo(buf, SocketFlags.NONE, to); } //assumes you connect()ed /// ditto ptrdiff_t sendTo(const(void)[] buf, SocketFlags flags) @trusted { static if (is(typeof(MSG_NOSIGNAL))) { flags = cast(SocketFlags)(flags | MSG_NOSIGNAL); } version(Windows) return .sendto(sock, buf.ptr, capToInt(buf.length), cast(int) flags, null, 0); else return .sendto(sock, buf.ptr, buf.length, cast(int) flags, null, 0); } //assumes you connect()ed /// ditto ptrdiff_t sendTo(const(void)[] buf) { return sendTo(buf, SocketFlags.NONE); } /** * Receive data on the connection. If the socket is blocking, `receive` * waits until there is data to be received. * Returns: The number of bytes actually received, `0` if the remote side * has closed the connection, or `Socket.ERROR` on failure. */ ptrdiff_t receive(void[] buf, SocketFlags flags) @trusted { version(Windows) // Does not use size_t { return buf.length ? .recv(sock, buf.ptr, capToInt(buf.length), cast(int) flags) : 0; } else { return buf.length ? .recv(sock, buf.ptr, buf.length, cast(int) flags) : 0; } } /// ditto ptrdiff_t receive(void[] buf) { return receive(buf, SocketFlags.NONE); } /** * Receive data and get the remote endpoint `Address`. * If the socket is blocking, `receiveFrom` waits until there is data to * be received. * Returns: The number of bytes actually received, `0` if the remote side * has closed the connection, or `Socket.ERROR` on failure. */ ptrdiff_t receiveFrom(void[] buf, SocketFlags flags, ref Address from) @trusted { if (!buf.length) //return 0 and don't think the connection closed return 0; if (from is null || from.addressFamily != _family) from = createAddress(); socklen_t nameLen = from.nameLen; version(Windows) { auto read = .recvfrom(sock, buf.ptr, capToInt(buf.length), cast(int) flags, from.name, &nameLen); from.setNameLen(nameLen); assert(from.addressFamily == _family); // if (!read) //connection closed return read; } else { auto read = .recvfrom(sock, buf.ptr, buf.length, cast(int) flags, from.name, &nameLen); from.setNameLen(nameLen); assert(from.addressFamily == _family); // if (!read) //connection closed return read; } } /// ditto ptrdiff_t receiveFrom(void[] buf, ref Address from) { return receiveFrom(buf, SocketFlags.NONE, from); } //assumes you connect()ed /// ditto ptrdiff_t receiveFrom(void[] buf, SocketFlags flags) @trusted { if (!buf.length) //return 0 and don't think the connection closed return 0; version(Windows) { auto read = .recvfrom(sock, buf.ptr, capToInt(buf.length), cast(int) flags, null, null); // if (!read) //connection closed return read; } else { auto read = .recvfrom(sock, buf.ptr, buf.length, cast(int) flags, null, null); // if (!read) //connection closed return read; } } //assumes you connect()ed /// ditto ptrdiff_t receiveFrom(void[] buf) { return receiveFrom(buf, SocketFlags.NONE); } /** * Get a socket option. * Returns: The number of bytes written to `result`. * The length, in bytes, of the actual result - very different from getsockopt() */ int getOption(SocketOptionLevel level, SocketOption option, void[] result) @trusted { socklen_t len = cast(socklen_t) result.length; if (_SOCKET_ERROR == .getsockopt(sock, cast(int) level, cast(int) option, result.ptr, &len)) throw new SocketOSException("Unable to get socket option"); return len; } /// Common case of getting integer and boolean options. int getOption(SocketOptionLevel level, SocketOption option, out int32_t result) @trusted { return getOption(level, option, (&result)[0 .. 1]); } /// Get the linger option. int getOption(SocketOptionLevel level, SocketOption option, out Linger result) @trusted { //return getOption(cast(SocketOptionLevel) SocketOptionLevel.SOCKET, SocketOption.LINGER, (&result)[0 .. 1]); return getOption(level, option, (&result.clinger)[0 .. 1]); } /// Get a timeout (duration) option. void getOption(SocketOptionLevel level, SocketOption option, out Duration result) @trusted { enforce(option == SocketOption.SNDTIMEO || option == SocketOption.RCVTIMEO, new SocketParameterException("Not a valid timeout option: " ~ to!string(option))); // WinSock returns the timeout values as a milliseconds DWORD, // while Linux and BSD return a timeval struct. version (Windows) { int msecs; getOption(level, option, (&msecs)[0 .. 1]); if (option == SocketOption.RCVTIMEO) msecs += WINSOCK_TIMEOUT_SKEW; result = dur!"msecs"(msecs); } else version (Posix) { TimeVal tv; getOption(level, option, (&tv.ctimeval)[0 .. 1]); result = dur!"seconds"(tv.seconds) + dur!"usecs"(tv.microseconds); } else static assert(false); } /// Set a socket option. void setOption(SocketOptionLevel level, SocketOption option, void[] value) @trusted { if (_SOCKET_ERROR == .setsockopt(sock, cast(int) level, cast(int) option, value.ptr, cast(uint) value.length)) throw new SocketOSException("Unable to set socket option"); } /// Common case for setting integer and boolean options. void setOption(SocketOptionLevel level, SocketOption option, int32_t value) @trusted { setOption(level, option, (&value)[0 .. 1]); } /// Set the linger option. void setOption(SocketOptionLevel level, SocketOption option, Linger value) @trusted { //setOption(cast(SocketOptionLevel) SocketOptionLevel.SOCKET, SocketOption.LINGER, (&value)[0 .. 1]); setOption(level, option, (&value.clinger)[0 .. 1]); } /** * Sets a timeout (duration) option, i.e. `SocketOption.SNDTIMEO` or * `RCVTIMEO`. Zero indicates no timeout. * * In a typical application, you might also want to consider using * a non-blocking socket instead of setting a timeout on a blocking one. * * Note: While the receive timeout setting is generally quite accurate * on *nix systems even for smaller durations, there are two issues to * be aware of on Windows: First, although undocumented, the effective * timeout duration seems to be the one set on the socket plus half * a second. `setOption()` tries to compensate for that, but still, * timeouts under 500ms are not possible on Windows. Second, be aware * that the actual amount of time spent until a blocking call returns * randomly varies on the order of 10ms. * * Params: * level = The level at which a socket option is defined. * option = Either `SocketOption.SNDTIMEO` or `SocketOption.RCVTIMEO`. * value = The timeout duration to set. Must not be negative. * * Throws: `SocketException` if setting the options fails. * * Example: * --- * import std.datetime; * import std.typecons; * auto pair = socketPair(); * scope(exit) foreach (s; pair) s.close(); * * // Set a receive timeout, and then wait at one end of * // the socket pair, knowing that no data will arrive. * pair[0].setOption(SocketOptionLevel.SOCKET, * SocketOption.RCVTIMEO, dur!"seconds"(1)); * * auto sw = StopWatch(Yes.autoStart); * ubyte[1] buffer; * pair[0].receive(buffer); * writefln("Waited %s ms until the socket timed out.", * sw.peek.msecs); * --- */ void setOption(SocketOptionLevel level, SocketOption option, Duration value) @trusted { enforce(option == SocketOption.SNDTIMEO || option == SocketOption.RCVTIMEO, new SocketParameterException("Not a valid timeout option: " ~ to!string(option))); enforce(value >= dur!"hnsecs"(0), new SocketParameterException( "Timeout duration must not be negative.")); version (Windows) { import std.algorithm.comparison : max; auto msecs = to!int(value.total!"msecs"); if (msecs != 0 && option == SocketOption.RCVTIMEO) msecs = max(1, msecs - WINSOCK_TIMEOUT_SKEW); setOption(level, option, msecs); } else version (Posix) { _ctimeval tv; value.split!("seconds", "usecs")(tv.tv_sec, tv.tv_usec); setOption(level, option, (&tv)[0 .. 1]); } else static assert(false); } /** * Get a text description of this socket's error status, and clear the * socket's error status. */ string getErrorText() { int32_t error; getOption(SocketOptionLevel.SOCKET, SocketOption.ERROR, error); return formatSocketError(error); } /** * Enables TCP keep-alive with the specified parameters. * * Params: * time = Number of seconds with no activity until the first * keep-alive packet is sent. * interval = Number of seconds between when successive keep-alive * packets are sent if no acknowledgement is received. * * Throws: `SocketOSException` if setting the options fails, or * `SocketFeatureException` if setting keep-alive parameters is * unsupported on the current platform. */ void setKeepAlive(int time, int interval) @trusted { version(Windows) { tcp_keepalive options; options.onoff = 1; options.keepalivetime = time * 1000; options.keepaliveinterval = interval * 1000; uint cbBytesReturned; enforce(WSAIoctl(sock, SIO_KEEPALIVE_VALS, &options, options.sizeof, null, 0, &cbBytesReturned, null, null) == 0, new SocketOSException("Error setting keep-alive")); } else static if (is(typeof(TCP_KEEPIDLE)) && is(typeof(TCP_KEEPINTVL))) { setOption(SocketOptionLevel.TCP, cast(SocketOption) TCP_KEEPIDLE, time); setOption(SocketOptionLevel.TCP, cast(SocketOption) TCP_KEEPINTVL, interval); setOption(SocketOptionLevel.SOCKET, SocketOption.KEEPALIVE, true); } else throw new SocketFeatureException("Setting keep-alive options " ~ "is not supported on this platform"); } /** * Wait for a socket to change status. A wait timeout of $(REF Duration, core, time) or * `TimeVal`, may be specified; if a timeout is not specified or the * `TimeVal` is `null`, the maximum timeout is used. The `TimeVal` * timeout has an unspecified value when `select` returns. * Returns: The number of sockets with status changes, `0` on timeout, * or `-1` on interruption. If the return value is greater than `0`, * the `SocketSets` are updated to only contain the sockets having status * changes. For a connecting socket, a write status change means the * connection is established and it's able to send. For a listening socket, * a read status change means there is an incoming connection request and * it's able to accept. * * `SocketSet`'s updated to include only those sockets which an event occured. * For a `connect()`ing socket, writeability means connected. * For a `listen()`ing socket, readability means listening * `Winsock`; possibly internally limited to 64 sockets per set. * * Returns: * the number of events, 0 on timeout, or -1 on interruption */ static int select(SocketSet checkRead, SocketSet checkWrite, SocketSet checkError, Duration timeout) @trusted { auto vals = timeout.split!("seconds", "usecs")(); TimeVal tv; tv.seconds = cast(tv.tv_sec_t ) vals.seconds; tv.microseconds = cast(tv.tv_usec_t) vals.usecs; return select(checkRead, checkWrite, checkError, &tv); } /// ditto //maximum timeout static int select(SocketSet checkRead, SocketSet checkWrite, SocketSet checkError) { return select(checkRead, checkWrite, checkError, null); } /// Ditto static int select(SocketSet checkRead, SocketSet checkWrite, SocketSet checkError, TimeVal* timeout) @trusted in { //make sure none of the SocketSet's are the same object if (checkRead) { assert(checkRead !is checkWrite); assert(checkRead !is checkError); } if (checkWrite) { assert(checkWrite !is checkError); } } do { fd_set* fr, fw, fe; int n = 0; version(Windows) { // Windows has a problem with empty fd_set`s that aren't null. fr = checkRead && checkRead.count ? checkRead.toFd_set() : null; fw = checkWrite && checkWrite.count ? checkWrite.toFd_set() : null; fe = checkError && checkError.count ? checkError.toFd_set() : null; } else { if (checkRead) { fr = checkRead.toFd_set(); n = checkRead.selectn(); } else { fr = null; } if (checkWrite) { fw = checkWrite.toFd_set(); int _n; _n = checkWrite.selectn(); if (_n > n) n = _n; } else { fw = null; } if (checkError) { fe = checkError.toFd_set(); int _n; _n = checkError.selectn(); if (_n > n) n = _n; } else { fe = null; } // Make sure the sets' capacity matches, to avoid select reading // out of bounds just because one set was bigger than another if (checkRead ) checkRead .setMinCapacity(n); if (checkWrite) checkWrite.setMinCapacity(n); if (checkError) checkError.setMinCapacity(n); } int result = .select(n, fr, fw, fe, &timeout.ctimeval); version(Windows) { if (_SOCKET_ERROR == result && WSAGetLastError() == WSAEINTR) return -1; } else version(Posix) { if (_SOCKET_ERROR == result && errno == EINTR) return -1; } else { static assert(0); } if (_SOCKET_ERROR == result) throw new SocketOSException("Socket select error"); return result; } /** * Can be overridden to support other addresses. * Returns: a new `Address` object for the current address family. */ protected Address createAddress() pure nothrow { Address result; switch (_family) { static if (is(sockaddr_un)) { case AddressFamily.UNIX: result = new UnixAddress; break; } case AddressFamily.INET: result = new InternetAddress; break; case AddressFamily.INET6: result = new Internet6Address; break; default: result = new UnknownAddress; } return result; } } /// `TcpSocket` is a shortcut class for a TCP Socket. class TcpSocket: Socket { /// Constructs a blocking TCP Socket. this(AddressFamily family) { super(family, SocketType.STREAM, ProtocolType.TCP); } /// Constructs a blocking IPv4 TCP Socket. this() { this(AddressFamily.INET); } //shortcut /// Constructs a blocking TCP Socket and connects to an `Address`. this(Address connectTo) { this(connectTo.addressFamily); connect(connectTo); } } /// `UdpSocket` is a shortcut class for a UDP Socket. class UdpSocket: Socket { /// Constructs a blocking UDP Socket. this(AddressFamily family) { super(family, SocketType.DGRAM, ProtocolType.UDP); } /// Constructs a blocking IPv4 UDP Socket. this() { this(AddressFamily.INET); } } // Issue 16514 @safe unittest { class TestSocket : Socket { override { const pure nothrow @nogc @property @safe socket_t handle() { assert(0); } const nothrow @nogc @property @trusted bool blocking() { assert(0); } @property @trusted void blocking(bool byes) { assert(0); } @property @safe AddressFamily addressFamily() { assert(0); } const @property @trusted bool isAlive() { assert(0); } @trusted void bind(Address addr) { assert(0); } @trusted void connect(Address to) { assert(0); } @trusted void listen(int backlog) { assert(0); } protected pure nothrow @safe Socket accepting() { assert(0); } @trusted Socket accept() { assert(0); } nothrow @nogc @trusted void shutdown(SocketShutdown how) { assert(0); } nothrow @nogc @trusted void close() { assert(0); } @property @trusted Address remoteAddress() { assert(0); } @property @trusted Address localAddress() { assert(0); } @trusted ptrdiff_t send(const(void)[] buf, SocketFlags flags) { assert(0); } @safe ptrdiff_t send(const(void)[] buf) { assert(0); } @trusted ptrdiff_t sendTo(const(void)[] buf, SocketFlags flags, Address to) { assert(0); } @safe ptrdiff_t sendTo(const(void)[] buf, Address to) { assert(0); } @trusted ptrdiff_t sendTo(const(void)[] buf, SocketFlags flags) { assert(0); } @safe ptrdiff_t sendTo(const(void)[] buf) { assert(0); } @trusted ptrdiff_t receive(void[] buf, SocketFlags flags) { assert(0); } @safe ptrdiff_t receive(void[] buf) { assert(0); } @trusted ptrdiff_t receiveFrom(void[] buf, SocketFlags flags, ref Address from) { assert(0); } @safe ptrdiff_t receiveFrom(void[] buf, ref Address from) { assert(0); } @trusted ptrdiff_t receiveFrom(void[] buf, SocketFlags flags) { assert(0); } @safe ptrdiff_t receiveFrom(void[] buf) { assert(0); } @trusted int getOption(SocketOptionLevel level, SocketOption option, void[] result) { assert(0); } @trusted int getOption(SocketOptionLevel level, SocketOption option, out int32_t result) { assert(0); } @trusted int getOption(SocketOptionLevel level, SocketOption option, out Linger result) { assert(0); } @trusted void getOption(SocketOptionLevel level, SocketOption option, out Duration result) { assert(0); } @trusted void setOption(SocketOptionLevel level, SocketOption option, void[] value) { assert(0); } @trusted void setOption(SocketOptionLevel level, SocketOption option, int32_t value) { assert(0); } @trusted void setOption(SocketOptionLevel level, SocketOption option, Linger value) { assert(0); } @trusted void setOption(SocketOptionLevel level, SocketOption option, Duration value) { assert(0); } @safe string getErrorText() { assert(0); } @trusted void setKeepAlive(int time, int interval) { assert(0); } protected pure nothrow @safe Address createAddress() { assert(0); } } } } /** * Creates a pair of connected sockets. * * The two sockets are indistinguishable. * * Throws: `SocketException` if creation of the sockets fails. */ Socket[2] socketPair() @trusted { version(Posix) { int[2] socks; if (socketpair(AF_UNIX, SOCK_STREAM, 0, socks) == -1) throw new SocketOSException("Unable to create socket pair"); Socket toSocket(size_t id) { auto s = new Socket; s.setSock(cast(socket_t) socks[id]); s._family = AddressFamily.UNIX; return s; } return [toSocket(0), toSocket(1)]; } else version(Windows) { // We do not have socketpair() on Windows, just manually create a // pair of sockets connected over some localhost port. Socket[2] result; auto listener = new TcpSocket(); listener.setOption(SocketOptionLevel.SOCKET, SocketOption.REUSEADDR, true); listener.bind(new InternetAddress(INADDR_LOOPBACK, InternetAddress.PORT_ANY)); auto addr = listener.localAddress; listener.listen(1); result[0] = new TcpSocket(addr); result[1] = listener.accept(); listener.close(); return result; } else static assert(false); } /// @safe unittest { immutable ubyte[] data = [1, 2, 3, 4]; auto pair = socketPair(); scope(exit) foreach (s; pair) s.close(); pair[0].send(data); auto buf = new ubyte[data.length]; pair[1].receive(buf); assert(buf == data); }
D
/** * Compiler implementation of the * $(LINK2 http://www.dlang.org, D programming language). * * Copyright: Copyright (c) 1999-2017 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 _expression.d) */ module ddmd.expression; import core.stdc.stdarg; import core.stdc.stdio; import core.stdc.string; import ddmd.access; import ddmd.aggregate; import ddmd.aliasthis; import ddmd.apply; import ddmd.argtypes; import ddmd.arrayop; import ddmd.arraytypes; import ddmd.attrib; import ddmd.astcodegen; import ddmd.gluelayer; import ddmd.canthrow; import ddmd.complex; import ddmd.constfold; import ddmd.ctfeexpr; import ddmd.dcast; import ddmd.dclass; import ddmd.declaration; import ddmd.delegatize; import ddmd.denum; import ddmd.dimport; import ddmd.dinterpret; import ddmd.dmangle; import ddmd.dmodule; import ddmd.dscope; import ddmd.dstruct; import ddmd.dsymbol; import ddmd.dtemplate; import ddmd.errors; import ddmd.escape; import ddmd.func; import ddmd.globals; import ddmd.hdrgen; import ddmd.id; import ddmd.identifier; import ddmd.imphint; import ddmd.inline; import ddmd.intrange; import ddmd.mtype; import ddmd.nspace; import ddmd.opover; import ddmd.optimize; import ddmd.parse; import ddmd.root.ctfloat; import ddmd.root.file; import ddmd.root.filename; import ddmd.root.outbuffer; import ddmd.root.rmem; import ddmd.root.rootobject; import ddmd.safe; import ddmd.sideeffect; import ddmd.target; import ddmd.tokens; import ddmd.traits; import ddmd.typinf; import ddmd.utf; import ddmd.utils; import ddmd.visitor; enum LOGSEMANTIC = false; void emplaceExp(T : Expression, Args...)(void* p, Args args) { scope tmp = new T(args); memcpy(p, cast(void*)tmp, __traits(classInstanceSize, T)); } void emplaceExp(T : UnionExp)(T* p, Expression e) { memcpy(p, cast(void*)e, e.size); } /************************************************************* * Given var, we need to get the * right 'this' pointer if var is in an outer class, but our * existing 'this' pointer is in an inner class. * Input: * e1 existing 'this' * ad struct or class we need the correct 'this' for * var the specific member of ad we're accessing */ extern (C++) Expression getRightThis(Loc loc, Scope* sc, AggregateDeclaration ad, Expression e1, Declaration var, int flag = 0) { //printf("\ngetRightThis(e1 = %s, ad = %s, var = %s)\n", e1.toChars(), ad.toChars(), var.toChars()); L1: Type t = e1.type.toBasetype(); //printf("e1.type = %s, var.type = %s\n", e1.type.toChars(), var.type.toChars()); /* If e1 is not the 'this' pointer for ad */ if (ad && !(t.ty == Tpointer && t.nextOf().ty == Tstruct && (cast(TypeStruct)t.nextOf()).sym == ad) && !(t.ty == Tstruct && (cast(TypeStruct)t).sym == ad)) { ClassDeclaration cd = ad.isClassDeclaration(); ClassDeclaration tcd = t.isClassHandle(); /* e1 is the right this if ad is a base class of e1 */ if (!cd || !tcd || !(tcd == cd || cd.isBaseOf(tcd, null))) { /* Only classes can be inner classes with an 'outer' * member pointing to the enclosing class instance */ if (tcd && tcd.isNested()) { /* e1 is the 'this' pointer for an inner class: tcd. * Rewrite it as the 'this' pointer for the outer class. */ e1 = new DotVarExp(loc, e1, tcd.vthis); e1.type = tcd.vthis.type; e1.type = e1.type.addMod(t.mod); // Do not call ensureStaticLinkTo() //e1 = e1.semantic(sc); // Skip up over nested functions, and get the enclosing // class type. int n = 0; Dsymbol s; for (s = tcd.toParent(); s && s.isFuncDeclaration(); s = s.toParent()) { FuncDeclaration f = s.isFuncDeclaration(); if (f.vthis) { //printf("rewriting e1 to %s's this\n", f.toChars()); n++; e1 = new VarExp(loc, f.vthis); } else { e1.error("need 'this' of type %s to access member %s from static function %s", ad.toChars(), var.toChars(), f.toChars()); e1 = new ErrorExp(); return e1; } } if (s && s.isClassDeclaration()) { e1.type = s.isClassDeclaration().type; e1.type = e1.type.addMod(t.mod); if (n > 1) e1 = e1.semantic(sc); } else e1 = e1.semantic(sc); goto L1; } /* Can't find a path from e1 to ad */ if (flag) return null; e1.error("this for %s needs to be type %s not type %s", var.toChars(), ad.toChars(), t.toChars()); return new ErrorExp(); } } return e1; } /***************************************** * Determine if 'this' is available. * If it is, return the FuncDeclaration that has it. */ extern (C++) FuncDeclaration hasThis(Scope* sc) { //printf("hasThis()\n"); Dsymbol p = sc.parent; while (p && p.isTemplateMixin()) p = p.parent; FuncDeclaration fdthis = p ? p.isFuncDeclaration() : null; //printf("fdthis = %p, '%s'\n", fdthis, fdthis ? fdthis.toChars() : ""); // Go upwards until we find the enclosing member function FuncDeclaration fd = fdthis; while (1) { if (!fd) { goto Lno; } if (!fd.isNested()) break; Dsymbol parent = fd.parent; while (1) { if (!parent) goto Lno; TemplateInstance ti = parent.isTemplateInstance(); if (ti) parent = ti.parent; else break; } fd = parent.isFuncDeclaration(); } if (!fd.isThis()) { goto Lno; } assert(fd.vthis); return fd; Lno: return null; // don't have 'this' available } extern (C++) bool isNeedThisScope(Scope* sc, Declaration d) { if (sc.intypeof == 1) return false; AggregateDeclaration ad = d.isThis(); if (!ad) return false; //printf("d = %s, ad = %s\n", d.toChars(), ad.toChars()); for (Dsymbol s = sc.parent; s; s = s.toParent2()) { //printf("\ts = %s %s, toParent2() = %p\n", s.kind(), s.toChars(), s.toParent2()); if (AggregateDeclaration ad2 = s.isAggregateDeclaration()) { if (ad2 == ad) return false; else if (ad2.isNested()) continue; else return true; } if (FuncDeclaration f = s.isFuncDeclaration()) { if (f.isMember2()) break; } } return true; } /*************************************** * Pull out any properties. */ extern (C++) Expression resolvePropertiesX(Scope* sc, Expression e1, Expression e2 = null) { //printf("resolvePropertiesX, e1 = %s %s, e2 = %s\n", Token.toChars(e1.op), e1.toChars(), e2 ? e2.toChars() : null); Loc loc = e1.loc; OverloadSet os; Dsymbol s; Objects* tiargs; Type tthis; if (e1.op == TOKdot) { DotExp de = cast(DotExp)e1; if (de.e2.op == TOKoverloadset) { tiargs = null; tthis = de.e1.type; os = (cast(OverExp)de.e2).vars; goto Los; } } else if (e1.op == TOKoverloadset) { tiargs = null; tthis = null; os = (cast(OverExp)e1).vars; Los: assert(os); FuncDeclaration fd = null; if (e2) { e2 = e2.semantic(sc); if (e2.op == TOKerror) return new ErrorExp(); e2 = resolveProperties(sc, e2); Expressions a; a.push(e2); for (size_t i = 0; i < os.a.dim; i++) { FuncDeclaration f = resolveFuncCall(loc, sc, os.a[i], tiargs, tthis, &a, 1); if (f) { if (f.errors) return new ErrorExp(); fd = f; assert(fd.type.ty == Tfunction); TypeFunction tf = cast(TypeFunction)fd.type; } } if (fd) { Expression e = new CallExp(loc, e1, e2); return e.semantic(sc); } } { for (size_t i = 0; i < os.a.dim; i++) { FuncDeclaration f = resolveFuncCall(loc, sc, os.a[i], tiargs, tthis, null, 1); if (f) { if (f.errors) return new ErrorExp(); fd = f; assert(fd.type.ty == Tfunction); TypeFunction tf = cast(TypeFunction)fd.type; if (!tf.isref && e2) goto Leproplvalue; } } if (fd) { Expression e = new CallExp(loc, e1); if (e2) e = new AssignExp(loc, e, e2); return e.semantic(sc); } } if (e2) goto Leprop; } else if (e1.op == TOKdotti) { DotTemplateInstanceExp dti = cast(DotTemplateInstanceExp)e1; if (!dti.findTempDecl(sc)) goto Leprop; if (!dti.ti.semanticTiargs(sc)) goto Leprop; tiargs = dti.ti.tiargs; tthis = dti.e1.type; if ((os = dti.ti.tempdecl.isOverloadSet()) !is null) goto Los; if ((s = dti.ti.tempdecl) !is null) goto Lfd; } else if (e1.op == TOKdottd) { DotTemplateExp dte = cast(DotTemplateExp)e1; s = dte.td; tiargs = null; tthis = dte.e1.type; goto Lfd; } else if (e1.op == TOKscope) { s = (cast(ScopeExp)e1).sds; TemplateInstance ti = s.isTemplateInstance(); if (ti && !ti.semanticRun && ti.tempdecl) { //assert(ti.needsTypeInference(sc)); if (!ti.semanticTiargs(sc)) goto Leprop; tiargs = ti.tiargs; tthis = null; if ((os = ti.tempdecl.isOverloadSet()) !is null) goto Los; if ((s = ti.tempdecl) !is null) goto Lfd; } } else if (e1.op == TOKtemplate) { s = (cast(TemplateExp)e1).td; tiargs = null; tthis = null; goto Lfd; } else if (e1.op == TOKdotvar && e1.type && e1.type.toBasetype().ty == Tfunction) { DotVarExp dve = cast(DotVarExp)e1; s = dve.var.isFuncDeclaration(); tiargs = null; tthis = dve.e1.type; goto Lfd; } else if (e1.op == TOKvar && e1.type && e1.type.toBasetype().ty == Tfunction) { s = (cast(VarExp)e1).var.isFuncDeclaration(); tiargs = null; tthis = null; Lfd: assert(s); if (e2) { e2 = e2.semantic(sc); if (e2.op == TOKerror) return new ErrorExp(); e2 = resolveProperties(sc, e2); Expressions a; a.push(e2); FuncDeclaration fd = resolveFuncCall(loc, sc, s, tiargs, tthis, &a, 1); if (fd && fd.type) { if (fd.errors) return new ErrorExp(); assert(fd.type.ty == Tfunction); TypeFunction tf = cast(TypeFunction)fd.type; Expression e = new CallExp(loc, e1, e2); return e.semantic(sc); } } { FuncDeclaration fd = resolveFuncCall(loc, sc, s, tiargs, tthis, null, 1); if (fd && fd.type) { if (fd.errors) return new ErrorExp(); assert(fd.type.ty == Tfunction); TypeFunction tf = cast(TypeFunction)fd.type; if (!e2 || tf.isref) { Expression e = new CallExp(loc, e1); if (e2) e = new AssignExp(loc, e, e2); return e.semantic(sc); } } } if (FuncDeclaration fd = s.isFuncDeclaration()) { // Keep better diagnostic message for invalid property usage of functions assert(fd.type.ty == Tfunction); TypeFunction tf = cast(TypeFunction)fd.type; Expression e = new CallExp(loc, e1, e2); return e.semantic(sc); } if (e2) goto Leprop; } if (e1.op == TOKvar) { VarExp ve = cast(VarExp)e1; VarDeclaration v = ve.var.isVarDeclaration(); if (v && ve.checkPurity(sc, v)) return new ErrorExp(); } if (e2) return null; if (e1.type && e1.op != TOKtype) // function type is not a property { /* Look for e1 being a lazy parameter; rewrite as delegate call */ if (e1.op == TOKvar) { VarExp ve = cast(VarExp)e1; if (ve.var.storage_class & STClazy) { Expression e = new CallExp(loc, e1); return e.semantic(sc); } } else if (e1.op == TOKdotvar) { // Check for reading overlapped pointer field in @safe code. if (checkUnsafeAccess(sc, e1, true, true)) return new ErrorExp(); } else if (e1.op == TOKdot) { e1.error("expression has no value"); return new ErrorExp(); } else if (e1.op == TOKcall) { CallExp ce = cast(CallExp)e1; // Check for reading overlapped pointer field in @safe code. if (checkUnsafeAccess(sc, ce.e1, true, true)) return new ErrorExp(); } } if (!e1.type) { error(loc, "cannot resolve type for %s", e1.toChars()); e1 = new ErrorExp(); } return e1; Leprop: error(loc, "not a property %s", e1.toChars()); return new ErrorExp(); Leproplvalue: error(loc, "%s is not an lvalue", e1.toChars()); return new ErrorExp(); } extern (C++) Expression resolveProperties(Scope* sc, Expression e) { //printf("resolveProperties(%s)\n", e.toChars()); e = resolvePropertiesX(sc, e); if (e.checkRightThis(sc)) return new ErrorExp(); return e; } /****************************** * Check the tail CallExp is really property function call. */ extern (C++) bool checkPropertyCall(Expression e, Expression emsg) { while (e.op == TOKcomma) e = (cast(CommaExp)e).e2; if (e.op == TOKcall) { CallExp ce = cast(CallExp)e; TypeFunction tf; if (ce.f) { tf = cast(TypeFunction)ce.f.type; /* If a forward reference to ce.f, try to resolve it */ if (!tf.deco && ce.f.semanticRun < PASSsemanticdone) { ce.f.semantic(null); tf = cast(TypeFunction)ce.f.type; } } else if (ce.e1.type.ty == Tfunction) tf = cast(TypeFunction)ce.e1.type; else if (ce.e1.type.ty == Tdelegate) tf = cast(TypeFunction)ce.e1.type.nextOf(); else if (ce.e1.type.ty == Tpointer && ce.e1.type.nextOf().ty == Tfunction) tf = cast(TypeFunction)ce.e1.type.nextOf(); else assert(0); } return false; } /****************************** * If e1 is a property function (template), resolve it. */ extern (C++) Expression resolvePropertiesOnly(Scope* sc, Expression e1) { //printf("e1 = %s %s\n", Token::toChars(e1.op), e1.toChars()); OverloadSet os; FuncDeclaration fd; TemplateDeclaration td; if (e1.op == TOKdot) { DotExp de = cast(DotExp)e1; if (de.e2.op == TOKoverloadset) { os = (cast(OverExp)de.e2).vars; goto Los; } } else if (e1.op == TOKoverloadset) { os = (cast(OverExp)e1).vars; Los: assert(os); for (size_t i = 0; i < os.a.dim; i++) { Dsymbol s = os.a[i]; fd = s.isFuncDeclaration(); td = s.isTemplateDeclaration(); if (fd) { if ((cast(TypeFunction)fd.type).isproperty) return resolveProperties(sc, e1); } else if (td && td.onemember && (fd = td.onemember.isFuncDeclaration()) !is null) { if ((cast(TypeFunction)fd.type).isproperty || (fd.storage_class2 & STCproperty) || (td._scope.stc & STCproperty)) { return resolveProperties(sc, e1); } } } } else if (e1.op == TOKdotti) { DotTemplateInstanceExp dti = cast(DotTemplateInstanceExp)e1; if (dti.ti.tempdecl && (td = dti.ti.tempdecl.isTemplateDeclaration()) !is null) goto Ltd; } else if (e1.op == TOKdottd) { td = (cast(DotTemplateExp)e1).td; goto Ltd; } else if (e1.op == TOKscope) { Dsymbol s = (cast(ScopeExp)e1).sds; TemplateInstance ti = s.isTemplateInstance(); if (ti && !ti.semanticRun && ti.tempdecl) { if ((td = ti.tempdecl.isTemplateDeclaration()) !is null) goto Ltd; } } else if (e1.op == TOKtemplate) { td = (cast(TemplateExp)e1).td; Ltd: assert(td); if (td.onemember && (fd = td.onemember.isFuncDeclaration()) !is null) { if ((cast(TypeFunction)fd.type).isproperty || (fd.storage_class2 & STCproperty) || (td._scope.stc & STCproperty)) { return resolveProperties(sc, e1); } } } else if (e1.op == TOKdotvar && e1.type.ty == Tfunction) { DotVarExp dve = cast(DotVarExp)e1; fd = dve.var.isFuncDeclaration(); goto Lfd; } else if (e1.op == TOKvar && e1.type.ty == Tfunction && (sc.intypeof || !(cast(VarExp)e1).var.needThis())) { fd = (cast(VarExp)e1).var.isFuncDeclaration(); Lfd: assert(fd); if ((cast(TypeFunction)fd.type).isproperty) return resolveProperties(sc, e1); } return e1; } /****************************** * Find symbol in accordance with the UFCS name look up rule */ extern (C++) Expression searchUFCS(Scope* sc, UnaExp ue, Identifier ident) { //printf("searchUFCS(ident = %s)\n", ident.toChars()); Loc loc = ue.loc; // TODO: merge with Scope.search.searchScopes() Dsymbol searchScopes(int flags) { Dsymbol s = null; for (Scope* scx = sc; scx; scx = scx.enclosing) { if (!scx.scopesym) continue; if (scx.scopesym.isModule()) flags |= SearchUnqualifiedModule; // tell Module.search() that SearchLocalsOnly is to be obeyed s = scx.scopesym.search(loc, ident, flags); if (s) { // overload set contains only module scope symbols. if (s.isOverloadSet()) break; // selective/renamed imports also be picked up if (AliasDeclaration ad = s.isAliasDeclaration()) { if (ad._import) break; } // See only module scope symbols for UFCS target. Dsymbol p = s.toParent2(); if (p && p.isModule()) break; } s = null; // Stop when we hit a module, but keep going if that is not just under the global scope if (scx.scopesym.isModule() && !(scx.enclosing && !scx.enclosing.enclosing)) break; } return s; } int flags = 0; Dsymbol s; if (sc.flags & SCOPEignoresymbolvisibility) flags |= IgnoreSymbolVisibility; Dsymbol sold = void; if (global.params.bug10378 || global.params.check10378) { sold = searchScopes(flags | IgnoreSymbolVisibility); if (!global.params.check10378) { s = sold; goto Lsearchdone; } } // First look in local scopes s = searchScopes(flags | SearchLocalsOnly); if (!s) { // Second look in imported modules s = searchScopes(flags | SearchImportsOnly); /** Still find private symbols, so that symbols that weren't access * checked by the compiler remain usable. Once the deprecation is over, * this should be moved to search_correct instead. */ if (!s && !(flags & IgnoreSymbolVisibility)) { s = searchScopes(flags | SearchLocalsOnly | IgnoreSymbolVisibility); if (!s) s = searchScopes(flags | SearchImportsOnly | IgnoreSymbolVisibility); if (s) .deprecation(loc, "%s is not visible from module %s", s.toPrettyChars(), sc._module.toChars()); } } if (global.params.check10378) { alias snew = s; if (sold !is snew) Scope.deprecation10378(loc, sold, snew); if (global.params.bug10378) s = sold; } Lsearchdone: if (!s) return ue.e1.type.Type.getProperty(loc, ident, 0); FuncDeclaration f = s.isFuncDeclaration(); if (f) { TemplateDeclaration td = getFuncTemplateDecl(f); if (td) { if (td.overroot) td = td.overroot; s = td; } } if (ue.op == TOKdotti) { DotTemplateInstanceExp dti = cast(DotTemplateInstanceExp)ue; auto ti = new TemplateInstance(loc, s.ident, dti.ti.tiargs); if (!ti.updateTempDecl(sc, s)) return new ErrorExp(); return new ScopeExp(loc, ti); } else { //printf("-searchUFCS() %s\n", s.toChars()); return new DsymbolExp(loc, s); } } /****************************** * check e is exp.opDispatch!(tiargs) or not * It's used to switch to UFCS the semantic analysis path */ extern (C++) bool isDotOpDispatch(Expression e) { return e.op == TOKdotti && (cast(DotTemplateInstanceExp)e).ti.name == Id.opDispatch; } /****************************** * Pull out callable entity with UFCS. */ extern (C++) Expression resolveUFCS(Scope* sc, CallExp ce) { Loc loc = ce.loc; Expression eleft; Expression e; if (ce.e1.op == TOKdotid) { DotIdExp die = cast(DotIdExp)ce.e1; Identifier ident = die.ident; Expression ex = die.semanticX(sc); if (ex != die) { ce.e1 = ex; return null; } eleft = die.e1; Type t = eleft.type.toBasetype(); if (t.ty == Tarray || t.ty == Tsarray || t.ty == Tnull || (t.isTypeBasic() && t.ty != Tvoid)) { /* Built-in types and arrays have no callable properties, so do shortcut. * It is necessary in: e.init() */ } else if (t.ty == Taarray) { if (ident == Id.remove) { /* Transform: * aa.remove(arg) into delete aa[arg] */ if (!ce.arguments || ce.arguments.dim != 1) { ce.error("expected key as argument to aa.remove()"); return new ErrorExp(); } if (!eleft.type.isMutable()) { ce.error("cannot remove key from %s associative array %s", MODtoChars(t.mod), eleft.toChars()); return new ErrorExp(); } Expression key = (*ce.arguments)[0]; key = key.semantic(sc); key = resolveProperties(sc, key); TypeAArray taa = cast(TypeAArray)t; key = key.implicitCastTo(sc, taa.index); if (key.checkValue()) return new ErrorExp(); semanticTypeInfo(sc, taa.index); return new RemoveExp(loc, eleft, key); } } else { if (Expression ey = die.semanticY(sc, 1)) { if (ey.op == TOKerror) return ey; ce.e1 = ey; if (isDotOpDispatch(ey)) { uint errors = global.startGagging(); e = ce.syntaxCopy().semantic(sc); if (!global.endGagging(errors)) return e; /* fall down to UFCS */ } else return null; } } e = searchUFCS(sc, die, ident); } else if (ce.e1.op == TOKdotti) { DotTemplateInstanceExp dti = cast(DotTemplateInstanceExp)ce.e1; if (Expression ey = dti.semanticY(sc, 1)) { ce.e1 = ey; return null; } eleft = dti.e1; e = searchUFCS(sc, dti, dti.ti.name); } else return null; // Rewrite ce.e1 = e; if (!ce.arguments) ce.arguments = new Expressions(); ce.arguments.shift(eleft); return null; } /****************************** * Pull out property with UFCS. */ extern (C++) Expression resolveUFCSProperties(Scope* sc, Expression e1, Expression e2 = null) { Loc loc = e1.loc; Expression eleft; Expression e; if (e1.op == TOKdotid) { DotIdExp die = cast(DotIdExp)e1; eleft = die.e1; e = searchUFCS(sc, die, die.ident); } else if (e1.op == TOKdotti) { DotTemplateInstanceExp dti; dti = cast(DotTemplateInstanceExp)e1; eleft = dti.e1; e = searchUFCS(sc, dti, dti.ti.name); } else return null; if (e is null) return null; // Rewrite if (e2) { // run semantic without gagging e2 = e2.semantic(sc); /* f(e1) = e2 */ Expression ex = e.copy(); auto a1 = new Expressions(); a1.setDim(1); (*a1)[0] = eleft; ex = new CallExp(loc, ex, a1); ex = ex.trySemantic(sc); /* f(e1, e2) */ auto a2 = new Expressions(); a2.setDim(2); (*a2)[0] = eleft; (*a2)[1] = e2; e = new CallExp(loc, e, a2); if (ex) { // if fallback setter exists, gag errors e = e.trySemantic(sc); if (!e) { checkPropertyCall(ex, e1); ex = new AssignExp(loc, ex, e2); return ex.semantic(sc); } } else { // strict setter prints errors if fails e = e.semantic(sc); } checkPropertyCall(e, e1); return e; } else { /* f(e1) */ auto arguments = new Expressions(); arguments.setDim(1); (*arguments)[0] = eleft; e = new CallExp(loc, e, arguments); e = e.semantic(sc); checkPropertyCall(e, e1); return e.semantic(sc); } } /****************************** * Perform semantic() on an array of Expressions. */ extern (C++) bool arrayExpressionSemantic(Expressions* exps, Scope* sc, bool preserveErrors = false) { bool err = false; if (exps) { for (size_t i = 0; i < exps.dim; i++) { Expression e = (*exps)[i]; if (e) { e = e.semantic(sc); if (e.op == TOKerror) err = true; if (preserveErrors || e.op != TOKerror) (*exps)[i] = e; } } } return err; } /**************************************** * Expand tuples. * Input: * exps aray of Expressions * Output: * exps rewritten in place */ extern (C++) void expandTuples(Expressions* exps) { //printf("expandTuples()\n"); if (exps) { for (size_t i = 0; i < exps.dim; i++) { Expression arg = (*exps)[i]; if (!arg) continue; // Look for tuple with 0 members if (arg.op == TOKtype) { TypeExp e = cast(TypeExp)arg; if (e.type.toBasetype().ty == Ttuple) { TypeTuple tt = cast(TypeTuple)e.type.toBasetype(); if (!tt.arguments || tt.arguments.dim == 0) { exps.remove(i); if (i == exps.dim) return; i--; continue; } } } // Inline expand all the tuples while (arg.op == TOKtuple) { TupleExp te = cast(TupleExp)arg; exps.remove(i); // remove arg exps.insert(i, te.exps); // replace with tuple contents if (i == exps.dim) return; // empty tuple, no more arguments (*exps)[i] = Expression.combine(te.e0, (*exps)[i]); arg = (*exps)[i]; } } } } /**************************************** * Expand alias this tuples. */ extern (C++) TupleDeclaration isAliasThisTuple(Expression e) { if (!e.type) return null; Type t = e.type.toBasetype(); Lagain: if (Dsymbol s = t.toDsymbol(null)) { AggregateDeclaration ad = s.isAggregateDeclaration(); if (ad) { s = ad.aliasthis; if (s && s.isVarDeclaration()) { TupleDeclaration td = s.isVarDeclaration().toAlias().isTupleDeclaration(); if (td && td.isexp) return td; } if (Type att = t.aliasthisOf()) { t = att; goto Lagain; } } } return null; } extern (C++) int expandAliasThisTuples(Expressions* exps, size_t starti = 0) { if (!exps || exps.dim == 0) return -1; for (size_t u = starti; u < exps.dim; u++) { Expression exp = (*exps)[u]; TupleDeclaration td = isAliasThisTuple(exp); if (td) { exps.remove(u); for (size_t i = 0; i < td.objects.dim; ++i) { Expression e = isExpression((*td.objects)[i]); assert(e); assert(e.op == TOKdsymbol); DsymbolExp se = cast(DsymbolExp)e; Declaration d = se.s.isDeclaration(); assert(d); e = new DotVarExp(exp.loc, exp, d); assert(d.type); e.type = d.type; exps.insert(u + i, e); } version (none) { printf("expansion ->\n"); for (size_t i = 0; i < exps.dim; ++i) { Expression e = (*exps)[i]; printf("\texps[%d] e = %s %s\n", i, Token.tochars[e.op], e.toChars()); } } return cast(int)u; } } return -1; } /**************************************** * The common type is determined by applying ?: to each pair. * Output: * exps[] properties resolved, implicitly cast to common type, rewritten in place * *pt if pt is not NULL, set to the common type * Returns: * true a semantic error was detected */ extern (C++) bool arrayExpressionToCommonType(Scope* sc, Expressions* exps, Type* pt) { /* Still have a problem with: * ubyte[][] = [ cast(ubyte[])"hello", [1]]; * which works if the array literal is initialized top down with the ubyte[][] * type, but fails with this function doing bottom up typing. */ //printf("arrayExpressionToCommonType()\n"); scope IntegerExp integerexp = new IntegerExp(0); scope CondExp condexp = new CondExp(Loc(), integerexp, null, null); Type t0 = null; Expression e0 = null; size_t j0 = ~0; for (size_t i = 0; i < exps.dim; i++) { Expression e = (*exps)[i]; if (!e) continue; e = resolveProperties(sc, e); if (!e.type) { e.error("%s has no value", e.toChars()); t0 = Type.terror; continue; } if (e.op == TOKtype) { e.checkValue(); // report an error "type T has no value" t0 = Type.terror; continue; } if (e.type.ty == Tvoid) { // void expressions do not concur to the determination of the common // type. continue; } if (checkNonAssignmentArrayOp(e)) { t0 = Type.terror; continue; } e = doCopyOrMove(sc, e); if (t0 && !t0.equals(e.type)) { /* This applies ?: to merge the types. It's backwards; * ?: should call this function to merge types. */ condexp.type = null; condexp.e1 = e0; condexp.e2 = e; condexp.loc = e.loc; Expression ex = condexp.semantic(sc); if (ex.op == TOKerror) e = ex; else { (*exps)[j0] = condexp.e1; e = condexp.e2; } } j0 = i; e0 = e; t0 = e.type; if (e.op != TOKerror) (*exps)[i] = e; } if (!t0) t0 = Type.tvoid; // [] is typed as void[] else if (t0.ty != Terror) { for (size_t i = 0; i < exps.dim; i++) { Expression e = (*exps)[i]; if (!e) continue; e = e.implicitCastTo(sc, t0); //assert(e.op != TOKerror); if (e.op == TOKerror) { /* https://issues.dlang.org/show_bug.cgi?id=13024 * a workaround for the bug in typeMerge - * it should paint e1 and e2 by deduced common type, * but doesn't in this particular case. */ t0 = Type.terror; break; } (*exps)[i] = e; } } if (pt) *pt = t0; return (t0 == Type.terror); } /**************************************** * Get TemplateDeclaration enclosing FuncDeclaration. */ extern (C++) TemplateDeclaration getFuncTemplateDecl(Dsymbol s) { FuncDeclaration f = s.isFuncDeclaration(); if (f && f.parent) { TemplateInstance ti = f.parent.isTemplateInstance(); if (ti && !ti.isTemplateMixin() && ti.tempdecl && (cast(TemplateDeclaration)ti.tempdecl).onemember && ti.tempdecl.ident == f.ident) { return cast(TemplateDeclaration)ti.tempdecl; } } return null; } /**************************************** * Preprocess arguments to function. * Output: * exps[] tuples expanded, properties resolved, rewritten in place * Returns: * true a semantic error occurred */ extern (C++) bool preFunctionParameters(Loc loc, Scope* sc, Expressions* exps) { bool err = false; if (exps) { expandTuples(exps); for (size_t i = 0; i < exps.dim; i++) { Expression arg = (*exps)[i]; arg = resolveProperties(sc, arg); if (arg.op == TOKtype) { arg.error("cannot pass type %s as a function argument", arg.toChars()); arg = new ErrorExp(); err = true; } else if (checkNonAssignmentArrayOp(arg)) { arg = new ErrorExp(); err = true; } (*exps)[i] = arg; } } return err; } /************************************************ * If we want the value of this expression, but do not want to call * the destructor on it. */ extern (C++) Expression valueNoDtor(Expression e) { if (e.op == TOKcall) { /* The struct value returned from the function is transferred * so do not call the destructor on it. * Recognize: * ((S _ctmp = S.init), _ctmp).this(...) * and make sure the destructor is not called on _ctmp * BUG: if e is a CommaExp, we should go down the right side. */ CallExp ce = cast(CallExp)e; if (ce.e1.op == TOKdotvar) { DotVarExp dve = cast(DotVarExp)ce.e1; if (dve.var.isCtorDeclaration()) { // It's a constructor call if (dve.e1.op == TOKcomma) { CommaExp comma = cast(CommaExp)dve.e1; if (comma.e2.op == TOKvar) { VarExp ve = cast(VarExp)comma.e2; VarDeclaration ctmp = ve.var.isVarDeclaration(); if (ctmp) { ctmp.storage_class |= STCnodtor; assert(!ce.isLvalue()); } } } } } } else if (e.op == TOKvar) { auto vtmp = (cast(VarExp)e).var.isVarDeclaration(); if (vtmp && (vtmp.storage_class & STCrvalue)) { vtmp.storage_class |= STCnodtor; } } return e; } /******************************************** * Issue an error if default construction is disabled for type t. * Default construction is required for arrays and 'out' parameters. * Returns: * true an error was issued */ extern (C++) bool checkDefCtor(Loc loc, Type t) { t = t.baseElemOf(); if (t.ty == Tstruct) { StructDeclaration sd = (cast(TypeStruct)t).sym; if (sd.noDefaultCtor) { sd.error(loc, "default construction is disabled"); return true; } } return false; } /********************************************* * If e is an instance of a struct, and that struct has a copy constructor, * rewrite e as: * (tmp = e),tmp * Input: * sc just used to specify the scope of created temporary variable */ extern (C++) Expression callCpCtor(Scope* sc, Expression e) { Type tv = e.type.baseElemOf(); if (tv.ty == Tstruct) { StructDeclaration sd = (cast(TypeStruct)tv).sym; if (sd.postblit) { /* Create a variable tmp, and replace the argument e with: * (tmp = e),tmp * and let AssignExp() handle the construction. * This is not the most efficient, ideally tmp would be constructed * directly onto the stack. */ auto tmp = copyToTemp(STCrvalue, "__copytmp", e); tmp.storage_class |= STCnodtor; tmp.semantic(sc); Expression de = new DeclarationExp(e.loc, tmp); Expression ve = new VarExp(e.loc, tmp); de.type = Type.tvoid; ve.type = e.type; e = Expression.combine(de, ve); } } return e; } /************************************************ * Handle the postblit call on lvalue, or the move of rvalue. */ extern (C++) Expression doCopyOrMove(Scope *sc, Expression e) { if (e.op == TOKquestion) { auto ce = cast(CondExp)e; ce.e1 = doCopyOrMove(sc, ce.e1); ce.e2 = doCopyOrMove(sc, ce.e2); } else { e = e.isLvalue() ? callCpCtor(sc, e) : valueNoDtor(e); } return e; } /**************************************** * Now that we know the exact type of the function we're calling, * the arguments[] need to be adjusted: * 1. implicitly convert argument to the corresponding parameter type * 2. add default arguments for any missing arguments * 3. do default promotions on arguments corresponding to ... * 4. add hidden _arguments[] argument * 5. call copy constructor for struct value arguments * Input: * tf type of the function * fd the function being called, NULL if called indirectly * Output: * *prettype return type of function * *peprefix expression to execute before arguments[] are evaluated, NULL if none * Returns: * true errors happened */ extern (C++) bool functionParameters(Loc loc, Scope* sc, TypeFunction tf, Type tthis, Expressions* arguments, FuncDeclaration fd, Type* prettype, Expression* peprefix) { //printf("functionParameters()\n"); assert(arguments); assert(fd || tf.next); size_t nargs = arguments ? arguments.dim : 0; size_t nparams = Parameter.dim(tf.parameters); uint olderrors = global.errors; bool err = false; *prettype = Type.terror; Expression eprefix = null; *peprefix = null; if (nargs > nparams && tf.varargs == 0) { error(loc, "expected %llu arguments, not %llu for non-variadic function type %s", cast(ulong)nparams, cast(ulong)nargs, tf.toChars()); return true; } // If inferring return type, and semantic3() needs to be run if not already run if (!tf.next && fd.inferRetType) { fd.functionSemantic(); } else if (fd && fd.parent) { TemplateInstance ti = fd.parent.isTemplateInstance(); if (ti && ti.tempdecl) { fd.functionSemantic3(); } } bool isCtorCall = fd && fd.needThis() && fd.isCtorDeclaration(); size_t n = (nargs > nparams) ? nargs : nparams; // n = max(nargs, nparams) /* If the function return type has wildcards in it, we'll need to figure out the actual type * based on the actual argument types. */ MOD wildmatch = 0; if (tthis && tf.isWild() && !isCtorCall) { Type t = tthis; if (t.isImmutable()) wildmatch = MODimmutable; else if (t.isWildConst()) wildmatch = MODwildconst; else if (t.isWild()) wildmatch = MODwild; else if (t.isConst()) wildmatch = MODconst; else wildmatch = MODmutable; } int done = 0; for (size_t i = 0; i < n; i++) { Expression arg; if (i < nargs) arg = (*arguments)[i]; else arg = null; if (i < nparams) { Parameter p = Parameter.getNth(tf.parameters, i); if (!arg) { if (!p.defaultArg) { if (tf.varargs == 2 && i + 1 == nparams) goto L2; error(loc, "expected %llu function arguments, not %llu", cast(ulong)nparams, cast(ulong)nargs); return true; } arg = p.defaultArg; arg = inlineCopy(arg, sc); // __FILE__, __LINE__, __MODULE__, __FUNCTION__, and __PRETTY_FUNCTION__ arg = arg.resolveLoc(loc, sc); arguments.push(arg); nargs++; } if (tf.varargs == 2 && i + 1 == nparams) { //printf("\t\tvarargs == 2, p.type = '%s'\n", p.type.toChars()); { MATCH m; if ((m = arg.implicitConvTo(p.type)) > MATCHnomatch) { if (p.type.nextOf() && arg.implicitConvTo(p.type.nextOf()) >= m) goto L2; else if (nargs != nparams) { error(loc, "expected %llu function arguments, not %llu", cast(ulong)nparams, cast(ulong)nargs); return true; } goto L1; } } L2: Type tb = p.type.toBasetype(); Type tret = p.isLazyArray(); switch (tb.ty) { case Tsarray: case Tarray: { /* Create a static array variable v of type arg.type: * T[dim] __arrayArg = [ arguments[i], ..., arguments[nargs-1] ]; * * The array literal in the initializer of the hidden variable * is now optimized. * https://issues.dlang.org/show_bug.cgi?id=2356 */ Type tbn = (cast(TypeArray)tb).next; Type tsa = tbn.sarrayOf(nargs - i); auto elements = new Expressions(); elements.setDim(nargs - i); for (size_t u = 0; u < elements.dim; u++) { Expression a = (*arguments)[i + u]; if (tret && a.implicitConvTo(tret)) { a = a.implicitCastTo(sc, tret); a = a.optimize(WANTvalue); a = toDelegate(a, a.type, sc); } else a = a.implicitCastTo(sc, tbn); (*elements)[u] = a; } // https://issues.dlang.org/show_bug.cgi?id=14395 // Convert to a static array literal, or its slice. arg = new ArrayLiteralExp(loc, elements); arg.type = tsa; if (tb.ty == Tarray) { arg = new SliceExp(loc, arg, null, null); arg.type = p.type; } break; } case Tclass: { /* Set arg to be: * new Tclass(arg0, arg1, ..., argn) */ auto args = new Expressions(); args.setDim(nargs - i); for (size_t u = i; u < nargs; u++) (*args)[u - i] = (*arguments)[u]; arg = new NewExp(loc, null, null, p.type, args); break; } default: if (!arg) { error(loc, "not enough arguments"); return true; } break; } arg = arg.semantic(sc); //printf("\targ = '%s'\n", arg.toChars()); arguments.setDim(i + 1); (*arguments)[i] = arg; nargs = i + 1; done = 1; } L1: if (!(p.storageClass & STClazy && p.type.ty == Tvoid)) { bool isRef = (p.storageClass & (STCref | STCout)) != 0; if (ubyte wm = arg.type.deduceWild(p.type, isRef)) { if (wildmatch) wildmatch = MODmerge(wildmatch, wm); else wildmatch = wm; //printf("[%d] p = %s, a = %s, wm = %d, wildmatch = %d\n", i, p.type.toChars(), arg.type.toChars(), wm, wildmatch); } } } if (done) break; } if ((wildmatch == MODmutable || wildmatch == MODimmutable) && tf.next.hasWild() && (tf.isref || !tf.next.implicitConvTo(tf.next.immutableOf()))) { if (fd) { /* If the called function may return the reference to * outer inout data, it should be rejected. * * void foo(ref inout(int) x) { * ref inout(int) bar(inout(int)) { return x; } * struct S { ref inout(int) bar() inout { return x; } } * bar(int.init) = 1; // bad! * S().bar() = 1; // bad! * } */ Dsymbol s = null; if (fd.isThis() || fd.isNested()) s = fd.toParent2(); for (; s; s = s.toParent2()) { if (auto ad = s.isAggregateDeclaration()) { if (ad.isNested()) continue; break; } if (auto ff = s.isFuncDeclaration()) { if ((cast(TypeFunction)ff.type).iswild) goto Linouterr; if (ff.isNested() || ff.isThis()) continue; } break; } } else if (tf.isWild()) { Linouterr: const(char)* s = wildmatch == MODmutable ? "mutable" : MODtoChars(wildmatch); error(loc, "modify inout to %s is not allowed inside inout function", s); return true; } } assert(nargs >= nparams); for (size_t i = 0; i < nargs; i++) { Expression arg = (*arguments)[i]; assert(arg); if (i < nparams) { Parameter p = Parameter.getNth(tf.parameters, i); if (!(p.storageClass & STClazy && p.type.ty == Tvoid)) { Type tprm = p.type; if (p.type.hasWild()) tprm = p.type.substWildTo(wildmatch); if (!tprm.equals(arg.type)) { //printf("arg.type = %s, p.type = %s\n", arg.type.toChars(), p.type.toChars()); arg = arg.implicitCastTo(sc, tprm); arg = arg.optimize(WANTvalue, (p.storageClass & (STCref | STCout)) != 0); } } if (p.storageClass & STCref) { arg = arg.toLvalue(sc, arg); // Look for mutable misaligned pointer, etc., in @safe mode err |= checkUnsafeAccess(sc, arg, false, true); } else if (p.storageClass & STCout) { Type t = arg.type; if (!t.isMutable() || !t.isAssignable()) // check blit assignable { arg.error("cannot modify struct %s with immutable members", arg.toChars()); err = true; } else { // Look for misaligned pointer, etc., in @safe mode err |= checkUnsafeAccess(sc, arg, false, true); err |= checkDefCtor(arg.loc, t); // t must be default constructible } arg = arg.toLvalue(sc, arg); } else if (p.storageClass & STClazy) { // Convert lazy argument to a delegate if (p.type.ty == Tvoid) arg = toDelegate(arg, p.type, sc); else arg = toDelegate(arg, arg.type, sc); } //printf("arg: %s\n", arg.toChars()); //printf("type: %s\n", arg.type.toChars()); if (tf.parameterEscapes(p)) { /* Argument value can escape from the called function. * Check arg to see if it matters. */ if (global.params.vsafe) err |= checkParamArgumentEscape(sc, fd, p.ident, arg, false); } else { /* Argument value cannot escape from the called function. */ Expression a = arg; if (a.op == TOKcast) a = (cast(CastExp)a).e1; if (a.op == TOKfunction) { /* Function literals can only appear once, so if this * appearance was scoped, there cannot be any others. */ FuncExp fe = cast(FuncExp)a; fe.fd.tookAddressOf = 0; } else if (a.op == TOKdelegate) { /* For passing a delegate to a scoped parameter, * this doesn't count as taking the address of it. * We only worry about 'escaping' references to the function. */ DelegateExp de = cast(DelegateExp)a; if (de.e1.op == TOKvar) { VarExp ve = cast(VarExp)de.e1; FuncDeclaration f = ve.var.isFuncDeclaration(); if (f) { f.tookAddressOf--; //printf("--tookAddressOf = %d\n", f.tookAddressOf); } } } } arg = arg.optimize(WANTvalue, (p.storageClass & (STCref | STCout)) != 0); } else { // These will be the trailing ... arguments // If not D linkage, do promotions if (tf.linkage != LINKd) { // Promote bytes, words, etc., to ints arg = integralPromotions(arg, sc); // Promote floats to doubles switch (arg.type.ty) { case Tfloat32: arg = arg.castTo(sc, Type.tfloat64); break; case Timaginary32: arg = arg.castTo(sc, Type.timaginary64); break; default: break; } if (tf.varargs == 1) { const(char)* p = tf.linkage == LINKc ? "extern(C)" : "extern(C++)"; if (arg.type.ty == Tarray) { arg.error("cannot pass dynamic arrays to %s vararg functions", p); err = true; } if (arg.type.ty == Tsarray) { arg.error("cannot pass static arrays to %s vararg functions", p); err = true; } } } // Do not allow types that need destructors if (arg.type.needsDestruction()) { arg.error("cannot pass types that need destruction as variadic arguments"); err = true; } // Convert static arrays to dynamic arrays // BUG: I don't think this is right for D2 Type tb = arg.type.toBasetype(); if (tb.ty == Tsarray) { TypeSArray ts = cast(TypeSArray)tb; Type ta = ts.next.arrayOf(); if (ts.size(arg.loc) == 0) arg = new NullExp(arg.loc, ta); else arg = arg.castTo(sc, ta); } if (tb.ty == Tstruct) { //arg = callCpCtor(sc, arg); } // Give error for overloaded function addresses if (arg.op == TOKsymoff) { SymOffExp se = cast(SymOffExp)arg; if (se.hasOverloads && !se.var.isFuncDeclaration().isUnique()) { arg.error("function %s is overloaded", arg.toChars()); err = true; } } if (arg.checkValue()) err = true; arg = arg.optimize(WANTvalue); } (*arguments)[i] = arg; } /* Remaining problems: * 1. order of evaluation - some function push L-to-R, others R-to-L. Until we resolve what array assignment does (which is * implemented by calling a function) we'll defer this for now. * 2. value structs (or static arrays of them) that need to be copy constructed * 3. value structs (or static arrays of them) that have destructors, and subsequent arguments that may throw before the * function gets called (functions normally destroy their parameters) * 2 and 3 are handled by doing the argument construction in 'eprefix' so that if a later argument throws, they are cleaned * up properly. Pushing arguments on the stack then cannot fail. */ if (1) { /* TODO: tackle problem 1) */ const bool leftToRight = true; // TODO: something like !fd.isArrayOp if (!leftToRight) assert(nargs == nparams); // no variadics for RTL order, as they would probably be evaluated LTR and so add complexity const ptrdiff_t start = (leftToRight ? 0 : cast(ptrdiff_t)nargs - 1); const ptrdiff_t end = (leftToRight ? cast(ptrdiff_t)nargs : -1); const ptrdiff_t step = (leftToRight ? 1 : -1); /* Compute indices of last throwing argument and first arg needing destruction. * Used to not set up destructors unless an arg needs destruction on a throw * in a later argument. */ ptrdiff_t lastthrow = -1; ptrdiff_t firstdtor = -1; for (ptrdiff_t i = start; i != end; i += step) { Expression arg = (*arguments)[i]; if (canThrow(arg, sc.func, false)) lastthrow = i; if (firstdtor == -1 && arg.type.needsDestruction()) { Parameter p = (i >= nparams ? null : Parameter.getNth(tf.parameters, i)); if (!(p && (p.storageClass & (STClazy | STCref | STCout)))) firstdtor = i; } } /* Does problem 3) apply to this call? */ const bool needsPrefix = (firstdtor >= 0 && lastthrow >= 0 && (lastthrow - firstdtor) * step > 0); /* If so, initialize 'eprefix' by declaring the gate */ VarDeclaration gate = null; if (needsPrefix) { // eprefix => bool __gate [= false] Identifier idtmp = Identifier.generateId("__gate"); gate = new VarDeclaration(loc, Type.tbool, idtmp, null); gate.storage_class |= STCtemp | STCctfe | STCvolatile; gate.semantic(sc); auto ae = new DeclarationExp(loc, gate); eprefix = ae.semantic(sc); } for (ptrdiff_t i = start; i != end; i += step) { Expression arg = (*arguments)[i]; Parameter parameter = (i >= nparams ? null : Parameter.getNth(tf.parameters, i)); const bool isRef = (parameter && (parameter.storageClass & (STCref | STCout))); const bool isLazy = (parameter && (parameter.storageClass & STClazy)); /* Skip lazy parameters */ if (isLazy) continue; /* Do we have a gate? Then we have a prefix and we're not yet past the last throwing arg. * Declare a temporary variable for this arg and append that declaration to 'eprefix', * which will implicitly take care of potential problem 2) for this arg. * 'eprefix' will therefore finally contain all args up to and including the last * potentially throwing arg, excluding all lazy parameters. */ if (gate) { const bool needsDtor = (!isRef && arg.type.needsDestruction() && i != lastthrow); /* Declare temporary 'auto __pfx = arg' (needsDtor) or 'auto __pfy = arg' (!needsDtor) */ auto tmp = copyToTemp(0, needsDtor ? "__pfx" : "__pfy", !isRef ? arg : arg.addressOf()); tmp.semantic(sc); /* Modify the destructor so it only runs if gate==false, i.e., * only if there was a throw while constructing the args */ if (!needsDtor) { if (tmp.edtor) { assert(i == lastthrow); tmp.edtor = null; } } else { // edtor => (__gate || edtor) assert(tmp.edtor); Expression e = tmp.edtor; e = new OrOrExp(e.loc, new VarExp(e.loc, gate), e); tmp.edtor = e.semantic(sc); //printf("edtor: %s\n", tmp.edtor.toChars()); } // eprefix => (eprefix, auto __pfx/y = arg) auto ae = new DeclarationExp(loc, tmp); eprefix = Expression.combine(eprefix, ae.semantic(sc)); // arg => __pfx/y arg = new VarExp(loc, tmp); arg = arg.semantic(sc); if (isRef) { arg = new PtrExp(loc, arg); arg = arg.semantic(sc); } /* Last throwing arg? Then finalize eprefix => (eprefix, gate = true), * i.e., disable the dtors right after constructing the last throwing arg. * From now on, the callee will take care of destructing the args because * the args are implicitly moved into function parameters. * * Set gate to null to let the next iterations know they don't need to * append to eprefix anymore. */ if (i == lastthrow) { auto e = new AssignExp(gate.loc, new VarExp(gate.loc, gate), new IntegerExp(gate.loc, 1, Type.tbool)); eprefix = Expression.combine(eprefix, e.semantic(sc)); gate = null; } } else { /* No gate, no prefix to append to. * Handle problem 2) by calling the copy constructor for value structs * (or static arrays of them) if appropriate. */ Type tv = arg.type.baseElemOf(); if (!isRef && tv.ty == Tstruct) arg = doCopyOrMove(sc, arg); } (*arguments)[i] = arg; } } //if (eprefix) printf("eprefix: %s\n", eprefix.toChars()); // If D linkage and variadic, add _arguments[] as first argument if (tf.linkage == LINKd && tf.varargs == 1) { assert(arguments.dim >= nparams); auto args = new Parameters(); args.setDim(arguments.dim - nparams); for (size_t i = 0; i < arguments.dim - nparams; i++) { auto arg = new Parameter(STCin, (*arguments)[nparams + i].type, null, null); (*args)[i] = arg; } auto tup = new TypeTuple(args); Expression e = new TypeidExp(loc, tup); e = e.semantic(sc); arguments.insert(0, e); } Type tret = tf.next; if (isCtorCall) { //printf("[%s] fd = %s %s, %d %d %d\n", loc.toChars(), fd.toChars(), fd.type.toChars(), // wildmatch, tf.isWild(), fd.isolateReturn()); if (!tthis) { assert(sc.intypeof || global.errors); tthis = fd.isThis().type.addMod(fd.type.mod); } if (tf.isWild() && !fd.isolateReturn()) { if (wildmatch) tret = tret.substWildTo(wildmatch); int offset; if (!tret.implicitConvTo(tthis) && !(MODimplicitConv(tret.mod, tthis.mod) && tret.isBaseOf(tthis, &offset) && offset == 0)) { const(char)* s1 = tret.isNaked() ? " mutable" : tret.modToChars(); const(char)* s2 = tthis.isNaked() ? " mutable" : tthis.modToChars(); .error(loc, "inout constructor %s creates%s object, not%s", fd.toPrettyChars(), s1, s2); err = true; } } tret = tthis; } else if (wildmatch && tret) { /* Adjust function return type based on wildmatch */ //printf("wildmatch = x%x, tret = %s\n", wildmatch, tret.toChars()); tret = tret.substWildTo(wildmatch); } *prettype = tret; *peprefix = eprefix; return (err || olderrors != global.errors); } /****************************************************************/ /* A type meant as a union of all the Expression types, * to serve essentially as a Variant that will sit on the stack * during CTFE to reduce memory consumption. */ struct UnionExp { // yes, default constructor does nothing extern (D) this(Expression e) { memcpy(&this, cast(void*)e, e.size); } /* Extract pointer to Expression */ extern (C++) Expression exp() { return cast(Expression)&u; } /* Convert to an allocated Expression */ extern (C++) Expression copy() { Expression e = exp(); //if (e.size > sizeof(u)) printf("%s\n", Token::toChars(e.op)); assert(e.size <= u.sizeof); if (e.op == TOKcantexp) return CTFEExp.cantexp; if (e.op == TOKvoidexp) return CTFEExp.voidexp; if (e.op == TOKbreak) return CTFEExp.breakexp; if (e.op == TOKcontinue) return CTFEExp.continueexp; if (e.op == TOKgoto) return CTFEExp.gotoexp; return e.copy(); } private: union __AnonStruct__u { char[__traits(classInstanceSize, Expression)] exp; char[__traits(classInstanceSize, IntegerExp)] integerexp; char[__traits(classInstanceSize, ErrorExp)] errorexp; char[__traits(classInstanceSize, RealExp)] realexp; char[__traits(classInstanceSize, ComplexExp)] complexexp; char[__traits(classInstanceSize, SymOffExp)] symoffexp; char[__traits(classInstanceSize, StringExp)] stringexp; char[__traits(classInstanceSize, ArrayLiteralExp)] arrayliteralexp; char[__traits(classInstanceSize, AssocArrayLiteralExp)] assocarrayliteralexp; char[__traits(classInstanceSize, StructLiteralExp)] structliteralexp; char[__traits(classInstanceSize, NullExp)] nullexp; char[__traits(classInstanceSize, DotVarExp)] dotvarexp; char[__traits(classInstanceSize, AddrExp)] addrexp; char[__traits(classInstanceSize, IndexExp)] indexexp; char[__traits(classInstanceSize, SliceExp)] sliceexp; // Ensure that the union is suitably aligned. real_t for_alignment_only; } __AnonStruct__u u; } /******************************** * Test to see if two reals are the same. * Regard NaN's as equivalent. * Regard +0 and -0 as different. */ extern (C++) int RealEquals(real_t x1, real_t x2) { return (CTFloat.isNaN(x1) && CTFloat.isNaN(x2)) || CTFloat.isIdentical(x1, x2); } /************************ TypeDotIdExp ************************************/ /* Things like: * int.size * foo.size * (foo).size * cast(foo).size */ extern (C++) DotIdExp typeDotIdExp(Loc loc, Type type, Identifier ident) { return new DotIdExp(loc, new TypeExp(loc, type), ident); } /*********************************************** * Mark variable v as modified if it is inside a constructor that var * is a field in. */ extern (C++) int modifyFieldVar(Loc loc, Scope* sc, VarDeclaration var, Expression e1) { //printf("modifyFieldVar(var = %s)\n", var.toChars()); Dsymbol s = sc.func; while (1) { FuncDeclaration fd = null; if (s) fd = s.isFuncDeclaration(); if (fd && ((fd.isCtorDeclaration() && var.isField()) || (fd.isStaticCtorDeclaration() && !var.isField())) && fd.toParent2() == var.toParent2() && (!e1 || e1.op == TOKthis)) { bool result = true; var.ctorinit = true; //printf("setting ctorinit\n"); if (var.isField() && sc.fieldinit && !sc.intypeof) { assert(e1); auto mustInit = ((var.storage_class & STCnodefaultctor) != 0 || var.type.needsNested()); auto dim = sc.fieldinit_dim; auto ad = fd.isMember2(); assert(ad); size_t i; for (i = 0; i < dim; i++) // same as findFieldIndexByName in ctfeexp.c ? { if (ad.fields[i] == var) break; } assert(i < dim); uint fi = sc.fieldinit[i]; if (fi & CSXthis_ctor) { if (var.type.isMutable() && e1.type.isMutable()) result = false; else { const(char)* modStr = !var.type.isMutable() ? MODtoChars(var.type.mod) : MODtoChars(e1.type.mod); .error(loc, "%s field '%s' initialized multiple times", modStr, var.toChars()); } } else if (sc.noctor || (fi & CSXlabel)) { if (!mustInit && var.type.isMutable() && e1.type.isMutable()) result = false; else { const(char)* modStr = !var.type.isMutable() ? MODtoChars(var.type.mod) : MODtoChars(e1.type.mod); .error(loc, "%s field '%s' initialization is not allowed in loops or after labels", modStr, var.toChars()); } } sc.fieldinit[i] |= CSXthis_ctor; if (var.overlapped) // https://issues.dlang.org/show_bug.cgi?id=15258 { foreach (j, v; ad.fields) { if (v is var || !var.isOverlappedWith(v)) continue; v.ctorinit = true; sc.fieldinit[j] = CSXthis_ctor; } } } else if (fd != sc.func) { if (var.type.isMutable()) result = false; else if (sc.func.fes) { const(char)* p = var.isField() ? "field" : var.kind(); .error(loc, "%s %s '%s' initialization is not allowed in foreach loop", MODtoChars(var.type.mod), p, var.toChars()); } else { const(char)* p = var.isField() ? "field" : var.kind(); .error(loc, "%s %s '%s' initialization is not allowed in nested function '%s'", MODtoChars(var.type.mod), p, var.toChars(), sc.func.toChars()); } } return result; } else { if (s) { s = s.toParent2(); continue; } } break; } return false; } extern (C++) Expression opAssignToOp(Loc loc, TOK op, Expression e1, Expression e2) { Expression e; switch (op) { case TOKaddass: e = new AddExp(loc, e1, e2); break; case TOKminass: e = new MinExp(loc, e1, e2); break; case TOKmulass: e = new MulExp(loc, e1, e2); break; case TOKdivass: e = new DivExp(loc, e1, e2); break; case TOKmodass: e = new ModExp(loc, e1, e2); break; case TOKandass: e = new AndExp(loc, e1, e2); break; case TOKorass: e = new OrExp(loc, e1, e2); break; case TOKxorass: e = new XorExp(loc, e1, e2); break; case TOKshlass: e = new ShlExp(loc, e1, e2); break; case TOKshrass: e = new ShrExp(loc, e1, e2); break; case TOKushrass: e = new UshrExp(loc, e1, e2); break; default: assert(0); } return e; } /****************************************************************/ extern (C++) Expression extractOpDollarSideEffect(Scope* sc, UnaExp ue) { Expression e0; Expression e1 = Expression.extractLast(ue.e1, &e0); // https://issues.dlang.org/show_bug.cgi?id=12585 // Extract the side effect part if ue.e1 is comma. if (!isTrivialExp(e1)) { /* Even if opDollar is needed, 'e1' should be evaluate only once. So * Rewrite: * e1.opIndex( ... use of $ ... ) * e1.opSlice( ... use of $ ... ) * as: * (ref __dop = e1, __dop).opIndex( ... __dop.opDollar ...) * (ref __dop = e1, __dop).opSlice( ... __dop.opDollar ...) */ e1 = extractSideEffect(sc, "__dop", e0, e1, false); assert(e1.op == TOKvar); VarExp ve = cast(VarExp)e1; ve.var.storage_class |= STCexptemp; // lifetime limited to expression } ue.e1 = e1; return e0; } /************************************** * Runs semantic on ae.arguments. Declares temporary variables * if '$' was used. */ extern (C++) Expression resolveOpDollar(Scope* sc, ArrayExp ae, Expression* pe0) { assert(!ae.lengthVar); *pe0 = null; AggregateDeclaration ad = isAggregate(ae.e1.type); Dsymbol slice = search_function(ad, Id.slice); //printf("slice = %s %s\n", slice.kind(), slice.toChars()); for (size_t i = 0; i < ae.arguments.dim; i++) { if (i == 0) *pe0 = extractOpDollarSideEffect(sc, ae); Expression e = (*ae.arguments)[i]; if (e.op == TOKinterval && !(slice && slice.isTemplateDeclaration())) { Lfallback: if (ae.arguments.dim == 1) return null; ae.error("multi-dimensional slicing requires template opSlice"); return new ErrorExp(); } //printf("[%d] e = %s\n", i, e.toChars()); // Create scope for '$' variable for this dimension auto sym = new ArrayScopeSymbol(sc, ae); sym.loc = ae.loc; sym.parent = sc.scopesym; sc = sc.push(sym); ae.lengthVar = null; // Create it only if required ae.currentDimension = i; // Dimension for $, if required e = e.semantic(sc); e = resolveProperties(sc, e); if (ae.lengthVar && sc.func) { // If $ was used, declare it now Expression de = new DeclarationExp(ae.loc, ae.lengthVar); de = de.semantic(sc); *pe0 = Expression.combine(*pe0, de); } sc = sc.pop(); if (e.op == TOKinterval) { IntervalExp ie = cast(IntervalExp)e; auto tiargs = new Objects(); Expression edim = new IntegerExp(ae.loc, i, Type.tsize_t); edim = edim.semantic(sc); tiargs.push(edim); auto fargs = new Expressions(); fargs.push(ie.lwr); fargs.push(ie.upr); uint xerrors = global.startGagging(); sc = sc.push(); FuncDeclaration fslice = resolveFuncCall(ae.loc, sc, slice, tiargs, ae.e1.type, fargs, 1); sc = sc.pop(); global.endGagging(xerrors); if (!fslice) goto Lfallback; e = new DotTemplateInstanceExp(ae.loc, ae.e1, slice.ident, tiargs); e = new CallExp(ae.loc, e, fargs); e = e.semantic(sc); } if (!e.type) { ae.error("%s has no value", e.toChars()); e = new ErrorExp(); } if (e.op == TOKerror) return e; (*ae.arguments)[i] = e; } return ae; } /************************************** * Runs semantic on se.lwr and se.upr. Declares a temporary variable * if '$' was used. */ extern (C++) Expression resolveOpDollar(Scope* sc, ArrayExp ae, IntervalExp ie, Expression* pe0) { //assert(!ae.lengthVar); if (!ie) return ae; VarDeclaration lengthVar = ae.lengthVar; // create scope for '$' auto sym = new ArrayScopeSymbol(sc, ae); sym.loc = ae.loc; sym.parent = sc.scopesym; sc = sc.push(sym); for (size_t i = 0; i < 2; ++i) { Expression e = i == 0 ? ie.lwr : ie.upr; e = e.semantic(sc); e = resolveProperties(sc, e); if (!e.type) { ae.error("%s has no value", e.toChars()); return new ErrorExp(); } (i == 0 ? ie.lwr : ie.upr) = e; } if (lengthVar != ae.lengthVar && sc.func) { // If $ was used, declare it now Expression de = new DeclarationExp(ae.loc, ae.lengthVar); de = de.semantic(sc); *pe0 = Expression.combine(*pe0, de); } sc = sc.pop(); return ae; } /*********************************************************** * Resolve `exp` as a compile-time known string. * Params: * sc = scope * exp = Expression which expected as a string * s = What the string is expected for, will be used in error diagnostic. * Returns: * String literal, or `null` if error happens. */ StringExp semanticString(Scope *sc, Expression exp, const char* s) { sc = sc.startCTFE(); exp = exp.semantic(sc); exp = resolveProperties(sc, exp); sc = sc.endCTFE(); if (exp.op == TOKerror) return null; auto e = exp; if (exp.type.isString()) { e = e.ctfeInterpret(); if (e.op == TOKerror) return null; } auto se = e.toStringExp(); if (!se) { exp.error("string expected for %s, not (%s) of type %s", s, exp.toChars(), exp.type.toChars()); return null; } return se; } enum OwnedBy : int { OWNEDcode, // normal code expression in AST OWNEDctfe, // value expression for CTFE OWNEDcache, // constant value cached for CTFE } alias OWNEDcode = OwnedBy.OWNEDcode; alias OWNEDctfe = OwnedBy.OWNEDctfe; alias OWNEDcache = OwnedBy.OWNEDcache; enum WANTvalue = 0; // default enum WANTexpand = 1; // expand const/immutable variables if possible /*********************************************************** */ extern (C++) abstract class Expression : RootObject { Loc loc; // file location Type type; // !=null means that semantic() has been run TOK op; // to minimize use of dynamic_cast ubyte size; // # of bytes in Expression so we can copy() it ubyte parens; // if this is a parenthesized expression final extern (D) this(Loc loc, TOK op, int size) { //printf("Expression::Expression(op = %d) this = %p\n", op, this); this.loc = loc; this.op = op; this.size = cast(ubyte)size; } static void _init() { CTFEExp.cantexp = new CTFEExp(TOKcantexp); CTFEExp.voidexp = new CTFEExp(TOKvoidexp); CTFEExp.breakexp = new CTFEExp(TOKbreak); CTFEExp.continueexp = new CTFEExp(TOKcontinue); CTFEExp.gotoexp = new CTFEExp(TOKgoto); } /********************************* * Does *not* do a deep copy. */ final Expression copy() { Expression e; if (!size) { debug { fprintf(stderr, "No expression copy for: %s\n", toChars()); printf("op = %d\n", op); print(); } assert(0); } e = cast(Expression)mem.xmalloc(size); //printf("Expression::copy(op = %d) e = %p\n", op, e); return cast(Expression)memcpy(cast(void*)e, cast(void*)this, size); } Expression syntaxCopy() { //printf("Expression::syntaxCopy()\n"); //print(); return copy(); } /************************** * Semantically analyze Expression. * Determine types, fold constants, etc. */ Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("Expression::semantic() %s\n", toChars()); } if (type) type = type.semantic(loc, sc); else type = Type.tvoid; return this; } /********************************** * Try to run semantic routines. * If they fail, return NULL. */ final Expression trySemantic(Scope* sc) { //printf("+trySemantic(%s)\n", toChars()); uint errors = global.startGagging(); Expression e = semantic(sc); if (global.endGagging(errors)) { e = null; } //printf("-trySemantic(%s)\n", toChars()); return e; } // kludge for template.isExpression() override final DYNCAST dyncast() const { return DYNCAST.expression; } override final void print() { fprintf(stderr, "%s\n", toChars()); fflush(stderr); } override const(char)* toChars() { OutBuffer buf; HdrGenState hgs; toCBuffer(this, &buf, &hgs); return buf.extractString(); } /******************** * Print AST data structure in a nice format. * Params: * indent = indentation level */ void printAST(int indent = 0) { foreach (i; 0 .. indent) printf(" "); printf("%s %s\n", Token.toChars(op), type ? type.toChars() : ""); } final void error(const(char)* format, ...) const { if (type != Type.terror) { va_list ap; va_start(ap, format); .verror(loc, format, ap); va_end(ap); } } final void warning(const(char)* format, ...) const { if (type != Type.terror) { va_list ap; va_start(ap, format); .vwarning(loc, format, ap); va_end(ap); } } final void deprecation(const(char)* format, ...) const { if (type != Type.terror) { va_list ap; va_start(ap, format); .vdeprecation(loc, format, ap); va_end(ap); } } /********************************** * Combine e1 and e2 by CommaExp if both are not NULL. */ static Expression combine(Expression e1, Expression e2) { if (e1) { if (e2) { e1 = new CommaExp(e1.loc, e1, e2); e1.type = e2.type; } } else e1 = e2; return e1; } /********************************** * If 'e' is a tree of commas, returns the leftmost expression * by stripping off it from the tree. The remained part of the tree * is returned via *pe0. * Otherwise 'e' is directly returned and *pe0 is set to NULL. */ static Expression extractLast(Expression e, Expression* pe0) { if (e.op != TOKcomma) { *pe0 = null; return e; } CommaExp ce = cast(CommaExp)e; if (ce.e2.op != TOKcomma) { *pe0 = ce.e1; return ce.e2; } else { *pe0 = e; Expression* pce = &ce.e2; while ((cast(CommaExp)(*pce)).e2.op == TOKcomma) { pce = &(cast(CommaExp)(*pce)).e2; } assert((*pce).op == TOKcomma); ce = cast(CommaExp)(*pce); *pce = ce.e1; return ce.e2; } } static Expressions* arraySyntaxCopy(Expressions* exps) { Expressions* a = null; if (exps) { a = new Expressions(); a.setDim(exps.dim); for (size_t i = 0; i < a.dim; i++) { Expression e = (*exps)[i]; (*a)[i] = e ? e.syntaxCopy() : null; } } return a; } dinteger_t toInteger() { //printf("Expression %s\n", Token::toChars(op)); error("integer constant expression expected instead of %s", toChars()); return 0; } uinteger_t toUInteger() { //printf("Expression %s\n", Token::toChars(op)); return cast(uinteger_t)toInteger(); } real_t toReal() { error("floating point constant expression expected instead of %s", toChars()); return CTFloat.zero; } real_t toImaginary() { error("floating point constant expression expected instead of %s", toChars()); return CTFloat.zero; } complex_t toComplex() { error("floating point constant expression expected instead of %s", toChars()); return complex_t(CTFloat.zero); } StringExp toStringExp() { return null; } /*************************************** * Return !=0 if expression is an lvalue. */ bool isLvalue() { return false; } /******************************* * Give error if we're not an lvalue. * If we can, convert expression to be an lvalue. */ Expression toLvalue(Scope* sc, Expression e) { if (!e) e = this; else if (!loc.filename) loc = e.loc; if (e.op == TOKtype) error("%s '%s' is a type, not an lvalue", e.type.kind(), e.type.toChars()); else error("%s is not an lvalue", e.toChars()); return new ErrorExp(); } Expression modifiableLvalue(Scope* sc, Expression e) { //printf("Expression::modifiableLvalue() %s, type = %s\n", toChars(), type.toChars()); // See if this expression is a modifiable lvalue (i.e. not const) if (checkModifiable(sc) == 1) { assert(type); if (!type.isMutable()) { if (op == TOKdotvar) { if (isNeedThisScope(sc, (cast(DotVarExp) this).var)) for (Dsymbol s = sc.func; s; s = s.toParent2()) { FuncDeclaration ff = s.isFuncDeclaration(); if (!ff) break; if (!ff.type.isMutable) { error("cannot modify %s in %s function", toChars(), MODtoChars(type.mod)); return new ErrorExp(); } } } error("cannot modify %s expression %s", MODtoChars(type.mod), toChars()); return new ErrorExp(); } else if (!type.isAssignable()) { error("cannot modify struct %s %s with immutable members", toChars(), type.toChars()); return new ErrorExp(); } } return toLvalue(sc, e); } final Expression implicitCastTo(Scope* sc, Type t) { return .implicitCastTo(this, sc, t); } final MATCH implicitConvTo(Type t) { return .implicitConvTo(this, t); } final Expression castTo(Scope* sc, Type t) { return .castTo(this, sc, t); } /**************************************** * Resolve __FILE__, __LINE__, __MODULE__, __FUNCTION__, __PRETTY_FUNCTION__ to loc. */ Expression resolveLoc(Loc loc, Scope* sc) { this.loc = loc; return this; } /**************************************** * Check that the expression has a valid type. * If not, generates an error "... has no type". * Returns: * true if the expression is not valid. * Note: * When this function returns true, `checkValue()` should also return true. */ bool checkType() { return false; } /**************************************** * Check that the expression has a valid value. * If not, generates an error "... has no value". * Returns: * true if the expression is not valid or has void type. */ bool checkValue() { if (type && type.toBasetype().ty == Tvoid) { error("expression %s is void and has no value", toChars()); //print(); assert(0); if (!global.gag) type = Type.terror; return true; } return false; } final bool checkScalar() { if (op == TOKerror) return true; if (type.toBasetype().ty == Terror) return true; if (!type.isscalar()) { error("'%s' is not a scalar, it is a %s", toChars(), type.toChars()); return true; } return checkValue(); } final bool checkNoBool() { if (op == TOKerror) return true; if (type.toBasetype().ty == Terror) return true; if (type.toBasetype().ty == Tbool) { error("operation not allowed on bool '%s'", toChars()); return true; } return false; } final bool checkIntegral() { if (op == TOKerror) return true; if (type.toBasetype().ty == Terror) return true; if (!type.isintegral()) { error("'%s' is not of integral type, it is a %s", toChars(), type.toChars()); return true; } return checkValue(); } final bool checkArithmetic() { if (op == TOKerror) return true; if (type.toBasetype().ty == Terror) return true; if (!type.isintegral() && !type.isfloating()) { error("'%s' is not of arithmetic type, it is a %s", toChars(), type.toChars()); return true; } return checkValue(); } final void checkDeprecated(Scope* sc, Dsymbol s) { s.checkDeprecated(loc, sc); } /********************************************* * Calling function f. * Check the purity, i.e. if we're in a pure function * we can only call other pure functions. * Returns true if error occurs. */ final bool checkPurity(Scope* sc, FuncDeclaration f) { if (!sc.func) return false; if (sc.func == f) return false; if (sc.intypeof == 1) return false; if (sc.flags & (SCOPEctfe | SCOPEdebug)) return false; /* Given: * void f() { * pure void g() { * /+pure+/ void h() { * /+pure+/ void i() { } * } * } * } * g() can call h() but not f() * i() can call h() and g() but not f() */ // Find the closest pure parent of the calling function FuncDeclaration outerfunc = sc.func; FuncDeclaration calledparent = f; if (outerfunc.isInstantiated()) { // The attributes of outerfunc should be inferred from the call of f. } else if (f.isInstantiated()) { // The attributes of f are inferred from its body. } else if (f.isFuncLiteralDeclaration()) { // The attributes of f are always inferred in its declared place. } else { /* Today, static local functions are impure by default, but they cannot * violate purity of enclosing functions. * * auto foo() pure { // non instantiated function * static auto bar() { // static, without pure attribute * impureFunc(); // impure call * // Although impureFunc is called inside bar, f(= impureFunc) * // is not callable inside pure outerfunc(= foo <- bar). * } * * bar(); * // Although bar is called inside foo, f(= bar) is callable * // bacause calledparent(= foo) is same with outerfunc(= foo). * } */ while (outerfunc.toParent2() && outerfunc.isPureBypassingInference() == PUREimpure && outerfunc.toParent2().isFuncDeclaration()) { outerfunc = outerfunc.toParent2().isFuncDeclaration(); if (outerfunc.type.ty == Terror) return true; } while (calledparent.toParent2() && calledparent.isPureBypassingInference() == PUREimpure && calledparent.toParent2().isFuncDeclaration()) { calledparent = calledparent.toParent2().isFuncDeclaration(); if (calledparent.type.ty == Terror) return true; } } // If the caller has a pure parent, then either the called func must be pure, // OR, they must have the same pure parent. if (!f.isPure() && calledparent != outerfunc) { FuncDeclaration ff = outerfunc; if (sc.flags & SCOPEcompile ? ff.isPureBypassingInference() >= PUREweak : ff.setImpure()) { error("pure %s '%s' cannot call impure %s '%s'", ff.kind(), ff.toPrettyChars(), f.kind(), f.toPrettyChars()); return true; } } return false; } /******************************************* * Accessing variable v. * Check for purity and safety violations. * Returns true if error occurs. */ final bool checkPurity(Scope* sc, VarDeclaration v) { //printf("v = %s %s\n", v.type.toChars(), v.toChars()); /* Look for purity and safety violations when accessing variable v * from current function. */ if (!sc.func) return false; if (sc.intypeof == 1) return false; // allow violations inside typeof(expression) if (sc.flags & (SCOPEctfe | SCOPEdebug)) return false; // allow violations inside compile-time evaluated expressions and debug conditionals if (v.ident == Id.ctfe) return false; // magic variable never violates pure and safe if (v.isImmutable()) return false; // always safe and pure to access immutables... if (v.isConst() && !v.isRef() && (v.isDataseg() || v.isParameter()) && v.type.implicitConvTo(v.type.immutableOf())) return false; // or const global/parameter values which have no mutable indirections if (v.storage_class & STCmanifest) return false; // ...or manifest constants bool err = false; if (v.isDataseg()) { // https://issues.dlang.org/show_bug.cgi?id=7533 // Accessing implicit generated __gate is pure. if (v.ident == Id.gate) return false; /* Accessing global mutable state. * Therefore, this function and all its immediately enclosing * functions must be pure. */ /* Today, static local functions are impure by default, but they cannot * violate purity of enclosing functions. * * auto foo() pure { // non instantiated function * static auto bar() { // static, without pure attribute * globalData++; // impure access * // Although globalData is accessed inside bar, * // it is not accessible inside pure foo. * } * } */ for (Dsymbol s = sc.func; s; s = s.toParent2()) { FuncDeclaration ff = s.isFuncDeclaration(); if (!ff) break; if (sc.flags & SCOPEcompile ? ff.isPureBypassingInference() >= PUREweak : ff.setImpure()) { error("pure %s '%s' cannot access mutable static data '%s'", ff.kind(), ff.toPrettyChars(), v.toChars()); err = true; break; } /* If the enclosing is an instantiated function or a lambda, its * attribute inference result is preferred. */ if (ff.isInstantiated()) break; if (ff.isFuncLiteralDeclaration()) break; } } else { /* Given: * void f() { * int fx; * pure void g() { * int gx; * /+pure+/ void h() { * int hx; * /+pure+/ void i() { } * } * } * } * i() can modify hx and gx but not fx */ Dsymbol vparent = v.toParent2(); for (Dsymbol s = sc.func; !err && s; s = s.toParent2()) { if (s == vparent) break; if (AggregateDeclaration ad = s.isAggregateDeclaration()) { if (ad.isNested()) continue; break; } FuncDeclaration ff = s.isFuncDeclaration(); if (!ff) break; if (ff.isNested() || ff.isThis()) { if (ff.type.isImmutable() || ff.type.isShared() && !MODimplicitConv(ff.type.mod, v.type.mod)) { OutBuffer ffbuf; OutBuffer vbuf; MODMatchToBuffer(&ffbuf, ff.type.mod, v.type.mod); MODMatchToBuffer(&vbuf, v.type.mod, ff.type.mod); error("%s%s '%s' cannot access %sdata '%s'", ffbuf.peekString(), ff.kind(), ff.toPrettyChars(), vbuf.peekString(), v.toChars()); err = true; break; } continue; } break; } } /* Do not allow safe functions to access __gshared data */ if (v.storage_class & STCgshared) { if (sc.func.setUnsafe()) { error("safe %s '%s' cannot access __gshared data '%s'", sc.func.kind(), sc.func.toChars(), v.toChars()); err = true; } } return err; } /********************************************* * Calling function f. * Check the safety, i.e. if we're in a @safe function * we can only call @safe or @trusted functions. * Returns true if error occurs. */ final bool checkSafety(Scope* sc, FuncDeclaration f) { if (!sc.func) return false; if (sc.func == f) return false; if (sc.intypeof == 1) return false; if (sc.flags & SCOPEctfe) return false; if (!f.isSafe() && !f.isTrusted()) { if (sc.flags & SCOPEcompile ? sc.func.isSafeBypassingInference() : sc.func.setUnsafe()) { if (loc.linnum == 0) // e.g. implicitly generated dtor loc = sc.func.loc; error("@safe %s '%s' cannot call @system %s '%s'", sc.func.kind(), sc.func.toPrettyChars(), f.kind(), f.toPrettyChars()); return true; } } return false; } /********************************************* * Calling function f. * Check the @nogc-ness, i.e. if we're in a @nogc function * we can only call other @nogc functions. * Returns true if error occurs. */ final bool checkNogc(Scope* sc, FuncDeclaration f) { if (!sc.func) return false; if (sc.func == f) return false; if (sc.intypeof == 1) return false; if (sc.flags & SCOPEctfe) return false; if (!f.isNogc()) { if (sc.flags & SCOPEcompile ? sc.func.isNogcBypassingInference() : sc.func.setGC()) { if (loc.linnum == 0) // e.g. implicitly generated dtor loc = sc.func.loc; error("@nogc %s '%s' cannot call non-@nogc %s '%s'", sc.func.kind(), sc.func.toPrettyChars(), f.kind(), f.toPrettyChars()); return true; } } return false; } /******************************************** * Check that the postblit is callable if t is an array of structs. * Returns true if error happens. */ final bool checkPostblit(Scope* sc, Type t) { t = t.baseElemOf(); if (t.ty == Tstruct) { // https://issues.dlang.org/show_bug.cgi?id=11395 // Require TypeInfo generation for array concatenation semanticTypeInfo(sc, t); StructDeclaration sd = (cast(TypeStruct)t).sym; if (sd.postblit) { if (sd.postblit.storage_class & STCdisable) { sd.error(loc, "is not copyable because it is annotated with @disable"); return true; } //checkDeprecated(sc, sd.postblit); // necessary? checkPurity(sc, sd.postblit); checkSafety(sc, sd.postblit); checkNogc(sc, sd.postblit); //checkAccess(sd, loc, sc, sd.postblit); // necessary? return false; } } return false; } final bool checkRightThis(Scope* sc) { if (op == TOKerror) return true; if (op == TOKvar && type.ty != Terror) { VarExp ve = cast(VarExp)this; if (isNeedThisScope(sc, ve.var)) { //printf("checkRightThis sc.intypeof = %d, ad = %p, func = %p, fdthis = %p\n", // sc.intypeof, sc.getStructClassScope(), func, fdthis); error("need 'this' for '%s' of type '%s'", ve.var.toChars(), ve.var.type.toChars()); return true; } } return false; } /******************************* * Check whether the expression allows RMW operations, error with rmw operator diagnostic if not. * ex is the RHS expression, or NULL if ++/-- is used (for diagnostics) * Returns true if error occurs. */ final bool checkReadModifyWrite(TOK rmwOp, Expression ex = null) { //printf("Expression::checkReadModifyWrite() %s %s", toChars(), ex ? ex.toChars() : ""); if (!type || !type.isShared()) return false; // atomicOp uses opAssign (+=/-=) rather than opOp (++/--) for the CT string literal. switch (rmwOp) { case TOKplusplus: case TOKpreplusplus: rmwOp = TOKaddass; break; case TOKminusminus: case TOKpreminusminus: rmwOp = TOKminass; break; default: break; } deprecation("read-modify-write operations are not allowed for shared variables. Use core.atomic.atomicOp!\"%s\"(%s, %s) instead.", Token.toChars(rmwOp), toChars(), ex ? ex.toChars() : "1"); return false; // note: enable when deprecation becomes an error. // return true; } /*************************************** * Parameters: * sc: scope * flag: 1: do not issue error message for invalid modification * Returns: * 0: is not modifiable * 1: is modifiable in default == being related to type.isMutable() * 2: is modifiable, because this is a part of initializing. */ int checkModifiable(Scope* sc, int flag = 0) { return type ? 1 : 0; // default modifiable } /***************************** * If expression can be tested for true or false, * returns the modified expression. * Otherwise returns ErrorExp. */ Expression toBoolean(Scope* sc) { // Default is 'yes' - do nothing debug { if (!type) print(); assert(type); } Expression e = this; Type t = type; Type tb = type.toBasetype(); Type att = null; Lagain: // Structs can be converted to bool using opCast(bool)() if (tb.ty == Tstruct) { AggregateDeclaration ad = (cast(TypeStruct)tb).sym; /* Don't really need to check for opCast first, but by doing so we * get better error messages if it isn't there. */ Dsymbol fd = search_function(ad, Id._cast); if (fd) { e = new CastExp(loc, e, Type.tbool); e = e.semantic(sc); return e; } // Forward to aliasthis. if (ad.aliasthis && tb != att) { if (!att && tb.checkAliasThisRec()) att = tb; e = resolveAliasThis(sc, e); t = e.type; tb = e.type.toBasetype(); goto Lagain; } } if (!t.isBoolean()) { if (tb != Type.terror) error("expression %s of type %s does not have a boolean value", toChars(), t.toChars()); return new ErrorExp(); } return e; } /************************************************ * Destructors are attached to VarDeclarations. * Hence, if expression returns a temp that needs a destructor, * make sure and create a VarDeclaration for that temp. */ Expression addDtorHook(Scope* sc) { return this; } /****************************** * Take address of expression. */ final Expression addressOf() { //printf("Expression::addressOf()\n"); debug { assert(op == TOKerror || isLvalue()); } Expression e = new AddrExp(loc, this); e.type = type.pointerTo(); return e; } /****************************** * If this is a reference, dereference it. */ final Expression deref() { //printf("Expression::deref()\n"); // type could be null if forward referencing an 'auto' variable if (type && type.ty == Treference) { Expression e = new PtrExp(loc, this); e.type = (cast(TypeReference)type).next; return e; } return this; } final Expression optimize(int result, bool keepLvalue = false) { return Expression_optimize(this, result, keepLvalue); } // Entry point for CTFE. // A compile-time result is required. Give an error if not possible final Expression ctfeInterpret() { return .ctfeInterpret(this); } final int isConst() { return .isConst(this); } /******************************** * Does this expression statically evaluate to a boolean 'result' (true or false)? */ bool isBool(bool result) { return false; } final Expression op_overload(Scope* sc) { return .op_overload(this, sc); } void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class IntegerExp : Expression { dinteger_t value; extern (D) this(Loc loc, dinteger_t value, Type type) { super(loc, TOKint64, __traits(classInstanceSize, IntegerExp)); //printf("IntegerExp(value = %lld, type = '%s')\n", value, type ? type.toChars() : ""); assert(type); if (!type.isscalar()) { //printf("%s, loc = %d\n", toChars(), loc.linnum); if (type.ty != Terror) error("integral constant must be scalar type, not %s", type.toChars()); type = Type.terror; } this.type = type; setInteger(value); } extern (D) this(dinteger_t value) { super(Loc(), TOKint64, __traits(classInstanceSize, IntegerExp)); this.type = Type.tint32; this.value = cast(d_int32)value; } override bool equals(RootObject o) { if (this == o) return true; if ((cast(Expression)o).op == TOKint64) { IntegerExp ne = cast(IntegerExp)o; if (type.toHeadMutable().equals(ne.type.toHeadMutable()) && value == ne.value) { return true; } } return false; } override Expression semantic(Scope* sc) { assert(type); if (type.ty == Terror) return new ErrorExp(); assert(type.deco); normalize(); return this; } override dinteger_t toInteger() { normalize(); // necessary until we fix all the paints of 'type' return value; } override real_t toReal() { normalize(); // necessary until we fix all the paints of 'type' Type t = type.toBasetype(); if (t.ty == Tuns64) return real_t(cast(d_uns64)value); else return real_t(cast(d_int64)value); } override real_t toImaginary() { return CTFloat.zero; } override complex_t toComplex() { return complex_t(toReal()); } override bool isBool(bool result) { bool r = toInteger() != 0; return result ? r : !r; } override Expression toLvalue(Scope* sc, Expression e) { if (!e) e = this; else if (!loc.filename) loc = e.loc; e.error("constant %s is not an lvalue", e.toChars()); return new ErrorExp(); } override void accept(Visitor v) { v.visit(this); } dinteger_t getInteger() { return value; } void setInteger(dinteger_t value) { this.value = value; normalize(); } private: void normalize() { /* 'Normalize' the value of the integer to be in range of the type */ switch (type.toBasetype().ty) { case Tbool: value = (value != 0); break; case Tint8: value = cast(d_int8)value; break; case Tchar: case Tuns8: value = cast(d_uns8)value; break; case Tint16: value = cast(d_int16)value; break; case Twchar: case Tuns16: value = cast(d_uns16)value; break; case Tint32: value = cast(d_int32)value; break; case Tdchar: case Tuns32: value = cast(d_uns32)value; break; case Tint64: value = cast(d_int64)value; break; case Tuns64: value = cast(d_uns64)value; break; case Tpointer: if (Target.ptrsize == 4) value = cast(d_uns32)value; else if (Target.ptrsize == 8) value = cast(d_uns64)value; else assert(0); break; default: break; } } } /*********************************************************** * Use this expression for error recovery. * It should behave as a 'sink' to prevent further cascaded error messages. */ extern (C++) final class ErrorExp : Expression { extern (D) this() { super(Loc(), TOKerror, __traits(classInstanceSize, ErrorExp)); type = Type.terror; } override Expression toLvalue(Scope* sc, Expression e) { return this; } override void accept(Visitor v) { v.visit(this); } extern (C++) static __gshared ErrorExp errorexp; // handy shared value } /*********************************************************** */ extern (C++) final class RealExp : Expression { real_t value; extern (D) this(Loc loc, real_t value, Type type) { super(loc, TOKfloat64, __traits(classInstanceSize, RealExp)); //printf("RealExp::RealExp(%Lg)\n", value); this.value = value; this.type = type; } override bool equals(RootObject o) { if (this == o) return true; if ((cast(Expression)o).op == TOKfloat64) { RealExp ne = cast(RealExp)o; if (type.toHeadMutable().equals(ne.type.toHeadMutable()) && RealEquals(value, ne.value)) { return true; } } return false; } override Expression semantic(Scope* sc) { if (!type) type = Type.tfloat64; else type = type.semantic(loc, sc); return this; } override dinteger_t toInteger() { return cast(sinteger_t)toReal(); } override uinteger_t toUInteger() { return cast(uinteger_t)toReal(); } override real_t toReal() { return type.isreal() ? value : CTFloat.zero; } override real_t toImaginary() { return type.isreal() ? CTFloat.zero : value; } override complex_t toComplex() { return complex_t(toReal(), toImaginary()); } override bool isBool(bool result) { return result ? cast(bool)value : !cast(bool)value; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class ComplexExp : Expression { complex_t value; extern (D) this(Loc loc, complex_t value, Type type) { super(loc, TOKcomplex80, __traits(classInstanceSize, ComplexExp)); this.value = value; this.type = type; //printf("ComplexExp::ComplexExp(%s)\n", toChars()); } override bool equals(RootObject o) { if (this == o) return true; if ((cast(Expression)o).op == TOKcomplex80) { ComplexExp ne = cast(ComplexExp)o; if (type.toHeadMutable().equals(ne.type.toHeadMutable()) && RealEquals(creall(value), creall(ne.value)) && RealEquals(cimagl(value), cimagl(ne.value))) { return true; } } return false; } override Expression semantic(Scope* sc) { if (!type) type = Type.tcomplex80; else type = type.semantic(loc, sc); return this; } override dinteger_t toInteger() { return cast(sinteger_t)toReal(); } override uinteger_t toUInteger() { return cast(uinteger_t)toReal(); } override real_t toReal() { return creall(value); } override real_t toImaginary() { return cimagl(value); } override complex_t toComplex() { return value; } override bool isBool(bool result) { if (result) return cast(bool)value; else return !value; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) class IdentifierExp : Expression { Identifier ident; final extern (D) this(Loc loc, Identifier ident) { super(loc, TOKidentifier, __traits(classInstanceSize, IdentifierExp)); this.ident = ident; } static IdentifierExp create(Loc loc, Identifier ident) { return new IdentifierExp(loc, ident); } override final Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("IdentifierExp::semantic('%s')\n", ident.toChars()); } if (type) // This is used as the dummy expression return this; Dsymbol scopesym; Dsymbol s = sc.search(loc, ident, &scopesym); if (s) { if (s.errors) return new ErrorExp(); Expression e; /* See if the symbol was a member of an enclosing 'with' */ WithScopeSymbol withsym = scopesym.isWithScopeSymbol(); if (withsym && withsym.withstate.wthis) { /* Disallow shadowing */ // First find the scope of the with Scope* scwith = sc; while (scwith.scopesym != scopesym) { scwith = scwith.enclosing; assert(scwith); } // Look at enclosing scopes for symbols with the same name, // in the same function for (Scope* scx = scwith; scx && scx.func == scwith.func; scx = scx.enclosing) { Dsymbol s2; if (scx.scopesym && scx.scopesym.symtab && (s2 = scx.scopesym.symtab.lookup(s.ident)) !is null && s != s2) { error("with symbol `%s` is shadowing local symbol `%s`", s.toPrettyChars(), s2.toPrettyChars()); return new ErrorExp(); } } s = s.toAlias(); // Same as wthis.ident // TODO: DotIdExp.semantic will find 'ident' from 'wthis' again. // The redudancy should be removed. e = new VarExp(loc, withsym.withstate.wthis); e = new DotIdExp(loc, e, ident); e = e.semantic(sc); } else { if (withsym) { Declaration d = s.isDeclaration(); if (d) checkAccess(loc, sc, null, d); } /* If f is really a function template, * then replace f with the function template declaration. */ FuncDeclaration f = s.isFuncDeclaration(); if (f) { TemplateDeclaration td = getFuncTemplateDecl(f); if (td) { if (td.overroot) // if not start of overloaded list of TemplateDeclaration's td = td.overroot; // then get the start e = new TemplateExp(loc, td, f); e = e.semantic(sc); return e; } } // Haven't done overload resolution yet, so pass 1 e = DsymbolExp.resolve(loc, sc, s, true); } return e; } if (hasThis(sc)) { AggregateDeclaration ad = sc.getStructClassScope(); if (ad && ad.aliasthis) { Expression e; e = new IdentifierExp(loc, Id.This); e = new DotIdExp(loc, e, ad.aliasthis.ident); e = new DotIdExp(loc, e, ident); e = e.trySemantic(sc); if (e) return e; } } if (ident == Id.ctfe) { if (sc.flags & SCOPEctfe) { error("variable `__ctfe` cannot be read at compile time"); return new ErrorExp(); } // Create the magic __ctfe bool variable auto vd = new VarDeclaration(loc, Type.tbool, Id.ctfe, null); vd.storage_class |= STCtemp; vd.semanticRun = PASSsemanticdone; Expression e = new VarExp(loc, vd); e = e.semantic(sc); return e; } // If we've reached this point and are inside a with() scope then we may // try one last attempt by checking whether the 'wthis' object supports // dynamic dispatching via opDispatch. // This is done by rewriting this expression as wthis.ident. for (Scope* sc2 = sc; sc2; sc2 = sc2.enclosing) { if (!sc2.scopesym) continue; if (auto ss = sc2.scopesym.isWithScopeSymbol()) { if (ss.withstate.wthis) { Expression e; e = new VarExp(loc, ss.withstate.wthis); e = new DotIdExp(loc, e, ident); e = e.trySemantic(sc); if (e) return e; } break; } } const(char)* n = importHint(ident.toChars()); if (n) error("`%s` is not defined, perhaps `import %s;` is needed?", ident.toChars(), n); else { s = sc.search_correct(ident); if (s) error("undefined identifier `%s`, did you mean %s `%s`?", ident.toChars(), s.kind(), s.toChars()); else error("undefined identifier `%s`", ident.toChars()); } return new ErrorExp(); } override final bool isLvalue() { return true; } override final Expression toLvalue(Scope* sc, Expression e) { return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class DollarExp : IdentifierExp { extern (D) this(Loc loc) { super(loc, Id.dollar); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * Won't be generated by parser. * A placeholder expression to call DsymbolExp.resolve on specific symbol. */ extern (C++) final class DsymbolExp : Expression { Dsymbol s; bool hasOverloads; extern (D) this(Loc loc, Dsymbol s, bool hasOverloads = true) { super(loc, TOKdsymbol, __traits(classInstanceSize, DsymbolExp)); this.s = s; this.hasOverloads = hasOverloads; } override Expression semantic(Scope* sc) { return resolve(loc ,sc, s, hasOverloads); } /**************************************** * Resolve a symbol `s` and wraps it in an expression object. * Params: * hasOverloads = works if the aliased symbol is a function. * true: it's overloaded and will be resolved later. * false: it's exact function symbol. */ static Expression resolve(Loc loc, Scope *sc, Dsymbol s, bool hasOverloads) { static if (LOGSEMANTIC) { printf("DsymbolExp::resolve(%s %s)\n", s.kind(), s.toChars()); } Lagain: Expression e; //printf("DsymbolExp:: %p '%s' is a symbol\n", this, toChars()); //printf("s = '%s', s.kind = '%s'\n", s.toChars(), s.kind()); Dsymbol olds = s; Declaration d = s.isDeclaration(); if (d && (d.storage_class & STCtemplateparameter)) { s = s.toAlias(); } else { if (!s.isFuncDeclaration()) // functions are checked after overloading s.checkDeprecated(loc, sc); // https://issues.dlang.org/show_bug.cgi?id=12023 // if 's' is a tuple variable, the tuple is returned. s = s.toAlias(); //printf("s = '%s', s.kind = '%s', s.needThis() = %p\n", s.toChars(), s.kind(), s.needThis()); if (s != olds && !s.isFuncDeclaration()) s.checkDeprecated(loc, sc); } if (auto em = s.isEnumMember()) { return em.getVarExp(loc, sc); } if (auto v = s.isVarDeclaration()) { //printf("Identifier '%s' is a variable, type '%s'\n", s.toChars(), v.type.toChars()); if (!v.type || // during variable type inference !v.type.deco && v.inuse) // during variable type semantic { if (v.inuse) // variable type depends on the variable itself .error(loc, "circular reference to %s '%s'", v.kind(), v.toPrettyChars()); else // variable type cannot be determined .error(loc, "forward reference to %s '%s'", v.kind(), v.toPrettyChars()); return new ErrorExp(); } if (v.type.ty == Terror) return new ErrorExp(); if ((v.storage_class & STCmanifest) && v._init) { if (v.inuse) { .error(loc, "circular initialization of %s '%s'", v.kind(), v.toPrettyChars()); return new ErrorExp(); } e = v.expandInitializer(loc); v.inuse++; e = e.semantic(sc); v.inuse--; return e; } // Change the ancestor lambdas to delegate before hasThis(sc) call. if (v.checkNestedReference(sc, loc)) return new ErrorExp(); if (v.needThis() && hasThis(sc)) e = new DotVarExp(loc, new ThisExp(loc), v); else e = new VarExp(loc, v); e = e.semantic(sc); return e; } if (auto fld = s.isFuncLiteralDeclaration()) { //printf("'%s' is a function literal\n", fld.toChars()); e = new FuncExp(loc, fld); return e.semantic(sc); } if (auto f = s.isFuncDeclaration()) { f = f.toAliasFunc(); if (!f.functionSemantic()) return new ErrorExp(); if (!hasOverloads && f.checkForwardRef(loc)) return new ErrorExp(); auto fd = s.isFuncDeclaration(); fd.type = f.type; return new VarExp(loc, fd, hasOverloads); } if (OverDeclaration od = s.isOverDeclaration()) { e = new VarExp(loc, od, true); e.type = Type.tvoid; return e; } if (OverloadSet o = s.isOverloadSet()) { //printf("'%s' is an overload set\n", o.toChars()); return new OverExp(loc, o); } if (Import imp = s.isImport()) { if (!imp.pkg) { .error(loc, "forward reference of import %s", imp.toChars()); return new ErrorExp(); } auto ie = new ScopeExp(loc, imp.pkg); return ie.semantic(sc); } if (Package pkg = s.isPackage()) { auto ie = new ScopeExp(loc, pkg); return ie.semantic(sc); } if (Module mod = s.isModule()) { auto ie = new ScopeExp(loc, mod); return ie.semantic(sc); } if (Nspace ns = s.isNspace()) { auto ie = new ScopeExp(loc, ns); return ie.semantic(sc); } if (Type t = s.getType()) { return (new TypeExp(loc, t)).semantic(sc); } if (TupleDeclaration tup = s.isTupleDeclaration()) { if (tup.needThis() && hasThis(sc)) e = new DotVarExp(loc, new ThisExp(loc), tup); else e = new TupleExp(loc, tup); e = e.semantic(sc); return e; } if (TemplateInstance ti = s.isTemplateInstance()) { ti.semantic(sc); if (!ti.inst || ti.errors) return new ErrorExp(); s = ti.toAlias(); if (!s.isTemplateInstance()) goto Lagain; e = new ScopeExp(loc, ti); e = e.semantic(sc); return e; } if (TemplateDeclaration td = s.isTemplateDeclaration()) { Dsymbol p = td.toParent2(); FuncDeclaration fdthis = hasThis(sc); AggregateDeclaration ad = p ? p.isAggregateDeclaration() : null; if (fdthis && ad && isAggregate(fdthis.vthis.type) == ad && (td._scope.stc & STCstatic) == 0) { e = new DotTemplateExp(loc, new ThisExp(loc), td); } else e = new TemplateExp(loc, td); e = e.semantic(sc); return e; } .error(loc, "%s '%s' is not a variable", s.kind(), s.toChars()); return new ErrorExp(); } override bool isLvalue() { return true; } override Expression toLvalue(Scope* sc, Expression e) { return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) class ThisExp : Expression { VarDeclaration var; final extern (D) this(Loc loc) { super(loc, TOKthis, __traits(classInstanceSize, ThisExp)); //printf("ThisExp::ThisExp() loc = %d\n", loc.linnum); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("ThisExp::semantic()\n"); } if (type) return this; FuncDeclaration fd = hasThis(sc); // fd is the uplevel function with the 'this' variable /* Special case for typeof(this) and typeof(super) since both * should work even if they are not inside a non-static member function */ if (!fd && sc.intypeof == 1) { // Find enclosing struct or class for (Dsymbol s = sc.getStructClassScope(); 1; s = s.parent) { if (!s) { error("%s is not in a class or struct scope", toChars()); goto Lerr; } ClassDeclaration cd = s.isClassDeclaration(); if (cd) { type = cd.type; return this; } StructDeclaration sd = s.isStructDeclaration(); if (sd) { type = sd.type; return this; } } } if (!fd) goto Lerr; assert(fd.vthis); var = fd.vthis; assert(var.parent); type = var.type; if (var.checkNestedReference(sc, loc)) return new ErrorExp(); if (!sc.intypeof) sc.callSuper |= CSXthis; return this; Lerr: error("'this' is only defined in non-static member functions, not %s", sc.parent.toChars()); return new ErrorExp(); } override final bool isBool(bool result) { return result ? true : false; } override final bool isLvalue() { // Class `this` should be an rvalue; struct `this` should be an lvalue. return type.toBasetype().ty != Tclass; } override final Expression toLvalue(Scope* sc, Expression e) { if (type.toBasetype().ty == Tclass) { // Class `this` is an rvalue; struct `this` is an lvalue. return Expression.toLvalue(sc, e); } return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class SuperExp : ThisExp { extern (D) this(Loc loc) { super(loc); op = TOKsuper; } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("SuperExp::semantic('%s')\n", toChars()); } if (type) return this; FuncDeclaration fd = hasThis(sc); ClassDeclaration cd; Dsymbol s; /* Special case for typeof(this) and typeof(super) since both * should work even if they are not inside a non-static member function */ if (!fd && sc.intypeof == 1) { // Find enclosing class for (s = sc.getStructClassScope(); 1; s = s.parent) { if (!s) { error("%s is not in a class scope", toChars()); goto Lerr; } cd = s.isClassDeclaration(); if (cd) { cd = cd.baseClass; if (!cd) { error("class %s has no 'super'", s.toChars()); goto Lerr; } type = cd.type; return this; } } } if (!fd) goto Lerr; var = fd.vthis; assert(var && var.parent); s = fd.toParent(); while (s && s.isTemplateInstance()) s = s.toParent(); if (s.isTemplateDeclaration()) // allow inside template constraint s = s.toParent(); assert(s); cd = s.isClassDeclaration(); //printf("parent is %s %s\n", fd.toParent().kind(), fd.toParent().toChars()); if (!cd) goto Lerr; if (!cd.baseClass) { error("no base class for %s", cd.toChars()); type = var.type; } else { type = cd.baseClass.type; type = type.castMod(var.type.mod); } if (var.checkNestedReference(sc, loc)) return new ErrorExp(); if (!sc.intypeof) sc.callSuper |= CSXsuper; return this; Lerr: error("'super' is only allowed in non-static class member functions"); return new ErrorExp(); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class NullExp : Expression { ubyte committed; // !=0 if type is committed extern (D) this(Loc loc, Type type = null) { super(loc, TOKnull, __traits(classInstanceSize, NullExp)); this.type = type; } override bool equals(RootObject o) { if (o && o.dyncast() == DYNCAST.expression) { Expression e = cast(Expression)o; if (e.op == TOKnull && type.equals(e.type)) { return true; } } return false; } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("NullExp::semantic('%s')\n", toChars()); } // NULL is the same as (void *)0 if (type) return this; type = Type.tnull; return this; } override bool isBool(bool result) { return result ? false : true; } override StringExp toStringExp() { if (implicitConvTo(Type.tstring)) { auto se = new StringExp(loc, cast(char*)mem.xcalloc(1, 1), 0); se.type = Type.tstring; return se; } return null; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class StringExp : Expression { union { char* string; // if sz == 1 wchar* wstring; // if sz == 2 dchar* dstring; // if sz == 4 } // (const if ownedByCtfe == OWNEDcode) size_t len; // number of code units ubyte sz = 1; // 1: char, 2: wchar, 4: dchar ubyte committed; // !=0 if type is committed char postfix = 0; // 'c', 'w', 'd' OwnedBy ownedByCtfe = OWNEDcode; extern (D) this(Loc loc, char* string) { super(loc, TOKstring, __traits(classInstanceSize, StringExp)); this.string = string; this.len = strlen(string); this.sz = 1; // work around LDC bug #1286 } extern (D) this(Loc loc, void* string, size_t len) { super(loc, TOKstring, __traits(classInstanceSize, StringExp)); this.string = cast(char*)string; this.len = len; this.sz = 1; // work around LDC bug #1286 } extern (D) this(Loc loc, void* string, size_t len, char postfix) { super(loc, TOKstring, __traits(classInstanceSize, StringExp)); this.string = cast(char*)string; this.len = len; this.postfix = postfix; this.sz = 1; // work around LDC bug #1286 } static StringExp create(Loc loc, char* s) { return new StringExp(loc, s); } override bool equals(RootObject o) { //printf("StringExp::equals('%s') %s\n", o.toChars(), toChars()); if (o && o.dyncast() == DYNCAST.expression) { Expression e = cast(Expression)o; if (e.op == TOKstring) { return compare(o) == 0; } } return false; } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("StringExp::semantic() %s\n", toChars()); } if (type) return this; OutBuffer buffer; size_t newlen = 0; const(char)* p; size_t u; dchar c; switch (postfix) { case 'd': for (u = 0; u < len;) { p = utf_decodeChar(string, len, u, c); if (p) { error("%s", p); return new ErrorExp(); } else { buffer.write4(c); newlen++; } } buffer.write4(0); dstring = cast(dchar*)buffer.extractData(); len = newlen; sz = 4; type = new TypeDArray(Type.tdchar.immutableOf()); committed = 1; break; case 'w': for (u = 0; u < len;) { p = utf_decodeChar(string, len, u, c); if (p) { error("%s", p); return new ErrorExp(); } else { buffer.writeUTF16(c); newlen++; if (c >= 0x10000) newlen++; } } buffer.writeUTF16(0); wstring = cast(wchar*)buffer.extractData(); len = newlen; sz = 2; type = new TypeDArray(Type.twchar.immutableOf()); committed = 1; break; case 'c': committed = 1; goto default; default: type = new TypeDArray(Type.tchar.immutableOf()); break; } type = type.semantic(loc, sc); //type = type.immutableOf(); //printf("type = %s\n", type.toChars()); return this; } /********************************** * Return the number of code units the string would be if it were re-encoded * as tynto. * Params: * tynto = code unit type of the target encoding * Returns: * number of code units */ final size_t numberOfCodeUnits(int tynto = 0) const { int encSize; switch (tynto) { case 0: return len; case Tchar: encSize = 1; break; case Twchar: encSize = 2; break; case Tdchar: encSize = 4; break; default: assert(0); } if (sz == encSize) return len; size_t result = 0; dchar c; switch (sz) { case 1: for (size_t u = 0; u < len;) { if (const p = utf_decodeChar(string, len, u, c)) { error("%s", p); return 0; } result += utf_codeLength(encSize, c); } break; case 2: for (size_t u = 0; u < len;) { if (const p = utf_decodeWchar(wstring, len, u, c)) { error("%s", p); return 0; } result += utf_codeLength(encSize, c); } break; case 4: foreach (u; 0 .. len) { result += utf_codeLength(encSize, dstring[u]); } break; default: assert(0); } return result; } /********************************************** * Write the contents of the string to dest. * Use numberOfCodeUnits() to determine size of result. * Params: * dest = destination * tyto = encoding type of the result * zero = add terminating 0 */ void writeTo(void* dest, bool zero, int tyto = 0) const { int encSize; switch (tyto) { case 0: encSize = sz; break; case Tchar: encSize = 1; break; case Twchar: encSize = 2; break; case Tdchar: encSize = 4; break; default: assert(0); } if (sz == encSize) { memcpy(dest, string, len * sz); if (zero) memset(dest + len * sz, 0, sz); } else assert(0); } /********************************************* * Get the code unit at index i * Params: * i = index * Returns: * code unit at index i */ final dchar getCodeUnit(size_t i) const pure { assert(i < len); final switch (sz) { case 1: return string[i]; case 2: return wstring[i]; case 4: return dstring[i]; } } /********************************************* * Set the code unit at index i to c * Params: * i = index * c = code unit to set it to */ final void setCodeUnit(size_t i, dchar c) { assert(i < len); final switch (sz) { case 1: string[i] = cast(char)c; break; case 2: wstring[i] = cast(wchar)c; break; case 4: dstring[i] = c; break; } } /************************************************** * If the string data is UTF-8 and can be accessed directly, * return a pointer to it. * Do not assume a terminating 0. * Returns: * pointer to string data if possible, null if not */ char* toPtr() { return (sz == 1) ? string : null; } override StringExp toStringExp() { return this; } /**************************************** * Convert string to char[]. */ StringExp toUTF8(Scope* sc) { if (sz != 1) { // Convert to UTF-8 string committed = 0; Expression e = castTo(sc, Type.tchar.arrayOf()); e = e.optimize(WANTvalue); assert(e.op == TOKstring); StringExp se = cast(StringExp)e; assert(se.sz == 1); return se; } return this; } override int compare(RootObject obj) { //printf("StringExp::compare()\n"); // Used to sort case statement expressions so we can do an efficient lookup StringExp se2 = cast(StringExp)obj; // This is a kludge so isExpression() in template.c will return 5 // for StringExp's. if (!se2) return 5; assert(se2.op == TOKstring); size_t len1 = len; size_t len2 = se2.len; //printf("sz = %d, len1 = %d, len2 = %d\n", sz, (int)len1, (int)len2); if (len1 == len2) { switch (sz) { case 1: return memcmp(string, se2.string, len1); case 2: { wchar* s1 = cast(wchar*)string; wchar* s2 = cast(wchar*)se2.string; for (size_t u = 0; u < len; u++) { if (s1[u] != s2[u]) return s1[u] - s2[u]; } } break; case 4: { dchar* s1 = cast(dchar*)string; dchar* s2 = cast(dchar*)se2.string; for (size_t u = 0; u < len; u++) { if (s1[u] != s2[u]) return s1[u] - s2[u]; } } break; default: assert(0); } } return cast(int)(len1 - len2); } override bool isBool(bool result) { return result ? true : false; } override bool isLvalue() { /* string literal is rvalue in default, but * conversion to reference of static array is only allowed. */ return (type && type.toBasetype().ty == Tsarray); } override Expression toLvalue(Scope* sc, Expression e) { //printf("StringExp::toLvalue(%s) type = %s\n", toChars(), type ? type.toChars() : NULL); return (type && type.toBasetype().ty == Tsarray) ? this : Expression.toLvalue(sc, e); } override Expression modifiableLvalue(Scope* sc, Expression e) { error("cannot modify string literal %s", toChars()); return new ErrorExp(); } uint charAt(uinteger_t i) const { uint value; switch (sz) { case 1: value = (cast(char*)string)[cast(size_t)i]; break; case 2: value = (cast(ushort*)string)[cast(size_t)i]; break; case 4: value = (cast(uint*)string)[cast(size_t)i]; break; default: assert(0); } return value; } /******************************** * Convert string contents to a 0 terminated string, * allocated by mem.xmalloc(). */ extern (D) final const(char)[] toStringz() const { auto nbytes = len * sz; char* s = cast(char*)mem.xmalloc(nbytes + sz); writeTo(s, true); return s[0 .. nbytes]; } extern (D) const(char)[] peekSlice() const { assert(sz == 1); return this.string[0 .. len]; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class TupleExp : Expression { /* Tuple-field access may need to take out its side effect part. * For example: * foo().tupleof * is rewritten as: * (ref __tup = foo(); tuple(__tup.field0, __tup.field1, ...)) * The declaration of temporary variable __tup will be stored in TupleExp.e0. */ Expression e0; Expressions* exps; extern (D) this(Loc loc, Expression e0, Expressions* exps) { super(loc, TOKtuple, __traits(classInstanceSize, TupleExp)); //printf("TupleExp(this = %p)\n", this); this.e0 = e0; this.exps = exps; } extern (D) this(Loc loc, Expressions* exps) { super(loc, TOKtuple, __traits(classInstanceSize, TupleExp)); //printf("TupleExp(this = %p)\n", this); this.exps = exps; } extern (D) this(Loc loc, TupleDeclaration tup) { super(loc, TOKtuple, __traits(classInstanceSize, TupleExp)); this.exps = new Expressions(); this.exps.reserve(tup.objects.dim); for (size_t i = 0; i < tup.objects.dim; i++) { RootObject o = (*tup.objects)[i]; if (Dsymbol s = getDsymbol(o)) { /* If tuple element represents a symbol, translate to DsymbolExp * to supply implicit 'this' if needed later. */ Expression e = new DsymbolExp(loc, s); this.exps.push(e); } else if (o.dyncast() == DYNCAST.expression) { auto e = (cast(Expression)o).copy(); e.loc = loc; // https://issues.dlang.org/show_bug.cgi?id=15669 this.exps.push(e); } else if (o.dyncast() == DYNCAST.type) { Type t = cast(Type)o; Expression e = new TypeExp(loc, t); this.exps.push(e); } else { error("%s is not an expression", o.toChars()); } } } override Expression syntaxCopy() { return new TupleExp(loc, e0 ? e0.syntaxCopy() : null, arraySyntaxCopy(exps)); } override bool equals(RootObject o) { if (this == o) return true; if ((cast(Expression)o).op == TOKtuple) { TupleExp te = cast(TupleExp)o; if (exps.dim != te.exps.dim) return false; if (e0 && !e0.equals(te.e0) || !e0 && te.e0) return false; for (size_t i = 0; i < exps.dim; i++) { Expression e1 = (*exps)[i]; Expression e2 = (*te.exps)[i]; if (!e1.equals(e2)) return false; } return true; } return false; } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("+TupleExp::semantic(%s)\n", toChars()); } if (type) return this; if (e0) e0 = e0.semantic(sc); // Run semantic() on each argument bool err = false; for (size_t i = 0; i < exps.dim; i++) { Expression e = (*exps)[i]; e = e.semantic(sc); if (!e.type) { error("%s has no value", e.toChars()); err = true; } else if (e.op == TOKerror) err = true; else (*exps)[i] = e; } if (err) return new ErrorExp(); expandTuples(exps); type = new TypeTuple(exps); type = type.semantic(loc, sc); //printf("-TupleExp::semantic(%s)\n", toChars()); return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * [ e1, e2, e3, ... ] */ extern (C++) final class ArrayLiteralExp : Expression { /** If !is null, elements[] can be sparse and basis is used for the * "default" element value. In other words, non-null elements[i] overrides * this 'basis' value. */ Expression basis; Expressions* elements; OwnedBy ownedByCtfe = OWNEDcode; extern (D) this(Loc loc, Expressions* elements) { super(loc, TOKarrayliteral, __traits(classInstanceSize, ArrayLiteralExp)); this.elements = elements; } extern (D) this(Loc loc, Expression e) { super(loc, TOKarrayliteral, __traits(classInstanceSize, ArrayLiteralExp)); elements = new Expressions(); elements.push(e); } extern (D) this(Loc loc, Expression basis, Expressions* elements) { super(loc, TOKarrayliteral, __traits(classInstanceSize, ArrayLiteralExp)); this.basis = basis; this.elements = elements; } override Expression syntaxCopy() { return new ArrayLiteralExp(loc, basis ? basis.syntaxCopy() : null, arraySyntaxCopy(elements)); } override bool equals(RootObject o) { if (this == o) return true; if (o && o.dyncast() == DYNCAST.expression && (cast(Expression)o).op == TOKarrayliteral) { ArrayLiteralExp ae = cast(ArrayLiteralExp)o; if (elements.dim != ae.elements.dim) return false; if (elements.dim == 0 && !type.equals(ae.type)) { return false; } for (size_t i = 0; i < elements.dim; i++) { Expression e1 = (*elements)[i]; Expression e2 = (*ae.elements)[i]; if (!e1) e1 = basis; if (!e2) e2 = ae.basis; if (e1 != e2 && (!e1 || !e2 || !e1.equals(e2))) return false; } return true; } return false; } final Expression getElement(size_t i) { auto el = (*elements)[i]; if (!el) el = basis; return el; } /** Copy element `Expressions` in the parameters when they're `ArrayLiteralExp`s. * Params: * e1 = If it's ArrayLiteralExp, its `elements` will be copied. * Otherwise, `e1` itself will be pushed into the new `Expressions`. * e2 = If it's not `null`, it will be pushed/appended to the new * `Expressions` by the same way with `e1`. * Returns: * Newly allocated `Expressions`. Note that it points to the original * `Expression` values in e1 and e2. */ static Expressions* copyElements(Expression e1, Expression e2 = null) { auto elems = new Expressions(); void append(ArrayLiteralExp ale) { if (!ale.elements) return; auto d = elems.dim; elems.append(ale.elements); foreach (ref el; (*elems)[][d .. elems.dim]) { if (!el) el = ale.basis; } } if (e1.op == TOKarrayliteral) append(cast(ArrayLiteralExp)e1); else elems.push(e1); if (e2) { if (e2.op == TOKarrayliteral) append(cast(ArrayLiteralExp)e2); else elems.push(e2); } return elems; } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("ArrayLiteralExp::semantic('%s')\n", toChars()); } if (type) return this; /* Perhaps an empty array literal [ ] should be rewritten as null? */ if (basis) basis = basis.semantic(sc); if (arrayExpressionSemantic(elements, sc) || (basis && basis.op == TOKerror)) return new ErrorExp(); expandTuples(elements); Type t0; if (basis) elements.push(basis); bool err = arrayExpressionToCommonType(sc, elements, &t0); if (basis) basis = elements.pop(); if (err) return new ErrorExp(); type = t0.arrayOf(); type = type.semantic(loc, sc); /* Disallow array literals of type void being used. */ if (elements.dim > 0 && t0.ty == Tvoid) { error("%s of type %s has no value", toChars(), type.toChars()); return new ErrorExp(); } semanticTypeInfo(sc, type); return this; } override bool isBool(bool result) { size_t dim = elements ? elements.dim : 0; return result ? (dim != 0) : (dim == 0); } override StringExp toStringExp() { TY telem = type.nextOf().toBasetype().ty; if (telem == Tchar || telem == Twchar || telem == Tdchar || (telem == Tvoid && (!elements || elements.dim == 0))) { ubyte sz = 1; if (telem == Twchar) sz = 2; else if (telem == Tdchar) sz = 4; OutBuffer buf; if (elements) { for (size_t i = 0; i < elements.dim; ++i) { auto ch = getElement(i); if (ch.op != TOKint64) return null; if (sz == 1) buf.writeByte(cast(uint)ch.toInteger()); else if (sz == 2) buf.writeword(cast(uint)ch.toInteger()); else buf.write4(cast(uint)ch.toInteger()); } } char prefix; if (sz == 1) { prefix = 'c'; buf.writeByte(0); } else if (sz == 2) { prefix = 'w'; buf.writeword(0); } else { prefix = 'd'; buf.write4(0); } const(size_t) len = buf.offset / sz - 1; auto se = new StringExp(loc, buf.extractData(), len, prefix); se.sz = sz; se.type = type; return se; } return null; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * [ key0 : value0, key1 : value1, ... ] */ extern (C++) final class AssocArrayLiteralExp : Expression { Expressions* keys; Expressions* values; OwnedBy ownedByCtfe = OWNEDcode; extern (D) this(Loc loc, Expressions* keys, Expressions* values) { super(loc, TOKassocarrayliteral, __traits(classInstanceSize, AssocArrayLiteralExp)); assert(keys.dim == values.dim); this.keys = keys; this.values = values; } override bool equals(RootObject o) { if (this == o) return true; if (o && o.dyncast() == DYNCAST.expression && (cast(Expression)o).op == TOKassocarrayliteral) { AssocArrayLiteralExp ae = cast(AssocArrayLiteralExp)o; if (keys.dim != ae.keys.dim) return false; size_t count = 0; for (size_t i = 0; i < keys.dim; i++) { for (size_t j = 0; j < ae.keys.dim; j++) { if ((*keys)[i].equals((*ae.keys)[j])) { if (!(*values)[i].equals((*ae.values)[j])) return false; ++count; } } } return count == keys.dim; } return false; } override Expression syntaxCopy() { return new AssocArrayLiteralExp(loc, arraySyntaxCopy(keys), arraySyntaxCopy(values)); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("AssocArrayLiteralExp::semantic('%s')\n", toChars()); } if (type) return this; // Run semantic() on each element bool err_keys = arrayExpressionSemantic(keys, sc); bool err_vals = arrayExpressionSemantic(values, sc); if (err_keys || err_vals) return new ErrorExp(); expandTuples(keys); expandTuples(values); if (keys.dim != values.dim) { error("number of keys is %u, must match number of values %u", keys.dim, values.dim); return new ErrorExp(); } Type tkey = null; Type tvalue = null; err_keys = arrayExpressionToCommonType(sc, keys, &tkey); err_vals = arrayExpressionToCommonType(sc, values, &tvalue); if (err_keys || err_vals) return new ErrorExp(); if (tkey == Type.terror || tvalue == Type.terror) return new ErrorExp(); type = new TypeAArray(tvalue, tkey); type = type.semantic(loc, sc); semanticTypeInfo(sc, type); return this; } override bool isBool(bool result) { size_t dim = keys.dim; return result ? (dim != 0) : (dim == 0); } override void accept(Visitor v) { v.visit(this); } } enum stageScrub = 0x1; /// scrubReturnValue is running enum stageSearchPointers = 0x2; /// hasNonConstPointers is running enum stageOptimize = 0x4; /// optimize is running enum stageApply = 0x8; /// apply is running enum stageInlineScan = 0x10; /// inlineScan is running enum stageToCBuffer = 0x20; /// toCBuffer is running /*********************************************************** * sd( e1, e2, e3, ... ) */ extern (C++) final class StructLiteralExp : Expression { StructDeclaration sd; /// which aggregate this is for Expressions* elements; /// parallels sd.fields[] with null entries for fields to skip Type stype; /// final type of result (can be different from sd's type) bool useStaticInit; /// if this is true, use the StructDeclaration's init symbol Symbol* sym; /// back end symbol to initialize with literal OwnedBy ownedByCtfe = OWNEDcode; /** pointer to the origin instance of the expression. * once a new expression is created, origin is set to 'this'. * anytime when an expression copy is created, 'origin' pointer is set to * 'origin' pointer value of the original expression. */ StructLiteralExp origin; /// those fields need to prevent a infinite recursion when one field of struct initialized with 'this' pointer. StructLiteralExp inlinecopy; /** anytime when recursive function is calling, 'stageflags' marks with bit flag of * current stage and unmarks before return from this function. * 'inlinecopy' uses similar 'stageflags' and from multiple evaluation 'doInline' * (with infinite recursion) of this expression. */ int stageflags; extern (D) this(Loc loc, StructDeclaration sd, Expressions* elements, Type stype = null) { super(loc, TOKstructliteral, __traits(classInstanceSize, StructLiteralExp)); this.sd = sd; if (!elements) elements = new Expressions(); this.elements = elements; this.stype = stype; this.origin = this; //printf("StructLiteralExp::StructLiteralExp(%s)\n", toChars()); } static StructLiteralExp create(Loc loc, StructDeclaration sd, void* elements, Type stype = null) { return new StructLiteralExp(loc, sd, cast(Expressions*)elements, stype); } override bool equals(RootObject o) { if (this == o) return true; if (o && o.dyncast() == DYNCAST.expression && (cast(Expression)o).op == TOKstructliteral) { StructLiteralExp se = cast(StructLiteralExp)o; if (!type.equals(se.type)) return false; if (elements.dim != se.elements.dim) return false; for (size_t i = 0; i < elements.dim; i++) { Expression e1 = (*elements)[i]; Expression e2 = (*se.elements)[i]; if (e1 != e2 && (!e1 || !e2 || !e1.equals(e2))) return false; } return true; } return false; } override Expression syntaxCopy() { auto exp = new StructLiteralExp(loc, sd, arraySyntaxCopy(elements), type ? type : stype); exp.origin = this; return exp; } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("StructLiteralExp::semantic('%s')\n", toChars()); } if (type) return this; sd.size(loc); if (sd.sizeok != SIZEOKdone) return new ErrorExp(); if (arrayExpressionSemantic(elements, sc)) // run semantic() on each element return new ErrorExp(); expandTuples(elements); /* Fit elements[] to the corresponding type of field[]. */ if (!sd.fit(loc, sc, elements, stype)) return new ErrorExp(); /* Fill out remainder of elements[] with default initializers for fields[] */ if (!sd.fill(loc, elements, false)) { /* An error in the initializer needs to be recorded as an error * in the enclosing function or template, since the initializer * will be part of the stuct declaration. */ global.increaseErrorCount(); return new ErrorExp(); } if (checkFrameAccess(loc, sc, sd, elements.dim)) return new ErrorExp(); type = stype ? stype : sd.type; return this; } /************************************** * Gets expression at offset of type. * Returns NULL if not found. */ Expression getField(Type type, uint offset) { //printf("StructLiteralExp::getField(this = %s, type = %s, offset = %u)\n", // /*toChars()*/"", type.toChars(), offset); Expression e = null; int i = getFieldIndex(type, offset); if (i != -1) { //printf("\ti = %d\n", i); if (i == sd.fields.dim - 1 && sd.isNested()) return null; assert(i < elements.dim); e = (*elements)[i]; if (e) { //printf("e = %s, e.type = %s\n", e.toChars(), e.type.toChars()); /* If type is a static array, and e is an initializer for that array, * then the field initializer should be an array literal of e. */ if (e.type.castMod(0) != type.castMod(0) && type.ty == Tsarray) { TypeSArray tsa = cast(TypeSArray)type; size_t length = cast(size_t)tsa.dim.toInteger(); auto z = new Expressions(); z.setDim(length); for (size_t q = 0; q < length; ++q) (*z)[q] = e.copy(); e = new ArrayLiteralExp(loc, z); e.type = type; } else { e = e.copy(); e.type = type; } if (useStaticInit && e.op == TOKstructliteral && e.type.needsNested()) { StructLiteralExp se = cast(StructLiteralExp)e; se.useStaticInit = true; } } } return e; } /************************************ * Get index of field. * Returns -1 if not found. */ int getFieldIndex(Type type, uint offset) { /* Find which field offset is by looking at the field offsets */ if (elements.dim) { for (size_t i = 0; i < sd.fields.dim; i++) { VarDeclaration v = sd.fields[i]; if (offset == v.offset && type.size() == v.type.size()) { /* context field might not be filled. */ if (i == sd.fields.dim - 1 && sd.isNested()) return cast(int)i; Expression e = (*elements)[i]; if (e) { return cast(int)i; } break; } } } return -1; } override Expression addDtorHook(Scope* sc) { /* If struct requires a destructor, rewrite as: * (S tmp = S()),tmp * so that the destructor can be hung on tmp. */ if (sd.dtor && sc.func) { /* Make an identifier for the temporary of the form: * __sl%s%d, where %s is the struct name */ const(size_t) len = 10; char[len + 1] buf; buf[len] = 0; strcpy(buf.ptr, "__sl"); strncat(buf.ptr, sd.ident.toChars(), len - 4 - 1); assert(buf[len] == 0); auto tmp = copyToTemp(0, buf.ptr, this); Expression ae = new DeclarationExp(loc, tmp); Expression e = new CommaExp(loc, ae, new VarExp(loc, tmp)); e = e.semantic(sc); return e; } return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * Mainly just a placeholder */ extern (C++) final class TypeExp : Expression { extern (D) this(Loc loc, Type type) { super(loc, TOKtype, __traits(classInstanceSize, TypeExp)); //printf("TypeExp::TypeExp(%s)\n", type.toChars()); this.type = type; } override Expression syntaxCopy() { return new TypeExp(loc, type.syntaxCopy()); } override Expression semantic(Scope* sc) { if (type.ty == Terror) return new ErrorExp(); //printf("TypeExp::semantic(%s)\n", type.toChars()); Expression e; Type t; Dsymbol s; type.resolve(loc, sc, &e, &t, &s, true); if (e) { //printf("e = %s %s\n", Token::toChars(e.op), e.toChars()); e = e.semantic(sc); } else if (t) { //printf("t = %d %s\n", t.ty, t.toChars()); type = t.semantic(loc, sc); e = this; } else if (s) { //printf("s = %s %s\n", s.kind(), s.toChars()); e = DsymbolExp.resolve(loc, sc, s, true); } else assert(0); if (global.params.vcomplex) type.checkComplexTransition(loc); return e; } override bool checkType() { error("type %s is not an expression", toChars()); return true; } override bool checkValue() { error("type %s has no value", toChars()); return true; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * Mainly just a placeholder of * Package, Module, Nspace, and TemplateInstance (including TemplateMixin) * * A template instance that requires IFTI: * foo!tiargs(fargs) // foo!tiargs * is left until CallExp::semantic() or resolveProperties() */ extern (C++) final class ScopeExp : Expression { ScopeDsymbol sds; extern (D) this(Loc loc, ScopeDsymbol sds) { super(loc, TOKscope, __traits(classInstanceSize, ScopeExp)); //printf("ScopeExp::ScopeExp(sds = '%s')\n", sds.toChars()); //static int count; if (++count == 38) *(char*)0=0; this.sds = sds; assert(!sds.isTemplateDeclaration()); // instead, you should use TemplateExp } override Expression syntaxCopy() { return new ScopeExp(loc, cast(ScopeDsymbol)sds.syntaxCopy(null)); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("+ScopeExp::semantic(%p '%s')\n", this, toChars()); } if (type) return this; ScopeDsymbol sds2 = sds; TemplateInstance ti = sds2.isTemplateInstance(); while (ti) { WithScopeSymbol withsym; if (!ti.findTempDecl(sc, &withsym) || !ti.semanticTiargs(sc)) { return new ErrorExp(); } if (withsym && withsym.withstate.wthis) { Expression e = new VarExp(loc, withsym.withstate.wthis); e = new DotTemplateInstanceExp(loc, e, ti); return e.semantic(sc); } if (ti.needsTypeInference(sc)) { if (TemplateDeclaration td = ti.tempdecl.isTemplateDeclaration()) { Dsymbol p = td.toParent2(); FuncDeclaration fdthis = hasThis(sc); AggregateDeclaration ad = p ? p.isAggregateDeclaration() : null; if (fdthis && ad && isAggregate(fdthis.vthis.type) == ad && (td._scope.stc & STCstatic) == 0) { Expression e = new DotTemplateInstanceExp(loc, new ThisExp(loc), ti.name, ti.tiargs); return e.semantic(sc); } } else if (OverloadSet os = ti.tempdecl.isOverloadSet()) { FuncDeclaration fdthis = hasThis(sc); AggregateDeclaration ad = os.parent.isAggregateDeclaration(); if (fdthis && ad && isAggregate(fdthis.vthis.type) == ad) { Expression e = new DotTemplateInstanceExp(loc, new ThisExp(loc), ti.name, ti.tiargs); return e.semantic(sc); } } // ti is an instance which requires IFTI. sds = ti; type = Type.tvoid; return this; } ti.semantic(sc); if (!ti.inst || ti.errors) return new ErrorExp(); Dsymbol s = ti.toAlias(); if (s == ti) { sds = ti; type = Type.tvoid; return this; } sds2 = s.isScopeDsymbol(); if (sds2) { ti = sds2.isTemplateInstance(); //printf("+ sds2 = %s, '%s'\n", sds2.kind(), sds2.toChars()); continue; } if (auto v = s.isVarDeclaration()) { if (!v.type) { error("forward reference of %s %s", v.kind(), v.toChars()); return new ErrorExp(); } if ((v.storage_class & STCmanifest) && v._init) { /* When an instance that will be converted to a constant exists, * the instance representation "foo!tiargs" is treated like a * variable name, and its recursive appearance check (note that * it's equivalent with a recursive instantiation of foo) is done * separately from the circular initialization check for the * eponymous enum variable declaration. * * template foo(T) { * enum bool foo = foo; // recursive definition check (v.inuse) * } * template bar(T) { * enum bool bar = bar!T; // recursive instantiation check (ti.inuse) * } */ if (ti.inuse) { error("recursive expansion of %s '%s'", ti.kind(), ti.toPrettyChars()); return new ErrorExp(); } auto e = v.expandInitializer(loc); ti.inuse++; e = e.semantic(sc); ti.inuse--; return e; } } //printf("s = %s, '%s'\n", s.kind(), s.toChars()); auto e = DsymbolExp.resolve(loc, sc, s, true); //printf("-1ScopeExp::semantic()\n"); return e; } //printf("sds2 = %s, '%s'\n", sds2.kind(), sds2.toChars()); //printf("\tparent = '%s'\n", sds2.parent.toChars()); sds2.semantic(sc); if (auto t = sds2.getType()) // (Aggregate|Enum)Declaration return (new TypeExp(loc, t)).semantic(sc); if (auto td = sds2.isTemplateDeclaration()) return (new TemplateExp(loc, td)).semantic(sc); sds = sds2; type = Type.tvoid; //printf("-2ScopeExp::semantic() %s\n", toChars()); return this; } override bool checkType() { if (sds.isPackage()) { error("%s %s has no type", sds.kind(), sds.toChars()); return true; } if (auto ti = sds.isTemplateInstance()) { //assert(ti.needsTypeInference(sc)); if (ti.tempdecl && ti.semantictiargsdone && ti.semanticRun == PASSinit) { error("partial %s %s has no type", sds.kind(), toChars()); return true; } } return false; } override bool checkValue() { error("%s %s has no value", sds.kind(), sds.toChars()); return true; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * Mainly just a placeholder */ extern (C++) final class TemplateExp : Expression { TemplateDeclaration td; FuncDeclaration fd; extern (D) this(Loc loc, TemplateDeclaration td, FuncDeclaration fd = null) { super(loc, TOKtemplate, __traits(classInstanceSize, TemplateExp)); //printf("TemplateExp(): %s\n", td.toChars()); this.td = td; this.fd = fd; } override bool isLvalue() { return fd !is null; } override Expression toLvalue(Scope* sc, Expression e) { if (!fd) return Expression.toLvalue(sc, e); assert(sc); return DsymbolExp.resolve(loc, sc, fd, true); } override bool checkType() { error("%s %s has no type", td.kind(), toChars()); return true; } override bool checkValue() { error("%s %s has no value", td.kind(), toChars()); return true; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * thisexp.new(newargs) newtype(arguments) */ extern (C++) final class NewExp : Expression { Expression thisexp; // if !=null, 'this' for class being allocated Expressions* newargs; // Array of Expression's to call new operator Type newtype; Expressions* arguments; // Array of Expression's Expression argprefix; // expression to be evaluated just before arguments[] CtorDeclaration member; // constructor function NewDeclaration allocator; // allocator function int onstack; // allocate on stack extern (D) this(Loc loc, Expression thisexp, Expressions* newargs, Type newtype, Expressions* arguments) { super(loc, TOKnew, __traits(classInstanceSize, NewExp)); this.thisexp = thisexp; this.newargs = newargs; this.newtype = newtype; this.arguments = arguments; } override Expression syntaxCopy() { return new NewExp(loc, thisexp ? thisexp.syntaxCopy() : null, arraySyntaxCopy(newargs), newtype.syntaxCopy(), arraySyntaxCopy(arguments)); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("NewExp::semantic() %s\n", toChars()); if (thisexp) printf("\tthisexp = %s\n", thisexp.toChars()); printf("\tnewtype: %s\n", newtype.toChars()); } if (type) // if semantic() already run return this; // https://issues.dlang.org/show_bug.cgi?id=11581 // With the syntax `new T[edim]` or `thisexp.new T[edim]`, // T should be analyzed first and edim should go into arguments iff it's // not a tuple. Expression edim = null; if (!arguments && newtype.ty == Tsarray) { edim = (cast(TypeSArray)newtype).dim; newtype = (cast(TypeNext)newtype).next; } ClassDeclaration cdthis = null; if (thisexp) { thisexp = thisexp.semantic(sc); if (thisexp.op == TOKerror) return new ErrorExp(); cdthis = thisexp.type.isClassHandle(); if (!cdthis) { error("'this' for nested class must be a class type, not %s", thisexp.type.toChars()); return new ErrorExp(); } sc = sc.push(cdthis); type = newtype.semantic(loc, sc); sc = sc.pop(); } else { type = newtype.semantic(loc, sc); } if (type.ty == Terror) return new ErrorExp(); if (edim) { if (type.toBasetype().ty == Ttuple) { // --> new T[edim] type = new TypeSArray(type, edim); type = type.semantic(loc, sc); if (type.ty == Terror) return new ErrorExp(); } else { // --> new T[](edim) arguments = new Expressions(); arguments.push(edim); type = type.arrayOf(); } } newtype = type; // in case type gets cast to something else Type tb = type.toBasetype(); //printf("tb: %s, deco = %s\n", tb.toChars(), tb.deco); if (arrayExpressionSemantic(newargs, sc) || preFunctionParameters(loc, sc, newargs)) { return new ErrorExp(); } if (arrayExpressionSemantic(arguments, sc) || preFunctionParameters(loc, sc, arguments)) { return new ErrorExp(); } if (thisexp && tb.ty != Tclass) { error("e.new is only for allocating nested classes, not %s", tb.toChars()); return new ErrorExp(); } size_t nargs = arguments ? arguments.dim : 0; Expression newprefix = null; if (tb.ty == Tclass) { auto cd = (cast(TypeClass)tb).sym; cd.size(loc); if (cd.sizeok != SIZEOKdone) return new ErrorExp(); if (!cd.ctor) cd.ctor = cd.searchCtor(); if (cd.noDefaultCtor && !nargs && !cd.defaultCtor) { error("default construction is disabled for type %s", cd.type.toChars()); return new ErrorExp(); } if (cd.isInterfaceDeclaration()) { error("cannot create instance of interface %s", cd.toChars()); return new ErrorExp(); } if (cd.isAbstract()) { error("cannot create instance of abstract class %s", cd.toChars()); for (size_t i = 0; i < cd.vtbl.dim; i++) { FuncDeclaration fd = cd.vtbl[i].isFuncDeclaration(); if (fd && fd.isAbstract()) { errorSupplemental(loc, "function '%s' is not implemented", fd.toFullSignature()); } } return new ErrorExp(); } // checkDeprecated() is already done in newtype.semantic(). if (cd.isNested()) { /* We need a 'this' pointer for the nested class. * Ensure we have the right one. */ Dsymbol s = cd.toParent2(); //printf("cd isNested, parent = %s '%s'\n", s.kind(), s.toPrettyChars()); if (auto cdn = s.isClassDeclaration()) { if (!cdthis) { // Supply an implicit 'this' and try again thisexp = new ThisExp(loc); for (Dsymbol sp = sc.parent; 1; sp = sp.parent) { if (!sp) { error("outer class %s 'this' needed to 'new' nested class %s", cdn.toChars(), cd.toChars()); return new ErrorExp(); } ClassDeclaration cdp = sp.isClassDeclaration(); if (!cdp) continue; if (cdp == cdn || cdn.isBaseOf(cdp, null)) break; // Add a '.outer' and try again thisexp = new DotIdExp(loc, thisexp, Id.outer); } thisexp = thisexp.semantic(sc); if (thisexp.op == TOKerror) return new ErrorExp(); cdthis = thisexp.type.isClassHandle(); } if (cdthis != cdn && !cdn.isBaseOf(cdthis, null)) { //printf("cdthis = %s\n", cdthis.toChars()); error("'this' for nested class must be of type %s, not %s", cdn.toChars(), thisexp.type.toChars()); return new ErrorExp(); } if (!MODimplicitConv(thisexp.type.mod, newtype.mod)) { error("nested type %s should have the same or weaker constancy as enclosing type %s", newtype.toChars(), thisexp.type.toChars()); return new ErrorExp(); } } else if (thisexp) { error("e.new is only for allocating nested classes"); return new ErrorExp(); } else if (auto fdn = s.isFuncDeclaration()) { // make sure the parent context fdn of cd is reachable from sc if (!ensureStaticLinkTo(sc.parent, fdn)) { error("outer function context of %s is needed to 'new' nested class %s", fdn.toPrettyChars(), cd.toPrettyChars()); return new ErrorExp(); } } else assert(0); } else if (thisexp) { error("e.new is only for allocating nested classes"); return new ErrorExp(); } if (cd.aggNew) { // Prepend the size argument to newargs[] Expression e = new IntegerExp(loc, cd.size(loc), Type.tsize_t); if (!newargs) newargs = new Expressions(); newargs.shift(e); FuncDeclaration f = resolveFuncCall(loc, sc, cd.aggNew, null, tb, newargs); if (!f || f.errors) return new ErrorExp(); checkDeprecated(sc, f); checkPurity(sc, f); checkSafety(sc, f); checkNogc(sc, f); checkAccess(cd, loc, sc, f); TypeFunction tf = cast(TypeFunction)f.type; Type rettype; if (functionParameters(loc, sc, tf, null, newargs, f, &rettype, &newprefix)) return new ErrorExp(); allocator = f.isNewDeclaration(); assert(allocator); } else { if (newargs && newargs.dim) { error("no allocator for %s", cd.toChars()); return new ErrorExp(); } } if (cd.ctor) { FuncDeclaration f = resolveFuncCall(loc, sc, cd.ctor, null, tb, arguments, 0); if (!f || f.errors) return new ErrorExp(); checkDeprecated(sc, f); checkPurity(sc, f); checkSafety(sc, f); checkNogc(sc, f); checkAccess(cd, loc, sc, f); TypeFunction tf = cast(TypeFunction)f.type; if (!arguments) arguments = new Expressions(); if (functionParameters(loc, sc, tf, type, arguments, f, &type, &argprefix)) return new ErrorExp(); member = f.isCtorDeclaration(); assert(member); } else { if (nargs) { error("no constructor for %s", cd.toChars()); return new ErrorExp(); } } } else if (tb.ty == Tstruct) { auto sd = (cast(TypeStruct)tb).sym; sd.size(loc); if (sd.sizeok != SIZEOKdone) return new ErrorExp(); if (!sd.ctor) sd.ctor = sd.searchCtor(); if (sd.noDefaultCtor && !nargs) { error("default construction is disabled for type %s", sd.type.toChars()); return new ErrorExp(); } // checkDeprecated() is already done in newtype.semantic(). if (sd.aggNew) { // Prepend the uint size argument to newargs[] Expression e = new IntegerExp(loc, sd.size(loc), Type.tsize_t); if (!newargs) newargs = new Expressions(); newargs.shift(e); FuncDeclaration f = resolveFuncCall(loc, sc, sd.aggNew, null, tb, newargs); if (!f || f.errors) return new ErrorExp(); checkDeprecated(sc, f); checkPurity(sc, f); checkSafety(sc, f); checkNogc(sc, f); checkAccess(sd, loc, sc, f); TypeFunction tf = cast(TypeFunction)f.type; Type rettype; if (functionParameters(loc, sc, tf, null, newargs, f, &rettype, &newprefix)) return new ErrorExp(); allocator = f.isNewDeclaration(); assert(allocator); } else { if (newargs && newargs.dim) { error("no allocator for %s", sd.toChars()); return new ErrorExp(); } } if (sd.ctor && nargs) { FuncDeclaration f = resolveFuncCall(loc, sc, sd.ctor, null, tb, arguments, 0); if (!f || f.errors) return new ErrorExp(); checkDeprecated(sc, f); checkPurity(sc, f); checkSafety(sc, f); checkNogc(sc, f); checkAccess(sd, loc, sc, f); TypeFunction tf = cast(TypeFunction)f.type; if (!arguments) arguments = new Expressions(); if (functionParameters(loc, sc, tf, type, arguments, f, &type, &argprefix)) return new ErrorExp(); member = f.isCtorDeclaration(); assert(member); if (checkFrameAccess(loc, sc, sd, sd.fields.dim)) return new ErrorExp(); } else { if (!arguments) arguments = new Expressions(); if (!sd.fit(loc, sc, arguments, tb)) return new ErrorExp(); if (!sd.fill(loc, arguments, false)) return new ErrorExp(); if (checkFrameAccess(loc, sc, sd, arguments ? arguments.dim : 0)) return new ErrorExp(); } type = type.pointerTo(); } else if (tb.ty == Tarray && nargs) { Type tn = tb.nextOf().baseElemOf(); Dsymbol s = tn.toDsymbol(sc); AggregateDeclaration ad = s ? s.isAggregateDeclaration() : null; if (ad && ad.noDefaultCtor) { error("default construction is disabled for type %s", tb.nextOf().toChars()); return new ErrorExp(); } for (size_t i = 0; i < nargs; i++) { if (tb.ty != Tarray) { error("too many arguments for array"); return new ErrorExp(); } Expression arg = (*arguments)[i]; arg = resolveProperties(sc, arg); arg = arg.implicitCastTo(sc, Type.tsize_t); arg = arg.optimize(WANTvalue); if (arg.op == TOKint64 && cast(sinteger_t)arg.toInteger() < 0) { error("negative array index %s", arg.toChars()); return new ErrorExp(); } (*arguments)[i] = arg; tb = (cast(TypeDArray)tb).next.toBasetype(); } } else if (tb.isscalar()) { if (!nargs) { } else if (nargs == 1) { Expression e = (*arguments)[0]; e = e.implicitCastTo(sc, tb); (*arguments)[0] = e; } else { error("more than one argument for construction of %s", type.toChars()); return new ErrorExp(); } type = type.pointerTo(); } else { error("new can only create structs, dynamic arrays or class objects, not %s's", type.toChars()); return new ErrorExp(); } //printf("NewExp: '%s'\n", toChars()); //printf("NewExp:type '%s'\n", type.toChars()); semanticTypeInfo(sc, type); if (newprefix) return combine(newprefix, this); return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * thisexp.new(newargs) class baseclasses { } (arguments) */ extern (C++) final class NewAnonClassExp : Expression { Expression thisexp; // if !=null, 'this' for class being allocated Expressions* newargs; // Array of Expression's to call new operator ClassDeclaration cd; // class being instantiated Expressions* arguments; // Array of Expression's to call class constructor extern (D) this(Loc loc, Expression thisexp, Expressions* newargs, ClassDeclaration cd, Expressions* arguments) { super(loc, TOKnewanonclass, __traits(classInstanceSize, NewAnonClassExp)); this.thisexp = thisexp; this.newargs = newargs; this.cd = cd; this.arguments = arguments; } override Expression syntaxCopy() { return new NewAnonClassExp(loc, thisexp ? thisexp.syntaxCopy() : null, arraySyntaxCopy(newargs), cast(ClassDeclaration)cd.syntaxCopy(null), arraySyntaxCopy(arguments)); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("NewAnonClassExp::semantic() %s\n", toChars()); //printf("thisexp = %p\n", thisexp); //printf("type: %s\n", type.toChars()); } Expression d = new DeclarationExp(loc, cd); sc = sc.push(); // just create new scope sc.flags &= ~SCOPEctfe; // temporary stop CTFE d = d.semantic(sc); sc = sc.pop(); if (!cd.errors && sc.intypeof && !sc.parent.inNonRoot()) { ScopeDsymbol sds = sc.tinst ? cast(ScopeDsymbol)sc.tinst : sc._module; sds.members.push(cd); } Expression n = new NewExp(loc, thisexp, newargs, cd.type, arguments); Expression c = new CommaExp(loc, d, n); return c.semantic(sc); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) class SymbolExp : Expression { Declaration var; bool hasOverloads; final extern (D) this(Loc loc, TOK op, int size, Declaration var, bool hasOverloads) { super(loc, op, size); assert(var); this.var = var; this.hasOverloads = hasOverloads; } override void accept(Visitor v) { v.visit(this); } override void printAST(int indent) { Expression.printAST(indent); foreach (i; 0 .. indent + 2) printf(" "); printf(".var: %s\n", var ? var.toChars() : ""); } } /*********************************************************** * Offset from symbol */ extern (C++) final class SymOffExp : SymbolExp { dinteger_t offset; extern (D) this(Loc loc, Declaration var, dinteger_t offset, bool hasOverloads = true) { if (auto v = var.isVarDeclaration()) { // FIXME: This error report will never be handled anyone. // It should be done before the SymOffExp construction. if (v.needThis()) .error(loc, "need 'this' for address of %s", v.toChars()); hasOverloads = false; } super(loc, TOKsymoff, __traits(classInstanceSize, SymOffExp), var, hasOverloads); this.offset = offset; } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("SymOffExp::semantic('%s')\n", toChars()); } //var.semantic(sc); if (!type) type = var.type.pointerTo(); if (auto v = var.isVarDeclaration()) { if (v.checkNestedReference(sc, loc)) return new ErrorExp(); } else if (auto f = var.isFuncDeclaration()) { if (f.checkNestedReference(sc, loc)) return new ErrorExp(); } return this; } override bool isBool(bool result) { return result ? true : false; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * Variable */ extern (C++) final class VarExp : SymbolExp { extern (D) this(Loc loc, Declaration var, bool hasOverloads = true) { if (var.isVarDeclaration()) hasOverloads = false; super(loc, TOKvar, __traits(classInstanceSize, VarExp), var, hasOverloads); //printf("VarExp(this = %p, '%s', loc = %s)\n", this, var.toChars(), loc.toChars()); //if (strcmp(var.ident.toChars(), "func") == 0) assert(0); this.type = var.type; } static VarExp create(Loc loc, Declaration var, bool hasOverloads = true) { return new VarExp(loc, var, hasOverloads); } override bool equals(RootObject o) { if (this == o) return true; if ((cast(Expression)o).op == TOKvar) { VarExp ne = cast(VarExp)o; if (type.toHeadMutable().equals(ne.type.toHeadMutable()) && var == ne.var) { return true; } } return false; } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("VarExp::semantic(%s)\n", toChars()); } if (auto fd = var.isFuncDeclaration()) { //printf("L%d fd = %s\n", __LINE__, f.toChars()); if (!fd.functionSemantic()) return new ErrorExp(); } if (!type) type = var.type; if (type && !type.deco) type = type.semantic(loc, sc); /* Fix for 1161 doesn't work because it causes protection * problems when instantiating imported templates passing private * variables as alias template parameters. */ //checkAccess(loc, sc, NULL, var); if (auto vd = var.isVarDeclaration()) { if (vd.checkNestedReference(sc, loc)) return new ErrorExp(); // https://issues.dlang.org/show_bug.cgi?id=12025 // If the variable is not actually used in runtime code, // the purity violation error is redundant. //checkPurity(sc, vd); } else if (auto fd = var.isFuncDeclaration()) { // TODO: If fd isn't yet resolved its overload, the checkNestedReference // call would cause incorrect validation. // Maybe here should be moved in CallExp, or AddrExp for functions. if (fd.checkNestedReference(sc, loc)) return new ErrorExp(); } else if (auto od = var.isOverDeclaration()) { type = Type.tvoid; // ambiguous type? } return this; } override int checkModifiable(Scope* sc, int flag) { //printf("VarExp::checkModifiable %s", toChars()); assert(type); return var.checkModify(loc, sc, type, null, flag); } bool checkReadModifyWrite(); override bool isLvalue() { if (var.storage_class & (STClazy | STCrvalue | STCmanifest)) return false; return true; } override Expression toLvalue(Scope* sc, Expression e) { if (var.storage_class & STCmanifest) { error("manifest constant '%s' is not lvalue", var.toChars()); return new ErrorExp(); } if (var.storage_class & STClazy) { error("lazy variables cannot be lvalues"); return new ErrorExp(); } if (var.ident == Id.ctfe) { error("compiler-generated variable __ctfe is not an lvalue"); return new ErrorExp(); } if (var.ident == Id.dollar) // https://issues.dlang.org/show_bug.cgi?id=13574 { error("'$' is not an lvalue"); return new ErrorExp(); } return this; } override Expression modifiableLvalue(Scope* sc, Expression e) { //printf("VarExp::modifiableLvalue('%s')\n", var.toChars()); if (var.storage_class & STCmanifest) { error("cannot modify manifest constant '%s'", toChars()); return new ErrorExp(); } // See if this expression is a modifiable lvalue (i.e. not const) return Expression.modifiableLvalue(sc, e); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * Overload Set */ extern (C++) final class OverExp : Expression { OverloadSet vars; extern (D) this(Loc loc, OverloadSet s) { super(loc, TOKoverloadset, __traits(classInstanceSize, OverExp)); //printf("OverExp(this = %p, '%s')\n", this, var.toChars()); vars = s; type = Type.tvoid; } override bool isLvalue() { return true; } override Expression toLvalue(Scope* sc, Expression e) { return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * Function/Delegate literal */ extern (C++) final class FuncExp : Expression { FuncLiteralDeclaration fd; TemplateDeclaration td; TOK tok; extern (D) this(Loc loc, Dsymbol s) { super(loc, TOKfunction, __traits(classInstanceSize, FuncExp)); this.td = s.isTemplateDeclaration(); this.fd = s.isFuncLiteralDeclaration(); if (td) { assert(td.literal); assert(td.members && td.members.dim == 1); fd = (*td.members)[0].isFuncLiteralDeclaration(); } tok = fd.tok; // save original kind of function/delegate/(infer) assert(fd.fbody); } override bool equals(RootObject o) { if (this == o) return true; if (o.dyncast() != DYNCAST.expression) return false; if ((cast(Expression)o).op == TOKfunction) { FuncExp fe = cast(FuncExp)o; return fd == fe.fd; } return false; } void genIdent(Scope* sc) { if (fd.ident == Id.empty) { const(char)* s; if (fd.fes) s = "__foreachbody"; else if (fd.tok == TOKreserved) s = "__lambda"; else if (fd.tok == TOKdelegate) s = "__dgliteral"; else s = "__funcliteral"; DsymbolTable symtab; if (FuncDeclaration func = sc.parent.isFuncDeclaration()) { if (func.localsymtab is null) { // Inside template constraint, symtab is not set yet. // Initialize it lazily. func.localsymtab = new DsymbolTable(); } symtab = func.localsymtab; } else { ScopeDsymbol sds = sc.parent.isScopeDsymbol(); if (!sds.symtab) { // Inside template constraint, symtab may not be set yet. // Initialize it lazily. assert(sds.isTemplateInstance()); sds.symtab = new DsymbolTable(); } symtab = sds.symtab; } assert(symtab); Identifier id = Identifier.generateId(s, symtab.len() + 1); fd.ident = id; if (td) td.ident = id; symtab.insert(td ? cast(Dsymbol)td : cast(Dsymbol)fd); } } override Expression syntaxCopy() { if (td) return new FuncExp(loc, td.syntaxCopy(null)); else if (fd.semanticRun == PASSinit) return new FuncExp(loc, fd.syntaxCopy(null)); else // https://issues.dlang.org/show_bug.cgi?id=13481 // Prevent multiple semantic analysis of lambda body. return new FuncExp(loc, fd); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("FuncExp::semantic(%s)\n", toChars()); if (fd.treq) printf(" treq = %s\n", fd.treq.toChars()); } Expression e = this; sc = sc.push(); // just create new scope sc.flags &= ~SCOPEctfe; // temporary stop CTFE sc.protection = Prot(PROTpublic); // https://issues.dlang.org/show_bug.cgi?id=12506 if (!type || type == Type.tvoid) { /* fd.treq might be incomplete type, * so should not semantic it. * void foo(T)(T delegate(int) dg){} * foo(a=>a); // in IFTI, treq == T delegate(int) */ //if (fd.treq) // fd.treq = fd.treq.semantic(loc, sc); genIdent(sc); // Set target of return type inference if (fd.treq && !fd.type.nextOf()) { TypeFunction tfv = null; if (fd.treq.ty == Tdelegate || (fd.treq.ty == Tpointer && fd.treq.nextOf().ty == Tfunction)) tfv = cast(TypeFunction)fd.treq.nextOf(); if (tfv) { TypeFunction tfl = cast(TypeFunction)fd.type; tfl.next = tfv.nextOf(); } } //printf("td = %p, treq = %p\n", td, fd.treq); if (td) { assert(td.parameters && td.parameters.dim); td.semantic(sc); type = Type.tvoid; // temporary type if (fd.treq) // defer type determination { FuncExp fe; if (matchType(fd.treq, sc, &fe) > MATCHnomatch) e = fe; else e = new ErrorExp(); } goto Ldone; } uint olderrors = global.errors; fd.semantic(sc); if (olderrors == global.errors) { fd.semantic2(sc); if (olderrors == global.errors) fd.semantic3(sc); } if (olderrors != global.errors) { if (fd.type && fd.type.ty == Tfunction && !fd.type.nextOf()) (cast(TypeFunction)fd.type).next = Type.terror; e = new ErrorExp(); goto Ldone; } // Type is a "delegate to" or "pointer to" the function literal if ((fd.isNested() && fd.tok == TOKdelegate) || (tok == TOKreserved && fd.treq && fd.treq.ty == Tdelegate)) { type = new TypeDelegate(fd.type); type = type.semantic(loc, sc); fd.tok = TOKdelegate; } else { type = new TypePointer(fd.type); type = type.semantic(loc, sc); //type = fd.type.pointerTo(); /* A lambda expression deduced to function pointer might become * to a delegate literal implicitly. * * auto foo(void function() fp) { return 1; } * assert(foo({}) == 1); * * So, should keep fd.tok == TOKreserve if fd.treq == NULL. */ if (fd.treq && fd.treq.ty == Tpointer) { // change to non-nested fd.tok = TOKfunction; fd.vthis = null; } } fd.tookAddressOf++; } Ldone: sc = sc.pop(); return e; } // used from CallExp::semantic() Expression semantic(Scope* sc, Expressions* arguments) { if ((!type || type == Type.tvoid) && td && arguments && arguments.dim) { for (size_t k = 0; k < arguments.dim; k++) { Expression checkarg = (*arguments)[k]; if (checkarg.op == TOKerror) return checkarg; } genIdent(sc); assert(td.parameters && td.parameters.dim); td.semantic(sc); TypeFunction tfl = cast(TypeFunction)fd.type; size_t dim = Parameter.dim(tfl.parameters); if (arguments.dim < dim) { // Default arguments are always typed, so they don't need inference. Parameter p = Parameter.getNth(tfl.parameters, arguments.dim); if (p.defaultArg) dim = arguments.dim; } if ((!tfl.varargs && arguments.dim == dim) || (tfl.varargs && arguments.dim >= dim)) { auto tiargs = new Objects(); tiargs.reserve(td.parameters.dim); for (size_t i = 0; i < td.parameters.dim; i++) { TemplateParameter tp = (*td.parameters)[i]; for (size_t u = 0; u < dim; u++) { Parameter p = Parameter.getNth(tfl.parameters, u); if (p.type.ty == Tident && (cast(TypeIdentifier)p.type).ident == tp.ident) { Expression e = (*arguments)[u]; tiargs.push(e.type); u = dim; // break inner loop } } } auto ti = new TemplateInstance(loc, td, tiargs); return (new ScopeExp(loc, ti)).semantic(sc); } error("cannot infer function literal type"); return new ErrorExp(); } return semantic(sc); } MATCH matchType(Type to, Scope* sc, FuncExp* presult, int flag = 0) { //printf("FuncExp::matchType('%s'), to=%s\n", type ? type.toChars() : "null", to.toChars()); if (presult) *presult = null; TypeFunction tof = null; if (to.ty == Tdelegate) { if (tok == TOKfunction) { if (!flag) error("cannot match function literal to delegate type '%s'", to.toChars()); return MATCHnomatch; } tof = cast(TypeFunction)to.nextOf(); } else if (to.ty == Tpointer && to.nextOf().ty == Tfunction) { if (tok == TOKdelegate) { if (!flag) error("cannot match delegate literal to function pointer type '%s'", to.toChars()); return MATCHnomatch; } tof = cast(TypeFunction)to.nextOf(); } if (td) { if (!tof) { L1: if (!flag) error("cannot infer parameter types from %s", to.toChars()); return MATCHnomatch; } // Parameter types inference from 'tof' assert(td._scope); TypeFunction tf = cast(TypeFunction)fd.type; //printf("\ttof = %s\n", tof.toChars()); //printf("\ttf = %s\n", tf.toChars()); size_t dim = Parameter.dim(tf.parameters); if (Parameter.dim(tof.parameters) != dim || tof.varargs != tf.varargs) goto L1; auto tiargs = new Objects(); tiargs.reserve(td.parameters.dim); for (size_t i = 0; i < td.parameters.dim; i++) { TemplateParameter tp = (*td.parameters)[i]; size_t u = 0; for (; u < dim; u++) { Parameter p = Parameter.getNth(tf.parameters, u); if (p.type.ty == Tident && (cast(TypeIdentifier)p.type).ident == tp.ident) { break; } } assert(u < dim); Parameter pto = Parameter.getNth(tof.parameters, u); Type t = pto.type; if (t.ty == Terror) goto L1; tiargs.push(t); } // Set target of return type inference if (!tf.next && tof.next) fd.treq = to; auto ti = new TemplateInstance(loc, td, tiargs); Expression ex = (new ScopeExp(loc, ti)).semantic(td._scope); // Reset inference target for the later re-semantic fd.treq = null; if (ex.op == TOKerror) return MATCHnomatch; if (ex.op != TOKfunction) goto L1; return (cast(FuncExp)ex).matchType(to, sc, presult, flag); } if (!tof || !tof.next) return MATCHnomatch; assert(type && type != Type.tvoid); TypeFunction tfx = cast(TypeFunction)fd.type; bool convertMatch = (type.ty != to.ty); if (fd.inferRetType && tfx.next.implicitConvTo(tof.next) == MATCHconvert) { /* If return type is inferred and covariant return, * tweak return statements to required return type. * * interface I {} * class C : Object, I{} * * I delegate() dg = delegate() { return new class C(); } */ convertMatch = true; auto tfy = new TypeFunction(tfx.parameters, tof.next, tfx.varargs, tfx.linkage, STCundefined); tfy.mod = tfx.mod; tfy.isnothrow = tfx.isnothrow; tfy.isnogc = tfx.isnogc; tfy.purity = tfx.purity; tfy.isproperty = tfx.isproperty; tfy.isref = tfx.isref; tfy.iswild = tfx.iswild; tfy.deco = tfy.merge().deco; tfx = tfy; } Type tx; if (tok == TOKdelegate || tok == TOKreserved && (type.ty == Tdelegate || type.ty == Tpointer && to.ty == Tdelegate)) { // Allow conversion from implicit function pointer to delegate tx = new TypeDelegate(tfx); tx.deco = tx.merge().deco; } else { assert(tok == TOKfunction || tok == TOKreserved && type.ty == Tpointer); tx = tfx.pointerTo(); } //printf("\ttx = %s, to = %s\n", tx.toChars(), to.toChars()); MATCH m = tx.implicitConvTo(to); if (m > MATCHnomatch) { // MATCHexact: exact type match // MATCHconst: covairiant type match (eg. attributes difference) // MATCHconvert: context conversion m = convertMatch ? MATCHconvert : tx.equals(to) ? MATCHexact : MATCHconst; if (presult) { (*presult) = cast(FuncExp)copy(); (*presult).type = to; // https://issues.dlang.org/show_bug.cgi?id=12508 // Tweak function body for covariant returns. (*presult).fd.modifyReturns(sc, tof.next); } } else if (!flag) { error("cannot implicitly convert expression `%s` of type `%s` to `%s`", toChars(), tx.toChars(), to.toChars()); } return m; } override const(char)* toChars() { return fd.toChars(); } override bool checkType() { if (td) { error("template lambda has no type"); return true; } return false; } override bool checkValue() { if (td) { error("template lambda has no value"); return true; } return false; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * Declaration of a symbol * * D grammar allows declarations only as statements. However in AST representation * it can be part of any expression. This is used, for example, during internal * syntax re-writes to inject hidden symbols. */ extern (C++) final class DeclarationExp : Expression { Dsymbol declaration; extern (D) this(Loc loc, Dsymbol declaration) { super(loc, TOKdeclaration, __traits(classInstanceSize, DeclarationExp)); this.declaration = declaration; } override Expression syntaxCopy() { return new DeclarationExp(loc, declaration.syntaxCopy(null)); } override Expression semantic(Scope* sc) { if (type) return this; static if (LOGSEMANTIC) { printf("DeclarationExp::semantic() %s\n", toChars()); } uint olderrors = global.errors; /* This is here to support extern(linkage) declaration, * where the extern(linkage) winds up being an AttribDeclaration * wrapper. */ Dsymbol s = declaration; while (1) { AttribDeclaration ad = s.isAttribDeclaration(); if (ad) { if (ad.decl && ad.decl.dim == 1) { s = (*ad.decl)[0]; continue; } } break; } VarDeclaration v = s.isVarDeclaration(); if (v) { // Do semantic() on initializer first, so: // int a = a; // will be illegal. declaration.semantic(sc); s.parent = sc.parent; } //printf("inserting '%s' %p into sc = %p\n", s.toChars(), s, sc); // Insert into both local scope and function scope. // Must be unique in both. if (s.ident) { if (!sc.insert(s)) { error("declaration %s is already defined", s.toPrettyChars()); return new ErrorExp(); } else if (sc.func) { // https://issues.dlang.org/show_bug.cgi?id=11720 // include Dataseg variables if ((s.isFuncDeclaration() || s.isAggregateDeclaration() || s.isEnumDeclaration() || v && v.isDataseg()) && !sc.func.localsymtab.insert(s)) { error("declaration %s is already defined in another scope in %s", s.toPrettyChars(), sc.func.toChars()); return new ErrorExp(); } else { // Disallow shadowing for (Scope* scx = sc.enclosing; scx && scx.func == sc.func; scx = scx.enclosing) { Dsymbol s2; if (scx.scopesym && scx.scopesym.symtab && (s2 = scx.scopesym.symtab.lookup(s.ident)) !is null && s != s2) { error("%s %s is shadowing %s %s", s.kind(), s.ident.toChars(), s2.kind(), s2.toPrettyChars()); return new ErrorExp(); } } } } } if (!s.isVarDeclaration()) { Scope* sc2 = sc; if (sc2.stc & (STCpure | STCnothrow | STCnogc)) sc2 = sc.push(); sc2.stc &= ~(STCpure | STCnothrow | STCnogc); declaration.semantic(sc2); if (sc2 != sc) sc2.pop(); s.parent = sc.parent; } if (global.errors == olderrors) { declaration.semantic2(sc); if (global.errors == olderrors) { declaration.semantic3(sc); } } // todo: error in declaration should be propagated. type = Type.tvoid; return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * typeid(int) */ extern (C++) final class TypeidExp : Expression { RootObject obj; extern (D) this(Loc loc, RootObject o) { super(loc, TOKtypeid, __traits(classInstanceSize, TypeidExp)); this.obj = o; } override Expression syntaxCopy() { return new TypeidExp(loc, objectSyntaxCopy(obj)); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("TypeidExp::semantic() %s\n", toChars()); } Type ta = isType(obj); Expression ea = isExpression(obj); Dsymbol sa = isDsymbol(obj); //printf("ta %p ea %p sa %p\n", ta, ea, sa); if (ta) { ta.resolve(loc, sc, &ea, &ta, &sa, true); } if (ea) { if (auto sym = getDsymbol(ea)) ea = DsymbolExp.resolve(loc, sc, sym, false); else ea = ea.semantic(sc); ea = resolveProperties(sc, ea); ta = ea.type; if (ea.op == TOKtype) ea = null; } if (!ta) { //printf("ta %p ea %p sa %p\n", ta, ea, sa); error("no type for typeid(%s)", ea ? ea.toChars() : (sa ? sa.toChars() : "")); return new ErrorExp(); } if (global.params.vcomplex) ta.checkComplexTransition(loc); Expression e; if (ea && ta.toBasetype().ty == Tclass) { /* Get the dynamic type, which is .classinfo */ ea = ea.semantic(sc); e = new TypeidExp(ea.loc, ea); e.type = Type.typeinfoclass.type; } else if (ta.ty == Terror) { e = new ErrorExp(); } else { // Handle this in the glue layer e = new TypeidExp(loc, ta); e.type = getTypeInfoType(ta, sc); semanticTypeInfo(sc, ta); if (ea) { e = new CommaExp(loc, ea, e); // execute ea e = e.semantic(sc); } } return e; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * __traits(identifier, args...) */ extern (C++) final class TraitsExp : Expression { Identifier ident; Objects* args; extern (D) this(Loc loc, Identifier ident, Objects* args) { super(loc, TOKtraits, __traits(classInstanceSize, TraitsExp)); this.ident = ident; this.args = args; } override Expression syntaxCopy() { return new TraitsExp(loc, ident, TemplateInstance.arraySyntaxCopy(args)); } override Expression semantic(Scope* sc) { return semanticTraits(this, sc); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class HaltExp : Expression { extern (D) this(Loc loc) { super(loc, TOKhalt, __traits(classInstanceSize, HaltExp)); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("HaltExp::semantic()\n"); } type = Type.tvoid; return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * is(targ id tok tspec) * is(targ id == tok2) */ extern (C++) final class IsExp : Expression { Type targ; Identifier id; // can be null TOK tok; // ':' or '==' Type tspec; // can be null TOK tok2; // 'struct', 'union', etc. TemplateParameters* parameters; extern (D) this(Loc loc, Type targ, Identifier id, TOK tok, Type tspec, TOK tok2, TemplateParameters* parameters) { super(loc, TOKis, __traits(classInstanceSize, IsExp)); this.targ = targ; this.id = id; this.tok = tok; this.tspec = tspec; this.tok2 = tok2; this.parameters = parameters; } override Expression syntaxCopy() { // This section is identical to that in TemplateDeclaration::syntaxCopy() TemplateParameters* p = null; if (parameters) { p = new TemplateParameters(); p.setDim(parameters.dim); for (size_t i = 0; i < p.dim; i++) (*p)[i] = (*parameters)[i].syntaxCopy(); } return new IsExp(loc, targ.syntaxCopy(), id, tok, tspec ? tspec.syntaxCopy() : null, tok2, p); } override Expression semantic(Scope* sc) { /* is(targ id tok tspec) * is(targ id : tok2) * is(targ id == tok2) */ //printf("IsExp::semantic(%s)\n", toChars()); if (id && !(sc.flags & SCOPEcondition)) { error("can only declare type aliases within static if conditionals or static asserts"); return new ErrorExp(); } Type tded = null; Scope* sc2 = sc.copy(); // keep sc.flags sc2.tinst = null; sc2.minst = null; sc2.flags |= SCOPEfullinst; Type t = targ.trySemantic(loc, sc2); sc2.pop(); if (!t) goto Lno; // errors, so condition is false targ = t; if (tok2 != TOKreserved) { switch (tok2) { case TOKstruct: if (targ.ty != Tstruct) goto Lno; if ((cast(TypeStruct)targ).sym.isUnionDeclaration()) goto Lno; tded = targ; break; case TOKunion: if (targ.ty != Tstruct) goto Lno; if (!(cast(TypeStruct)targ).sym.isUnionDeclaration()) goto Lno; tded = targ; break; case TOKclass: if (targ.ty != Tclass) goto Lno; if ((cast(TypeClass)targ).sym.isInterfaceDeclaration()) goto Lno; tded = targ; break; case TOKinterface: if (targ.ty != Tclass) goto Lno; if (!(cast(TypeClass)targ).sym.isInterfaceDeclaration()) goto Lno; tded = targ; break; case TOKconst: if (!targ.isConst()) goto Lno; tded = targ; break; case TOKimmutable: if (!targ.isImmutable()) goto Lno; tded = targ; break; case TOKshared: if (!targ.isShared()) goto Lno; tded = targ; break; case TOKwild: if (!targ.isWild()) goto Lno; tded = targ; break; case TOKsuper: // If class or interface, get the base class and interfaces if (targ.ty != Tclass) goto Lno; else { ClassDeclaration cd = (cast(TypeClass)targ).sym; auto args = new Parameters(); args.reserve(cd.baseclasses.dim); if (cd.semanticRun < PASSsemanticdone) cd.semantic(null); for (size_t i = 0; i < cd.baseclasses.dim; i++) { BaseClass* b = (*cd.baseclasses)[i]; args.push(new Parameter(STCin, b.type, null, null)); } tded = new TypeTuple(args); } break; case TOKenum: if (targ.ty != Tenum) goto Lno; if (id) tded = (cast(TypeEnum)targ).sym.getMemtype(loc); else tded = targ; if (tded.ty == Terror) return new ErrorExp(); break; case TOKdelegate: if (targ.ty != Tdelegate) goto Lno; tded = (cast(TypeDelegate)targ).next; // the underlying function type break; case TOKfunction: case TOKparameters: { if (targ.ty != Tfunction) goto Lno; tded = targ; /* Generate tuple from function parameter types. */ assert(tded.ty == Tfunction); Parameters* params = (cast(TypeFunction)tded).parameters; size_t dim = Parameter.dim(params); auto args = new Parameters(); args.reserve(dim); for (size_t i = 0; i < dim; i++) { Parameter arg = Parameter.getNth(params, i); assert(arg && arg.type); /* If one of the default arguments was an error, don't return an invalid tuple */ if (tok2 == TOKparameters && arg.defaultArg && arg.defaultArg.op == TOKerror) return new ErrorExp(); args.push(new Parameter(arg.storageClass, arg.type, (tok2 == TOKparameters) ? arg.ident : null, (tok2 == TOKparameters) ? arg.defaultArg : null)); } tded = new TypeTuple(args); break; } case TOKreturn: /* Get the 'return type' for the function, * delegate, or pointer to function. */ if (targ.ty == Tfunction) tded = (cast(TypeFunction)targ).next; else if (targ.ty == Tdelegate) { tded = (cast(TypeDelegate)targ).next; tded = (cast(TypeFunction)tded).next; } else if (targ.ty == Tpointer && (cast(TypePointer)targ).next.ty == Tfunction) { tded = (cast(TypePointer)targ).next; tded = (cast(TypeFunction)tded).next; } else goto Lno; break; case TOKargTypes: /* Generate a type tuple of the equivalent types used to determine if a * function argument of this type can be passed in registers. * The results of this are highly platform dependent, and intended * primarly for use in implementing va_arg(). */ tded = toArgTypes(targ); if (!tded) goto Lno; // not valid for a parameter break; case TOKvector: if (targ.ty != Tvector) goto Lno; tded = (cast(TypeVector)targ).basetype; break; default: assert(0); } goto Lyes; } else if (tspec && !id && !(parameters && parameters.dim)) { /* Evaluate to true if targ matches tspec * is(targ == tspec) * is(targ : tspec) */ tspec = tspec.semantic(loc, sc); //printf("targ = %s, %s\n", targ.toChars(), targ.deco); //printf("tspec = %s, %s\n", tspec.toChars(), tspec.deco); if (tok == TOKcolon) { if (targ.implicitConvTo(tspec)) goto Lyes; else goto Lno; } else /* == */ { if (targ.equals(tspec)) goto Lyes; else goto Lno; } } else if (tspec) { /* Evaluate to true if targ matches tspec. * If true, declare id as an alias for the specialized type. * is(targ == tspec, tpl) * is(targ : tspec, tpl) * is(targ id == tspec) * is(targ id : tspec) * is(targ id == tspec, tpl) * is(targ id : tspec, tpl) */ Identifier tid = id ? id : Identifier.generateId("__isexp_id"); parameters.insert(0, new TemplateTypeParameter(loc, tid, null, null)); Objects dedtypes; dedtypes.setDim(parameters.dim); dedtypes.zero(); MATCH m = deduceType(targ, sc, tspec, parameters, &dedtypes); //printf("targ: %s\n", targ.toChars()); //printf("tspec: %s\n", tspec.toChars()); if (m <= MATCHnomatch || (m != MATCHexact && tok == TOKequal)) { goto Lno; } else { tded = cast(Type)dedtypes[0]; if (!tded) tded = targ; Objects tiargs; tiargs.setDim(1); tiargs[0] = targ; /* Declare trailing parameters */ for (size_t i = 1; i < parameters.dim; i++) { TemplateParameter tp = (*parameters)[i]; Declaration s = null; m = tp.matchArg(loc, sc, &tiargs, i, parameters, &dedtypes, &s); if (m <= MATCHnomatch) goto Lno; s.semantic(sc); if (sc.sds) s.addMember(sc, sc.sds); else if (!sc.insert(s)) error("declaration %s is already defined", s.toChars()); unSpeculative(sc, s); } goto Lyes; } } else if (id) { /* Declare id as an alias for type targ. Evaluate to true * is(targ id) */ tded = targ; goto Lyes; } Lyes: if (id) { Dsymbol s; Tuple tup = isTuple(tded); if (tup) s = new TupleDeclaration(loc, id, &tup.objects); else s = new AliasDeclaration(loc, id, tded); s.semantic(sc); /* The reason for the !tup is unclear. It fails Phobos unittests if it is not there. * More investigation is needed. */ if (!tup && !sc.insert(s)) error("declaration %s is already defined", s.toChars()); if (sc.sds) s.addMember(sc, sc.sds); unSpeculative(sc, s); } //printf("Lyes\n"); return new IntegerExp(loc, 1, Type.tbool); Lno: //printf("Lno\n"); return new IntegerExp(loc, 0, Type.tbool); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) class UnaExp : Expression { Expression e1; Type att1; // Save alias this type to detect recursion final extern (D) this(Loc loc, TOK op, int size, Expression e1) { super(loc, op, size); this.e1 = e1; } override Expression syntaxCopy() { UnaExp e = cast(UnaExp)copy(); e.type = null; e.e1 = e.e1.syntaxCopy(); return e; } override abstract Expression semantic(Scope* sc); /************************** * Helper function for easy error propagation. * If error occurs, returns ErrorExp. Otherwise returns NULL. */ final Expression unaSemantic(Scope* sc) { static if (LOGSEMANTIC) { printf("UnaExp::semantic('%s')\n", toChars()); } Expression e1x = e1.semantic(sc); if (e1x.op == TOKerror) return e1x; e1 = e1x; return null; } /******************************** * The type for a unary expression is incompatible. * Print error message. * Returns: * ErrorExp */ final Expression incompatibleTypes() { if (e1.type.toBasetype() == Type.terror) return e1; if (e1.op == TOKtype) { error("incompatible type for (%s(%s)): cannot use '%s' with types", Token.toChars(op), e1.toChars(), Token.toChars(op)); } else { error("incompatible type for (%s(%s)): '%s'", Token.toChars(op), e1.toChars(), e1.type.toChars()); } return new ErrorExp(); } /********************* * Mark the operand as will never be dereferenced, * which is useful info for @safe checks. * Do before semantic() on operands rewrites them. */ final void setNoderefOperand() { if (e1.op == TOKdotid) (cast(DotIdExp)e1).noderef = true; } override final Expression resolveLoc(Loc loc, Scope* sc) { e1 = e1.resolveLoc(loc, sc); return this; } override void accept(Visitor v) { v.visit(this); } override void printAST(int indent) { Expression.printAST(indent); e1.printAST(indent + 2); } } extern (C++) alias fp_t = UnionExp function(Loc loc, Type, Expression, Expression); extern (C++) alias fp2_t = int function(Loc loc, TOK, Expression, Expression); /*********************************************************** */ extern (C++) abstract class BinExp : Expression { Expression e1; Expression e2; Type att1; // Save alias this type to detect recursion Type att2; // Save alias this type to detect recursion final extern (D) this(Loc loc, TOK op, int size, Expression e1, Expression e2) { super(loc, op, size); this.e1 = e1; this.e2 = e2; } override Expression syntaxCopy() { BinExp e = cast(BinExp)copy(); e.type = null; e.e1 = e.e1.syntaxCopy(); e.e2 = e.e2.syntaxCopy(); return e; } override abstract Expression semantic(Scope* sc); /************************** * Helper function for easy error propagation. * If error occurs, returns ErrorExp. Otherwise returns NULL. */ final Expression binSemantic(Scope* sc) { static if (LOGSEMANTIC) { printf("BinExp::semantic('%s')\n", toChars()); } Expression e1x = e1.semantic(sc); Expression e2x = e2.semantic(sc); if (e1x.op == TOKerror) return e1x; if (e2x.op == TOKerror) return e2x; e1 = e1x; e2 = e2x; return null; } final Expression binSemanticProp(Scope* sc) { if (Expression ex = binSemantic(sc)) return ex; Expression e1x = resolveProperties(sc, e1); Expression e2x = resolveProperties(sc, e2); if (e1x.op == TOKerror) return e1x; if (e2x.op == TOKerror) return e2x; e1 = e1x; e2 = e2x; return null; } /******************************** * The types for a binary expression are incompatible. * Print error message. * Returns: * ErrorExp */ final Expression incompatibleTypes() { if (e1.type.toBasetype() == Type.terror) return e1; if (e2.type.toBasetype() == Type.terror) return e2; // CondExp uses 'a ? b : c' but we're comparing 'b : c' TOK thisOp = (op == TOKquestion) ? TOKcolon : op; if (e1.op == TOKtype || e2.op == TOKtype) { error("incompatible types for ((%s) %s (%s)): cannot use '%s' with types", e1.toChars(), Token.toChars(thisOp), e2.toChars(), Token.toChars(op)); } else { error("incompatible types for ((%s) %s (%s)): '%s' and '%s'", e1.toChars(), Token.toChars(thisOp), e2.toChars(), e1.type.toChars(), e2.type.toChars()); } return new ErrorExp(); } final Expression checkOpAssignTypes(Scope* sc) { // At that point t1 and t2 are the merged types. type is the original type of the lhs. Type t1 = e1.type; Type t2 = e2.type; // T opAssign floating yields a floating. Prevent truncating conversions (float to int). // See issue 3841. // Should we also prevent double to float (type.isfloating() && type.size() < t2.size()) ? if (op == TOKaddass || op == TOKminass || op == TOKmulass || op == TOKdivass || op == TOKmodass || op == TOKpowass) { if ((type.isintegral() && t2.isfloating())) { warning("%s %s %s is performing truncating conversion", type.toChars(), Token.toChars(op), t2.toChars()); } } // generate an error if this is a nonsensical *=,/=, or %=, eg real *= imaginary if (op == TOKmulass || op == TOKdivass || op == TOKmodass) { // Any multiplication by an imaginary or complex number yields a complex result. // r *= c, i*=c, r*=i, i*=i are all forbidden operations. const(char)* opstr = Token.toChars(op); if (t1.isreal() && t2.iscomplex()) { error("%s %s %s is undefined. Did you mean %s %s %s.re ?", t1.toChars(), opstr, t2.toChars(), t1.toChars(), opstr, t2.toChars()); return new ErrorExp(); } else if (t1.isimaginary() && t2.iscomplex()) { error("%s %s %s is undefined. Did you mean %s %s %s.im ?", t1.toChars(), opstr, t2.toChars(), t1.toChars(), opstr, t2.toChars()); return new ErrorExp(); } else if ((t1.isreal() || t1.isimaginary()) && t2.isimaginary()) { error("%s %s %s is an undefined operation", t1.toChars(), opstr, t2.toChars()); return new ErrorExp(); } } // generate an error if this is a nonsensical += or -=, eg real += imaginary if (op == TOKaddass || op == TOKminass) { // Addition or subtraction of a real and an imaginary is a complex result. // Thus, r+=i, r+=c, i+=r, i+=c are all forbidden operations. if ((t1.isreal() && (t2.isimaginary() || t2.iscomplex())) || (t1.isimaginary() && (t2.isreal() || t2.iscomplex()))) { error("%s %s %s is undefined (result is complex)", t1.toChars(), Token.toChars(op), t2.toChars()); return new ErrorExp(); } if (type.isreal() || type.isimaginary()) { assert(global.errors || t2.isfloating()); e2 = e2.castTo(sc, t1); } } if (op == TOKmulass) { if (t2.isfloating()) { if (t1.isreal()) { if (t2.isimaginary() || t2.iscomplex()) { e2 = e2.castTo(sc, t1); } } else if (t1.isimaginary()) { if (t2.isimaginary() || t2.iscomplex()) { switch (t1.ty) { case Timaginary32: t2 = Type.tfloat32; break; case Timaginary64: t2 = Type.tfloat64; break; case Timaginary80: t2 = Type.tfloat80; break; default: assert(0); } e2 = e2.castTo(sc, t2); } } } } else if (op == TOKdivass) { if (t2.isimaginary()) { if (t1.isreal()) { // x/iv = i(-x/v) // Therefore, the result is 0 e2 = new CommaExp(loc, e2, new RealExp(loc, CTFloat.zero, t1)); e2.type = t1; Expression e = new AssignExp(loc, e1, e2); e.type = t1; return e; } else if (t1.isimaginary()) { Type t3; switch (t1.ty) { case Timaginary32: t3 = Type.tfloat32; break; case Timaginary64: t3 = Type.tfloat64; break; case Timaginary80: t3 = Type.tfloat80; break; default: assert(0); } e2 = e2.castTo(sc, t3); Expression e = new AssignExp(loc, e1, e2); e.type = t1; return e; } } } else if (op == TOKmodass) { if (t2.iscomplex()) { error("cannot perform modulo complex arithmetic"); return new ErrorExp(); } } return this; } final bool checkIntegralBin() { bool r1 = e1.checkIntegral(); bool r2 = e2.checkIntegral(); return (r1 || r2); } final bool checkArithmeticBin() { bool r1 = e1.checkArithmetic(); bool r2 = e2.checkArithmetic(); return (r1 || r2); } /********************* * Mark the operands as will never be dereferenced, * which is useful info for @safe checks. * Do before semantic() on operands rewrites them. */ final void setNoderefOperands() { if (e1.op == TOKdotid) (cast(DotIdExp)e1).noderef = true; if (e2.op == TOKdotid) (cast(DotIdExp)e2).noderef = true; } final Expression reorderSettingAAElem(Scope* sc) { BinExp be = this; if (be.e1.op != TOKindex) return be; auto ie = cast(IndexExp)be.e1; if (ie.e1.type.toBasetype().ty != Taarray) return be; /* Fix evaluation order of setting AA element * https://issues.dlang.org/show_bug.cgi?id=3825 * Rewrite: * aa[k1][k2][k3] op= val; * as: * auto ref __aatmp = aa; * auto ref __aakey3 = k1, __aakey2 = k2, __aakey1 = k3; * auto ref __aaval = val; * __aatmp[__aakey3][__aakey2][__aakey1] op= __aaval; // assignment */ Expression e0; while (1) { Expression de; ie.e2 = extractSideEffect(sc, "__aakey", de, ie.e2); e0 = Expression.combine(de, e0); Expression ie1 = ie.e1; if (ie1.op != TOKindex || (cast(IndexExp)ie1).e1.type.toBasetype().ty != Taarray) { break; } ie = cast(IndexExp)ie1; } assert(ie.e1.type.toBasetype().ty == Taarray); Expression de; ie.e1 = extractSideEffect(sc, "__aatmp", de, ie.e1); e0 = Expression.combine(de, e0); be.e2 = extractSideEffect(sc, "__aaval", e0, be.e2, true); //printf("-e0 = %s, be = %s\n", e0.toChars(), be.toChars()); return Expression.combine(e0, be); } override void accept(Visitor v) { v.visit(this); } override void printAST(int indent) { Expression.printAST(indent); e1.printAST(indent + 2); e2.printAST(indent + 2); } } /*********************************************************** */ extern (C++) class BinAssignExp : BinExp { final extern (D) this(Loc loc, TOK op, int size, Expression e1, Expression e2) { super(loc, op, size, e1, e2); } override Expression semantic(Scope* sc) { if (type) return this; Expression e = op_overload(sc); if (e) return e; if (e1.checkReadModifyWrite(op, e2)) return new ErrorExp(); if (e1.op == TOKarraylength) { // arr.length op= e2; e = ArrayLengthExp.rewriteOpAssign(this); e = e.semantic(sc); return e; } if (e1.op == TOKslice || e1.type.ty == Tarray || e1.type.ty == Tsarray) { // T[] op= ... if (e2.implicitConvTo(e1.type.nextOf())) { // T[] op= T e2 = e2.castTo(sc, e1.type.nextOf()); } else if (Expression ex = typeCombine(this, sc)) return ex; type = e1.type; return arrayOp(this, sc); } e1 = e1.semantic(sc); e1 = e1.optimize(WANTvalue); e1 = e1.modifiableLvalue(sc, e1); type = e1.type; if (checkScalar()) return new ErrorExp(); int arith = (op == TOKaddass || op == TOKminass || op == TOKmulass || op == TOKdivass || op == TOKmodass || op == TOKpowass); int bitwise = (op == TOKandass || op == TOKorass || op == TOKxorass); int shift = (op == TOKshlass || op == TOKshrass || op == TOKushrass); if (bitwise && type.toBasetype().ty == Tbool) e2 = e2.implicitCastTo(sc, type); else if (checkNoBool()) return new ErrorExp(); if ((op == TOKaddass || op == TOKminass) && e1.type.toBasetype().ty == Tpointer && e2.type.toBasetype().isintegral()) return scaleFactor(this, sc); if (Expression ex = typeCombine(this, sc)) return ex; if (arith && checkArithmeticBin()) return new ErrorExp(); if ((bitwise || shift) && checkIntegralBin()) return new ErrorExp(); if (shift) { e2 = e2.castTo(sc, Type.tshiftcnt); } if (!Target.isVectorOpSupported(type.toBasetype(), op, e2.type.toBasetype())) return incompatibleTypes(); if (e1.op == TOKerror || e2.op == TOKerror) return new ErrorExp(); e = checkOpAssignTypes(sc); if (e.op == TOKerror) return e; assert(e.op == TOKassign || e == this); return (cast(BinExp)e).reorderSettingAAElem(sc); } override final bool isLvalue() { return true; } override final Expression toLvalue(Scope* sc, Expression ex) { // Lvalue-ness will be handled in glue layer. return this; } override final Expression modifiableLvalue(Scope* sc, Expression e) { // should check e1.checkModifiable() ? return toLvalue(sc, this); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class CompileExp : UnaExp { extern (D) this(Loc loc, Expression e) { super(loc, TOKmixin, __traits(classInstanceSize, CompileExp), e); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("CompileExp::semantic('%s')\n", toChars()); } auto se = semanticString(sc, e1, "argument to mixin"); if (!se) return new ErrorExp(); se = se.toUTF8(sc); uint errors = global.errors; scope p = new Parser!ASTCodegen(loc, sc._module, se.toStringz(), false); p.nextToken(); //printf("p.loc.linnum = %d\n", p.loc.linnum); Expression e = p.parseExpression(); if (p.errors) { assert(global.errors != errors); // should have caught all these cases return new ErrorExp(); } if (p.token.value != TOKeof) { error("incomplete mixin expression (%s)", se.toChars()); return new ErrorExp(); } return e.semantic(sc); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class ImportExp : UnaExp { extern (D) this(Loc loc, Expression e) { super(loc, TOKimport, __traits(classInstanceSize, ImportExp), e); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("ImportExp::semantic('%s')\n", toChars()); } auto se = semanticString(sc, e1, "file name argument"); if (!se) return new ErrorExp(); se = se.toUTF8(sc); auto namez = se.toStringz().ptr; if (!global.params.fileImppath) { error("need -Jpath switch to import text file %s", namez); return new ErrorExp(); } /* Be wary of CWE-22: Improper Limitation of a Pathname to a Restricted Directory * ('Path Traversal') attacks. * http://cwe.mitre.org/data/definitions/22.html */ auto name = FileName.safeSearchPath(global.filePath, namez); if (!name) { error("file %s cannot be found or not in a path specified with -J", se.toChars()); return new ErrorExp(); } if (global.params.verbose) fprintf(global.stdmsg, "file %.*s\t(%s)\n", cast(int)se.len, se.string, name); if (global.params.moduleDeps !is null) { OutBuffer* ob = global.params.moduleDeps; Module imod = sc.instantiatingModule(); if (!global.params.moduleDepsFile) ob.writestring("depsFile "); ob.writestring(imod.toPrettyChars()); ob.writestring(" ("); escapePath(ob, imod.srcfile.toChars()); ob.writestring(") : "); if (global.params.moduleDepsFile) ob.writestring("string : "); ob.write(se.string, se.len); ob.writestring(" ("); escapePath(ob, name); ob.writestring(")"); ob.writenl(); } { auto f = File(name); if (f.read()) { error("cannot read file %s", f.toChars()); return new ErrorExp(); } else { f._ref = 1; se = new StringExp(loc, f.buffer, f.len); } } return se.semantic(sc); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class AssertExp : UnaExp { Expression msg; extern (D) this(Loc loc, Expression e, Expression msg = null) { super(loc, TOKassert, __traits(classInstanceSize, AssertExp), e); this.msg = msg; } override Expression syntaxCopy() { return new AssertExp(loc, e1.syntaxCopy(), msg ? msg.syntaxCopy() : null); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("AssertExp::semantic('%s')\n", toChars()); } if (Expression ex = unaSemantic(sc)) return ex; e1 = resolveProperties(sc, e1); // BUG: see if we can do compile time elimination of the Assert e1 = e1.optimize(WANTvalue); e1 = e1.toBoolean(sc); if (msg) { msg = msg.semantic(sc); msg = resolveProperties(sc, msg); msg = msg.implicitCastTo(sc, Type.tchar.constOf().arrayOf()); msg = msg.optimize(WANTvalue); } if (e1.op == TOKerror) return e1; if (msg && msg.op == TOKerror) return msg; auto f1 = checkNonAssignmentArrayOp(e1); auto f2 = msg && checkNonAssignmentArrayOp(msg); if (f1 || f2) return new ErrorExp(); if (e1.isBool(false)) { FuncDeclaration fd = sc.parent.isFuncDeclaration(); if (fd) fd.hasReturnExp |= 4; sc.callSuper |= CSXhalt; if (sc.fieldinit) { for (size_t i = 0; i < sc.fieldinit_dim; i++) sc.fieldinit[i] |= CSXhalt; } if (!global.params.useAssert) { Expression e = new HaltExp(loc); e = e.semantic(sc); return e; } } type = Type.tvoid; return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class DotIdExp : UnaExp { Identifier ident; bool noderef; // true if the result of the expression will never be dereferenced extern (D) this(Loc loc, Expression e, Identifier ident) { super(loc, TOKdotid, __traits(classInstanceSize, DotIdExp), e); this.ident = ident; } static DotIdExp create(Loc loc, Expression e, Identifier ident) { return new DotIdExp(loc, e, ident); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("DotIdExp::semantic(this = %p, '%s')\n", this, toChars()); //printf("e1.op = %d, '%s'\n", e1.op, Token::toChars(e1.op)); } Expression e = semanticY(sc, 1); if (e && isDotOpDispatch(e)) { uint errors = global.startGagging(); e = resolvePropertiesX(sc, e); if (global.endGagging(errors)) e = null; /* fall down to UFCS */ else return e; } if (!e) // if failed to find the property { /* If ident is not a valid property, rewrite: * e1.ident * as: * .ident(e1) */ e = resolveUFCSProperties(sc, this); } return e; } // Run semantic in e1 Expression semanticX(Scope* sc) { //printf("DotIdExp::semanticX(this = %p, '%s')\n", this, toChars()); if (Expression ex = unaSemantic(sc)) return ex; if (ident == Id._mangleof) { // symbol.mangleof Dsymbol ds; switch (e1.op) { case TOKscope: ds = (cast(ScopeExp)e1).sds; goto L1; case TOKvar: ds = (cast(VarExp)e1).var; goto L1; case TOKdotvar: ds = (cast(DotVarExp)e1).var; goto L1; case TOKoverloadset: ds = (cast(OverExp)e1).vars; goto L1; case TOKtemplate: { TemplateExp te = cast(TemplateExp)e1; ds = te.fd ? cast(Dsymbol)te.fd : te.td; } L1: { assert(ds); if (auto f = ds.isFuncDeclaration()) { if (f.checkForwardRef(loc)) return new ErrorExp(); } OutBuffer buf; mangleToBuffer(ds, &buf); const s = buf.peekSlice(); Expression e = new StringExp(loc, buf.extractString(), s.length); e = e.semantic(sc); return e; } default: break; } } if (e1.op == TOKvar && e1.type.toBasetype().ty == Tsarray && ident == Id.length) { // bypass checkPurity return e1.type.dotExp(sc, e1, ident, noderef ? Type.DotExpFlag.noDeref : 0); } if (e1.op == TOKdot) { } else { e1 = resolvePropertiesX(sc, e1); } if (e1.op == TOKtuple && ident == Id.offsetof) { /* 'distribute' the .offsetof to each of the tuple elements. */ TupleExp te = cast(TupleExp)e1; auto exps = new Expressions(); exps.setDim(te.exps.dim); for (size_t i = 0; i < exps.dim; i++) { Expression e = (*te.exps)[i]; e = e.semantic(sc); e = new DotIdExp(e.loc, e, Id.offsetof); (*exps)[i] = e; } // Don't evaluate te.e0 in runtime Expression e = new TupleExp(loc, null, exps); e = e.semantic(sc); return e; } if (e1.op == TOKtuple && ident == Id.length) { TupleExp te = cast(TupleExp)e1; // Don't evaluate te.e0 in runtime Expression e = new IntegerExp(loc, te.exps.dim, Type.tsize_t); return e; } // https://issues.dlang.org/show_bug.cgi?id=14416 // Template has no built-in properties except for 'stringof'. if ((e1.op == TOKdottd || e1.op == TOKtemplate) && ident != Id.stringof) { error("template %s does not have property '%s'", e1.toChars(), ident.toChars()); return new ErrorExp(); } if (!e1.type) { error("expression %s does not have property '%s'", e1.toChars(), ident.toChars()); return new ErrorExp(); } return this; } // Resolve e1.ident without seeing UFCS. // If flag == 1, stop "not a property" error and return NULL. Expression semanticY(Scope* sc, int flag) { //printf("DotIdExp::semanticY(this = %p, '%s')\n", this, toChars()); //{ static int z; fflush(stdout); if (++z == 10) *(char*)0=0; } /* Special case: rewrite this.id and super.id * to be classtype.id and baseclasstype.id * if we have no this pointer. */ if ((e1.op == TOKthis || e1.op == TOKsuper) && !hasThis(sc)) { if (AggregateDeclaration ad = sc.getStructClassScope()) { if (e1.op == TOKthis) { e1 = new TypeExp(e1.loc, ad.type); } else { ClassDeclaration cd = ad.isClassDeclaration(); if (cd && cd.baseClass) e1 = new TypeExp(e1.loc, cd.baseClass.type); } } } Expression e = semanticX(sc); if (e != this) return e; Expression eleft; Expression eright; if (e1.op == TOKdot) { DotExp de = cast(DotExp)e1; eleft = de.e1; eright = de.e2; } else { eleft = null; eright = e1; } Type t1b = e1.type.toBasetype(); if (eright.op == TOKscope) // also used for template alias's { ScopeExp ie = cast(ScopeExp)eright; int flags = SearchLocalsOnly; /* Disable access to another module's private imports. * The check for 'is sds our current module' is because * the current module should have access to its own imports. */ if (ie.sds.isModule() && ie.sds != sc._module) flags |= IgnorePrivateImports; if (sc.flags & SCOPEignoresymbolvisibility) flags |= IgnoreSymbolVisibility; Dsymbol s = ie.sds.search(loc, ident, flags); /* Check for visibility before resolving aliases because public * aliases to private symbols are public. */ if (s && !(sc.flags & SCOPEignoresymbolvisibility) && !symbolIsVisible(sc._module, s)) { if (s.isDeclaration()) .error(loc, "%s is not visible from module %s", s.toPrettyChars(), sc._module.toChars()); else .deprecation(loc, "%s is not visible from module %s", s.toPrettyChars(), sc._module.toChars()); // s = null; } if (s) { if (auto p = s.isPackage()) checkAccess(loc, sc, p); // if 's' is a tuple variable, the tuple is returned. s = s.toAlias(); checkDeprecated(sc, s); EnumMember em = s.isEnumMember(); if (em) { return em.getVarExp(loc, sc); } VarDeclaration v = s.isVarDeclaration(); if (v) { //printf("DotIdExp:: Identifier '%s' is a variable, type '%s'\n", toChars(), v.type.toChars()); if (!v.type || !v.type.deco && v.inuse) { if (v.inuse) error("circular reference to %s '%s'", v.kind(), v.toPrettyChars()); else error("forward reference to %s '%s'", v.kind(), v.toPrettyChars()); return new ErrorExp(); } if (v.type.ty == Terror) return new ErrorExp(); if ((v.storage_class & STCmanifest) && v._init) { if (v.inuse) { .error(loc, "circular initialization of %s '%s'", v.kind(), v.toPrettyChars()); return new ErrorExp(); } e = v.expandInitializer(loc); v.inuse++; e = e.semantic(sc); v.inuse--; return e; } if (v.needThis()) { if (!eleft) eleft = new ThisExp(loc); e = new DotVarExp(loc, eleft, v); e = e.semantic(sc); } else { e = new VarExp(loc, v); if (eleft) { e = new CommaExp(loc, eleft, e); e.type = v.type; } } e = e.deref(); return e.semantic(sc); } FuncDeclaration f = s.isFuncDeclaration(); if (f) { //printf("it's a function\n"); if (!f.functionSemantic()) return new ErrorExp(); if (f.needThis()) { if (!eleft) eleft = new ThisExp(loc); e = new DotVarExp(loc, eleft, f, true); e = e.semantic(sc); } else { e = new VarExp(loc, f, true); if (eleft) { e = new CommaExp(loc, eleft, e); e.type = f.type; } } return e; } if (auto td = s.isTemplateDeclaration()) { if (eleft) e = new DotTemplateExp(loc, eleft, td); else e = new TemplateExp(loc, td); e = e.semantic(sc); return e; } if (OverDeclaration od = s.isOverDeclaration()) { e = new VarExp(loc, od, true); if (eleft) { e = new CommaExp(loc, eleft, e); e.type = Type.tvoid; // ambiguous type? } return e; } OverloadSet o = s.isOverloadSet(); if (o) { //printf("'%s' is an overload set\n", o.toChars()); return new OverExp(loc, o); } if (auto t = s.getType()) { return (new TypeExp(loc, t)).semantic(sc); } TupleDeclaration tup = s.isTupleDeclaration(); if (tup) { if (eleft) { e = new DotVarExp(loc, eleft, tup); e = e.semantic(sc); return e; } e = new TupleExp(loc, tup); e = e.semantic(sc); return e; } ScopeDsymbol sds = s.isScopeDsymbol(); if (sds) { //printf("it's a ScopeDsymbol %s\n", ident.toChars()); e = new ScopeExp(loc, sds); e = e.semantic(sc); if (eleft) e = new DotExp(loc, eleft, e); return e; } Import imp = s.isImport(); if (imp) { ie = new ScopeExp(loc, imp.pkg); return ie.semantic(sc); } // BUG: handle other cases like in IdentifierExp::semantic() debug { printf("s = '%s', kind = '%s'\n", s.toChars(), s.kind()); } assert(0); } else if (ident == Id.stringof) { const p = ie.toChars(); e = new StringExp(loc, cast(char*)p, strlen(p)); e = e.semantic(sc); return e; } if (ie.sds.isPackage() || ie.sds.isImport() || ie.sds.isModule()) { flag = 0; } if (flag) return null; s = ie.sds.search_correct(ident); if (s) error("undefined identifier `%s` in %s `%s`, did you mean %s `%s`?", ident.toChars(), ie.sds.kind(), ie.sds.toPrettyChars(), s.kind(), s.toChars()); else error("undefined identifier `%s` in %s `%s`", ident.toChars(), ie.sds.kind(), ie.sds.toPrettyChars()); return new ErrorExp(); } else if (t1b.ty == Tpointer && e1.type.ty != Tenum && ident != Id._init && ident != Id.__sizeof && ident != Id.__xalignof && ident != Id.offsetof && ident != Id._mangleof && ident != Id.stringof) { Type t1bn = t1b.nextOf(); if (flag) { AggregateDeclaration ad = isAggregate(t1bn); if (ad && !ad.members) // https://issues.dlang.org/show_bug.cgi?id=11312 return null; } /* Rewrite: * p.ident * as: * (*p).ident */ if (flag && t1bn.ty == Tvoid) return null; e = new PtrExp(loc, e1); e = e.semantic(sc); return e.type.dotExp(sc, e, ident, flag | (noderef ? Type.DotExpFlag.noDeref : 0)); } else { if (e1.op == TOKtype || e1.op == TOKtemplate) flag = 0; e = e1.type.dotExp(sc, e1, ident, flag | (noderef ? Type.DotExpFlag.noDeref : 0)); if (e) e = e.semantic(sc); return e; } } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * Mainly just a placeholder */ extern (C++) final class DotTemplateExp : UnaExp { TemplateDeclaration td; extern (D) this(Loc loc, Expression e, TemplateDeclaration td) { super(loc, TOKdottd, __traits(classInstanceSize, DotTemplateExp), e); this.td = td; } override Expression semantic(Scope* sc) { if (Expression ex = unaSemantic(sc)) return ex; return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class DotVarExp : UnaExp { Declaration var; bool hasOverloads; extern (D) this(Loc loc, Expression e, Declaration var, bool hasOverloads = true) { if (var.isVarDeclaration()) hasOverloads = false; super(loc, TOKdotvar, __traits(classInstanceSize, DotVarExp), e); //printf("DotVarExp()\n"); this.var = var; this.hasOverloads = hasOverloads; } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("DotVarExp::semantic('%s')\n", toChars()); } if (type) return this; var = var.toAlias().isDeclaration(); e1 = e1.semantic(sc); if (auto tup = var.isTupleDeclaration()) { /* Replace: * e1.tuple(a, b, c) * with: * tuple(e1.a, e1.b, e1.c) */ Expression e0; Expression ev = sc.func ? extractSideEffect(sc, "__tup", e0, e1) : e1; auto exps = new Expressions(); exps.reserve(tup.objects.dim); for (size_t i = 0; i < tup.objects.dim; i++) { RootObject o = (*tup.objects)[i]; Expression e; if (o.dyncast() == DYNCAST.expression) { e = cast(Expression)o; if (e.op == TOKdsymbol) { Dsymbol s = (cast(DsymbolExp)e).s; e = new DotVarExp(loc, ev, s.isDeclaration()); } } else if (o.dyncast() == DYNCAST.dsymbol) { e = new DsymbolExp(loc, cast(Dsymbol)o); } else if (o.dyncast() == DYNCAST.type) { e = new TypeExp(loc, cast(Type)o); } else { error("%s is not an expression", o.toChars()); return new ErrorExp(); } exps.push(e); } Expression e = new TupleExp(loc, e0, exps); e = e.semantic(sc); return e; } e1 = e1.addDtorHook(sc); Type t1 = e1.type; if (FuncDeclaration fd = var.isFuncDeclaration()) { // for functions, do checks after overload resolution if (!fd.functionSemantic()) return new ErrorExp(); /* https://issues.dlang.org/show_bug.cgi?id=13843 * If fd obviously has no overloads, we should * normalize AST, and it will give a chance to wrap fd with FuncExp. */ if (fd.isNested() || fd.isFuncLiteralDeclaration()) { // (e1, fd) auto e = DsymbolExp.resolve(loc, sc, fd, false); return Expression.combine(e1, e); } type = fd.type; assert(type); } else if (OverDeclaration od = var.isOverDeclaration()) { type = Type.tvoid; // ambiguous type? } else { type = var.type; if (!type && global.errors) { // var is goofed up, just return 0 return new ErrorExp(); } assert(type); if (t1.ty == Tpointer) t1 = t1.nextOf(); type = type.addMod(t1.mod); Dsymbol vparent = var.toParent(); AggregateDeclaration ad = vparent ? vparent.isAggregateDeclaration() : null; if (Expression e1x = getRightThis(loc, sc, ad, e1, var, 1)) e1 = e1x; else { /* Later checkRightThis will report correct error for invalid field variable access. */ Expression e = new VarExp(loc, var); e = e.semantic(sc); return e; } checkAccess(loc, sc, e1, var); VarDeclaration v = var.isVarDeclaration(); if (v && (v.isDataseg() || (v.storage_class & STCmanifest))) { Expression e = expandVar(WANTvalue, v); if (e) return e; } if (v && v.isDataseg()) // fix https://issues.dlang.org/show_bug.cgi?id=8238 { // (e1, v) checkAccess(loc, sc, e1, v); Expression e = new VarExp(loc, v); e = new CommaExp(loc, e1, e); e = e.semantic(sc); return e; } } //printf("-DotVarExp::semantic('%s')\n", toChars()); return this; } override int checkModifiable(Scope* sc, int flag) { //printf("DotVarExp::checkModifiable %s %s\n", toChars(), type.toChars()); if (checkUnsafeAccess(sc, this, false, !flag)) return 2; if (e1.op == TOKthis) return var.checkModify(loc, sc, type, e1, flag); //printf("\te1 = %s\n", e1.toChars()); return e1.checkModifiable(sc, flag); } bool checkReadModifyWrite(); override bool isLvalue() { return true; } override Expression toLvalue(Scope* sc, Expression e) { //printf("DotVarExp::toLvalue(%s)\n", toChars()); return this; } override Expression modifiableLvalue(Scope* sc, Expression e) { version (none) { printf("DotVarExp::modifiableLvalue(%s)\n", toChars()); printf("e1.type = %s\n", e1.type.toChars()); printf("var.type = %s\n", var.type.toChars()); } return Expression.modifiableLvalue(sc, e); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * foo.bar!(args) */ extern (C++) final class DotTemplateInstanceExp : UnaExp { TemplateInstance ti; extern (D) this(Loc loc, Expression e, Identifier name, Objects* tiargs) { super(loc, TOKdotti, __traits(classInstanceSize, DotTemplateInstanceExp), e); //printf("DotTemplateInstanceExp()\n"); this.ti = new TemplateInstance(loc, name, tiargs); } extern (D) this(Loc loc, Expression e, TemplateInstance ti) { super(loc, TOKdotti, __traits(classInstanceSize, DotTemplateInstanceExp), e); this.ti = ti; } override Expression syntaxCopy() { return new DotTemplateInstanceExp(loc, e1.syntaxCopy(), ti.name, TemplateInstance.arraySyntaxCopy(ti.tiargs)); } bool findTempDecl(Scope* sc) { static if (LOGSEMANTIC) { printf("DotTemplateInstanceExp::findTempDecl('%s')\n", toChars()); } if (ti.tempdecl) return true; Expression e = new DotIdExp(loc, e1, ti.name); e = e.semantic(sc); if (e.op == TOKdot) e = (cast(DotExp)e).e2; Dsymbol s = null; switch (e.op) { case TOKoverloadset: s = (cast(OverExp)e).vars; break; case TOKdottd: s = (cast(DotTemplateExp)e).td; break; case TOKscope: s = (cast(ScopeExp)e).sds; break; case TOKdotvar: s = (cast(DotVarExp)e).var; break; case TOKvar: s = (cast(VarExp)e).var; break; default: return false; } return ti.updateTempDecl(sc, s); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("DotTemplateInstanceExp::semantic('%s')\n", toChars()); } // Indicate we need to resolve by UFCS. Expression e = semanticY(sc, 1); if (!e) e = resolveUFCSProperties(sc, this); return e; } // Resolve e1.ident!tiargs without seeing UFCS. // If flag == 1, stop "not a property" error and return NULL. Expression semanticY(Scope* sc, int flag) { static if (LOGSEMANTIC) { printf("DotTemplateInstanceExpY::semantic('%s')\n", toChars()); } auto die = new DotIdExp(loc, e1, ti.name); Expression e = die.semanticX(sc); if (e == die) { e1 = die.e1; // take back Type t1b = e1.type.toBasetype(); if (t1b.ty == Tarray || t1b.ty == Tsarray || t1b.ty == Taarray || t1b.ty == Tnull || (t1b.isTypeBasic() && t1b.ty != Tvoid)) { /* No built-in type has templatized properties, so do shortcut. * It is necessary in: 1024.max!"a < b" */ if (flag) return null; } e = die.semanticY(sc, flag); if (flag && e && isDotOpDispatch(e)) { /* opDispatch!tiargs would be a function template that needs IFTI, * so it's not a template */ e = null; /* fall down to UFCS */ } if (flag && !e) return null; } assert(e); L1: if (e.op == TOKerror) return e; if (e.op == TOKdotvar) { DotVarExp dve = cast(DotVarExp)e; if (FuncDeclaration fd = dve.var.isFuncDeclaration()) { TemplateDeclaration td = fd.findTemplateDeclRoot(); if (td) { e = new DotTemplateExp(dve.loc, dve.e1, td); e = e.semantic(sc); } } else if (OverDeclaration od = dve.var.isOverDeclaration()) { e1 = dve.e1; // pull semantic() result if (!findTempDecl(sc)) goto Lerr; if (ti.needsTypeInference(sc)) return this; ti.semantic(sc); if (!ti.inst || ti.errors) // if template failed to expand return new ErrorExp(); Dsymbol s = ti.toAlias(); Declaration v = s.isDeclaration(); if (v) { if (v.type && !v.type.deco) v.type = v.type.semantic(v.loc, sc); e = new DotVarExp(loc, e1, v); e = e.semantic(sc); return e; } e = new ScopeExp(loc, ti); e = new DotExp(loc, e1, e); e = e.semantic(sc); return e; } } else if (e.op == TOKvar) { VarExp ve = cast(VarExp)e; if (FuncDeclaration fd = ve.var.isFuncDeclaration()) { TemplateDeclaration td = fd.findTemplateDeclRoot(); if (td) { e = new TemplateExp(ve.loc, td); e = e.semantic(sc); } } else if (OverDeclaration od = ve.var.isOverDeclaration()) { ti.tempdecl = od; e = new ScopeExp(loc, ti); e = e.semantic(sc); return e; } } if (e.op == TOKdottd) { DotTemplateExp dte = cast(DotTemplateExp)e; e1 = dte.e1; // pull semantic() result ti.tempdecl = dte.td; if (!ti.semanticTiargs(sc)) return new ErrorExp(); if (ti.needsTypeInference(sc)) return this; ti.semantic(sc); if (!ti.inst || ti.errors) // if template failed to expand return new ErrorExp(); Dsymbol s = ti.toAlias(); Declaration v = s.isDeclaration(); if (v && (v.isFuncDeclaration() || v.isVarDeclaration())) { e = new DotVarExp(loc, e1, v); e = e.semantic(sc); return e; } e = new ScopeExp(loc, ti); e = new DotExp(loc, e1, e); e = e.semantic(sc); return e; } else if (e.op == TOKtemplate) { ti.tempdecl = (cast(TemplateExp)e).td; e = new ScopeExp(loc, ti); e = e.semantic(sc); return e; } else if (e.op == TOKdot) { DotExp de = cast(DotExp)e; if (de.e2.op == TOKoverloadset) { if (!findTempDecl(sc) || !ti.semanticTiargs(sc)) { return new ErrorExp(); } if (ti.needsTypeInference(sc)) return this; ti.semantic(sc); if (!ti.inst || ti.errors) // if template failed to expand return new ErrorExp(); Dsymbol s = ti.toAlias(); Declaration v = s.isDeclaration(); if (v) { if (v.type && !v.type.deco) v.type = v.type.semantic(v.loc, sc); e = new DotVarExp(loc, e1, v); e = e.semantic(sc); return e; } e = new ScopeExp(loc, ti); e = new DotExp(loc, e1, e); e = e.semantic(sc); return e; } } else if (e.op == TOKoverloadset) { OverExp oe = cast(OverExp)e; ti.tempdecl = oe.vars; e = new ScopeExp(loc, ti); e = e.semantic(sc); return e; } Lerr: error("%s isn't a template", e.toChars()); return new ErrorExp(); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class DelegateExp : UnaExp { FuncDeclaration func; bool hasOverloads; extern (D) this(Loc loc, Expression e, FuncDeclaration f, bool hasOverloads = true) { super(loc, TOKdelegate, __traits(classInstanceSize, DelegateExp), e); this.func = f; this.hasOverloads = hasOverloads; } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("DelegateExp::semantic('%s')\n", toChars()); } if (type) return this; e1 = e1.semantic(sc); type = new TypeDelegate(func.type); type = type.semantic(loc, sc); FuncDeclaration f = func.toAliasFunc(); AggregateDeclaration ad = f.toParent().isAggregateDeclaration(); if (f.needThis()) e1 = getRightThis(loc, sc, ad, e1, f); if (f.type.ty == Tfunction) { TypeFunction tf = cast(TypeFunction)f.type; if (!MODmethodConv(e1.type.mod, f.type.mod)) { OutBuffer thisBuf, funcBuf; MODMatchToBuffer(&thisBuf, e1.type.mod, tf.mod); MODMatchToBuffer(&funcBuf, tf.mod, e1.type.mod); error("%smethod %s is not callable using a %s%s", funcBuf.peekString(), f.toPrettyChars(), thisBuf.peekString(), e1.toChars()); return new ErrorExp(); } } if (ad && ad.isClassDeclaration() && ad.type != e1.type) { // A downcast is required for interfaces // https://issues.dlang.org/show_bug.cgi?id=3706 e1 = new CastExp(loc, e1, ad.type); e1 = e1.semantic(sc); } return this; } override void accept(Visitor v) { v.visit(this); } override void printAST(int indent) { UnaExp.printAST(indent); foreach (i; 0 .. indent + 2) printf(" "); printf(".func: %s\n", func ? func.toChars() : ""); } } /*********************************************************** */ extern (C++) final class DotTypeExp : UnaExp { Dsymbol sym; // symbol that represents a type extern (D) this(Loc loc, Expression e, Dsymbol s) { super(loc, TOKdottype, __traits(classInstanceSize, DotTypeExp), e); this.sym = s; } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("DotTypeExp::semantic('%s')\n", toChars()); } if (type) return this; if (auto e = unaSemantic(sc)) return e; type = sym.getType().addMod(e1.type.mod); return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class CallExp : UnaExp { Expressions* arguments; // function arguments FuncDeclaration f; // symbol to call bool directcall; // true if a virtual call is devirtualized extern (D) this(Loc loc, Expression e, Expressions* exps) { super(loc, TOKcall, __traits(classInstanceSize, CallExp), e); this.arguments = exps; } extern (D) this(Loc loc, Expression e) { super(loc, TOKcall, __traits(classInstanceSize, CallExp), e); } extern (D) this(Loc loc, Expression e, Expression earg1) { super(loc, TOKcall, __traits(classInstanceSize, CallExp), e); auto arguments = new Expressions(); if (earg1) { arguments.setDim(1); (*arguments)[0] = earg1; } this.arguments = arguments; } extern (D) this(Loc loc, Expression e, Expression earg1, Expression earg2) { super(loc, TOKcall, __traits(classInstanceSize, CallExp), e); auto arguments = new Expressions(); arguments.setDim(2); (*arguments)[0] = earg1; (*arguments)[1] = earg2; this.arguments = arguments; } static CallExp create(Loc loc, Expression e, Expressions* exps) { return new CallExp(loc, e, exps); } static CallExp create(Loc loc, Expression e) { return new CallExp(loc, e); } static CallExp create(Loc loc, Expression e, Expression earg1) { return new CallExp(loc, e, earg1); } override Expression syntaxCopy() { return new CallExp(loc, e1.syntaxCopy(), arraySyntaxCopy(arguments)); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("CallExp::semantic() %s\n", toChars()); } if (type) return this; // semantic() already run version (none) { if (arguments && arguments.dim) { Expression earg = (*arguments)[0]; earg.print(); if (earg.type) earg.type.print(); } } Type t1; Objects* tiargs = null; // initial list of template arguments Expression ethis = null; Type tthis = null; Expression e1org = e1; if (e1.op == TOKcomma) { /* Rewrite (a,b)(args) as (a,(b(args))) */ auto ce = cast(CommaExp)e1; e1 = ce.e2; ce.e2 = this; return ce.semantic(sc); } if (e1.op == TOKdelegate) { DelegateExp de = cast(DelegateExp)e1; e1 = new DotVarExp(de.loc, de.e1, de.func, de.hasOverloads); return semantic(sc); } if (e1.op == TOKfunction) { if (arrayExpressionSemantic(arguments, sc) || preFunctionParameters(loc, sc, arguments)) { return new ErrorExp(); } // Run e1 semantic even if arguments have any errors FuncExp fe = cast(FuncExp)e1; e1 = fe.semantic(sc, arguments); if (e1.op == TOKerror) return e1; } if (Expression ex = resolveUFCS(sc, this)) return ex; /* This recognizes: * foo!(tiargs)(funcargs) */ if (e1.op == TOKscope) { ScopeExp se = cast(ScopeExp)e1; TemplateInstance ti = se.sds.isTemplateInstance(); if (ti) { /* Attempt to instantiate ti. If that works, go with it. * If not, go with partial explicit specialization. */ WithScopeSymbol withsym; if (!ti.findTempDecl(sc, &withsym) || !ti.semanticTiargs(sc)) { return new ErrorExp(); } if (withsym && withsym.withstate.wthis) { e1 = new VarExp(e1.loc, withsym.withstate.wthis); e1 = new DotTemplateInstanceExp(e1.loc, e1, ti); goto Ldotti; } if (ti.needsTypeInference(sc, 1)) { /* Go with partial explicit specialization */ tiargs = ti.tiargs; assert(ti.tempdecl); if (TemplateDeclaration td = ti.tempdecl.isTemplateDeclaration()) e1 = new TemplateExp(loc, td); else if (OverDeclaration od = ti.tempdecl.isOverDeclaration()) e1 = new VarExp(loc, od); else e1 = new OverExp(loc, ti.tempdecl.isOverloadSet()); } else { Expression e1x = e1.semantic(sc); if (e1x.op == TOKerror) return e1x; e1 = e1x; } } } /* This recognizes: * expr.foo!(tiargs)(funcargs) */ Ldotti: if (e1.op == TOKdotti && !e1.type) { DotTemplateInstanceExp se = cast(DotTemplateInstanceExp)e1; TemplateInstance ti = se.ti; { /* Attempt to instantiate ti. If that works, go with it. * If not, go with partial explicit specialization. */ if (!se.findTempDecl(sc) || !ti.semanticTiargs(sc)) { return new ErrorExp(); } if (ti.needsTypeInference(sc, 1)) { /* Go with partial explicit specialization */ tiargs = ti.tiargs; assert(ti.tempdecl); if (TemplateDeclaration td = ti.tempdecl.isTemplateDeclaration()) e1 = new DotTemplateExp(loc, se.e1, td); else if (OverDeclaration od = ti.tempdecl.isOverDeclaration()) { e1 = new DotVarExp(loc, se.e1, od, true); } else e1 = new DotExp(loc, se.e1, new OverExp(loc, ti.tempdecl.isOverloadSet())); } else { Expression e1x = e1.semantic(sc); if (e1x.op == TOKerror) return e1x; e1 = e1x; } } } Lagain: //printf("Lagain: %s\n", toChars()); f = null; if (e1.op == TOKthis || e1.op == TOKsuper) { // semantic() run later for these } else { if (e1.op == TOKdotid) { DotIdExp die = cast(DotIdExp)e1; e1 = die.semantic(sc); /* Look for e1 having been rewritten to expr.opDispatch!(string) * We handle such earlier, so go back. * Note that in the rewrite, we carefully did not run semantic() on e1 */ if (e1.op == TOKdotti && !e1.type) { goto Ldotti; } } else { static __gshared int nest; if (++nest > 500) { error("recursive evaluation of %s", toChars()); --nest; return new ErrorExp(); } Expression ex = unaSemantic(sc); --nest; if (ex) return ex; } /* Look for e1 being a lazy parameter */ if (e1.op == TOKvar) { VarExp ve = cast(VarExp)e1; if (ve.var.storage_class & STClazy) { // lazy parameters can be called without violating purity and safety Type tw = ve.var.type; Type tc = ve.var.type.substWildTo(MODconst); auto tf = new TypeFunction(null, tc, 0, LINKd, STCsafe | STCpure); (tf = cast(TypeFunction)tf.semantic(loc, sc)).next = tw; // hack for bug7757 auto t = new TypeDelegate(tf); ve.type = t.semantic(loc, sc); } VarDeclaration v = ve.var.isVarDeclaration(); if (v && ve.checkPurity(sc, v)) return new ErrorExp(); } if (e1.op == TOKsymoff && (cast(SymOffExp)e1).hasOverloads) { SymOffExp se = cast(SymOffExp)e1; e1 = new VarExp(se.loc, se.var, true); e1 = e1.semantic(sc); } else if (e1.op == TOKdot) { DotExp de = cast(DotExp)e1; if (de.e2.op == TOKoverloadset) { ethis = de.e1; tthis = de.e1.type; e1 = de.e2; } } else if (e1.op == TOKstar && e1.type.ty == Tfunction) { // Rewrite (*fp)(arguments) to fp(arguments) e1 = (cast(PtrExp)e1).e1; } } t1 = e1.type ? e1.type.toBasetype() : null; if (e1.op == TOKerror) return e1; if (arrayExpressionSemantic(arguments, sc) || preFunctionParameters(loc, sc, arguments)) { return new ErrorExp(); } // Check for call operator overload if (t1) { if (t1.ty == Tstruct) { auto sd = (cast(TypeStruct)t1).sym; sd.size(loc); // Resolve forward references to construct object if (sd.sizeok != SIZEOKdone) return new ErrorExp(); if (!sd.ctor) sd.ctor = sd.searchCtor(); // First look for constructor if (e1.op == TOKtype && sd.ctor) { if (!sd.noDefaultCtor && !(arguments && arguments.dim)) goto Lx; auto sle = new StructLiteralExp(loc, sd, null, e1.type); if (!sd.fill(loc, sle.elements, true)) return new ErrorExp(); if (checkFrameAccess(loc, sc, sd, sle.elements.dim)) return new ErrorExp(); // https://issues.dlang.org/show_bug.cgi?id=14556 // Set concrete type to avoid further redundant semantic(). sle.type = e1.type; /* Constructor takes a mutable object, so don't use * the immutable initializer symbol. */ sle.useStaticInit = false; Expression e = sle; if (auto cf = sd.ctor.isCtorDeclaration()) { e = new DotVarExp(loc, e, cf, true); } else if (auto td = sd.ctor.isTemplateDeclaration()) { e = new DotTemplateExp(loc, e, td); } else if (auto os = sd.ctor.isOverloadSet()) { e = new DotExp(loc, e, new OverExp(loc, os)); } else assert(0); e = new CallExp(loc, e, arguments); e = e.semantic(sc); return e; } // No constructor, look for overload of opCall if (search_function(sd, Id.call)) goto L1; // overload of opCall, therefore it's a call if (e1.op != TOKtype) { if (sd.aliasthis && e1.type != att1) { if (!att1 && e1.type.checkAliasThisRec()) att1 = e1.type; e1 = resolveAliasThis(sc, e1); goto Lagain; } error("%s %s does not overload ()", sd.kind(), sd.toChars()); return new ErrorExp(); } /* It's a struct literal */ Lx: Expression e = new StructLiteralExp(loc, sd, arguments, e1.type); e = e.semantic(sc); return e; } else if (t1.ty == Tclass) { L1: // Rewrite as e1.call(arguments) Expression e = new DotIdExp(loc, e1, Id.call); e = new CallExp(loc, e, arguments); e = e.semantic(sc); return e; } else if (e1.op == TOKtype && t1.isscalar()) { Expression e; // Make sure to use the the enum type itself rather than its // base type // https://issues.dlang.org/show_bug.cgi?id=16346 if (e1.type.ty == Tenum) { t1 = e1.type; } if (!arguments || arguments.dim == 0) { e = t1.defaultInitLiteral(loc); } else if (arguments.dim == 1) { e = (*arguments)[0]; e = e.implicitCastTo(sc, t1); e = new CastExp(loc, e, t1); } else { error("more than one argument for construction of %s", t1.toChars()); e = new ErrorExp(); } e = e.semantic(sc); return e; } } static FuncDeclaration resolveOverloadSet(Loc loc, Scope* sc, OverloadSet os, Objects* tiargs, Type tthis, Expressions* arguments) { FuncDeclaration f = null; foreach (s; os.a) { if (tiargs && s.isFuncDeclaration()) continue; if (auto f2 = resolveFuncCall(loc, sc, s, tiargs, tthis, arguments, 1)) { if (f2.errors) return null; if (f) { /* Error if match in more than one overload set, * even if one is a 'better' match than the other. */ ScopeDsymbol.multiplyDefined(loc, f, f2); } else f = f2; } } if (!f) .error(loc, "no overload matches for %s", os.toChars()); else if (f.errors) f = null; return f; } if (e1.op == TOKdotvar && t1.ty == Tfunction || e1.op == TOKdottd) { UnaExp ue = cast(UnaExp)e1; Expression ue1 = ue.e1; Expression ue1old = ue1; // need for 'right this' check VarDeclaration v; if (ue1.op == TOKvar && (v = (cast(VarExp)ue1).var.isVarDeclaration()) !is null && v.needThis()) { ue.e1 = new TypeExp(ue1.loc, ue1.type); ue1 = null; } DotVarExp dve; DotTemplateExp dte; Dsymbol s; if (e1.op == TOKdotvar) { dve = cast(DotVarExp)e1; dte = null; s = dve.var; tiargs = null; } else { dve = null; dte = cast(DotTemplateExp)e1; s = dte.td; } // Do overload resolution f = resolveFuncCall(loc, sc, s, tiargs, ue1 ? ue1.type : null, arguments); if (!f || f.errors || f.type.ty == Terror) return new ErrorExp(); if (f.interfaceVirtual) { /* Cast 'this' to the type of the interface, and replace f with the interface's equivalent */ auto b = f.interfaceVirtual; auto ad2 = b.sym; ue.e1 = ue.e1.castTo(sc, ad2.type.addMod(ue.e1.type.mod)); ue.e1 = ue.e1.semantic(sc); ue1 = ue.e1; auto vi = f.findVtblIndex(&ad2.vtbl, cast(int)ad2.vtbl.dim); assert(vi >= 0); f = ad2.vtbl[vi].isFuncDeclaration(); assert(f); } if (f.needThis()) { AggregateDeclaration ad = f.toParent2().isAggregateDeclaration(); ue.e1 = getRightThis(loc, sc, ad, ue.e1, f); if (ue.e1.op == TOKerror) return ue.e1; ethis = ue.e1; tthis = ue.e1.type; if (!(f.type.ty == Tfunction && (cast(TypeFunction)f.type).isscope)) { if (global.params.vsafe && checkParamArgumentEscape(sc, f, Id.This, ethis, false)) return new ErrorExp(); } } /* Cannot call public functions from inside invariant * (because then the invariant would have infinite recursion) */ if (sc.func && sc.func.isInvariantDeclaration() && ue.e1.op == TOKthis && f.addPostInvariant()) { error("cannot call public/export function %s from invariant", f.toChars()); return new ErrorExp(); } checkDeprecated(sc, f); checkPurity(sc, f); checkSafety(sc, f); checkNogc(sc, f); checkAccess(loc, sc, ue.e1, f); if (!f.needThis()) { e1 = Expression.combine(ue.e1, new VarExp(loc, f, false)); } else { if (ue1old.checkRightThis(sc)) return new ErrorExp(); if (e1.op == TOKdotvar) { dve.var = f; e1.type = f.type; } else { e1 = new DotVarExp(loc, dte.e1, f, false); e1 = e1.semantic(sc); if (e1.op == TOKerror) return new ErrorExp(); ue = cast(UnaExp)e1; } version (none) { printf("ue.e1 = %s\n", ue.e1.toChars()); printf("f = %s\n", f.toChars()); printf("t = %s\n", t.toChars()); printf("e1 = %s\n", e1.toChars()); printf("e1.type = %s\n", e1.type.toChars()); } // See if we need to adjust the 'this' pointer AggregateDeclaration ad = f.isThis(); ClassDeclaration cd = ue.e1.type.isClassHandle(); if (ad && cd && ad.isClassDeclaration()) { if (ue.e1.op == TOKdottype) { ue.e1 = (cast(DotTypeExp)ue.e1).e1; directcall = true; } else if (ue.e1.op == TOKsuper) directcall = true; else if ((cd.storage_class & STCfinal) != 0) // https://issues.dlang.org/show_bug.cgi?id=14211 directcall = true; if (ad != cd) { ue.e1 = ue.e1.castTo(sc, ad.type.addMod(ue.e1.type.mod)); ue.e1 = ue.e1.semantic(sc); } } } // If we've got a pointer to a function then deference it // https://issues.dlang.org/show_bug.cgi?id=16483 if (e1.type.ty == Tpointer && e1.type.nextOf().ty == Tfunction) { Expression e = new PtrExp(loc, e1); e.type = e1.type.nextOf(); e1 = e; } t1 = e1.type; } else if (e1.op == TOKsuper) { // Base class constructor call auto ad = sc.func ? sc.func.isThis() : null; auto cd = ad ? ad.isClassDeclaration() : null; if (!cd || !cd.baseClass || !sc.func.isCtorDeclaration()) { error("super class constructor call must be in a constructor"); return new ErrorExp(); } if (!cd.baseClass.ctor) { error("no super class constructor for %s", cd.baseClass.toChars()); return new ErrorExp(); } if (!sc.intypeof && !(sc.callSuper & CSXhalt)) { if (sc.noctor || sc.callSuper & CSXlabel) error("constructor calls not allowed in loops or after labels"); if (sc.callSuper & (CSXsuper_ctor | CSXthis_ctor)) error("multiple constructor calls"); if ((sc.callSuper & CSXreturn) && !(sc.callSuper & CSXany_ctor)) error("an earlier return statement skips constructor"); sc.callSuper |= CSXany_ctor | CSXsuper_ctor; } tthis = cd.type.addMod(sc.func.type.mod); if (auto os = cd.baseClass.ctor.isOverloadSet()) f = resolveOverloadSet(loc, sc, os, null, tthis, arguments); else f = resolveFuncCall(loc, sc, cd.baseClass.ctor, null, tthis, arguments, 0); if (!f || f.errors) return new ErrorExp(); checkDeprecated(sc, f); checkPurity(sc, f); checkSafety(sc, f); checkNogc(sc, f); checkAccess(loc, sc, null, f); e1 = new DotVarExp(e1.loc, e1, f, false); e1 = e1.semantic(sc); t1 = e1.type; } else if (e1.op == TOKthis) { // same class constructor call auto ad = sc.func ? sc.func.isThis() : null; if (!ad || !sc.func.isCtorDeclaration()) { error("constructor call must be in a constructor"); return new ErrorExp(); } if (!sc.intypeof && !(sc.callSuper & CSXhalt)) { if (sc.noctor || sc.callSuper & CSXlabel) error("constructor calls not allowed in loops or after labels"); if (sc.callSuper & (CSXsuper_ctor | CSXthis_ctor)) error("multiple constructor calls"); if ((sc.callSuper & CSXreturn) && !(sc.callSuper & CSXany_ctor)) error("an earlier return statement skips constructor"); sc.callSuper |= CSXany_ctor | CSXthis_ctor; } tthis = ad.type.addMod(sc.func.type.mod); if (auto os = ad.ctor.isOverloadSet()) f = resolveOverloadSet(loc, sc, os, null, tthis, arguments); else f = resolveFuncCall(loc, sc, ad.ctor, null, tthis, arguments, 0); if (!f || f.errors) return new ErrorExp(); checkDeprecated(sc, f); checkPurity(sc, f); checkSafety(sc, f); checkNogc(sc, f); //checkAccess(loc, sc, NULL, f); // necessary? e1 = new DotVarExp(e1.loc, e1, f, false); e1 = e1.semantic(sc); t1 = e1.type; // BUG: this should really be done by checking the static // call graph if (f == sc.func) { error("cyclic constructor call"); return new ErrorExp(); } } else if (e1.op == TOKoverloadset) { auto os = (cast(OverExp)e1).vars; f = resolveOverloadSet(loc, sc, os, tiargs, tthis, arguments); if (!f) return new ErrorExp(); if (ethis) e1 = new DotVarExp(loc, ethis, f, false); else e1 = new VarExp(loc, f, false); goto Lagain; } else if (!t1) { error("function expected before (), not '%s'", e1.toChars()); return new ErrorExp(); } else if (t1.ty == Terror) { return new ErrorExp(); } else if (t1.ty != Tfunction) { TypeFunction tf; const(char)* p; Dsymbol s; f = null; if (e1.op == TOKfunction) { // function literal that direct called is always inferred. assert((cast(FuncExp)e1).fd); f = (cast(FuncExp)e1).fd; tf = cast(TypeFunction)f.type; p = "function literal"; } else if (t1.ty == Tdelegate) { TypeDelegate td = cast(TypeDelegate)t1; assert(td.next.ty == Tfunction); tf = cast(TypeFunction)td.next; p = "delegate"; } else if (t1.ty == Tpointer && (cast(TypePointer)t1).next.ty == Tfunction) { tf = cast(TypeFunction)(cast(TypePointer)t1).next; p = "function pointer"; } else if (e1.op == TOKdotvar && (cast(DotVarExp)e1).var.isOverDeclaration()) { DotVarExp dve = cast(DotVarExp)e1; f = resolveFuncCall(loc, sc, dve.var, tiargs, dve.e1.type, arguments, 2); if (!f) return new ErrorExp(); if (f.needThis()) { dve.var = f; dve.type = f.type; dve.hasOverloads = false; goto Lagain; } e1 = new VarExp(dve.loc, f, false); Expression e = new CommaExp(loc, dve.e1, this); return e.semantic(sc); } else if (e1.op == TOKvar && (cast(VarExp)e1).var.isOverDeclaration()) { s = (cast(VarExp)e1).var; goto L2; } else if (e1.op == TOKtemplate) { s = (cast(TemplateExp)e1).td; L2: f = resolveFuncCall(loc, sc, s, tiargs, null, arguments); if (!f || f.errors) return new ErrorExp(); if (f.needThis()) { if (hasThis(sc)) { // Supply an implicit 'this', as in // this.ident e1 = new DotVarExp(loc, (new ThisExp(loc)).semantic(sc), f, false); goto Lagain; } else if (isNeedThisScope(sc, f)) { error("need 'this' for '%s' of type '%s'", f.toChars(), f.type.toChars()); return new ErrorExp(); } } e1 = new VarExp(e1.loc, f, false); goto Lagain; } else { error("function expected before (), not %s of type %s", e1.toChars(), e1.type.toChars()); return new ErrorExp(); } if (!tf.callMatch(null, arguments)) { OutBuffer buf; buf.writeByte('('); argExpTypesToCBuffer(&buf, arguments); buf.writeByte(')'); if (tthis) tthis.modToBuffer(&buf); //printf("tf = %s, args = %s\n", tf.deco, (*arguments)[0].type.deco); .error(loc, "%s %s %s is not callable using argument types %s", p, e1.toChars(), parametersTypeToChars(tf.parameters, tf.varargs), buf.peekString()); return new ErrorExp(); } // Purity and safety check should run after testing arguments matching if (f) { checkPurity(sc, f); checkSafety(sc, f); checkNogc(sc, f); if (f.checkNestedReference(sc, loc)) return new ErrorExp(); } else if (sc.func && sc.intypeof != 1 && !(sc.flags & SCOPEctfe)) { bool err = false; if (!tf.purity && !(sc.flags & SCOPEdebug) && sc.func.setImpure()) { error("pure %s '%s' cannot call impure %s '%s'", sc.func.kind(), sc.func.toPrettyChars(), p, e1.toChars()); err = true; } if (!tf.isnogc && sc.func.setGC()) { error("@nogc %s '%s' cannot call non-@nogc %s '%s'", sc.func.kind(), sc.func.toPrettyChars(), p, e1.toChars()); err = true; } if (tf.trust <= TRUSTsystem && sc.func.setUnsafe()) { error("@safe %s '%s' cannot call @system %s '%s'", sc.func.kind(), sc.func.toPrettyChars(), p, e1.toChars()); err = true; } if (err) return new ErrorExp(); } if (t1.ty == Tpointer) { Expression e = new PtrExp(loc, e1); e.type = tf; e1 = e; } t1 = tf; } else if (e1.op == TOKvar) { // Do overload resolution VarExp ve = cast(VarExp)e1; f = ve.var.isFuncDeclaration(); assert(f); tiargs = null; if (ve.hasOverloads) f = resolveFuncCall(loc, sc, f, tiargs, null, arguments, 2); else { f = f.toAliasFunc(); TypeFunction tf = cast(TypeFunction)f.type; if (!tf.callMatch(null, arguments)) { OutBuffer buf; buf.writeByte('('); argExpTypesToCBuffer(&buf, arguments); buf.writeByte(')'); //printf("tf = %s, args = %s\n", tf.deco, (*arguments)[0].type.deco); .error(loc, "%s %s is not callable using argument types %s", e1.toChars(), parametersTypeToChars(tf.parameters, tf.varargs), buf.peekString()); f = null; } } if (!f || f.errors) return new ErrorExp(); if (f.needThis()) { // Change the ancestor lambdas to delegate before hasThis(sc) call. if (f.checkNestedReference(sc, loc)) return new ErrorExp(); if (hasThis(sc)) { // Supply an implicit 'this', as in // this.ident e1 = new DotVarExp(loc, (new ThisExp(loc)).semantic(sc), ve.var); // Note: we cannot use f directly, because further overload resolution // through the supplied 'this' may cause different result. goto Lagain; } else if (isNeedThisScope(sc, f)) { error("need 'this' for '%s' of type '%s'", f.toChars(), f.type.toChars()); return new ErrorExp(); } } checkDeprecated(sc, f); checkPurity(sc, f); checkSafety(sc, f); checkNogc(sc, f); checkAccess(loc, sc, null, f); if (f.checkNestedReference(sc, loc)) return new ErrorExp(); ethis = null; tthis = null; if (ve.hasOverloads) { e1 = new VarExp(ve.loc, f, false); e1.type = f.type; } t1 = f.type; } assert(t1.ty == Tfunction); Expression argprefix; if (!arguments) arguments = new Expressions(); if (functionParameters(loc, sc, cast(TypeFunction)t1, tthis, arguments, f, &type, &argprefix)) return new ErrorExp(); if (!type) { e1 = e1org; // https://issues.dlang.org/show_bug.cgi?id=10922 // avoid recursive expression printing error("forward reference to inferred return type of function call '%s'", toChars()); return new ErrorExp(); } if (f && f.tintro) { Type t = type; int offset = 0; TypeFunction tf = cast(TypeFunction)f.tintro; if (tf.next.isBaseOf(t, &offset) && offset) { type = tf.next; return combine(argprefix, castTo(sc, t)); } } // Handle the case of a direct lambda call if (f && f.isFuncLiteralDeclaration() && sc.func && !sc.intypeof) { f.tookAddressOf = 0; } return combine(argprefix, this); } override bool isLvalue() { Type tb = e1.type.toBasetype(); if (tb.ty == Tdelegate || tb.ty == Tpointer) tb = tb.nextOf(); if (tb.ty == Tfunction && (cast(TypeFunction)tb).isref) { if (e1.op == TOKdotvar) if ((cast(DotVarExp)e1).var.isCtorDeclaration()) return false; return true; // function returns a reference } return false; } override Expression toLvalue(Scope* sc, Expression e) { if (isLvalue()) return this; return Expression.toLvalue(sc, e); } override Expression addDtorHook(Scope* sc) { /* Only need to add dtor hook if it's a type that needs destruction. * Use same logic as VarDeclaration::callScopeDtor() */ if (e1.type && e1.type.ty == Tfunction) { TypeFunction tf = cast(TypeFunction)e1.type; if (tf.isref) return this; } Type tv = type.baseElemOf(); if (tv.ty == Tstruct) { TypeStruct ts = cast(TypeStruct)tv; StructDeclaration sd = ts.sym; if (sd.dtor) { /* Type needs destruction, so declare a tmp * which the back end will recognize and call dtor on */ auto tmp = copyToTemp(0, "__tmpfordtor", this); auto de = new DeclarationExp(loc, tmp); auto ve = new VarExp(loc, tmp); Expression e = new CommaExp(loc, de, ve); e = e.semantic(sc); return e; } } return this; } override void accept(Visitor v) { v.visit(this); } } FuncDeclaration isFuncAddress(Expression e, bool* hasOverloads = null) { if (e.op == TOKaddress) { auto ae1 = (cast(AddrExp)e).e1; if (ae1.op == TOKvar) { auto ve = cast(VarExp)ae1; if (hasOverloads) *hasOverloads = ve.hasOverloads; return ve.var.isFuncDeclaration(); } if (ae1.op == TOKdotvar) { auto dve = cast(DotVarExp)ae1; if (hasOverloads) *hasOverloads = dve.hasOverloads; return dve.var.isFuncDeclaration(); } } else { if (e.op == TOKsymoff) { auto soe = cast(SymOffExp)e; if (hasOverloads) *hasOverloads = soe.hasOverloads; return soe.var.isFuncDeclaration(); } if (e.op == TOKdelegate) { auto dge = cast(DelegateExp)e; if (hasOverloads) *hasOverloads = dge.hasOverloads; return dge.func.isFuncDeclaration(); } } return null; } /*********************************************************** */ extern (C++) final class AddrExp : UnaExp { extern (D) this(Loc loc, Expression e) { super(loc, TOKaddress, __traits(classInstanceSize, AddrExp), e); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("AddrExp::semantic('%s')\n", toChars()); } if (type) return this; if (Expression ex = unaSemantic(sc)) return ex; int wasCond = e1.op == TOKquestion; if (e1.op == TOKdotti) { DotTemplateInstanceExp dti = cast(DotTemplateInstanceExp)e1; TemplateInstance ti = dti.ti; { //assert(ti.needsTypeInference(sc)); ti.semantic(sc); if (!ti.inst || ti.errors) // if template failed to expand return new ErrorExp(); Dsymbol s = ti.toAlias(); FuncDeclaration f = s.isFuncDeclaration(); if (f) { e1 = new DotVarExp(e1.loc, dti.e1, f); e1 = e1.semantic(sc); } } } else if (e1.op == TOKscope) { TemplateInstance ti = (cast(ScopeExp)e1).sds.isTemplateInstance(); if (ti) { //assert(ti.needsTypeInference(sc)); ti.semantic(sc); if (!ti.inst || ti.errors) // if template failed to expand return new ErrorExp(); Dsymbol s = ti.toAlias(); FuncDeclaration f = s.isFuncDeclaration(); if (f) { e1 = new VarExp(e1.loc, f); e1 = e1.semantic(sc); } } } e1 = e1.toLvalue(sc, null); if (e1.op == TOKerror) return e1; if (checkNonAssignmentArrayOp(e1)) return new ErrorExp(); if (!e1.type) { error("cannot take address of %s", e1.toChars()); return new ErrorExp(); } bool hasOverloads; if (auto f = isFuncAddress(this, &hasOverloads)) { if (!hasOverloads && f.checkForwardRef(loc)) return new ErrorExp(); } else if (!e1.type.deco) { if (e1.op == TOKvar) { VarExp ve = cast(VarExp)e1; Declaration d = ve.var; error("forward reference to %s %s", d.kind(), d.toChars()); } else error("forward reference to %s", e1.toChars()); return new ErrorExp(); } type = e1.type.pointerTo(); bool checkAddressVar(VarDeclaration v) { if (v) { if (!v.canTakeAddressOf()) { error("cannot take address of %s", e1.toChars()); return false; } if (sc.func && !sc.intypeof && !v.isDataseg()) { const(char)* p = v.isParameter() ? "parameter" : "local"; if (global.params.vsafe) { // Taking the address of v means it cannot be set to 'scope' later v.storage_class &= ~STCmaybescope; v.doNotInferScope = true; if (v.storage_class & STCscope && sc.func.setUnsafe()) { error("cannot take address of scope %s %s in @safe function %s", p, v.toChars(), sc.func.toChars()); return false; } } else if (sc.func.setUnsafe()) { error("cannot take address of %s %s in @safe function %s", p, v.toChars(), sc.func.toChars()); return false; } } } return true; } // See if this should really be a delegate if (e1.op == TOKdotvar) { DotVarExp dve = cast(DotVarExp)e1; FuncDeclaration f = dve.var.isFuncDeclaration(); if (f) { f = f.toAliasFunc(); // FIXME, should see overloads // https://issues.dlang.org/show_bug.cgi?id=1983 if (!dve.hasOverloads) f.tookAddressOf++; Expression e; if (f.needThis()) e = new DelegateExp(loc, dve.e1, f, dve.hasOverloads); else // It is a function pointer. Convert &v.f() --> (v, &V.f()) e = new CommaExp(loc, dve.e1, new AddrExp(loc, new VarExp(loc, f, dve.hasOverloads))); e = e.semantic(sc); return e; } // Look for misaligned pointer in @safe mode if (checkUnsafeAccess(sc, dve, !type.isMutable(), true)) return new ErrorExp(); if (dve.e1.op == TOKvar && global.params.vsafe) { VarExp ve = cast(VarExp)dve.e1; VarDeclaration v = ve.var.isVarDeclaration(); if (v) { if (!checkAddressVar(v)) return new ErrorExp(); } } else if ((dve.e1.op == TOKthis || dve.e1.op == TOKsuper) && global.params.vsafe) { ThisExp ve = cast(ThisExp)dve.e1; VarDeclaration v = ve.var.isVarDeclaration(); if (v && v.storage_class & STCref) { if (!checkAddressVar(v)) return new ErrorExp(); } } } else if (e1.op == TOKvar) { VarExp ve = cast(VarExp)e1; VarDeclaration v = ve.var.isVarDeclaration(); if (v) { if (!checkAddressVar(v)) return new ErrorExp(); ve.checkPurity(sc, v); } FuncDeclaration f = ve.var.isFuncDeclaration(); if (f) { /* Because nested functions cannot be overloaded, * mark here that we took its address because castTo() * may not be called with an exact match. */ if (!ve.hasOverloads || f.isNested()) f.tookAddressOf++; if (f.isNested()) { if (f.isFuncLiteralDeclaration()) { if (!f.FuncDeclaration.isNested()) { /* Supply a 'null' for a this pointer if no this is available */ Expression e = new DelegateExp(loc, new NullExp(loc, Type.tnull), f, ve.hasOverloads); e = e.semantic(sc); return e; } } Expression e = new DelegateExp(loc, e1, f, ve.hasOverloads); e = e.semantic(sc); return e; } if (f.needThis()) { if (hasThis(sc)) { /* Should probably supply 'this' after overload resolution, * not before. */ Expression ethis = new ThisExp(loc); Expression e = new DelegateExp(loc, ethis, f, ve.hasOverloads); e = e.semantic(sc); return e; } if (sc.func && !sc.intypeof) { if (sc.func.setUnsafe()) { error("'this' reference necessary to take address of member %s in @safe function %s", f.toChars(), sc.func.toChars()); } } } } } else if ((e1.op == TOKthis || e1.op == TOKsuper) && global.params.vsafe) { ThisExp ve = cast(ThisExp)e1; VarDeclaration v = ve.var.isVarDeclaration(); if (v) { if (!checkAddressVar(v)) return new ErrorExp(); } } else if (e1.op == TOKcall) { CallExp ce = cast(CallExp)e1; if (ce.e1.type.ty == Tfunction) { TypeFunction tf = cast(TypeFunction)ce.e1.type; if (tf.isref && sc.func && !sc.intypeof && sc.func.setUnsafe()) { error("cannot take address of ref return of %s() in @safe function %s", ce.e1.toChars(), sc.func.toChars()); } } } else if (e1.op == TOKindex) { /* For: * int[3] a; * &a[i] * check 'a' the same as for a regular variable */ IndexExp ei = cast(IndexExp)e1; Type tyi = ei.e1.type.toBasetype(); if (tyi.ty == Tsarray && ei.e1.op == TOKvar) { VarExp ve = cast(VarExp)ei.e1; VarDeclaration v = ve.var.isVarDeclaration(); if (v) { if (!checkAddressVar(v)) return new ErrorExp(); ve.checkPurity(sc, v); } } } else if (wasCond) { /* a ? b : c was transformed to *(a ? &b : &c), but we still * need to do safety checks */ assert(e1.op == TOKstar); PtrExp pe = cast(PtrExp)e1; assert(pe.e1.op == TOKquestion); CondExp ce = cast(CondExp)pe.e1; assert(ce.e1.op == TOKaddress); assert(ce.e2.op == TOKaddress); // Re-run semantic on the address expressions only ce.e1.type = null; ce.e1 = ce.e1.semantic(sc); ce.e2.type = null; ce.e2 = ce.e2.semantic(sc); } return optimize(WANTvalue); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class PtrExp : UnaExp { extern (D) this(Loc loc, Expression e) { super(loc, TOKstar, __traits(classInstanceSize, PtrExp), e); //if (e.type) // type = ((TypePointer *)e.type).next; } extern (D) this(Loc loc, Expression e, Type t) { super(loc, TOKstar, __traits(classInstanceSize, PtrExp), e); type = t; } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("PtrExp::semantic('%s')\n", toChars()); } if (type) return this; Expression e = op_overload(sc); if (e) return e; Type tb = e1.type.toBasetype(); switch (tb.ty) { case Tpointer: type = (cast(TypePointer)tb).next; break; case Tsarray: case Tarray: if (isNonAssignmentArrayOp(e1)) goto default; error("using * on an array is no longer supported; use *(%s).ptr instead", e1.toChars()); type = (cast(TypeArray)tb).next; e1 = e1.castTo(sc, type.pointerTo()); break; default: error("can only * a pointer, not a '%s'", e1.type.toChars()); goto case Terror; case Terror: return new ErrorExp(); } if (checkValue()) return new ErrorExp(); return this; } override int checkModifiable(Scope* sc, int flag) { if (e1.op == TOKsymoff) { SymOffExp se = cast(SymOffExp)e1; return se.var.checkModify(loc, sc, type, null, flag); } else if (e1.op == TOKaddress) { AddrExp ae = cast(AddrExp)e1; return ae.e1.checkModifiable(sc, flag); } return 1; } override bool isLvalue() { return true; } override Expression toLvalue(Scope* sc, Expression e) { return this; } override Expression modifiableLvalue(Scope* sc, Expression e) { //printf("PtrExp::modifiableLvalue() %s, type %s\n", toChars(), type.toChars()); return Expression.modifiableLvalue(sc, e); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class NegExp : UnaExp { extern (D) this(Loc loc, Expression e) { super(loc, TOKneg, __traits(classInstanceSize, NegExp), e); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("NegExp::semantic('%s')\n", toChars()); } if (type) return this; Expression e = op_overload(sc); if (e) return e; type = e1.type; Type tb = type.toBasetype(); if (tb.ty == Tarray || tb.ty == Tsarray) { if (!isArrayOpValid(e1)) { error("invalid array operation %s (possible missing [])", toChars()); return new ErrorExp(); } return this; } if (!Target.isVectorOpSupported(tb, op)) return incompatibleTypes(); if (e1.checkNoBool()) return new ErrorExp(); if (e1.checkArithmetic()) return new ErrorExp(); return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class UAddExp : UnaExp { extern (D) this(Loc loc, Expression e) { super(loc, TOKuadd, __traits(classInstanceSize, UAddExp), e); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("UAddExp::semantic('%s')\n", toChars()); } assert(!type); Expression e = op_overload(sc); if (e) return e; if (!Target.isVectorOpSupported(e1.type.toBasetype(), op)) return incompatibleTypes(); if (e1.checkNoBool()) return new ErrorExp(); if (e1.checkArithmetic()) return new ErrorExp(); return e1; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class ComExp : UnaExp { extern (D) this(Loc loc, Expression e) { super(loc, TOKtilde, __traits(classInstanceSize, ComExp), e); } override Expression semantic(Scope* sc) { if (type) return this; Expression e = op_overload(sc); if (e) return e; type = e1.type; Type tb = type.toBasetype(); if (tb.ty == Tarray || tb.ty == Tsarray) { if (!isArrayOpValid(e1)) { error("invalid array operation %s (possible missing [])", toChars()); return new ErrorExp(); } return this; } if (!Target.isVectorOpSupported(tb, op)) return incompatibleTypes(); if (e1.checkNoBool()) return new ErrorExp(); if (e1.checkIntegral()) return new ErrorExp(); return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class NotExp : UnaExp { extern (D) this(Loc loc, Expression e) { super(loc, TOKnot, __traits(classInstanceSize, NotExp), e); } override Expression semantic(Scope* sc) { if (type) return this; setNoderefOperand(); // Note there is no operator overload if (Expression ex = unaSemantic(sc)) return ex; e1 = resolveProperties(sc, e1); e1 = e1.toBoolean(sc); if (e1.type == Type.terror) return e1; if (!Target.isVectorOpSupported(e1.type.toBasetype(), op)) return incompatibleTypes(); // https://issues.dlang.org/show_bug.cgi?id=13910 // Today NotExp can take an array as its operand. if (checkNonAssignmentArrayOp(e1)) return new ErrorExp(); type = Type.tbool; return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class DeleteExp : UnaExp { bool isRAII; // true if called automatically as a result of scoped destruction extern (D) this(Loc loc, Expression e, bool isRAII) { super(loc, TOKdelete, __traits(classInstanceSize, DeleteExp), e); this.isRAII = isRAII; } override Expression semantic(Scope* sc) { if (Expression ex = unaSemantic(sc)) return ex; e1 = resolveProperties(sc, e1); e1 = e1.modifiableLvalue(sc, null); if (e1.op == TOKerror) return e1; type = Type.tvoid; AggregateDeclaration ad = null; Type tb = e1.type.toBasetype(); switch (tb.ty) { case Tclass: { auto cd = (cast(TypeClass)tb).sym; if (cd.isCOMinterface()) { /* Because COM classes are deleted by IUnknown.Release() */ error("cannot delete instance of COM interface %s", cd.toChars()); return new ErrorExp(); } ad = cd; break; } case Tpointer: tb = (cast(TypePointer)tb).next.toBasetype(); if (tb.ty == Tstruct) { ad = (cast(TypeStruct)tb).sym; auto f = ad.aggDelete; auto fd = ad.dtor; if (!f) { semanticTypeInfo(sc, tb); break; } /* Construct: * ea = copy e1 to a tmp to do side effects only once * eb = call destructor * ec = call deallocator */ Expression ea = null; Expression eb = null; Expression ec = null; VarDeclaration v = null; if (fd && f) { v = copyToTemp(0, "__tmpea", e1); v.semantic(sc); ea = new DeclarationExp(loc, v); ea.type = v.type; } if (fd) { Expression e = ea ? new VarExp(loc, v) : e1; e = new DotVarExp(Loc(), e, fd, false); eb = new CallExp(loc, e); eb = eb.semantic(sc); } if (f) { Type tpv = Type.tvoid.pointerTo(); Expression e = ea ? new VarExp(loc, v) : e1.castTo(sc, tpv); e = new CallExp(loc, new VarExp(loc, f, false), e); ec = e.semantic(sc); } ea = combine(ea, eb); ea = combine(ea, ec); assert(ea); return ea; } break; case Tarray: { Type tv = tb.nextOf().baseElemOf(); if (tv.ty == Tstruct) { ad = (cast(TypeStruct)tv).sym; if (ad.dtor) semanticTypeInfo(sc, ad.type); } break; } default: error("cannot delete type %s", e1.type.toChars()); return new ErrorExp(); } bool err = false; if (ad) { if (ad.dtor) { err |= checkPurity(sc, ad.dtor); err |= checkSafety(sc, ad.dtor); err |= checkNogc(sc, ad.dtor); } if (ad.aggDelete && tb.ty != Tarray) { err |= checkPurity(sc, ad.aggDelete); err |= checkSafety(sc, ad.aggDelete); err |= checkNogc(sc, ad.aggDelete); } if (err) return new ErrorExp(); } if (!sc.intypeof && sc.func && !isRAII && sc.func.setUnsafe()) { error("%s is not @safe but is used in @safe function %s", toChars(), sc.func.toChars()); err = true; } if (err) return new ErrorExp(); return this; } override Expression toBoolean(Scope* sc) { error("delete does not give a boolean result"); return new ErrorExp(); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * Possible to cast to one type while painting to another type */ extern (C++) final class CastExp : UnaExp { Type to; // type to cast to ubyte mod = cast(ubyte)~0; // MODxxxxx extern (D) this(Loc loc, Expression e, Type t) { super(loc, TOKcast, __traits(classInstanceSize, CastExp), e); this.to = t; } /* For cast(const) and cast(immutable) */ extern (D) this(Loc loc, Expression e, ubyte mod) { super(loc, TOKcast, __traits(classInstanceSize, CastExp), e); this.mod = mod; } override Expression syntaxCopy() { return to ? new CastExp(loc, e1.syntaxCopy(), to.syntaxCopy()) : new CastExp(loc, e1.syntaxCopy(), mod); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("CastExp::semantic('%s')\n", toChars()); } //static int x; assert(++x < 10); if (type) return this; if (to) { to = to.semantic(loc, sc); if (to == Type.terror) return new ErrorExp(); if (!to.hasPointers()) setNoderefOperand(); // When e1 is a template lambda, this cast may instantiate it with // the type 'to'. e1 = inferType(e1, to); } if (auto e = unaSemantic(sc)) return e; auto e1x = resolveProperties(sc, e1); if (e1x.op == TOKerror) return e1x; if (e1x.checkType()) return new ErrorExp(); e1 = e1x; if (!e1.type) { error("cannot cast %s", e1.toChars()); return new ErrorExp(); } if (!to) // Handle cast(const) and cast(immutable), etc. { to = e1.type.castMod(mod); to = to.semantic(loc, sc); if (to == Type.terror) return new ErrorExp(); } if (to.ty == Ttuple) { error("cannot cast %s to tuple type %s", e1.toChars(), to.toChars()); return new ErrorExp(); } // cast(void) is used to mark e1 as unused, so it is safe if (to.ty == Tvoid) { type = to; return this; } if (!to.equals(e1.type) && mod == cast(ubyte)~0) { if (Expression e = op_overload(sc)) return e.implicitCastTo(sc, to); } Type t1b = e1.type.toBasetype(); Type tob = to.toBasetype(); if (tob.ty == Tstruct && !tob.equals(t1b)) { /* Look to replace: * cast(S)t * with: * S(t) */ // Rewrite as to.call(e1) Expression e = new TypeExp(loc, to); e = new CallExp(loc, e, e1); e = e.trySemantic(sc); if (e) return e; } if (!t1b.equals(tob) && (t1b.ty == Tarray || t1b.ty == Tsarray)) { if (checkNonAssignmentArrayOp(e1)) return new ErrorExp(); } // Look for casting to a vector type if (tob.ty == Tvector && t1b.ty != Tvector) { return new VectorExp(loc, e1, to); } Expression ex = e1.castTo(sc, to); if (ex.op == TOKerror) return ex; // Check for unsafe casts if (sc.func && !sc.intypeof && !isSafeCast(ex, t1b, tob) && sc.func.setUnsafe()) { error("cast from %s to %s not allowed in safe code", e1.type.toChars(), to.toChars()); return new ErrorExp(); } return ex; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class VectorExp : UnaExp { TypeVector to; // the target vector type before semantic() uint dim = ~0; // number of elements in the vector extern (D) this(Loc loc, Expression e, Type t) { super(loc, TOKvector, __traits(classInstanceSize, VectorExp), e); assert(t.ty == Tvector); to = cast(TypeVector)t; } override Expression syntaxCopy() { return new VectorExp(loc, e1.syntaxCopy(), to.syntaxCopy()); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("VectorExp::semantic('%s')\n", toChars()); } if (type) return this; e1 = e1.semantic(sc); type = to.semantic(loc, sc); if (e1.op == TOKerror || type.ty == Terror) return e1; Type tb = type.toBasetype(); assert(tb.ty == Tvector); TypeVector tv = cast(TypeVector)tb; Type te = tv.elementType(); dim = cast(int)(tv.size(loc) / te.size(loc)); bool checkElem(Expression elem) { if (elem.isConst() == 1) return false; error("constant expression expected, not %s", elem.toChars()); return true; } e1 = e1.optimize(WANTvalue); bool result; if (e1.op == TOKarrayliteral) { foreach (i; 0 .. dim) { // Do not stop on first error - check all AST nodes even if error found result |= checkElem((cast(ArrayLiteralExp)e1).getElement(i)); } } else if (e1.type.ty == Tvoid) checkElem(e1); return result ? new ErrorExp() : this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class SliceExp : UnaExp { Expression upr; // null if implicit 0 Expression lwr; // null if implicit [length - 1] VarDeclaration lengthVar; bool upperIsInBounds; // true if upr <= e1.length bool lowerIsLessThanUpper; // true if lwr <= upr /************************************************************/ extern (D) this(Loc loc, Expression e1, IntervalExp ie) { super(loc, TOKslice, __traits(classInstanceSize, SliceExp), e1); this.upr = ie ? ie.upr : null; this.lwr = ie ? ie.lwr : null; } extern (D) this(Loc loc, Expression e1, Expression lwr, Expression upr) { super(loc, TOKslice, __traits(classInstanceSize, SliceExp), e1); this.upr = upr; this.lwr = lwr; } override Expression syntaxCopy() { auto se = new SliceExp(loc, e1.syntaxCopy(), lwr ? lwr.syntaxCopy() : null, upr ? upr.syntaxCopy() : null); se.lengthVar = this.lengthVar; // bug7871 return se; } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("SliceExp::semantic('%s')\n", toChars()); } if (type) return this; // operator overloading should be handled in ArrayExp already. if (Expression ex = unaSemantic(sc)) return ex; e1 = resolveProperties(sc, e1); if (e1.op == TOKtype && e1.type.ty != Ttuple) { if (lwr || upr) { error("cannot slice type '%s'", e1.toChars()); return new ErrorExp(); } Expression e = new TypeExp(loc, e1.type.arrayOf()); return e.semantic(sc); } if (!lwr && !upr) { if (e1.op == TOKarrayliteral) { // Convert [a,b,c][] to [a,b,c] Type t1b = e1.type.toBasetype(); Expression e = e1; if (t1b.ty == Tsarray) { e = e.copy(); e.type = t1b.nextOf().arrayOf(); } return e; } if (e1.op == TOKslice) { // Convert e[][] to e[] SliceExp se = cast(SliceExp)e1; if (!se.lwr && !se.upr) return se; } if (isArrayOpOperand(e1)) { // Convert (a[]+b[])[] to a[]+b[] return e1; } } if (e1.op == TOKerror) return e1; if (e1.type.ty == Terror) return new ErrorExp(); Type t1b = e1.type.toBasetype(); if (t1b.ty == Tpointer) { if ((cast(TypePointer)t1b).next.ty == Tfunction) { error("cannot slice function pointer %s", e1.toChars()); return new ErrorExp(); } if (!lwr || !upr) { error("need upper and lower bound to slice pointer"); return new ErrorExp(); } if (sc.func && !sc.intypeof && sc.func.setUnsafe()) { error("pointer slicing not allowed in safe functions"); return new ErrorExp(); } } else if (t1b.ty == Tarray) { } else if (t1b.ty == Tsarray) { } else if (t1b.ty == Ttuple) { if (!lwr && !upr) return e1; if (!lwr || !upr) { error("need upper and lower bound to slice tuple"); return new ErrorExp(); } } else if (t1b.ty == Tvector) { // Convert e1 to corresponding static array TypeVector tv1 = cast(TypeVector)t1b; t1b = tv1.basetype; t1b = t1b.castMod(tv1.mod); e1.type = t1b; } else { error("%s cannot be sliced with []", t1b.ty == Tvoid ? e1.toChars() : t1b.toChars()); return new ErrorExp(); } /* Run semantic on lwr and upr. */ Scope* scx = sc; if (t1b.ty == Tsarray || t1b.ty == Tarray || t1b.ty == Ttuple) { // Create scope for 'length' variable ScopeDsymbol sym = new ArrayScopeSymbol(sc, this); sym.loc = loc; sym.parent = sc.scopesym; sc = sc.push(sym); } if (lwr) { if (t1b.ty == Ttuple) sc = sc.startCTFE(); lwr = lwr.semantic(sc); lwr = resolveProperties(sc, lwr); if (t1b.ty == Ttuple) sc = sc.endCTFE(); lwr = lwr.implicitCastTo(sc, Type.tsize_t); } if (upr) { if (t1b.ty == Ttuple) sc = sc.startCTFE(); upr = upr.semantic(sc); upr = resolveProperties(sc, upr); if (t1b.ty == Ttuple) sc = sc.endCTFE(); upr = upr.implicitCastTo(sc, Type.tsize_t); } if (sc != scx) sc = sc.pop(); if (lwr && lwr.type == Type.terror || upr && upr.type == Type.terror) { return new ErrorExp(); } if (t1b.ty == Ttuple) { lwr = lwr.ctfeInterpret(); upr = upr.ctfeInterpret(); uinteger_t i1 = lwr.toUInteger(); uinteger_t i2 = upr.toUInteger(); TupleExp te; TypeTuple tup; size_t length; if (e1.op == TOKtuple) // slicing an expression tuple { te = cast(TupleExp)e1; tup = null; length = te.exps.dim; } else if (e1.op == TOKtype) // slicing a type tuple { te = null; tup = cast(TypeTuple)t1b; length = Parameter.dim(tup.arguments); } else assert(0); if (i2 < i1 || length < i2) { error("string slice [%llu .. %llu] is out of bounds", i1, i2); return new ErrorExp(); } size_t j1 = cast(size_t)i1; size_t j2 = cast(size_t)i2; Expression e; if (e1.op == TOKtuple) { auto exps = new Expressions(); exps.setDim(j2 - j1); for (size_t i = 0; i < j2 - j1; i++) { (*exps)[i] = (*te.exps)[j1 + i]; } e = new TupleExp(loc, te.e0, exps); } else { auto args = new Parameters(); args.reserve(j2 - j1); for (size_t i = j1; i < j2; i++) { Parameter arg = Parameter.getNth(tup.arguments, i); args.push(arg); } e = new TypeExp(e1.loc, new TypeTuple(args)); } e = e.semantic(sc); return e; } type = t1b.nextOf().arrayOf(); // Allow typedef[] -> typedef[] if (type.equals(t1b)) type = e1.type; if (lwr && upr) { lwr = lwr.optimize(WANTvalue); upr = upr.optimize(WANTvalue); IntRange lwrRange = getIntRange(lwr); IntRange uprRange = getIntRange(upr); if (t1b.ty == Tsarray || t1b.ty == Tarray) { Expression el = new ArrayLengthExp(loc, e1); el = el.semantic(sc); el = el.optimize(WANTvalue); if (el.op == TOKint64) { dinteger_t length = el.toInteger(); auto bounds = IntRange(SignExtendedNumber(0), SignExtendedNumber(length)); this.upperIsInBounds = bounds.contains(uprRange); } } else if (t1b.ty == Tpointer) { this.upperIsInBounds = true; } else assert(0); this.lowerIsLessThanUpper = (lwrRange.imax <= uprRange.imin); //printf("upperIsInBounds = %d lowerIsLessThanUpper = %d\n", upperIsInBounds, lowerIsLessThanUpper); } return this; } override int checkModifiable(Scope* sc, int flag) { //printf("SliceExp::checkModifiable %s\n", toChars()); if (e1.type.ty == Tsarray || (e1.op == TOKindex && e1.type.ty != Tarray) || e1.op == TOKslice) { return e1.checkModifiable(sc, flag); } return 1; } override bool isLvalue() { /* slice expression is rvalue in default, but * conversion to reference of static array is only allowed. */ return (type && type.toBasetype().ty == Tsarray); } override Expression toLvalue(Scope* sc, Expression e) { //printf("SliceExp::toLvalue(%s) type = %s\n", toChars(), type ? type.toChars() : NULL); return (type && type.toBasetype().ty == Tsarray) ? this : Expression.toLvalue(sc, e); } override Expression modifiableLvalue(Scope* sc, Expression e) { error("slice expression %s is not a modifiable lvalue", toChars()); return this; } override bool isBool(bool result) { return e1.isBool(result); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class ArrayLengthExp : UnaExp { extern (D) this(Loc loc, Expression e1) { super(loc, TOKarraylength, __traits(classInstanceSize, ArrayLengthExp), e1); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("ArrayLengthExp::semantic('%s')\n", toChars()); } if (type) return this; if (Expression ex = unaSemantic(sc)) return ex; e1 = resolveProperties(sc, e1); type = Type.tsize_t; return this; } /********************* * Rewrite: * array.length op= e2 * as: * array.length = array.length op e2 * or: * auto tmp = &array; * (*tmp).length = (*tmp).length op e2 */ static Expression rewriteOpAssign(BinExp exp) { Expression e; assert(exp.e1.op == TOKarraylength); ArrayLengthExp ale = cast(ArrayLengthExp)exp.e1; if (ale.e1.op == TOKvar) { e = opAssignToOp(exp.loc, exp.op, ale, exp.e2); e = new AssignExp(exp.loc, ale.syntaxCopy(), e); } else { /* auto tmp = &array; * (*tmp).length = (*tmp).length op e2 */ auto tmp = copyToTemp(0, "__arraylength", new AddrExp(ale.loc, ale.e1)); Expression e1 = new ArrayLengthExp(ale.loc, new PtrExp(ale.loc, new VarExp(ale.loc, tmp))); Expression elvalue = e1.syntaxCopy(); e = opAssignToOp(exp.loc, exp.op, e1, exp.e2); e = new AssignExp(exp.loc, elvalue, e); e = new CommaExp(exp.loc, new DeclarationExp(ale.loc, tmp), e); } return e; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * e1 [ a0, a1, a2, a3 ,... ] */ extern (C++) final class ArrayExp : UnaExp { Expressions* arguments; // Array of Expression's size_t currentDimension; // for opDollar VarDeclaration lengthVar; extern (D) this(Loc loc, Expression e1, Expression index = null) { super(loc, TOKarray, __traits(classInstanceSize, ArrayExp), e1); arguments = new Expressions(); if (index) arguments.push(index); } extern (D) this(Loc loc, Expression e1, Expressions* args) { super(loc, TOKarray, __traits(classInstanceSize, ArrayExp), e1); arguments = args; } override Expression syntaxCopy() { auto ae = new ArrayExp(loc, e1.syntaxCopy(), arraySyntaxCopy(arguments)); ae.lengthVar = this.lengthVar; // bug7871 return ae; } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("ArrayExp::semantic('%s')\n", toChars()); } assert(!type); Expression e = op_overload(sc); if (e) return e; if (isAggregate(e1.type)) error("no [] operator overload for type %s", e1.type.toChars()); else error("only one index allowed to index %s", e1.type.toChars()); return new ErrorExp(); } override bool isLvalue() { if (type && type.toBasetype().ty == Tvoid) return false; return true; } override Expression toLvalue(Scope* sc, Expression e) { if (type && type.toBasetype().ty == Tvoid) error("voids have no value"); return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class DotExp : BinExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKdot, __traits(classInstanceSize, DotExp), e1, e2); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("DotExp::semantic('%s')\n", toChars()); if (type) printf("\ttype = %s\n", type.toChars()); } e1 = e1.semantic(sc); e2 = e2.semantic(sc); if (e1.op == TOKtype) return e2; if (e2.op == TOKtype) return e2; if (e2.op == TOKtemplate) { auto td = (cast(TemplateExp)e2).td; Expression e = new DotTemplateExp(loc, e1, td); return e.semantic(sc); } if (!type) type = e2.type; return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class CommaExp : BinExp { /// This is needed because AssignExp rewrites CommaExp, hence it needs /// to trigger the deprecation. const bool isGenerated; /// Temporary variable to enable / disable deprecation of comma expression /// depending on the context. /// Since most constructor calls are rewritting, the only place where /// false will be passed will be from the parser. bool allowCommaExp; extern (D) this(Loc loc, Expression e1, Expression e2, bool generated = true) { super(loc, TOKcomma, __traits(classInstanceSize, CommaExp), e1, e2); allowCommaExp = isGenerated = generated; } override Expression semantic(Scope* sc) { if (type) return this; // Allow `((a,b),(x,y))` if (allowCommaExp) { CommaExp.allow(e1); CommaExp.allow(e2); } if (Expression ex = binSemanticProp(sc)) return ex; e1 = e1.addDtorHook(sc); if (checkNonAssignmentArrayOp(e1)) return new ErrorExp(); type = e2.type; if (type !is Type.tvoid && !allowCommaExp && !isGenerated) deprecation("Using the result of a comma expression is deprecated"); return this; } override int checkModifiable(Scope* sc, int flag) { return e2.checkModifiable(sc, flag); } override bool isLvalue() { return e2.isLvalue(); } override Expression toLvalue(Scope* sc, Expression e) { e2 = e2.toLvalue(sc, null); return this; } override Expression modifiableLvalue(Scope* sc, Expression e) { e2 = e2.modifiableLvalue(sc, e); return this; } override bool isBool(bool result) { return e2.isBool(result); } override Expression toBoolean(Scope* sc) { auto ex2 = e2.toBoolean(sc); if (ex2.op == TOKerror) return ex2; e2 = ex2; return this; } override Expression addDtorHook(Scope* sc) { e2 = e2.addDtorHook(sc); return this; } override void accept(Visitor v) { v.visit(this); } /** * If the argument is a CommaExp, set a flag to prevent deprecation messages * * It's impossible to know from CommaExp.semantic if the result will * be used, hence when there is a result (type != void), a deprecation * message is always emitted. * However, some construct can produce a result but won't use it * (ExpStatement and for loop increment). Those should call this function * to prevent unwanted deprecations to be emitted. * * Params: * exp = An expression that discards its result. * If the argument is null or not a CommaExp, nothing happens. */ static void allow(Expression exp) { if (exp && exp.op == TOK.TOKcomma) (cast(CommaExp)exp).allowCommaExp = true; } } /*********************************************************** * Mainly just a placeholder */ extern (C++) final class IntervalExp : Expression { Expression lwr; Expression upr; extern (D) this(Loc loc, Expression lwr, Expression upr) { super(loc, TOKinterval, __traits(classInstanceSize, IntervalExp)); this.lwr = lwr; this.upr = upr; } override Expression syntaxCopy() { return new IntervalExp(loc, lwr.syntaxCopy(), upr.syntaxCopy()); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("IntervalExp::semantic('%s')\n", toChars()); } if (type) return this; Expression le = lwr; le = le.semantic(sc); le = resolveProperties(sc, le); Expression ue = upr; ue = ue.semantic(sc); ue = resolveProperties(sc, ue); if (le.op == TOKerror) return le; if (ue.op == TOKerror) return ue; lwr = le; upr = ue; type = Type.tvoid; return this; } override Expression modifiableLvalue(Scope* sc, Expression e) { if (sc.func.setUnsafe()) { error("cannot modify delegate pointer in @safe code %s", toChars()); return new ErrorExp(); } return Expression.modifiableLvalue(sc, e); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class DelegatePtrExp : UnaExp { extern (D) this(Loc loc, Expression e1) { super(loc, TOKdelegateptr, __traits(classInstanceSize, DelegatePtrExp), e1); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("DelegatePtrExp::semantic('%s')\n", toChars()); } if (!type) { unaSemantic(sc); e1 = resolveProperties(sc, e1); if (e1.op == TOKerror) return e1; type = Type.tvoidptr; } return this; } override bool isLvalue() { return e1.isLvalue(); } override Expression toLvalue(Scope* sc, Expression e) { e1 = e1.toLvalue(sc, e); return this; } override Expression modifiableLvalue(Scope* sc, Expression e) { if (sc.func.setUnsafe()) { error("cannot modify delegate pointer in @safe code %s", toChars()); return new ErrorExp(); } return Expression.modifiableLvalue(sc, e); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class DelegateFuncptrExp : UnaExp { extern (D) this(Loc loc, Expression e1) { super(loc, TOKdelegatefuncptr, __traits(classInstanceSize, DelegateFuncptrExp), e1); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("DelegateFuncptrExp::semantic('%s')\n", toChars()); } if (!type) { unaSemantic(sc); e1 = resolveProperties(sc, e1); if (e1.op == TOKerror) return e1; type = e1.type.nextOf().pointerTo(); } return this; } override bool isLvalue() { return e1.isLvalue(); } override Expression toLvalue(Scope* sc, Expression e) { e1 = e1.toLvalue(sc, e); return this; } override Expression modifiableLvalue(Scope* sc, Expression e) { if (sc.func.setUnsafe()) { error("cannot modify delegate function pointer in @safe code %s", toChars()); return new ErrorExp(); } return Expression.modifiableLvalue(sc, e); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * e1 [ e2 ] */ extern (C++) final class IndexExp : BinExp { VarDeclaration lengthVar; bool modifiable = false; // assume it is an rvalue bool indexIsInBounds; // true if 0 <= e2 && e2 <= e1.length - 1 extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKindex, __traits(classInstanceSize, IndexExp), e1, e2); //printf("IndexExp::IndexExp('%s')\n", toChars()); } override Expression syntaxCopy() { auto ie = new IndexExp(loc, e1.syntaxCopy(), e2.syntaxCopy()); ie.lengthVar = this.lengthVar; // bug7871 return ie; } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("IndexExp::semantic('%s')\n", toChars()); } if (type) return this; // operator overloading should be handled in ArrayExp already. if (!e1.type) e1 = e1.semantic(sc); assert(e1.type); // semantic() should already be run on it if (e1.op == TOKtype && e1.type.ty != Ttuple) { e2 = e2.semantic(sc); e2 = resolveProperties(sc, e2); Type nt; if (e2.op == TOKtype) nt = new TypeAArray(e1.type, e2.type); else nt = new TypeSArray(e1.type, e2); Expression e = new TypeExp(loc, nt); return e.semantic(sc); } if (e1.op == TOKerror) return e1; if (e1.type.ty == Terror) return new ErrorExp(); // Note that unlike C we do not implement the int[ptr] Type t1b = e1.type.toBasetype(); if (t1b.ty == Tvector) { // Convert e1 to corresponding static array TypeVector tv1 = cast(TypeVector)t1b; t1b = tv1.basetype; t1b = t1b.castMod(tv1.mod); e1.type = t1b; } /* Run semantic on e2 */ Scope* scx = sc; if (t1b.ty == Tsarray || t1b.ty == Tarray || t1b.ty == Ttuple) { // Create scope for 'length' variable ScopeDsymbol sym = new ArrayScopeSymbol(sc, this); sym.loc = loc; sym.parent = sc.scopesym; sc = sc.push(sym); } if (t1b.ty == Ttuple) sc = sc.startCTFE(); e2 = e2.semantic(sc); e2 = resolveProperties(sc, e2); if (t1b.ty == Ttuple) sc = sc.endCTFE(); if (e2.op == TOKtuple) { TupleExp te = cast(TupleExp)e2; if (te.exps && te.exps.dim == 1) e2 = Expression.combine(te.e0, (*te.exps)[0]); // bug 4444 fix } if (sc != scx) sc = sc.pop(); if (e2.type == Type.terror) return new ErrorExp(); if (checkNonAssignmentArrayOp(e1)) return new ErrorExp(); switch (t1b.ty) { case Tpointer: if ((cast(TypePointer)t1b).next.ty == Tfunction) { error("cannot index function pointer %s", e1.toChars()); return new ErrorExp(); } e2 = e2.implicitCastTo(sc, Type.tsize_t); if (e2.type == Type.terror) return new ErrorExp(); e2 = e2.optimize(WANTvalue); if (e2.op == TOKint64 && e2.toInteger() == 0) { } else if (sc.func && sc.func.setUnsafe()) { error("safe function '%s' cannot index pointer '%s'", sc.func.toPrettyChars(), e1.toChars()); return new ErrorExp(); } type = (cast(TypeNext)t1b).next; break; case Tarray: e2 = e2.implicitCastTo(sc, Type.tsize_t); if (e2.type == Type.terror) return new ErrorExp(); type = (cast(TypeNext)t1b).next; break; case Tsarray: { e2 = e2.implicitCastTo(sc, Type.tsize_t); if (e2.type == Type.terror) return new ErrorExp(); type = t1b.nextOf(); break; } case Taarray: { TypeAArray taa = cast(TypeAArray)t1b; /* We can skip the implicit conversion if they differ only by * constness * https://issues.dlang.org/show_bug.cgi?id=2684 * see also bug https://issues.dlang.org/show_bug.cgi?id=2954 b */ if (!arrayTypeCompatibleWithoutCasting(e2.loc, e2.type, taa.index)) { e2 = e2.implicitCastTo(sc, taa.index); // type checking if (e2.type == Type.terror) return new ErrorExp(); } semanticTypeInfo(sc, taa); type = taa.next; break; } case Ttuple: { e2 = e2.implicitCastTo(sc, Type.tsize_t); if (e2.type == Type.terror) return new ErrorExp(); e2 = e2.ctfeInterpret(); uinteger_t index = e2.toUInteger(); TupleExp te; TypeTuple tup; size_t length; if (e1.op == TOKtuple) { te = cast(TupleExp)e1; tup = null; length = te.exps.dim; } else if (e1.op == TOKtype) { te = null; tup = cast(TypeTuple)t1b; length = Parameter.dim(tup.arguments); } else assert(0); if (length <= index) { error("array index [%llu] is outside array bounds [0 .. %llu]", index, cast(ulong)length); return new ErrorExp(); } Expression e; if (e1.op == TOKtuple) { e = (*te.exps)[cast(size_t)index]; e = combine(te.e0, e); } else e = new TypeExp(e1.loc, Parameter.getNth(tup.arguments, cast(size_t)index).type); return e; } default: error("%s must be an array or pointer type, not %s", e1.toChars(), e1.type.toChars()); return new ErrorExp(); } if (t1b.ty == Tsarray || t1b.ty == Tarray) { Expression el = new ArrayLengthExp(loc, e1); el = el.semantic(sc); el = el.optimize(WANTvalue); if (el.op == TOKint64) { e2 = e2.optimize(WANTvalue); dinteger_t length = el.toInteger(); if (length) { auto bounds = IntRange(SignExtendedNumber(0), SignExtendedNumber(length - 1)); indexIsInBounds = bounds.contains(getIntRange(e2)); } } } return this; } override int checkModifiable(Scope* sc, int flag) { if (e1.type.ty == Tsarray || e1.type.ty == Taarray || (e1.op == TOKindex && e1.type.ty != Tarray) || e1.op == TOKslice) { return e1.checkModifiable(sc, flag); } return 1; } override bool isLvalue() { return true; } override Expression toLvalue(Scope* sc, Expression e) { return this; } override Expression modifiableLvalue(Scope* sc, Expression e) { //printf("IndexExp::modifiableLvalue(%s)\n", toChars()); Expression ex = markSettingAAElem(); if (ex.op == TOKerror) return ex; return Expression.modifiableLvalue(sc, e); } Expression markSettingAAElem() { if (e1.type.toBasetype().ty == Taarray) { Type t2b = e2.type.toBasetype(); if (t2b.ty == Tarray && t2b.nextOf().isMutable()) { error("associative arrays can only be assigned values with immutable keys, not %s", e2.type.toChars()); return new ErrorExp(); } modifiable = true; if (e1.op == TOKindex) { Expression ex = (cast(IndexExp)e1).markSettingAAElem(); if (ex.op == TOKerror) return ex; assert(ex == e1); } } return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * For both i++ and i-- */ extern (C++) final class PostExp : BinExp { extern (D) this(TOK op, Loc loc, Expression e) { super(loc, op, __traits(classInstanceSize, PostExp), e, new IntegerExp(loc, 1, Type.tint32)); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("PostExp::semantic('%s')\n", toChars()); } if (type) return this; if (Expression ex = binSemantic(sc)) return ex; Expression e1x = resolveProperties(sc, e1); if (e1x.op == TOKerror) return e1x; e1 = e1x; Expression e = op_overload(sc); if (e) return e; if (e1.checkReadModifyWrite(op)) return new ErrorExp(); if (e1.op == TOKslice) { const(char)* s = op == TOKplusplus ? "increment" : "decrement"; error("cannot post-%s array slice '%s', use pre-%s instead", s, e1.toChars(), s); return new ErrorExp(); } e1 = e1.optimize(WANTvalue); Type t1 = e1.type.toBasetype(); if (t1.ty == Tclass || t1.ty == Tstruct || e1.op == TOKarraylength) { /* Check for operator overloading, * but rewrite in terms of ++e instead of e++ */ /* If e1 is not trivial, take a reference to it */ Expression de = null; if (e1.op != TOKvar && e1.op != TOKarraylength) { // ref v = e1; auto v = copyToTemp(STCref, "__postref", e1); de = new DeclarationExp(loc, v); e1 = new VarExp(e1.loc, v); } /* Rewrite as: * auto tmp = e1; ++e1; tmp */ auto tmp = copyToTemp(0, "__pitmp", e1); Expression ea = new DeclarationExp(loc, tmp); Expression eb = e1.syntaxCopy(); eb = new PreExp(op == TOKplusplus ? TOKpreplusplus : TOKpreminusminus, loc, eb); Expression ec = new VarExp(loc, tmp); // Combine de,ea,eb,ec if (de) ea = new CommaExp(loc, de, ea); e = new CommaExp(loc, ea, eb); e = new CommaExp(loc, e, ec); e = e.semantic(sc); return e; } e1 = e1.modifiableLvalue(sc, e1); e = this; if (e1.checkScalar()) return new ErrorExp(); if (e1.checkNoBool()) return new ErrorExp(); if (e1.type.ty == Tpointer) e = scaleFactor(this, sc); else e2 = e2.castTo(sc, e1.type); e.type = e1.type; return e; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * For both ++i and --i */ extern (C++) final class PreExp : UnaExp { extern (D) this(TOK op, Loc loc, Expression e) { super(loc, op, __traits(classInstanceSize, PreExp), e); } override Expression semantic(Scope* sc) { Expression e = op_overload(sc); // printf("PreExp::semantic('%s')\n", toChars()); if (e) return e; // Rewrite as e1+=1 or e1-=1 if (op == TOKpreplusplus) e = new AddAssignExp(loc, e1, new IntegerExp(loc, 1, Type.tint32)); else e = new MinAssignExp(loc, e1, new IntegerExp(loc, 1, Type.tint32)); return e.semantic(sc); } override void accept(Visitor v) { v.visit(this); } } enum MemorySet { blockAssign = 1, // setting the contents of an array referenceInit = 2, // setting the reference of STCref variable } /*********************************************************** */ extern (C++) class AssignExp : BinExp { int memset; // combination of MemorySet flags /************************************************************/ /* op can be TOKassign, TOKconstruct, or TOKblit */ final extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKassign, __traits(classInstanceSize, AssignExp), e1, e2); } override final Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("AssignExp::semantic('%s')\n", toChars()); } //printf("e1.op = %d, '%s'\n", e1.op, Token::toChars(e1.op)); //printf("e2.op = %d, '%s'\n", e2.op, Token::toChars(e2.op)); if (type) return this; Expression e1old = e1; if (e2.op == TOKcomma) { /* Rewrite to get rid of the comma from rvalue */ if (!(cast(CommaExp)e2).isGenerated) deprecation("Using the result of a comma expression is deprecated"); Expression e0; e2 = Expression.extractLast(e2, &e0); Expression e = Expression.combine(e0, this); return e.semantic(sc); } /* Look for operator overloading of a[arguments] = e2. * Do it before e1.semantic() otherwise the ArrayExp will have been * converted to unary operator overloading already. */ if (e1.op == TOKarray) { Expression result; ArrayExp ae = cast(ArrayExp)e1; ae.e1 = ae.e1.semantic(sc); ae.e1 = resolveProperties(sc, ae.e1); Expression ae1old = ae.e1; const(bool) maybeSlice = (ae.arguments.dim == 0 || ae.arguments.dim == 1 && (*ae.arguments)[0].op == TOKinterval); IntervalExp ie = null; if (maybeSlice && ae.arguments.dim) { assert((*ae.arguments)[0].op == TOKinterval); ie = cast(IntervalExp)(*ae.arguments)[0]; } while (true) { if (ae.e1.op == TOKerror) return ae.e1; Expression e0 = null; Expression ae1save = ae.e1; ae.lengthVar = null; Type t1b = ae.e1.type.toBasetype(); AggregateDeclaration ad = isAggregate(t1b); if (!ad) break; if (search_function(ad, Id.indexass)) { // Deal with $ result = resolveOpDollar(sc, ae, &e0); if (!result) // a[i..j] = e2 might be: a.opSliceAssign(e2, i, j) goto Lfallback; if (result.op == TOKerror) return result; result = e2.semantic(sc); if (result.op == TOKerror) return result; e2 = result; /* Rewrite (a[arguments] = e2) as: * a.opIndexAssign(e2, arguments) */ Expressions* a = ae.arguments.copy(); a.insert(0, e2); result = new DotIdExp(loc, ae.e1, Id.indexass); result = new CallExp(loc, result, a); if (maybeSlice) // a[] = e2 might be: a.opSliceAssign(e2) result = result.trySemantic(sc); else result = result.semantic(sc); if (result) { result = Expression.combine(e0, result); return result; } } Lfallback: if (maybeSlice && search_function(ad, Id.sliceass)) { // Deal with $ result = resolveOpDollar(sc, ae, ie, &e0); if (result.op == TOKerror) return result; result = e2.semantic(sc); if (result.op == TOKerror) return result; e2 = result; /* Rewrite (a[i..j] = e2) as: * a.opSliceAssign(e2, i, j) */ auto a = new Expressions(); a.push(e2); if (ie) { a.push(ie.lwr); a.push(ie.upr); } result = new DotIdExp(loc, ae.e1, Id.sliceass); result = new CallExp(loc, result, a); result = result.semantic(sc); result = Expression.combine(e0, result); return result; } // No operator overloading member function found yet, but // there might be an alias this to try. if (ad.aliasthis && t1b != ae.att1) { if (!ae.att1 && t1b.checkAliasThisRec()) ae.att1 = t1b; /* Rewrite (a[arguments] op e2) as: * a.aliasthis[arguments] op e2 */ ae.e1 = resolveAliasThis(sc, ae1save, true); if (ae.e1) continue; } break; } ae.e1 = ae1old; // recovery ae.lengthVar = null; } /* Run this.e1 semantic. */ { Expression e1x = e1; /* With UFCS, e.f = value * Could mean: * .f(e, value) * or: * .f(e) = value */ if (e1x.op == TOKdotti) { DotTemplateInstanceExp dti = cast(DotTemplateInstanceExp)e1x; Expression e = dti.semanticY(sc, 1); if (!e) return resolveUFCSProperties(sc, e1x, e2); e1x = e; } else if (e1x.op == TOKdotid) { DotIdExp die = cast(DotIdExp)e1x; Expression e = die.semanticY(sc, 1); if (e && isDotOpDispatch(e)) { uint errors = global.startGagging(); e = resolvePropertiesX(sc, e, e2); if (global.endGagging(errors)) e = null; /* fall down to UFCS */ else return e; } if (!e) return resolveUFCSProperties(sc, e1x, e2); e1x = e; } else e1x = e1x.semantic(sc); /* We have f = value. * Could mean: * f(value) * or: * f() = value */ if (Expression e = resolvePropertiesX(sc, e1x, e2)) return e; if (e1x.checkRightThis(sc)) return new ErrorExp(); e1 = e1x; assert(e1.type); } Type t1 = e1.type.toBasetype(); /* Run this.e2 semantic. * Different from other binary expressions, the analysis of e2 * depends on the result of e1 in assignments. */ { Expression e2x = inferType(e2, t1.baseElemOf()); e2x = e2x.semantic(sc); e2x = resolveProperties(sc, e2x); if (e2x.op == TOKerror) return e2x; if (e2x.checkValue()) return new ErrorExp(); e2 = e2x; } /* Rewrite tuple assignment as a tuple of assignments. */ { Expression e2x = e2; Ltupleassign: if (e1.op == TOKtuple && e2x.op == TOKtuple) { TupleExp tup1 = cast(TupleExp)e1; TupleExp tup2 = cast(TupleExp)e2x; size_t dim = tup1.exps.dim; Expression e = null; if (dim != tup2.exps.dim) { error("mismatched tuple lengths, %d and %d", cast(int)dim, cast(int)tup2.exps.dim); return new ErrorExp(); } if (dim == 0) { e = new IntegerExp(loc, 0, Type.tint32); e = new CastExp(loc, e, Type.tvoid); // avoid "has no effect" error e = combine(combine(tup1.e0, tup2.e0), e); } else { auto exps = new Expressions(); exps.setDim(dim); for (size_t i = 0; i < dim; i++) { Expression ex1 = (*tup1.exps)[i]; Expression ex2 = (*tup2.exps)[i]; (*exps)[i] = new AssignExp(loc, ex1, ex2); } e = new TupleExp(loc, combine(tup1.e0, tup2.e0), exps); } return e.semantic(sc); } /* Look for form: e1 = e2.aliasthis. */ if (e1.op == TOKtuple) { TupleDeclaration td = isAliasThisTuple(e2x); if (!td) goto Lnomatch; assert(e1.type.ty == Ttuple); TypeTuple tt = cast(TypeTuple)e1.type; Expression e0; Expression ev = extractSideEffect(sc, "__tup", e0, e2x); auto iexps = new Expressions(); iexps.push(ev); for (size_t u = 0; u < iexps.dim; u++) { Lexpand: Expression e = (*iexps)[u]; Parameter arg = Parameter.getNth(tt.arguments, u); //printf("[%d] iexps.dim = %d, ", u, iexps.dim); //printf("e = (%s %s, %s), ", Token::tochars[e.op], e.toChars(), e.type.toChars()); //printf("arg = (%s, %s)\n", arg.toChars(), arg.type.toChars()); if (!arg || !e.type.implicitConvTo(arg.type)) { // expand initializer to tuple if (expandAliasThisTuples(iexps, u) != -1) { if (iexps.dim <= u) break; goto Lexpand; } goto Lnomatch; } } e2x = new TupleExp(e2x.loc, e0, iexps); e2x = e2x.semantic(sc); if (e2x.op == TOKerror) return e2x; // Do not need to overwrite this.e2 goto Ltupleassign; } Lnomatch: } /* Inside constructor, if this is the first assignment of object field, * rewrite this to initializing the field. */ if (op == TOKassign && e1.checkModifiable(sc) == 2) { //printf("[%s] change to init - %s\n", loc.toChars(), toChars()); op = TOKconstruct; // https://issues.dlang.org/show_bug.cgi?id=13515 // set Index::modifiable flag for complex AA element initialization if (e1.op == TOKindex) { Expression e1x = (cast(IndexExp)e1).markSettingAAElem(); if (e1x.op == TOKerror) return e1x; } } else if (op == TOKconstruct && e1.op == TOKvar && (cast(VarExp)e1).var.storage_class & (STCout | STCref)) { memset |= MemorySet.referenceInit; } /* If it is an assignment from a 'foreign' type, * check for operator overloading. */ if (memset & MemorySet.referenceInit) { // If this is an initialization of a reference, // do nothing } else if (t1.ty == Tstruct) { auto e1x = e1; auto e2x = e2; auto sd = (cast(TypeStruct)t1).sym; if (op == TOKconstruct) { Type t2 = e2x.type.toBasetype(); if (t2.ty == Tstruct && sd == (cast(TypeStruct)t2).sym) { sd.size(loc); if (sd.sizeok != SIZEOKdone) return new ErrorExp(); if (!sd.ctor) sd.ctor = sd.searchCtor(); // https://issues.dlang.org/show_bug.cgi?id=15661 // Look for the form from last of comma chain. auto e2y = e2x; while (e2y.op == TOKcomma) e2y = (cast(CommaExp)e2y).e2; CallExp ce = (e2y.op == TOKcall) ? cast(CallExp)e2y : null; DotVarExp dve = (ce && ce.e1.op == TOKdotvar) ? cast(DotVarExp)ce.e1 : null; if (sd.ctor && ce && dve && dve.var.isCtorDeclaration() && e2y.type.implicitConvTo(t1)) { /* Look for form of constructor call which is: * __ctmp.ctor(arguments...) */ /* Before calling the constructor, initialize * variable with a bit copy of the default * initializer */ Expression einit; if (sd.zeroInit == 1 && !sd.isNested()) { // https://issues.dlang.org/show_bug.cgi?id=14606 // Always use BlitExp for the special expression: (struct = 0) einit = new IntegerExp(loc, 0, Type.tint32); } else if (sd.isNested()) { auto sle = new StructLiteralExp(loc, sd, null, t1); if (!sd.fill(loc, sle.elements, true)) return new ErrorExp(); if (checkFrameAccess(loc, sc, sd, sle.elements.dim)) return new ErrorExp(); sle.type = t1; einit = sle; } else { einit = t1.defaultInit(loc); } auto ae = new BlitExp(loc, e1, einit); ae.type = e1x.type; /* Replace __ctmp being constructed with e1. * We need to copy constructor call expression, * because it may be used in other place. */ auto dvx = cast(DotVarExp)dve.copy(); dvx.e1 = e1x; auto cx = cast(CallExp)ce.copy(); cx.e1 = dvx; Expression e0; extractLast(e2x, &e0); auto e = combine(ae, cx); e = combine(e0, e); e = e.semantic(sc); return e; } if (sd.postblit) { /* We have a copy constructor for this */ if (e2x.op == TOKquestion) { /* Rewrite as: * a ? e1 = b : e1 = c; */ CondExp econd = cast(CondExp)e2x; Expression ea1 = new ConstructExp(econd.e1.loc, e1x, econd.e1); Expression ea2 = new ConstructExp(econd.e1.loc, e1x, econd.e2); Expression e = new CondExp(loc, econd.econd, ea1, ea2); return e.semantic(sc); } if (e2x.isLvalue()) { if (!e2x.type.implicitConvTo(e1x.type)) { error("conversion error from %s to %s", e2x.type.toChars(), e1x.type.toChars()); return new ErrorExp(); } /* Rewrite as: * (e1 = e2).postblit(); * * Blit assignment e1 = e2 returns a reference to the original e1, * then call the postblit on it. */ Expression e = e1x.copy(); e.type = e.type.mutableOf(); e = new BlitExp(loc, e, e2x); e = new DotVarExp(loc, e, sd.postblit, false); e = new CallExp(loc, e); return e.semantic(sc); } else { /* The struct value returned from the function is transferred * so should not call the destructor on it. */ e2x = valueNoDtor(e2x); } } } else if (!e2x.implicitConvTo(t1)) { sd.size(loc); if (sd.sizeok != SIZEOKdone) return new ErrorExp(); if (!sd.ctor) sd.ctor = sd.searchCtor(); if (sd.ctor) { /* Look for implicit constructor call * Rewrite as: * e1 = init, e1.ctor(e2) */ Expression einit; einit = new BlitExp(loc, e1x, e1x.type.defaultInit(loc)); einit.type = e1x.type; Expression e; e = new DotIdExp(loc, e1x, Id.ctor); e = new CallExp(loc, e, e2x); e = new CommaExp(loc, einit, e); e = e.semantic(sc); return e; } if (search_function(sd, Id.call)) { /* Look for static opCall * https://issues.dlang.org/show_bug.cgi?id=2702 * Rewrite as: * e1 = typeof(e1).opCall(arguments) */ e2x = typeDotIdExp(e2x.loc, e1x.type, Id.call); e2x = new CallExp(loc, e2x, this.e2); e2x = e2x.semantic(sc); e2x = resolveProperties(sc, e2x); if (e2x.op == TOKerror) return e2x; if (e2x.checkValue()) return new ErrorExp(); } } else // https://issues.dlang.org/show_bug.cgi?id=11355 { AggregateDeclaration ad2 = isAggregate(e2x.type); if (ad2 && ad2.aliasthis && !(att2 && e2x.type == att2)) { if (!att2 && e2.type.checkAliasThisRec()) att2 = e2.type; /* Rewrite (e1 op e2) as: * (e1 op e2.aliasthis) */ e2 = new DotIdExp(e2.loc, e2, ad2.aliasthis.ident); return semantic(sc); } } } else if (op == TOKassign) { if (e1x.op == TOKindex && (cast(IndexExp)e1x).e1.type.toBasetype().ty == Taarray) { /* * Rewrite: * aa[key] = e2; * as: * ref __aatmp = aa; * ref __aakey = key; * ref __aaval = e2; * (__aakey in __aatmp * ? __aatmp[__aakey].opAssign(__aaval) * : ConstructExp(__aatmp[__aakey], __aaval)); */ IndexExp ie = cast(IndexExp)e1x; Type t2 = e2x.type.toBasetype(); Expression e0 = null; Expression ea = extractSideEffect(sc, "__aatmp", e0, ie.e1); Expression ek = extractSideEffect(sc, "__aakey", e0, ie.e2); Expression ev = extractSideEffect(sc, "__aaval", e0, e2x); AssignExp ae = cast(AssignExp)copy(); ae.e1 = new IndexExp(loc, ea, ek); ae.e1 = ae.e1.semantic(sc); ae.e1 = ae.e1.optimize(WANTvalue); ae.e2 = ev; Expression e = ae.op_overload(sc); if (e) { Expression ey = null; if (t2.ty == Tstruct && sd == t2.toDsymbol(sc)) { ey = ev; } else if (!ev.implicitConvTo(ie.type) && sd.ctor) { // Look for implicit constructor call // Rewrite as S().ctor(e2) ey = new StructLiteralExp(loc, sd, null); ey = new DotIdExp(loc, ey, Id.ctor); ey = new CallExp(loc, ey, ev); ey = ey.trySemantic(sc); } if (ey) { Expression ex; ex = new IndexExp(loc, ea, ek); ex = ex.semantic(sc); ex = ex.optimize(WANTvalue); ex = ex.modifiableLvalue(sc, ex); // allocate new slot ey = new ConstructExp(loc, ex, ey); ey = ey.semantic(sc); if (ey.op == TOKerror) return ey; ex = e; // https://issues.dlang.org/show_bug.cgi?id=14144 // The whole expression should have the common type // of opAssign() return and assigned AA entry. // Even if there's no common type, expression should be typed as void. Type t = null; if (!typeMerge(sc, TOKquestion, &t, &ex, &ey)) { ex = new CastExp(ex.loc, ex, Type.tvoid); ey = new CastExp(ey.loc, ey, Type.tvoid); } e = new CondExp(loc, new InExp(loc, ek, ea), ex, ey); } e = combine(e0, e); e = e.semantic(sc); return e; } } else { Expression e = op_overload(sc); if (e) return e; } } else assert(op == TOKblit); e1 = e1x; e2 = e2x; } else if (t1.ty == Tclass) { // Disallow assignment operator overloads for same type if (op == TOKassign && !e2.implicitConvTo(e1.type)) { Expression e = op_overload(sc); if (e) return e; } } else if (t1.ty == Tsarray) { // SliceExp cannot have static array type without context inference. assert(e1.op != TOKslice); Expression e1x = e1; Expression e2x = e2; if (e2x.implicitConvTo(e1x.type)) { if (op != TOKblit && (e2x.op == TOKslice && (cast(UnaExp)e2x).e1.isLvalue() || e2x.op == TOKcast && (cast(UnaExp)e2x).e1.isLvalue() || e2x.op != TOKslice && e2x.isLvalue())) { if (e1x.checkPostblit(sc, t1)) return new ErrorExp(); } // e2 matches to t1 because of the implicit length match, so if (isUnaArrayOp(e2x.op) || isBinArrayOp(e2x.op)) { // convert e1 to e1[] // e.g. e1[] = a[] + b[]; e1x = new SliceExp(e1x.loc, e1x, null, null); e1x = e1x.semantic(sc); } else { // convert e2 to t1 later // e.g. e1 = [1, 2, 3]; } } else { if (e2x.implicitConvTo(t1.nextOf().arrayOf()) > MATCHnomatch) { uinteger_t dim1 = (cast(TypeSArray)t1).dim.toInteger(); uinteger_t dim2 = dim1; if (e2x.op == TOKarrayliteral) { ArrayLiteralExp ale = cast(ArrayLiteralExp)e2x; dim2 = ale.elements ? ale.elements.dim : 0; } else if (e2x.op == TOKslice) { Type tx = toStaticArrayType(cast(SliceExp)e2x); if (tx) dim2 = (cast(TypeSArray)tx).dim.toInteger(); } if (dim1 != dim2) { error("mismatched array lengths, %d and %d", cast(int)dim1, cast(int)dim2); return new ErrorExp(); } } // May be block or element-wise assignment, so // convert e1 to e1[] if (op != TOKassign) { // If multidimensional static array, treat as one large array dinteger_t dim = (cast(TypeSArray)t1).dim.toInteger(); Type t = t1; while (1) { t = t.nextOf().toBasetype(); if (t.ty != Tsarray) break; dim *= (cast(TypeSArray)t).dim.toInteger(); e1x.type = t.nextOf().sarrayOf(dim); } } e1x = new SliceExp(e1x.loc, e1x, null, null); e1x = e1x.semantic(sc); } if (e1x.op == TOKerror) return e1x; if (e2x.op == TOKerror) return e2x; e1 = e1x; e2 = e2x; t1 = e1x.type.toBasetype(); } /* Check the mutability of e1. */ if (e1.op == TOKarraylength) { // e1 is not an lvalue, but we let code generator handle it ArrayLengthExp ale = cast(ArrayLengthExp)e1; Expression ale1x = ale.e1; ale1x = ale1x.modifiableLvalue(sc, e1); if (ale1x.op == TOKerror) return ale1x; ale.e1 = ale1x; Type tn = ale.e1.type.toBasetype().nextOf(); checkDefCtor(ale.loc, tn); semanticTypeInfo(sc, tn); } else if (e1.op == TOKslice) { Type tn = e1.type.nextOf(); if (op == TOKassign && !tn.isMutable()) { error("slice %s is not mutable", e1.toChars()); return new ErrorExp(); } // For conditional operator, both branches need conversion. SliceExp se = cast(SliceExp)e1; while (se.e1.op == TOKslice) se = cast(SliceExp)se.e1; if (se.e1.op == TOKquestion && se.e1.type.toBasetype().ty == Tsarray) { se.e1 = se.e1.modifiableLvalue(sc, e1); if (se.e1.op == TOKerror) return se.e1; } } else { Expression e1x = e1; // Try to do a decent error message with the expression // before it got constant folded if (e1x.op != TOKvar) e1x = e1x.optimize(WANTvalue); if (op == TOKassign) e1x = e1x.modifiableLvalue(sc, e1old); if (e1x.op == TOKerror) return e1x; e1 = e1x; } /* Tweak e2 based on the type of e1. */ Expression e2x = e2; Type t2 = e2x.type.toBasetype(); // If it is a array, get the element type. Note that it may be // multi-dimensional. Type telem = t1; while (telem.ty == Tarray) telem = telem.nextOf(); if (e1.op == TOKslice && t1.nextOf() && (telem.ty != Tvoid || e2x.op == TOKnull) && e2x.implicitConvTo(t1.nextOf())) { // Check for block assignment. If it is of type void[], void[][], etc, // '= null' is the only allowable block assignment (Bug 7493) memset |= MemorySet.blockAssign; // make it easy for back end to tell what this is e2x = e2x.implicitCastTo(sc, t1.nextOf()); if (op != TOKblit && e2x.isLvalue() && e1.checkPostblit(sc, t1.nextOf())) { return new ErrorExp(); } } else if (e1.op == TOKslice && (t2.ty == Tarray || t2.ty == Tsarray) && t2.nextOf().implicitConvTo(t1.nextOf())) { // Check element-wise assignment. /* If assigned elements number is known at compile time, * check the mismatch. */ SliceExp se1 = cast(SliceExp)e1; TypeSArray tsa1 = cast(TypeSArray)toStaticArrayType(se1); TypeSArray tsa2 = null; if (e2x.op == TOKarrayliteral) tsa2 = cast(TypeSArray)t2.nextOf().sarrayOf((cast(ArrayLiteralExp)e2x).elements.dim); else if (e2x.op == TOKslice) tsa2 = cast(TypeSArray)toStaticArrayType(cast(SliceExp)e2x); else if (t2.ty == Tsarray) tsa2 = cast(TypeSArray)t2; if (tsa1 && tsa2) { uinteger_t dim1 = tsa1.dim.toInteger(); uinteger_t dim2 = tsa2.dim.toInteger(); if (dim1 != dim2) { error("mismatched array lengths, %d and %d", cast(int)dim1, cast(int)dim2); return new ErrorExp(); } } if (op != TOKblit && (e2x.op == TOKslice && (cast(UnaExp)e2x).e1.isLvalue() || e2x.op == TOKcast && (cast(UnaExp)e2x).e1.isLvalue() || e2x.op != TOKslice && e2x.isLvalue())) { if (e1.checkPostblit(sc, t1.nextOf())) return new ErrorExp(); } if (0 && global.params.warnings && !global.gag && op == TOKassign && e2x.op != TOKslice && e2x.op != TOKassign && e2x.op != TOKarrayliteral && e2x.op != TOKstring && !(e2x.op == TOKadd || e2x.op == TOKmin || e2x.op == TOKmul || e2x.op == TOKdiv || e2x.op == TOKmod || e2x.op == TOKxor || e2x.op == TOKand || e2x.op == TOKor || e2x.op == TOKpow || e2x.op == TOKtilde || e2x.op == TOKneg)) { const(char)* e1str = e1.toChars(); const(char)* e2str = e2x.toChars(); warning("explicit element-wise assignment %s = (%s)[] is better than %s = %s", e1str, e2str, e1str, e2str); } Type t2n = t2.nextOf(); Type t1n = t1.nextOf(); int offset; if (t2n.equivalent(t1n) || t1n.isBaseOf(t2n, &offset) && offset == 0) { /* Allow copy of distinct qualifier elements. * eg. * char[] dst; const(char)[] src; * dst[] = src; * * class C {} class D : C {} * C[2] ca; D[] da; * ca[] = da; */ if (isArrayOpValid(e2x)) { // Don't add CastExp to keep AST for array operations e2x = e2x.copy(); e2x.type = e1.type.constOf(); } else e2x = e2x.castTo(sc, e1.type.constOf()); } else { /* https://issues.dlang.org/show_bug.cgi?id=15778 * A string literal has an array type of immutable * elements by default, and normally it cannot be convertible to * array type of mutable elements. But for element-wise assignment, * elements need to be const at best. So we should give a chance * to change code unit size for polysemous string literal. */ if (e2x.op == TOKstring) e2x = e2x.implicitCastTo(sc, e1.type.constOf()); else e2x = e2x.implicitCastTo(sc, e1.type); } if (t1n.toBasetype.ty == Tvoid && t2n.toBasetype.ty == Tvoid) { if (!sc.intypeof && sc.func && sc.func.setUnsafe()) { error("cannot copy void[] to void[] in @safe code"); return new ErrorExp(); } } } else { if (0 && global.params.warnings && !global.gag && op == TOKassign && t1.ty == Tarray && t2.ty == Tsarray && e2x.op != TOKslice && t2.implicitConvTo(t1)) { // Disallow ar[] = sa (Converted to ar[] = sa[]) // Disallow da = sa (Converted to da = sa[]) const(char)* e1str = e1.toChars(); const(char)* e2str = e2x.toChars(); const(char)* atypestr = e1.op == TOKslice ? "element-wise" : "slice"; warning("explicit %s assignment %s = (%s)[] is better than %s = %s", atypestr, e1str, e2str, e1str, e2str); } if (op == TOKblit) e2x = e2x.castTo(sc, e1.type); else e2x = e2x.implicitCastTo(sc, e1.type); } if (e2x.op == TOKerror) return e2x; e2 = e2x; t2 = e2.type.toBasetype(); /* Look for array operations */ if ((t2.ty == Tarray || t2.ty == Tsarray) && isArrayOpValid(e2)) { // Look for valid array operations if (!(memset & MemorySet.blockAssign) && e1.op == TOKslice && (isUnaArrayOp(e2.op) || isBinArrayOp(e2.op))) { type = e1.type; if (op == TOKconstruct) // https://issues.dlang.org/show_bug.cgi?id=10282 // tweak mutability of e1 element e1.type = e1.type.nextOf().mutableOf().arrayOf(); return arrayOp(this, sc); } // Drop invalid array operations in e2 // d = a[] + b[], d = (a[] + b[])[0..2], etc if (checkNonAssignmentArrayOp(e2, !(memset & MemorySet.blockAssign) && op == TOKassign)) return new ErrorExp(); // Remains valid array assignments // d = d[], d = [1,2,3], etc } /* Don't allow assignment to classes that were allocated on the stack with: * scope Class c = new Class(); */ if (e1.op == TOKvar && op == TOKassign) { VarExp ve = cast(VarExp)e1; VarDeclaration vd = ve.var.isVarDeclaration(); if (vd && (vd.onstack || vd.mynew)) { assert(t1.ty == Tclass); error("cannot rebind scope variables"); } } if (e1.op == TOKvar && (cast(VarExp)e1).var.ident == Id.ctfe) { error("cannot modify compiler-generated variable __ctfe"); } type = e1.type; assert(type); auto result = op == TOKassign ? reorderSettingAAElem(sc) : this; checkAssignEscape(sc, result, false); return result; } override final bool isLvalue() { // Array-op 'x[] = y[]' should make an rvalue. // Setting array length 'x.length = v' should make an rvalue. if (e1.op == TOKslice || e1.op == TOKarraylength) { return false; } return true; } override final Expression toLvalue(Scope* sc, Expression ex) { if (e1.op == TOKslice || e1.op == TOKarraylength) { return Expression.toLvalue(sc, ex); } /* In front-end level, AssignExp should make an lvalue of e1. * Taking the address of e1 will be handled in low level layer, * so this function does nothing. */ return this; } override final Expression toBoolean(Scope* sc) { // Things like: // if (a = b) ... // are usually mistakes. error("assignment cannot be used as a condition, perhaps == was meant?"); return new ErrorExp(); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class ConstructExp : AssignExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, e1, e2); op = TOKconstruct; } // Internal use only. If `v` is a reference variable, the assinment // will become a reference initialization automatically. extern (D) this(Loc loc, VarDeclaration v, Expression e2) { auto ve = new VarExp(loc, v); assert(v.type && ve.type); super(loc, ve, e2); op = TOKconstruct; if (v.storage_class & (STCref | STCout)) memset |= MemorySet.referenceInit; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class BlitExp : AssignExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, e1, e2); op = TOKblit; } // Internal use only. If `v` is a reference variable, the assinment // will become a reference rebinding automatically. extern (D) this(Loc loc, VarDeclaration v, Expression e2) { auto ve = new VarExp(loc, v); assert(v.type && ve.type); super(loc, ve, e2); op = TOKblit; if (v.storage_class & (STCref | STCout)) memset |= MemorySet.referenceInit; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class AddAssignExp : BinAssignExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKaddass, __traits(classInstanceSize, AddAssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class MinAssignExp : BinAssignExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKminass, __traits(classInstanceSize, MinAssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class MulAssignExp : BinAssignExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKmulass, __traits(classInstanceSize, MulAssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class DivAssignExp : BinAssignExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKdivass, __traits(classInstanceSize, DivAssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class ModAssignExp : BinAssignExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKmodass, __traits(classInstanceSize, ModAssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class AndAssignExp : BinAssignExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKandass, __traits(classInstanceSize, AndAssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class OrAssignExp : BinAssignExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKorass, __traits(classInstanceSize, OrAssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class XorAssignExp : BinAssignExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKxorass, __traits(classInstanceSize, XorAssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class PowAssignExp : BinAssignExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKpowass, __traits(classInstanceSize, PowAssignExp), e1, e2); } override Expression semantic(Scope* sc) { if (type) return this; Expression e = op_overload(sc); if (e) return e; if (e1.checkReadModifyWrite(op, e2)) return new ErrorExp(); assert(e1.type && e2.type); if (e1.op == TOKslice || e1.type.ty == Tarray || e1.type.ty == Tsarray) { // T[] ^^= ... if (e2.implicitConvTo(e1.type.nextOf())) { // T[] ^^= T e2 = e2.castTo(sc, e1.type.nextOf()); } else if (Expression ex = typeCombine(this, sc)) return ex; // Check element types are arithmetic Type tb1 = e1.type.nextOf().toBasetype(); Type tb2 = e2.type.toBasetype(); if (tb2.ty == Tarray || tb2.ty == Tsarray) tb2 = tb2.nextOf().toBasetype(); if ((tb1.isintegral() || tb1.isfloating()) && (tb2.isintegral() || tb2.isfloating())) { type = e1.type; return arrayOp(this, sc); } } else { e1 = e1.modifiableLvalue(sc, e1); } if ((e1.type.isintegral() || e1.type.isfloating()) && (e2.type.isintegral() || e2.type.isfloating())) { Expression e0 = null; e = reorderSettingAAElem(sc); e = extractLast(e, &e0); assert(e == this); if (e1.op == TOKvar) { // Rewrite: e1 = e1 ^^ e2 e = new PowExp(loc, e1.syntaxCopy(), e2); e = new AssignExp(loc, e1, e); } else { // Rewrite: ref tmp = e1; tmp = tmp ^^ e2 auto v = copyToTemp(STCref, "__powtmp", e1); auto de = new DeclarationExp(e1.loc, v); auto ve = new VarExp(e1.loc, v); e = new PowExp(loc, ve, e2); e = new AssignExp(loc, new VarExp(e1.loc, v), e); e = new CommaExp(loc, de, e); } e = Expression.combine(e0, e); e = e.semantic(sc); return e; } return incompatibleTypes(); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class ShlAssignExp : BinAssignExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKshlass, __traits(classInstanceSize, ShlAssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class ShrAssignExp : BinAssignExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKshrass, __traits(classInstanceSize, ShrAssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class UshrAssignExp : BinAssignExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKushrass, __traits(classInstanceSize, UshrAssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class CatAssignExp : BinAssignExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKcatass, __traits(classInstanceSize, CatAssignExp), e1, e2); } override Expression semantic(Scope* sc) { if (type) return this; //printf("CatAssignExp::semantic() %s\n", toChars()); Expression e = op_overload(sc); if (e) return e; if (e1.op == TOKslice) { SliceExp se = cast(SliceExp)e1; if (se.e1.type.toBasetype().ty == Tsarray) { error("cannot append to static array %s", se.e1.type.toChars()); return new ErrorExp(); } } e1 = e1.modifiableLvalue(sc, e1); if (e1.op == TOKerror) return e1; if (e2.op == TOKerror) return e2; if (checkNonAssignmentArrayOp(e2)) return new ErrorExp(); Type tb1 = e1.type.toBasetype(); Type tb1next = tb1.nextOf(); Type tb2 = e2.type.toBasetype(); if ((tb1.ty == Tarray) && (tb2.ty == Tarray || tb2.ty == Tsarray) && (e2.implicitConvTo(e1.type) || (tb2.nextOf().implicitConvTo(tb1next) && (tb2.nextOf().size(Loc()) == tb1next.size(Loc()))))) { // Append array if (e1.checkPostblit(sc, tb1next)) return new ErrorExp(); e2 = e2.castTo(sc, e1.type); } else if ((tb1.ty == Tarray) && e2.implicitConvTo(tb1next)) { // Append element if (e2.checkPostblit(sc, tb2)) return new ErrorExp(); e2 = e2.castTo(sc, tb1next); e2 = doCopyOrMove(sc, e2); } else if (tb1.ty == Tarray && (tb1next.ty == Tchar || tb1next.ty == Twchar) && e2.type.ty != tb1next.ty && e2.implicitConvTo(Type.tdchar)) { // Append dchar to char[] or wchar[] e2 = e2.castTo(sc, Type.tdchar); /* Do not allow appending wchar to char[] because if wchar happens * to be a surrogate pair, nothing good can result. */ } else { error("cannot append type %s to type %s", tb2.toChars(), tb1.toChars()); return new ErrorExp(); } if (e2.checkValue()) return new ErrorExp(); type = e1.type; return reorderSettingAAElem(sc); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class AddExp : BinExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKadd, __traits(classInstanceSize, AddExp), e1, e2); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("AddExp::semantic('%s')\n", toChars()); } if (type) return this; if (Expression ex = binSemanticProp(sc)) return ex; Expression e = op_overload(sc); if (e) return e; Type tb1 = e1.type.toBasetype(); Type tb2 = e2.type.toBasetype(); bool err = false; if (tb1.ty == Tdelegate || tb1.ty == Tpointer && tb1.nextOf().ty == Tfunction) { err |= e1.checkArithmetic(); } if (tb2.ty == Tdelegate || tb2.ty == Tpointer && tb2.nextOf().ty == Tfunction) { err |= e2.checkArithmetic(); } if (err) return new ErrorExp(); if (tb1.ty == Tpointer && e2.type.isintegral() || tb2.ty == Tpointer && e1.type.isintegral()) { return scaleFactor(this, sc); } if (tb1.ty == Tpointer && tb2.ty == Tpointer) { return incompatibleTypes(); } if (Expression ex = typeCombine(this, sc)) return ex; Type tb = type.toBasetype(); if (tb.ty == Tarray || tb.ty == Tsarray) { if (!isArrayOpValid(this)) { error("invalid array operation %s (possible missing [])", toChars()); return new ErrorExp(); } return this; } tb1 = e1.type.toBasetype(); if (!Target.isVectorOpSupported(tb1, op, tb2)) return incompatibleTypes(); if ((tb1.isreal() && e2.type.isimaginary()) || (tb1.isimaginary() && e2.type.isreal())) { switch (type.toBasetype().ty) { case Tfloat32: case Timaginary32: type = Type.tcomplex32; break; case Tfloat64: case Timaginary64: type = Type.tcomplex64; break; case Tfloat80: case Timaginary80: type = Type.tcomplex80; break; default: assert(0); } } return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class MinExp : BinExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKmin, __traits(classInstanceSize, MinExp), e1, e2); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("MinExp::semantic('%s')\n", toChars()); } if (type) return this; if (Expression ex = binSemanticProp(sc)) return ex; Expression e = op_overload(sc); if (e) return e; Type t1 = e1.type.toBasetype(); Type t2 = e2.type.toBasetype(); bool err = false; if (t1.ty == Tdelegate || t1.ty == Tpointer && t1.nextOf().ty == Tfunction) { err |= e1.checkArithmetic(); } if (t2.ty == Tdelegate || t2.ty == Tpointer && t2.nextOf().ty == Tfunction) { err |= e2.checkArithmetic(); } if (err) return new ErrorExp(); if (t1.ty == Tpointer) { if (t2.ty == Tpointer) { // Need to divide the result by the stride // Replace (ptr - ptr) with (ptr - ptr) / stride d_int64 stride; // make sure pointer types are compatible if (Expression ex = typeCombine(this, sc)) return ex; type = Type.tptrdiff_t; stride = t2.nextOf().size(); if (stride == 0) { e = new IntegerExp(loc, 0, Type.tptrdiff_t); } else { e = new DivExp(loc, this, new IntegerExp(Loc(), stride, Type.tptrdiff_t)); e.type = Type.tptrdiff_t; } } else if (t2.isintegral()) e = scaleFactor(this, sc); else { error("can't subtract %s from pointer", t2.toChars()); e = new ErrorExp(); } return e; } if (t2.ty == Tpointer) { type = e2.type; error("can't subtract pointer from %s", e1.type.toChars()); return new ErrorExp(); } if (Expression ex = typeCombine(this, sc)) return ex; Type tb = type.toBasetype(); if (tb.ty == Tarray || tb.ty == Tsarray) { if (!isArrayOpValid(this)) { error("invalid array operation %s (possible missing [])", toChars()); return new ErrorExp(); } return this; } t1 = e1.type.toBasetype(); t2 = e2.type.toBasetype(); if (!Target.isVectorOpSupported(t1, op, t2)) return incompatibleTypes(); if ((t1.isreal() && t2.isimaginary()) || (t1.isimaginary() && t2.isreal())) { switch (type.ty) { case Tfloat32: case Timaginary32: type = Type.tcomplex32; break; case Tfloat64: case Timaginary64: type = Type.tcomplex64; break; case Tfloat80: case Timaginary80: type = Type.tcomplex80; break; default: assert(0); } } return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class CatExp : BinExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKcat, __traits(classInstanceSize, CatExp), e1, e2); } override Expression semantic(Scope* sc) { //printf("CatExp::semantic() %s\n", toChars()); if (type) return this; if (Expression ex = binSemanticProp(sc)) return ex; Expression e = op_overload(sc); if (e) return e; Type tb1 = e1.type.toBasetype(); Type tb2 = e2.type.toBasetype(); auto f1 = checkNonAssignmentArrayOp(e1); auto f2 = checkNonAssignmentArrayOp(e2); if (f1 || f2) return new ErrorExp(); /* BUG: Should handle things like: * char c; * c ~ ' ' * ' ' ~ c; */ version (none) { e1.type.print(); e2.type.print(); } Type tb1next = tb1.nextOf(); Type tb2next = tb2.nextOf(); // Check for: array ~ array if (tb1next && tb2next && (tb1next.implicitConvTo(tb2next) >= MATCHconst || tb2next.implicitConvTo(tb1next) >= MATCHconst || e1.op == TOKarrayliteral && e1.implicitConvTo(tb2) || e2.op == TOKarrayliteral && e2.implicitConvTo(tb1))) { /* https://issues.dlang.org/show_bug.cgi?id=9248 * Here to avoid the case of: * void*[] a = [cast(void*)1]; * void*[] b = [cast(void*)2]; * a ~ b; * becoming: * a ~ [cast(void*)b]; */ /* https://issues.dlang.org/show_bug.cgi?id=14682 * Also to avoid the case of: * int[][] a; * a ~ []; * becoming: * a ~ cast(int[])[]; */ goto Lpeer; } // Check for: array ~ element if ((tb1.ty == Tsarray || tb1.ty == Tarray) && tb2.ty != Tvoid) { if (e1.op == TOKarrayliteral) { e2 = doCopyOrMove(sc, e2); // https://issues.dlang.org/show_bug.cgi?id=14686 // Postblit call appears in AST, and this is // finally translated to an ArrayLiteralExp in below optimize(). } else if (e1.op == TOKstring) { // No postblit call exists on character (integer) value. } else { if (e2.checkPostblit(sc, tb2)) return new ErrorExp(); // Postblit call will be done in runtime helper function } if (e1.op == TOKarrayliteral && e1.implicitConvTo(tb2.arrayOf())) { e1 = e1.implicitCastTo(sc, tb2.arrayOf()); type = tb2.arrayOf(); goto L2elem; } if (e2.implicitConvTo(tb1next) >= MATCHconvert) { e2 = e2.implicitCastTo(sc, tb1next); type = tb1next.arrayOf(); L2elem: if (tb2.ty == Tarray || tb2.ty == Tsarray) { // Make e2 into [e2] e2 = new ArrayLiteralExp(e2.loc, e2); e2.type = type; } return optimize(WANTvalue); } } // Check for: element ~ array if ((tb2.ty == Tsarray || tb2.ty == Tarray) && tb1.ty != Tvoid) { if (e2.op == TOKarrayliteral) { e1 = doCopyOrMove(sc, e1); } else if (e2.op == TOKstring) { } else { if (e1.checkPostblit(sc, tb1)) return new ErrorExp(); } if (e2.op == TOKarrayliteral && e2.implicitConvTo(tb1.arrayOf())) { e2 = e2.implicitCastTo(sc, tb1.arrayOf()); type = tb1.arrayOf(); goto L1elem; } if (e1.implicitConvTo(tb2next) >= MATCHconvert) { e1 = e1.implicitCastTo(sc, tb2next); type = tb2next.arrayOf(); L1elem: if (tb1.ty == Tarray || tb1.ty == Tsarray) { // Make e1 into [e1] e1 = new ArrayLiteralExp(e1.loc, e1); e1.type = type; } return optimize(WANTvalue); } } Lpeer: if ((tb1.ty == Tsarray || tb1.ty == Tarray) && (tb2.ty == Tsarray || tb2.ty == Tarray) && (tb1next.mod || tb2next.mod) && (tb1next.mod != tb2next.mod)) { Type t1 = tb1next.mutableOf().constOf().arrayOf(); Type t2 = tb2next.mutableOf().constOf().arrayOf(); if (e1.op == TOKstring && !(cast(StringExp)e1).committed) e1.type = t1; else e1 = e1.castTo(sc, t1); if (e2.op == TOKstring && !(cast(StringExp)e2).committed) e2.type = t2; else e2 = e2.castTo(sc, t2); } if (Expression ex = typeCombine(this, sc)) return ex; type = type.toHeadMutable(); Type tb = type.toBasetype(); if (tb.ty == Tsarray) type = tb.nextOf().arrayOf(); if (type.ty == Tarray && tb1next && tb2next && tb1next.mod != tb2next.mod) { type = type.nextOf().toHeadMutable().arrayOf(); } if (Type tbn = tb.nextOf()) { if (checkPostblit(sc, tbn)) return new ErrorExp(); } version (none) { e1.type.print(); e2.type.print(); type.print(); print(); } Type t1 = e1.type.toBasetype(); Type t2 = e2.type.toBasetype(); if ((t1.ty == Tarray || t1.ty == Tsarray) && (t2.ty == Tarray || t2.ty == Tsarray)) { // Normalize to ArrayLiteralExp or StringExp as far as possible e = optimize(WANTvalue); } else { //printf("(%s) ~ (%s)\n", e1.toChars(), e2.toChars()); return incompatibleTypes(); } return e; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class MulExp : BinExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKmul, __traits(classInstanceSize, MulExp), e1, e2); } override Expression semantic(Scope* sc) { version (none) { printf("MulExp::semantic() %s\n", toChars()); } if (type) return this; if (Expression ex = binSemanticProp(sc)) return ex; Expression e = op_overload(sc); if (e) return e; if (Expression ex = typeCombine(this, sc)) return ex; Type tb = type.toBasetype(); if (tb.ty == Tarray || tb.ty == Tsarray) { if (!isArrayOpValid(this)) { error("invalid array operation %s (possible missing [])", toChars()); return new ErrorExp(); } return this; } if (checkArithmeticBin()) return new ErrorExp(); if (type.isfloating()) { Type t1 = e1.type; Type t2 = e2.type; if (t1.isreal()) { type = t2; } else if (t2.isreal()) { type = t1; } else if (t1.isimaginary()) { if (t2.isimaginary()) { switch (t1.toBasetype().ty) { case Timaginary32: type = Type.tfloat32; break; case Timaginary64: type = Type.tfloat64; break; case Timaginary80: type = Type.tfloat80; break; default: assert(0); } // iy * iv = -yv e1.type = type; e2.type = type; e = new NegExp(loc, this); e = e.semantic(sc); return e; } else type = t2; // t2 is complex } else if (t2.isimaginary()) { type = t1; // t1 is complex } } else if (!Target.isVectorOpSupported(tb, op, e2.type.toBasetype())) return incompatibleTypes(); return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class DivExp : BinExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKdiv, __traits(classInstanceSize, DivExp), e1, e2); } override Expression semantic(Scope* sc) { if (type) return this; if (Expression ex = binSemanticProp(sc)) return ex; Expression e = op_overload(sc); if (e) return e; if (Expression ex = typeCombine(this, sc)) return ex; Type tb = type.toBasetype(); if (tb.ty == Tarray || tb.ty == Tsarray) { if (!isArrayOpValid(this)) { error("invalid array operation %s (possible missing [])", toChars()); return new ErrorExp(); } return this; } if (checkArithmeticBin()) return new ErrorExp(); if (type.isfloating()) { Type t1 = e1.type; Type t2 = e2.type; if (t1.isreal()) { type = t2; if (t2.isimaginary()) { // x/iv = i(-x/v) e2.type = t1; e = new NegExp(loc, this); e = e.semantic(sc); return e; } } else if (t2.isreal()) { type = t1; } else if (t1.isimaginary()) { if (t2.isimaginary()) { switch (t1.toBasetype().ty) { case Timaginary32: type = Type.tfloat32; break; case Timaginary64: type = Type.tfloat64; break; case Timaginary80: type = Type.tfloat80; break; default: assert(0); } } else type = t2; // t2 is complex } else if (t2.isimaginary()) { type = t1; // t1 is complex } } else if (!Target.isVectorOpSupported(tb, op, e2.type.toBasetype())) return incompatibleTypes(); return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class ModExp : BinExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKmod, __traits(classInstanceSize, ModExp), e1, e2); } override Expression semantic(Scope* sc) { if (type) return this; if (Expression ex = binSemanticProp(sc)) return ex; Expression e = op_overload(sc); if (e) return e; if (Expression ex = typeCombine(this, sc)) return ex; Type tb = type.toBasetype(); if (tb.ty == Tarray || tb.ty == Tsarray) { if (!isArrayOpValid(this)) { error("invalid array operation %s (possible missing [])", toChars()); return new ErrorExp(); } return this; } if (!Target.isVectorOpSupported(tb, op, e2.type.toBasetype())) return incompatibleTypes(); if (checkArithmeticBin()) return new ErrorExp(); if (type.isfloating()) { type = e1.type; if (e2.type.iscomplex()) { error("cannot perform modulo complex arithmetic"); return new ErrorExp(); } } return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class PowExp : BinExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKpow, __traits(classInstanceSize, PowExp), e1, e2); } override Expression semantic(Scope* sc) { if (type) return this; //printf("PowExp::semantic() %s\n", toChars()); if (Expression ex = binSemanticProp(sc)) return ex; Expression e = op_overload(sc); if (e) return e; if (Expression ex = typeCombine(this, sc)) return ex; Type tb = type.toBasetype(); if (tb.ty == Tarray || tb.ty == Tsarray) { if (!isArrayOpValid(this)) { error("invalid array operation %s (possible missing [])", toChars()); return new ErrorExp(); } return this; } if (checkArithmeticBin()) return new ErrorExp(); if (!Target.isVectorOpSupported(tb, op, e2.type.toBasetype())) return incompatibleTypes(); // For built-in numeric types, there are several cases. // TODO: backend support, especially for e1 ^^ 2. // First, attempt to fold the expression. e = optimize(WANTvalue); if (e.op != TOKpow) { e = e.semantic(sc); return e; } // Determine if we're raising to an integer power. sinteger_t intpow = 0; if (e2.op == TOKint64 && (cast(sinteger_t)e2.toInteger() == 2 || cast(sinteger_t)e2.toInteger() == 3)) intpow = e2.toInteger(); else if (e2.op == TOKfloat64 && (e2.toReal() == real_t(cast(sinteger_t)e2.toReal()))) intpow = cast(sinteger_t)e2.toReal(); // Deal with x^^2, x^^3 immediately, since they are of practical importance. if (intpow == 2 || intpow == 3) { // Replace x^^2 with (tmp = x, tmp*tmp) // Replace x^^3 with (tmp = x, tmp*tmp*tmp) auto tmp = copyToTemp(0, "__powtmp", e1); Expression de = new DeclarationExp(loc, tmp); Expression ve = new VarExp(loc, tmp); /* Note that we're reusing ve. This should be ok. */ Expression me = new MulExp(loc, ve, ve); if (intpow == 3) me = new MulExp(loc, me, ve); e = new CommaExp(loc, de, me); e = e.semantic(sc); return e; } Module mmath = loadStdMath(); if (!mmath) { //error("requires std.math for ^^ operators"); //fatal(); // Leave handling of PowExp to the backend, or throw // an error gracefully if no backend support exists. if (Expression ex = typeCombine(this, sc)) return ex; return this; } e = new ScopeExp(loc, mmath); if (e2.op == TOKfloat64 && e2.toReal() == CTFloat.half) { // Replace e1 ^^ 0.5 with .std.math.sqrt(x) e = new CallExp(loc, new DotIdExp(loc, e, Id._sqrt), e1); } else { // Replace e1 ^^ e2 with .std.math.pow(e1, e2) e = new CallExp(loc, new DotIdExp(loc, e, Id._pow), e1, e2); } e = e.semantic(sc); return e; } override void accept(Visitor v) { v.visit(this); } } extern (C++) Module loadStdMath() { static __gshared Import impStdMath = null; if (!impStdMath) { auto a = new Identifiers(); a.push(Id.std); auto s = new Import(Loc(), a, Id.math, null, false); s.load(null); if (s.mod) { s.mod.importAll(null); s.mod.semantic(null); } impStdMath = s; } return impStdMath.mod; } /*********************************************************** */ extern (C++) final class ShlExp : BinExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKshl, __traits(classInstanceSize, ShlExp), e1, e2); } override Expression semantic(Scope* sc) { //printf("ShlExp::semantic(), type = %p\n", type); if (type) return this; if (Expression ex = binSemanticProp(sc)) return ex; Expression e = op_overload(sc); if (e) return e; if (checkIntegralBin()) return new ErrorExp(); if (!Target.isVectorOpSupported(e1.type.toBasetype(), op, e2.type.toBasetype())) return incompatibleTypes(); e1 = integralPromotions(e1, sc); e2 = e2.castTo(sc, Type.tshiftcnt); type = e1.type; return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class ShrExp : BinExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKshr, __traits(classInstanceSize, ShrExp), e1, e2); } override Expression semantic(Scope* sc) { if (type) return this; if (Expression ex = binSemanticProp(sc)) return ex; Expression e = op_overload(sc); if (e) return e; if (checkIntegralBin()) return new ErrorExp(); if (!Target.isVectorOpSupported(e1.type.toBasetype(), op, e2.type.toBasetype())) return incompatibleTypes(); e1 = integralPromotions(e1, sc); e2 = e2.castTo(sc, Type.tshiftcnt); type = e1.type; return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class UshrExp : BinExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKushr, __traits(classInstanceSize, UshrExp), e1, e2); } override Expression semantic(Scope* sc) { if (type) return this; if (Expression ex = binSemanticProp(sc)) return ex; Expression e = op_overload(sc); if (e) return e; if (checkIntegralBin()) return new ErrorExp(); if (!Target.isVectorOpSupported(e1.type.toBasetype(), op, e2.type.toBasetype())) return incompatibleTypes(); e1 = integralPromotions(e1, sc); e2 = e2.castTo(sc, Type.tshiftcnt); type = e1.type; return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class AndExp : BinExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKand, __traits(classInstanceSize, AndExp), e1, e2); } override Expression semantic(Scope* sc) { if (type) return this; if (Expression ex = binSemanticProp(sc)) return ex; Expression e = op_overload(sc); if (e) return e; if (e1.type.toBasetype().ty == Tbool && e2.type.toBasetype().ty == Tbool) { type = e1.type; return this; } if (Expression ex = typeCombine(this, sc)) return ex; Type tb = type.toBasetype(); if (tb.ty == Tarray || tb.ty == Tsarray) { if (!isArrayOpValid(this)) { error("invalid array operation %s (possible missing [])", toChars()); return new ErrorExp(); } return this; } if (!Target.isVectorOpSupported(tb, op, e2.type.toBasetype())) return incompatibleTypes(); if (checkIntegralBin()) return new ErrorExp(); return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class OrExp : BinExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKor, __traits(classInstanceSize, OrExp), e1, e2); } override Expression semantic(Scope* sc) { if (type) return this; if (Expression ex = binSemanticProp(sc)) return ex; Expression e = op_overload(sc); if (e) return e; if (e1.type.toBasetype().ty == Tbool && e2.type.toBasetype().ty == Tbool) { type = e1.type; return this; } if (Expression ex = typeCombine(this, sc)) return ex; Type tb = type.toBasetype(); if (tb.ty == Tarray || tb.ty == Tsarray) { if (!isArrayOpValid(this)) { error("invalid array operation %s (possible missing [])", toChars()); return new ErrorExp(); } return this; } if (!Target.isVectorOpSupported(tb, op, e2.type.toBasetype())) return incompatibleTypes(); if (checkIntegralBin()) return new ErrorExp(); return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class XorExp : BinExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKxor, __traits(classInstanceSize, XorExp), e1, e2); } override Expression semantic(Scope* sc) { if (type) return this; if (Expression ex = binSemanticProp(sc)) return ex; Expression e = op_overload(sc); if (e) return e; if (e1.type.toBasetype().ty == Tbool && e2.type.toBasetype().ty == Tbool) { type = e1.type; return this; } if (Expression ex = typeCombine(this, sc)) return ex; Type tb = type.toBasetype(); if (tb.ty == Tarray || tb.ty == Tsarray) { if (!isArrayOpValid(this)) { error("invalid array operation %s (possible missing [])", toChars()); return new ErrorExp(); } return this; } if (!Target.isVectorOpSupported(tb, op, e2.type.toBasetype())) return incompatibleTypes(); if (checkIntegralBin()) return new ErrorExp(); return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class OrOrExp : BinExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKoror, __traits(classInstanceSize, OrOrExp), e1, e2); } override Expression semantic(Scope* sc) { if (type) return this; setNoderefOperands(); // same as for AndAnd e1 = e1.semantic(sc); e1 = resolveProperties(sc, e1); e1 = e1.toBoolean(sc); uint cs1 = sc.callSuper; if (sc.flags & SCOPEcondition) { /* If in static if, don't evaluate e2 if we don't have to. */ e1 = e1.optimize(WANTvalue); if (e1.isBool(true)) { return new IntegerExp(loc, 1, Type.tbool); } } e2 = e2.semantic(sc); sc.mergeCallSuper(loc, cs1); e2 = resolveProperties(sc, e2); auto f1 = checkNonAssignmentArrayOp(e1); auto f2 = checkNonAssignmentArrayOp(e2); if (f1 || f2) return new ErrorExp(); if (e2.type.ty == Tvoid) type = Type.tvoid; else { e2 = e2.toBoolean(sc); type = Type.tbool; } if (e2.op == TOKtype || e2.op == TOKscope) { error("%s is not an expression", e2.toChars()); return new ErrorExp(); } if (e1.op == TOKerror) return e1; if (e2.op == TOKerror) return e2; return this; } override Expression toBoolean(Scope* sc) { auto ex2 = e2.toBoolean(sc); if (ex2.op == TOKerror) return ex2; e2 = ex2; return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class AndAndExp : BinExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKandand, __traits(classInstanceSize, AndAndExp), e1, e2); } override Expression semantic(Scope* sc) { if (type) return this; setNoderefOperands(); // same as for OrOr e1 = e1.semantic(sc); e1 = resolveProperties(sc, e1); e1 = e1.toBoolean(sc); uint cs1 = sc.callSuper; if (sc.flags & SCOPEcondition) { /* If in static if, don't evaluate e2 if we don't have to. */ e1 = e1.optimize(WANTvalue); if (e1.isBool(false)) { return new IntegerExp(loc, 0, Type.tbool); } } e2 = e2.semantic(sc); sc.mergeCallSuper(loc, cs1); e2 = resolveProperties(sc, e2); auto f1 = checkNonAssignmentArrayOp(e1); auto f2 = checkNonAssignmentArrayOp(e2); if (f1 || f2) return new ErrorExp(); if (e2.type.ty == Tvoid) type = Type.tvoid; else { e2 = e2.toBoolean(sc); type = Type.tbool; } if (e2.op == TOKtype || e2.op == TOKscope) { error("%s is not an expression", e2.toChars()); return new ErrorExp(); } if (e1.op == TOKerror) return e1; if (e2.op == TOKerror) return e2; return this; } override Expression toBoolean(Scope* sc) { auto ex2 = e2.toBoolean(sc); if (ex2.op == TOKerror) return ex2; e2 = ex2; return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class CmpExp : BinExp { extern (D) this(TOK op, Loc loc, Expression e1, Expression e2) { super(loc, op, __traits(classInstanceSize, CmpExp), e1, e2); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("CmpExp::semantic('%s')\n", toChars()); } if (type) return this; setNoderefOperands(); if (Expression ex = binSemanticProp(sc)) return ex; Type t1 = e1.type.toBasetype(); Type t2 = e2.type.toBasetype(); if (t1.ty == Tclass && e2.op == TOKnull || t2.ty == Tclass && e1.op == TOKnull) { error("do not use null when comparing class types"); return new ErrorExp(); } Expression e = op_overload(sc); if (e) { if (!e.type.isscalar() && e.type.equals(e1.type)) { error("recursive opCmp expansion"); return new ErrorExp(); } if (e.op == TOKcall) { e = new CmpExp(op, loc, e, new IntegerExp(loc, 0, Type.tint32)); e = e.semantic(sc); } return e; } if (Expression ex = typeCombine(this, sc)) return ex; auto f1 = checkNonAssignmentArrayOp(e1); auto f2 = checkNonAssignmentArrayOp(e2); if (f1 || f2) return new ErrorExp(); type = Type.tbool; // Special handling for array comparisons Expression arrayLowering = null; t1 = e1.type.toBasetype(); t2 = e2.type.toBasetype(); if ((t1.ty == Tarray || t1.ty == Tsarray || t1.ty == Tpointer) && (t2.ty == Tarray || t2.ty == Tsarray || t2.ty == Tpointer)) { Type t1next = t1.nextOf(); Type t2next = t2.nextOf(); if (t1next.implicitConvTo(t2next) < MATCHconst && t2next.implicitConvTo(t1next) < MATCHconst && (t1next.ty != Tvoid && t2next.ty != Tvoid)) { error("array comparison type mismatch, %s vs %s", t1next.toChars(), t2next.toChars()); return new ErrorExp(); } if ((t1.ty == Tarray || t1.ty == Tsarray) && (t2.ty == Tarray || t2.ty == Tsarray)) { // Lower to object.__cmp(e1, e2) Expression al = new IdentifierExp(loc, Id.empty); al = new DotIdExp(loc, al, Id.object); al = new DotIdExp(loc, al, Id.__cmp); al = al.semantic(sc); auto arguments = new Expressions(); arguments.push(e1); arguments.push(e2); al = new CallExp(loc, al, arguments); al = new CmpExp(op, loc, al, new IntegerExp(0)); arrayLowering = al; } } else if (t1.ty == Tstruct || t2.ty == Tstruct || (t1.ty == Tclass && t2.ty == Tclass)) { if (t2.ty == Tstruct) error("need member function opCmp() for %s %s to compare", t2.toDsymbol(sc).kind(), t2.toChars()); else error("need member function opCmp() for %s %s to compare", t1.toDsymbol(sc).kind(), t1.toChars()); return new ErrorExp(); } else if (t1.iscomplex() || t2.iscomplex()) { error("compare not defined for complex operands"); return new ErrorExp(); } else if (t1.ty == Taarray || t2.ty == Taarray) { error("%s is not defined for associative arrays", Token.toChars(op)); return new ErrorExp(); } else if (!Target.isVectorOpSupported(t1, op, t2)) { return incompatibleTypes(); } else { bool r1 = e1.checkValue(); bool r2 = e2.checkValue(); if (r1 || r2) return new ErrorExp(); } TOK altop; switch (op) { // Refer rel_integral[] table case TOKunord: altop = TOKerror; break; case TOKlg: altop = TOKnotequal; break; case TOKleg: altop = TOKerror; break; case TOKule: altop = TOKle; break; case TOKul: altop = TOKlt; break; case TOKuge: altop = TOKge; break; case TOKug: altop = TOKgt; break; case TOKue: altop = TOKequal; break; default: altop = TOKreserved; break; } if (altop == TOKerror && (t1.ty == Tarray || t1.ty == Tsarray || t2.ty == Tarray || t2.ty == Tsarray)) { error("'%s' is not defined for array comparisons", Token.toChars(op)); return new ErrorExp(); } if (altop != TOKreserved) { if (!t1.isfloating()) { if (altop == TOKerror) { const(char)* s = op == TOKunord ? "false" : "true"; error("floating point operator '%s' always returns %s for non-floating comparisons", Token.toChars(op), s); } else { error("use '%s' for non-floating comparisons rather than floating point operator '%s'", Token.toChars(altop), Token.toChars(op)); } } else { error("use std.math.isNaN to deal with NaN operands rather than floating point operator '%s'", Token.toChars(op)); } return new ErrorExp(); } //printf("CmpExp: %s, type = %s\n", e.toChars(), e.type.toChars()); if (arrayLowering) { arrayLowering = arrayLowering.semantic(sc); return arrayLowering; } return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class InExp : BinExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKin, __traits(classInstanceSize, InExp), e1, e2); } override Expression semantic(Scope* sc) { if (type) return this; if (Expression ex = binSemanticProp(sc)) return ex; Expression e = op_overload(sc); if (e) return e; Type t2b = e2.type.toBasetype(); switch (t2b.ty) { case Taarray: { TypeAArray ta = cast(TypeAArray)t2b; // Special handling for array keys if (!arrayTypeCompatible(e1.loc, e1.type, ta.index)) { // Convert key to type of key e1 = e1.implicitCastTo(sc, ta.index); } semanticTypeInfo(sc, ta.index); // Return type is pointer to value type = ta.nextOf().pointerTo(); break; } default: return incompatibleTypes(); case Terror: return new ErrorExp(); } return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * This deletes the key e1 from the associative array e2 */ extern (C++) final class RemoveExp : BinExp { extern (D) this(Loc loc, Expression e1, Expression e2) { super(loc, TOKremove, __traits(classInstanceSize, RemoveExp), e1, e2); type = Type.tbool; } override Expression semantic(Scope* sc) { if (Expression ex = binSemantic(sc)) return ex; return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * == and != */ extern (C++) final class EqualExp : BinExp { extern (D) this(TOK op, Loc loc, Expression e1, Expression e2) { super(loc, op, __traits(classInstanceSize, EqualExp), e1, e2); assert(op == TOKequal || op == TOKnotequal); } override Expression semantic(Scope* sc) { //printf("EqualExp::semantic('%s')\n", toChars()); if (type) return this; setNoderefOperands(); if (auto e = binSemanticProp(sc)) return e; if (e1.op == TOKtype || e2.op == TOKtype) return incompatibleTypes(); { auto t1 = e1.type; auto t2 = e2.type; if (t1.ty == Tenum && t2.ty == Tenum && !t1.equivalent(t2)) deprecation("Comparison between different enumeration types `%s` and `%s`; If this behavior is intended consider using `std.conv.asOriginalType`", t1.toChars(), t2.toChars()); } /* Before checking for operator overloading, check to see if we're * comparing the addresses of two statics. If so, we can just see * if they are the same symbol. */ if (e1.op == TOKaddress && e2.op == TOKaddress) { AddrExp ae1 = cast(AddrExp)e1; AddrExp ae2 = cast(AddrExp)e2; if (ae1.e1.op == TOKvar && ae2.e1.op == TOKvar) { VarExp ve1 = cast(VarExp)ae1.e1; VarExp ve2 = cast(VarExp)ae2.e1; if (ve1.var == ve2.var) { // They are the same, result is 'true' for ==, 'false' for != return new IntegerExp(loc, (op == TOKequal), Type.tbool); } } } if (auto e = op_overload(sc)) return e; if (auto e = typeCombine(this, sc)) return e; auto f1 = checkNonAssignmentArrayOp(e1); auto f2 = checkNonAssignmentArrayOp(e2); if (f1 || f2) return new ErrorExp(); type = Type.tbool; // Special handling for array comparisons if (!arrayTypeCompatible(loc, e1.type, e2.type)) { if (e1.type != e2.type && e1.type.isfloating() && e2.type.isfloating()) { // Cast both to complex e1 = e1.castTo(sc, Type.tcomplex80); e2 = e2.castTo(sc, Type.tcomplex80); } } if (e1.type.toBasetype().ty == Taarray) semanticTypeInfo(sc, e1.type.toBasetype()); Type t1 = e1.type.toBasetype(); Type t2 = e2.type.toBasetype(); if (!Target.isVectorOpSupported(t1, op, t2)) return incompatibleTypes(); return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * is and !is */ extern (C++) final class IdentityExp : BinExp { extern (D) this(TOK op, Loc loc, Expression e1, Expression e2) { super(loc, op, __traits(classInstanceSize, IdentityExp), e1, e2); } override Expression semantic(Scope* sc) { if (type) return this; setNoderefOperands(); if (auto e = binSemanticProp(sc)) return e; if (auto e = typeCombine(this, sc)) return e; auto f1 = checkNonAssignmentArrayOp(e1); auto f2 = checkNonAssignmentArrayOp(e2); if (f1 || f2) return new ErrorExp(); type = Type.tbool; if (e1.type != e2.type && e1.type.isfloating() && e2.type.isfloating()) { // Cast both to complex e1 = e1.castTo(sc, Type.tcomplex80); e2 = e2.castTo(sc, Type.tcomplex80); } auto tb1 = e1.type.toBasetype(); auto tb2 = e2.type.toBasetype(); if (!Target.isVectorOpSupported(tb1, op, tb2)) return incompatibleTypes(); if (e1.type.toBasetype().ty == Tsarray || e2.type.toBasetype().ty == Tsarray) deprecation("identity comparison of static arrays " ~ "implicitly coerces them to slices, " ~ "which are compared by reference"); return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class CondExp : BinExp { Expression econd; extern (D) this(Loc loc, Expression econd, Expression e1, Expression e2) { super(loc, TOKquestion, __traits(classInstanceSize, CondExp), e1, e2); this.econd = econd; } override Expression syntaxCopy() { return new CondExp(loc, econd.syntaxCopy(), e1.syntaxCopy(), e2.syntaxCopy()); } override Expression semantic(Scope* sc) { static if (LOGSEMANTIC) { printf("CondExp::semantic('%s')\n", toChars()); } if (type) return this; if (econd.op == TOKdotid) (cast(DotIdExp)econd).noderef = true; Expression ec = econd.semantic(sc); ec = resolveProperties(sc, ec); ec = ec.toBoolean(sc); uint cs0 = sc.callSuper; uint* fi0 = sc.saveFieldInit(); Expression e1x = e1.semantic(sc); e1x = resolveProperties(sc, e1x); uint cs1 = sc.callSuper; uint* fi1 = sc.fieldinit; sc.callSuper = cs0; sc.fieldinit = fi0; Expression e2x = e2.semantic(sc); e2x = resolveProperties(sc, e2x); sc.mergeCallSuper(loc, cs1); sc.mergeFieldInit(loc, fi1); if (ec.op == TOKerror) return ec; if (ec.type == Type.terror) return new ErrorExp(); econd = ec; if (e1x.op == TOKerror) return e1x; if (e1x.type == Type.terror) return new ErrorExp(); e1 = e1x; if (e2x.op == TOKerror) return e2x; if (e2x.type == Type.terror) return new ErrorExp(); e2 = e2x; auto f0 = checkNonAssignmentArrayOp(econd); auto f1 = checkNonAssignmentArrayOp(e1); auto f2 = checkNonAssignmentArrayOp(e2); if (f0 || f1 || f2) return new ErrorExp(); Type t1 = e1.type; Type t2 = e2.type; // If either operand is void the result is void, we have to cast both // the expression to void so that we explicitly discard the expression // value if any // https://issues.dlang.org/show_bug.cgi?id=16598 if (t1.ty == Tvoid || t2.ty == Tvoid) { type = Type.tvoid; e1 = e1.castTo(sc, type); e2 = e2.castTo(sc, type); } else if (t1 == t2) type = t1; else { if (Expression ex = typeCombine(this, sc)) return ex; switch (e1.type.toBasetype().ty) { case Tcomplex32: case Tcomplex64: case Tcomplex80: e2 = e2.castTo(sc, e1.type); break; default: break; } switch (e2.type.toBasetype().ty) { case Tcomplex32: case Tcomplex64: case Tcomplex80: e1 = e1.castTo(sc, e2.type); break; default: break; } if (type.toBasetype().ty == Tarray) { e1 = e1.castTo(sc, type); e2 = e2.castTo(sc, type); } } type = type.merge2(); version (none) { printf("res: %s\n", type.toChars()); printf("e1 : %s\n", e1.type.toChars()); printf("e2 : %s\n", e2.type.toChars()); } /* https://issues.dlang.org/show_bug.cgi?id=14696 * If either e1 or e2 contain temporaries which need dtor, * make them conditional. * Rewrite: * cond ? (__tmp1 = ..., __tmp1) : (__tmp2 = ..., __tmp2) * to: * (auto __cond = cond) ? (... __tmp1) : (... __tmp2) * and replace edtors of __tmp1 and __tmp2 with: * __tmp1.edtor --> __cond && __tmp1.dtor() * __tmp2.edtor --> __cond || __tmp2.dtor() */ hookDtors(sc); return this; } override int checkModifiable(Scope* sc, int flag) { return e1.checkModifiable(sc, flag) && e2.checkModifiable(sc, flag); } override bool isLvalue() { return e1.isLvalue() && e2.isLvalue(); } override Expression toLvalue(Scope* sc, Expression ex) { // convert (econd ? e1 : e2) to *(econd ? &e1 : &e2) CondExp e = cast(CondExp)copy(); e.e1 = e1.toLvalue(sc, null).addressOf(); e.e2 = e2.toLvalue(sc, null).addressOf(); e.type = type.pointerTo(); return new PtrExp(loc, e, type); } override Expression modifiableLvalue(Scope* sc, Expression e) { //error("conditional expression %s is not a modifiable lvalue", toChars()); e1 = e1.modifiableLvalue(sc, e1); e2 = e2.modifiableLvalue(sc, e2); return toLvalue(sc, this); } override Expression toBoolean(Scope* sc) { auto ex1 = e1.toBoolean(sc); auto ex2 = e2.toBoolean(sc); if (ex1.op == TOKerror) return ex1; if (ex2.op == TOKerror) return ex2; e1 = ex1; e2 = ex2; return this; } void hookDtors(Scope* sc) { extern (C++) final class DtorVisitor : StoppableVisitor { alias visit = super.visit; public: Scope* sc; CondExp ce; VarDeclaration vcond; bool isThen; extern (D) this(Scope* sc, CondExp ce) { this.sc = sc; this.ce = ce; } override void visit(Expression e) { //printf("(e = %s)\n", e.toChars()); } override void visit(DeclarationExp e) { auto v = e.declaration.isVarDeclaration(); if (v && !v.isDataseg()) { if (v._init) { if (auto ei = v._init.isExpInitializer()) ei.exp.accept(this); } if (v.needsScopeDtor()) { if (!vcond) { vcond = copyToTemp(STCvolatile, "__cond", ce.econd); vcond.semantic(sc); Expression de = new DeclarationExp(ce.econd.loc, vcond); de = de.semantic(sc); Expression ve = new VarExp(ce.econd.loc, vcond); ce.econd = Expression.combine(de, ve); } //printf("\t++v = %s, v.edtor = %s\n", v.toChars(), v.edtor.toChars()); Expression ve = new VarExp(vcond.loc, vcond); if (isThen) v.edtor = new AndAndExp(v.edtor.loc, ve, v.edtor); else v.edtor = new OrOrExp(v.edtor.loc, ve, v.edtor); v.edtor = v.edtor.semantic(sc); //printf("\t--v = %s, v.edtor = %s\n", v.toChars(), v.edtor.toChars()); } } } } scope DtorVisitor v = new DtorVisitor(sc, this); //printf("+%s\n", toChars()); v.isThen = true; walkPostorder(e1, v); v.isThen = false; walkPostorder(e2, v); //printf("-%s\n", toChars()); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) class DefaultInitExp : Expression { TOK subop; // which of the derived classes this is final extern (D) this(Loc loc, TOK subop, int size) { super(loc, TOKdefault, size); this.subop = subop; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class FileInitExp : DefaultInitExp { extern (D) this(Loc loc, TOK tok) { super(loc, tok, __traits(classInstanceSize, FileInitExp)); } override Expression semantic(Scope* sc) { //printf("FileInitExp::semantic()\n"); type = Type.tstring; return this; } override Expression resolveLoc(Loc loc, Scope* sc) { //printf("FileInitExp::resolve() %s\n", toChars()); const(char)* s = loc.filename ? loc.filename : sc._module.ident.toChars(); Expression e = new StringExp(loc, cast(char*)s); e = e.semantic(sc); e = e.castTo(sc, type); return e; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class LineInitExp : DefaultInitExp { extern (D) this(Loc loc) { super(loc, TOKline, __traits(classInstanceSize, LineInitExp)); } override Expression semantic(Scope* sc) { type = Type.tint32; return this; } override Expression resolveLoc(Loc loc, Scope* sc) { Expression e = new IntegerExp(loc, loc.linnum, Type.tint32); e = e.castTo(sc, type); return e; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class ModuleInitExp : DefaultInitExp { extern (D) this(Loc loc) { super(loc, TOKmodulestring, __traits(classInstanceSize, ModuleInitExp)); } override Expression semantic(Scope* sc) { //printf("ModuleInitExp::semantic()\n"); type = Type.tstring; return this; } override Expression resolveLoc(Loc loc, Scope* sc) { const(char)* s; if (sc.callsc) s = sc.callsc._module.toPrettyChars(); else s = sc._module.toPrettyChars(); Expression e = new StringExp(loc, cast(char*)s); e = e.semantic(sc); e = e.castTo(sc, type); return e; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class FuncInitExp : DefaultInitExp { extern (D) this(Loc loc) { super(loc, TOKfuncstring, __traits(classInstanceSize, FuncInitExp)); } override Expression semantic(Scope* sc) { //printf("FuncInitExp::semantic()\n"); type = Type.tstring; if (sc.func) return this.resolveLoc(Loc(), sc); return this; } override Expression resolveLoc(Loc loc, Scope* sc) { const(char)* s; if (sc.callsc && sc.callsc.func) s = sc.callsc.func.Dsymbol.toPrettyChars(); else if (sc.func) s = sc.func.Dsymbol.toPrettyChars(); else s = ""; Expression e = new StringExp(loc, cast(char*)s); e = e.semantic(sc); e = e.castTo(sc, type); return e; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class PrettyFuncInitExp : DefaultInitExp { extern (D) this(Loc loc) { super(loc, TOKprettyfunc, __traits(classInstanceSize, PrettyFuncInitExp)); } override Expression semantic(Scope* sc) { //printf("PrettyFuncInitExp::semantic()\n"); type = Type.tstring; if (sc.func) return this.resolveLoc(Loc(), sc); return this; } override Expression resolveLoc(Loc loc, Scope* sc) { FuncDeclaration fd; if (sc.callsc && sc.callsc.func) fd = sc.callsc.func; else fd = sc.func; const(char)* s; if (fd) { const(char)* funcStr = fd.Dsymbol.toPrettyChars(); OutBuffer buf; functionToBufferWithIdent(cast(TypeFunction)fd.type, &buf, funcStr); s = buf.extractString(); } else { s = ""; } Expression e = new StringExp(loc, cast(char*)s); e = e.semantic(sc); e = e.castTo(sc, type); return e; } override void accept(Visitor v) { v.visit(this); } }
D
#!/usr/bin/env rdmd -I.. -i import std.stdio; import std.datetime.stopwatch; import std.algorithm; import std.range; import std.math; import std.typecons; import std.traits; import std.conv; import kreikey.intmath; import kreikey.util; import kreikey.combinatorics; import kreikey.digits; import kreikey.primes; alias isPermutation = kreikey.combinatorics.isPermutation; void main() { StopWatch timer; timer.start(); writeln("Totient permutation"); auto tumber = findTotientPermutation(10000000); writefln("number: %s totient: %s ratio: %s", tumber.expand); timer.stop(); writefln("Finished in %s milliseconds.", timer.peek.total!"msecs"()); } auto findTotientPermutation(ulong top) { auto primes = new Primes!ulong(); ulong number; ulong totient; ulong bestProduct; ulong bestTotient; real smallestRatio = real.max; real ratio; ulong highNdx; ulong lowPrime; for (ulong lowNdx = primes.countUntil!(a => a >= sqrt(real(top)))() - 1; lowNdx < ulong.max; lowNdx--) { lowPrime = primes[lowNdx]; primes.reindex(); highNdx = lowNdx + primes.countUntil!(a => a >= real(top)/lowPrime)() - 1; primes.reset(); for (; highNdx > lowNdx; highNdx--) { number = primes[lowNdx] * primes[highNdx]; totient = getTotient(number); ratio = real(number)/totient; if (ratio > smallestRatio) break; if (totient.isPermutation(number) && ratio < smallestRatio) { writefln("%s, %s, %s", number, totient, ratio); smallestRatio = ratio; bestProduct = number; bestTotient = totient; } } } return tuple(bestProduct, bestTotient, smallestRatio); }
D
/***********************************************************************\ * imm.d * * * * Windows API header module * * * * Translated from MinGW Windows headers * * * * Placed into public domain * \***********************************************************************/ module win32.imm; pragma(lib, "imm32"); import win32.windef, win32.wingdi; import win32.winuser; // for the MFS_xxx enums. private import win32.w32api; const WM_CONVERTREQUESTEX = 0x108; const WM_IME_STARTCOMPOSITION = 0x10D; const WM_IME_ENDCOMPOSITION = 0x10E; const WM_IME_COMPOSITION = 0x10F; const WM_IME_KEYLAST = 0x10F; const WM_IME_SETCONTEXT = 0x281; const WM_IME_NOTIFY = 0x282; const WM_IME_CONTROL = 0x283; const WM_IME_COMPOSITIONFULL = 0x284; const WM_IME_SELECT = 0x285; const WM_IME_CHAR = 0x286; static if (_WIN32_WINNT >= 0x500) { const WM_IME_REQUEST = 0x288; } const WM_IME_KEYDOWN = 0x290; const WM_IME_KEYUP = 0x291; const IMC_GETCANDIDATEPOS=7; const IMC_SETCANDIDATEPOS=8; const IMC_GETCOMPOSITIONFONT=9; const IMC_SETCOMPOSITIONFONT=10; const IMC_GETCOMPOSITIONWINDOW=11; const IMC_SETCOMPOSITIONWINDOW=12; const IMC_GETSTATUSWINDOWPOS=15; const IMC_SETSTATUSWINDOWPOS=16; const IMC_CLOSESTATUSWINDOW=0x21; const IMC_OPENSTATUSWINDOW=0x22; const IMN_CLOSESTATUSWINDOW=1; const IMN_OPENSTATUSWINDOW=2; const IMN_CHANGECANDIDATE=3; const IMN_CLOSECANDIDATE=4; const IMN_OPENCANDIDATE=5; const IMN_SETCONVERSIONMODE=6; const IMN_SETSENTENCEMODE=7; const IMN_SETOPENSTATUS=8; const IMN_SETCANDIDATEPOS=9; const IMN_SETCOMPOSITIONFONT=10; const IMN_SETCOMPOSITIONWINDOW=11; const IMN_SETSTATUSWINDOWPOS=12; const IMN_GUIDELINE=13; const IMN_PRIVATE=14; const NI_OPENCANDIDATE=16; const NI_CLOSECANDIDATE=17; const NI_SELECTCANDIDATESTR=18; const NI_CHANGECANDIDATELIST=19; const NI_FINALIZECONVERSIONRESULT=20; const NI_COMPOSITIONSTR=21; const NI_SETCANDIDATE_PAGESTART=22; const NI_SETCANDIDATE_PAGESIZE=23; const NI_IMEMENUSELECTED=24; const ISC_SHOWUICANDIDATEWINDOW=1; const ISC_SHOWUICOMPOSITIONWINDOW=0x80000000; const ISC_SHOWUIGUIDELINE=0x40000000; const ISC_SHOWUIALLCANDIDATEWINDOW=15; const ISC_SHOWUIALL=0xC000000F; const CPS_COMPLETE=1; const CPS_CONVERT=2; const CPS_REVERT=3; const CPS_CANCEL=4; const IME_CHOTKEY_IME_NONIME_TOGGLE=16; const IME_CHOTKEY_SHAPE_TOGGLE=17; const IME_CHOTKEY_SYMBOL_TOGGLE=18; const IME_JHOTKEY_CLOSE_OPEN=0x30; const IME_KHOTKEY_SHAPE_TOGGLE=0x50; const IME_KHOTKEY_HANJACONVERT=0x51; const IME_KHOTKEY_ENGLISH=0x52; const IME_THOTKEY_IME_NONIME_TOGGLE=0x70; const IME_THOTKEY_SHAPE_TOGGLE=0x71; const IME_THOTKEY_SYMBOL_TOGGLE=0x72; const IME_HOTKEY_DSWITCH_FIRST=256; const IME_HOTKEY_DSWITCH_LAST=0x11F; const IME_ITHOTKEY_RESEND_RESULTSTR=512; const IME_ITHOTKEY_PREVIOUS_COMPOSITION=513; const IME_ITHOTKEY_UISTYLE_TOGGLE=514; const GCS_COMPREADSTR=1; const GCS_COMPREADATTR=2; const GCS_COMPREADCLAUSE=4; const GCS_COMPSTR=8; const GCS_COMPATTR=16; const GCS_COMPCLAUSE=32; const GCS_CURSORPOS=128; const GCS_DELTASTART=256; const GCS_RESULTREADSTR=512; const GCS_RESULTREADCLAUSE=1024; const GCS_RESULTSTR=2048; const GCS_RESULTCLAUSE=4096; const CS_INSERTCHAR=0x2000; const CS_NOMOVECARET=0x4000; const IMEVER_0310=0x3000A; const IMEVER_0400=0x40000; const IME_PROP_AT_CARET=0x10000; const IME_PROP_SPECIAL_UI=0x20000; const IME_PROP_CANDLIST_START_FROM_1=0x40000; const IME_PROP_UNICODE=0x80000; const UI_CAP_2700=1; const UI_CAP_ROT90=2; const UI_CAP_ROTANY=4; const SCS_CAP_COMPSTR=1; const SCS_CAP_MAKEREAD=2; const SELECT_CAP_CONVERSION=1; const SELECT_CAP_SENTENCE=2; const GGL_LEVEL=1; const GGL_INDEX=2; const GGL_STRING=3; const GGL_PRIVATE=4; const GL_LEVEL_NOGUIDELINE=0; const GL_LEVEL_FATAL=1; const GL_LEVEL_ERROR=2; const GL_LEVEL_WARNING=3; const GL_LEVEL_INFORMATION=4; const GL_ID_UNKNOWN=0; const GL_ID_NOMODULE=1; const GL_ID_NODICTIONARY=16; const GL_ID_CANNOTSAVE=17; const GL_ID_NOCONVERT=32; const GL_ID_TYPINGERROR=33; const GL_ID_TOOMANYSTROKE=34; const GL_ID_READINGCONFLICT=35; const GL_ID_INPUTREADING=36; const GL_ID_INPUTRADICAL=37; const GL_ID_INPUTCODE=38; const GL_ID_INPUTSYMBOL=39; const GL_ID_CHOOSECANDIDATE=40; const GL_ID_REVERSECONVERSION=41; const GL_ID_PRIVATE_FIRST=0x8000; const GL_ID_PRIVATE_LAST=0xFFFF; const DWORD IGP_GETIMEVERSION = -4; const IGP_PROPERTY=4; const IGP_CONVERSION=8; const IGP_SENTENCE=12; const IGP_UI=16; const IGP_SETCOMPSTR=0x14; const IGP_SELECT=0x18; const SCS_SETSTR = GCS_COMPREADSTR|GCS_COMPSTR; const SCS_CHANGEATTR = GCS_COMPREADATTR|GCS_COMPATTR; const SCS_CHANGECLAUSE = GCS_COMPREADCLAUSE|GCS_COMPCLAUSE; const ATTR_INPUT=0; const ATTR_TARGET_CONVERTED=1; const ATTR_CONVERTED=2; const ATTR_TARGET_NOTCONVERTED=3; const ATTR_INPUT_ERROR=4; const ATTR_FIXEDCONVERTED=5; const CFS_DEFAULT=0; const CFS_RECT=1; const CFS_POINT=2; const CFS_SCREEN=4; const CFS_FORCE_POSITION=32; const CFS_CANDIDATEPOS=64; const CFS_EXCLUDE=128; const GCL_CONVERSION=1; const GCL_REVERSECONVERSION=2; const GCL_REVERSE_LENGTH=3; const IME_CMODE_ALPHANUMERIC=0; const IME_CMODE_NATIVE=1; const IME_CMODE_CHINESE=IME_CMODE_NATIVE; const IME_CMODE_HANGEUL=IME_CMODE_NATIVE; const IME_CMODE_HANGUL=IME_CMODE_NATIVE; const IME_CMODE_JAPANESE=IME_CMODE_NATIVE; const IME_CMODE_KATAKANA=2; const IME_CMODE_LANGUAGE=3; const IME_CMODE_FULLSHAPE=8; const IME_CMODE_ROMAN=16; const IME_CMODE_CHARCODE=32; const IME_CMODE_HANJACONVERT=64; const IME_CMODE_SOFTKBD=128; const IME_CMODE_NOCONVERSION=256; const IME_CMODE_EUDC=512; const IME_CMODE_SYMBOL=1024; const IME_CMODE_FIXED=2048; const IME_SMODE_NONE=0; const IME_SMODE_PLAURALCLAUSE=1; const IME_SMODE_SINGLECONVERT=2; const IME_SMODE_AUTOMATIC=4; const IME_SMODE_PHRASEPREDICT=8; const IME_CAND_UNKNOWN=0; const IME_CAND_READ=1; const IME_CAND_CODE=2; const IME_CAND_MEANING=3; const IME_CAND_RADICAL=4; const IME_CAND_STROKE=5; const IMM_ERROR_NODATA=(-1); const IMM_ERROR_GENERAL=(-2); const IME_CONFIG_GENERAL=1; const IME_CONFIG_REGISTERWORD=2; const IME_CONFIG_SELECTDICTIONARY=3; const IME_ESC_QUERY_SUPPORT=3; const IME_ESC_RESERVED_FIRST=4; const IME_ESC_RESERVED_LAST=0x7FF; const IME_ESC_PRIVATE_FIRST=0x800; const IME_ESC_PRIVATE_LAST=0xFFF; const IME_ESC_SEQUENCE_TO_INTERNAL=0x1001; const IME_ESC_GET_EUDC_DICTIONARY=0x1003; const IME_ESC_SET_EUDC_DICTIONARY=0x1004; const IME_ESC_MAX_KEY=0x1005; const IME_ESC_IME_NAME=0x1006; const IME_ESC_SYNC_HOTKEY=0x1007; const IME_ESC_HANJA_MODE=0x1008; const IME_ESC_AUTOMATA=0x1009; const IME_REGWORD_STYLE_EUDC=1; const IME_REGWORD_STYLE_USER_FIRST=0x80000000; const IME_REGWORD_STYLE_USER_LAST=0xFFFFFFFF; const SOFTKEYBOARD_TYPE_T1=1; const SOFTKEYBOARD_TYPE_C1=2; const IMEMENUITEM_STRING_SIZE=80; const MOD_ALT=1; const MOD_CONTROL=2; const MOD_SHIFT=4; const MOD_WIN=8; const MOD_IGNORE_ALL_MODIFIER=1024; const MOD_ON_KEYUP=2048; const MOD_RIGHT=16384; const MOD_LEFT=32768; const IACE_CHILDREN=1; const IACE_DEFAULT=16; const IACE_IGNORENOCONTEXT=32; const IGIMIF_RIGHTMENU=1; const IGIMII_CMODE=1; const IGIMII_SMODE=2; const IGIMII_CONFIGURE=4; const IGIMII_TOOLS=8; const IGIMII_HELP=16; const IGIMII_OTHER=32; const IGIMII_INPUTTOOLS=64; const IMFT_RADIOCHECK=1; const IMFT_SEPARATOR=2; const IMFT_SUBMENU=4; const IMFS_GRAYED=MFS_GRAYED; const IMFS_DISABLED=MFS_DISABLED; const IMFS_CHECKED=MFS_CHECKED; const IMFS_HILITE=MFS_HILITE; const IMFS_ENABLED=MFS_ENABLED; const IMFS_UNCHECKED=MFS_UNCHECKED; const IMFS_UNHILITE=MFS_UNHILITE; const IMFS_DEFAULT=MFS_DEFAULT; const STYLE_DESCRIPTION_SIZE=32; alias DWORD HIMC; alias DWORD HIMCC; alias HKL* LPHKL; struct COMPOSITIONFORM{ DWORD dwStyle; POINT ptCurrentPos; RECT rcArea; } alias COMPOSITIONFORM* PCOMPOSITIONFORM, LPCOMPOSITIONFORM; struct CANDIDATEFORM{ DWORD dwIndex; DWORD dwStyle; POINT ptCurrentPos; RECT rcArea; } alias CANDIDATEFORM* PCANDIDATEFORM, LPCANDIDATEFORM; struct CANDIDATELIST{ DWORD dwSize; DWORD dwStyle; DWORD dwCount; DWORD dwSelection; DWORD dwPageStart; DWORD dwPageSize; DWORD[1] dwOffset; } alias CANDIDATELIST* PCANDIDATELIST, LPCANDIDATELIST; struct REGISTERWORDA{ LPSTR lpReading; LPSTR lpWord; } alias REGISTERWORDA* PREGISTERWORDA, LPREGISTERWORDA; struct REGISTERWORDW{ LPWSTR lpReading; LPWSTR lpWord; } alias REGISTERWORDW* PREGISTERWORDW, LPREGISTERWORDW; struct STYLEBUFA{ DWORD dwStyle; CHAR[STYLE_DESCRIPTION_SIZE] szDescription; } alias STYLEBUFA* PSTYLEBUFA, LPSTYLEBUFA; struct STYLEBUFW{ DWORD dwStyle; WCHAR[STYLE_DESCRIPTION_SIZE] szDescription; } alias STYLEBUFW* PSTYLEBUFW, LPSTYLEBUFW; struct IMEMENUITEMINFOA{ UINT cbSize = this.sizeof; UINT fType; UINT fState; UINT wID; HBITMAP hbmpChecked; HBITMAP hbmpUnchecked; DWORD dwItemData; CHAR[IMEMENUITEM_STRING_SIZE] szString; HBITMAP hbmpItem; } alias IMEMENUITEMINFOA* PIMEMENUITEMINFOA, LPIMEMENUITEMINFOA; struct IMEMENUITEMINFOW{ UINT cbSize = this.sizeof; UINT fType; UINT fState; UINT wID; HBITMAP hbmpChecked; HBITMAP hbmpUnchecked; DWORD dwItemData; WCHAR[IMEMENUITEM_STRING_SIZE] szString; HBITMAP hbmpItem; } alias IMEMENUITEMINFOW* PIMEMENUITEMINFOW, LPIMEMENUITEMINFOW; alias int function (LPCSTR, DWORD, LPCSTR, LPVOID) REGISTERWORDENUMPROCA; alias int function (LPCWSTR, DWORD, LPCWSTR, LPVOID) REGISTERWORDENUMPROCW; version(Unicode) { alias REGISTERWORDENUMPROCW REGISTERWORDENUMPROC; alias REGISTERWORDW REGISTERWORD; alias IMEMENUITEMINFOW IMEMENUITEMINFO; alias STYLEBUFW STYLEBUF; } else { alias REGISTERWORDENUMPROCA REGISTERWORDENUMPROC; alias REGISTERWORDA REGISTERWORD; alias IMEMENUITEMINFOA IMEMENUITEMINFO; alias STYLEBUFA STYLEBUF; } alias STYLEBUF* PSTYLEBUF, LPSTYLEBUF; alias REGISTERWORD* PREGISTERWORD, LPREGISTERWORD; alias IMEMENUITEMINFO* PIMEMENUITEMINFO, LPIMEMENUITEMINFO; extern (Windows): HKL ImmInstallIMEA(LPCSTR, LPCSTR); HKL ImmInstallIMEW(LPCWSTR, LPCWSTR); HWND ImmGetDefaultIMEWnd(HWND); UINT ImmGetDescriptionA(HKL, LPSTR, UINT); UINT ImmGetDescriptionW(HKL, LPWSTR, UINT); UINT ImmGetIMEFileNameA(HKL, LPSTR, UINT); UINT ImmGetIMEFileNameW(HKL, LPWSTR, UINT); DWORD ImmGetProperty(HKL, DWORD); BOOL ImmIsIME(HKL); BOOL ImmSimulateHotKey(HWND, DWORD); HIMC ImmCreateContext(); BOOL ImmDestroyContext(HIMC); HIMC ImmGetContext(HWND); BOOL ImmReleaseContext(HWND, HIMC); HIMC ImmAssociateContext(HWND, HIMC); LONG ImmGetCompositionStringA(HIMC, DWORD, PVOID, DWORD); LONG ImmGetCompositionStringW(HIMC, DWORD, PVOID, DWORD); BOOL ImmSetCompositionStringA(HIMC, DWORD, PCVOID, DWORD, PCVOID, DWORD); BOOL ImmSetCompositionStringW(HIMC, DWORD, PCVOID, DWORD, PCVOID, DWORD); DWORD ImmGetCandidateListCountA(HIMC, PDWORD); DWORD ImmGetCandidateListCountW(HIMC, PDWORD); DWORD ImmGetCandidateListA(HIMC, DWORD, PCANDIDATELIST, DWORD); DWORD ImmGetCandidateListW(HIMC, DWORD, PCANDIDATELIST, DWORD); DWORD ImmGetGuideLineA(HIMC, DWORD, LPSTR, DWORD); DWORD ImmGetGuideLineW(HIMC, DWORD, LPWSTR, DWORD); BOOL ImmGetConversionStatus(HIMC, LPDWORD, PDWORD); BOOL ImmSetConversionStatus(HIMC, DWORD, DWORD); BOOL ImmGetOpenStatus(HIMC); BOOL ImmSetOpenStatus(HIMC, BOOL); BOOL ImmGetCompositionFontA(HIMC, LPLOGFONTA); BOOL ImmGetCompositionFontW(HIMC, LPLOGFONTW); BOOL ImmSetCompositionFontA(HIMC, LPLOGFONTA); BOOL ImmSetCompositionFontW(HIMC, LPLOGFONTW); BOOL ImmConfigureIMEA(HKL, HWND, DWORD, PVOID); BOOL ImmConfigureIMEW(HKL, HWND, DWORD, PVOID); LRESULT ImmEscapeA(HKL, HIMC, UINT, PVOID); LRESULT ImmEscapeW(HKL, HIMC, UINT, PVOID); DWORD ImmGetConversionListA(HKL, HIMC, LPCSTR, PCANDIDATELIST, DWORD, UINT); DWORD ImmGetConversionListW(HKL, HIMC, LPCWSTR, PCANDIDATELIST, DWORD, UINT); BOOL ImmNotifyIME(HIMC, DWORD, DWORD, DWORD); BOOL ImmGetStatusWindowPos(HIMC, LPPOINT); BOOL ImmSetStatusWindowPos(HIMC, LPPOINT); BOOL ImmGetCompositionWindow(HIMC, PCOMPOSITIONFORM); BOOL ImmSetCompositionWindow(HIMC, PCOMPOSITIONFORM); BOOL ImmGetCandidateWindow(HIMC, DWORD, PCANDIDATEFORM); BOOL ImmSetCandidateWindow(HIMC, PCANDIDATEFORM); BOOL ImmIsUIMessageA(HWND, UINT, WPARAM, LPARAM); BOOL ImmIsUIMessageW(HWND, UINT, WPARAM, LPARAM); UINT ImmGetVirtualKey(HWND); BOOL ImmRegisterWordA(HKL, LPCSTR, DWORD, LPCSTR); BOOL ImmRegisterWordW(HKL, LPCWSTR, DWORD, LPCWSTR); BOOL ImmUnregisterWordA(HKL, LPCSTR, DWORD, LPCSTR); BOOL ImmUnregisterWordW(HKL, LPCWSTR, DWORD, LPCWSTR); UINT ImmGetRegisterWordStyleA(HKL, UINT, PSTYLEBUFA); UINT ImmGetRegisterWordStyleW(HKL, UINT, PSTYLEBUFW); UINT ImmEnumRegisterWordA(HKL, REGISTERWORDENUMPROCA, LPCSTR, DWORD, LPCSTR, PVOID); UINT ImmEnumRegisterWordW(HKL, REGISTERWORDENUMPROCW, LPCWSTR, DWORD, LPCWSTR, PVOID); BOOL EnableEUDC(BOOL); BOOL ImmDisableIME(DWORD); DWORD ImmGetImeMenuItemsA(HIMC, DWORD, DWORD, LPIMEMENUITEMINFOA, LPIMEMENUITEMINFOA, DWORD); DWORD ImmGetImeMenuItemsW(HIMC, DWORD, DWORD, LPIMEMENUITEMINFOW, LPIMEMENUITEMINFOW, DWORD); version(Unicode) { alias ImmEnumRegisterWordW ImmEnumRegisterWord; alias ImmGetRegisterWordStyleW ImmGetRegisterWordStyle; alias ImmUnregisterWordW ImmUnregisterWord; alias ImmRegisterWordW ImmRegisterWord; alias ImmInstallIMEW ImmInstallIME; alias ImmIsUIMessageW ImmIsUIMessage; alias ImmGetConversionListW ImmGetConversionList; alias ImmEscapeW ImmEscape; alias ImmConfigureIMEW ImmConfigureIME; alias ImmSetCompositionFontW ImmSetCompositionFont; alias ImmGetCompositionFontW ImmGetCompositionFont; alias ImmGetGuideLineW ImmGetGuideLine; alias ImmGetCandidateListW ImmGetCandidateList; alias ImmGetCandidateListCountW ImmGetCandidateListCount; alias ImmSetCompositionStringW ImmSetCompositionString; alias ImmGetCompositionStringW ImmGetCompositionString; alias ImmGetDescriptionW ImmGetDescription; alias ImmGetIMEFileNameW ImmGetIMEFileName; alias ImmGetImeMenuItemsW ImmGetImeMenuItems; } else { alias ImmEnumRegisterWordA ImmEnumRegisterWord; alias ImmGetRegisterWordStyleA ImmGetRegisterWordStyle; alias ImmUnregisterWordA ImmUnregisterWord; alias ImmRegisterWordA ImmRegisterWord; alias ImmInstallIMEA ImmInstallIME; alias ImmIsUIMessageA ImmIsUIMessage; alias ImmGetConversionListA ImmGetConversionList; alias ImmEscapeA ImmEscape; alias ImmConfigureIMEA ImmConfigureIME; alias ImmSetCompositionFontA ImmSetCompositionFont; alias ImmGetCompositionFontA ImmGetCompositionFont; alias ImmGetGuideLineA ImmGetGuideLine; alias ImmGetCandidateListA ImmGetCandidateList; alias ImmGetCandidateListCountA ImmGetCandidateListCount; alias ImmSetCompositionStringA ImmSetCompositionString; alias ImmGetCompositionStringA ImmGetCompositionString; alias ImmGetDescriptionA ImmGetDescription; alias ImmGetIMEFileNameA ImmGetIMEFileName; alias ImmGetImeMenuItemsW ImmGetImeMenuItems; }
D
/** * TypeInfo support code. * * Copyright: Copyright Digital Mars 2004 - 2009. * License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>. * Authors: Walter Bright */ /* Copyright Digital Mars 2004 - 2009. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at * http://www.boost.org/LICENSE_1_0.txt) */ module rt.typeinfo.ti_Acreal; private import rt.typeinfo.ti_creal; private import rt.util.hash; // creal[] class TypeInfo_Ac : TypeInfo_Array { override equals_t opEquals(const Object o) { return TypeInfo.opEquals(o); } @trusted: const: pure: nothrow: override string toString() const pure nothrow @safe { return "creal[]"; } override hash_t getHash(in void* p) { creal[] s = *cast(creal[]*)p; return hashOf(s.ptr, s.length * creal.sizeof); } override equals_t equals(in void* p1, in void* p2) { creal[] s1 = *cast(creal[]*)p1; creal[] s2 = *cast(creal[]*)p2; size_t len = s1.length; if (len != s2.length) return 0; for (size_t u = 0; u < len; u++) { if (!TypeInfo_c._equals(s1[u], s2[u])) return false; } return true; } override int compare(in void* p1, in void* p2) { creal[] s1 = *cast(creal[]*)p1; creal[] s2 = *cast(creal[]*)p2; size_t len = s1.length; if (s2.length < len) len = s2.length; for (size_t u = 0; u < len; u++) { int c = TypeInfo_c._compare(s1[u], s2[u]); if (c) return c; } if (s1.length < s2.length) return -1; else if (s1.length > s2.length) return 1; return 0; } override @property const(TypeInfo) next() nothrow pure { return typeid(creal); } }
D
/** This module provides a struct that encapsulates a SAMHeader `SAMHeader` encapsulates and owns a `sam_hdr_t*`, and provides convenience functions to read and write header records. */ module dhtslib.sam.header; import htslib.sam; import htslib.kstring; import dhtslib.memory; import core.stdc.stdlib : free; import core.stdc.string : memcpy; import std.conv : to; import std.string : toStringz, fromStringz; import std.traits : isSomeString; /// SAM specifications Section 1.3 /// Each header line begins with the character '@' followed by one of the /// two-letter header record type codes defined in this section. enum RecordType : immutable(char)[2] { HD = "HD", SQ = "SQ", RG = "RG", PG = "PG", CO = "CO", } /** SAMHeader encapsulates `sam_hdr_t*` and provides convenience wrappers to manipulate the header metadata/records. */ struct SAMHeader { BamHdr h; /// rc bam_hdr_t * wrapper /// Construct from existing pointer this(bam_hdr_t * h) { this.h = BamHdr(h); } /// Explicit postblit to avoid /// https://github.com/blachlylab/dhtslib/issues/122 this(this) { this.h = h; } bool isNull(){ return this.h is null; } /// Copy a SAMHeader auto dup(){ return SAMHeader(sam_hdr_dup(this.h)); } /* contig info */ /// number of reference sequences; from bam_hdr_t @property int nTargets() const { return this.h.n_targets; } /// length of specific reference sequence by number (`tid`) uint targetLength(int target) const in (target >= 0) in (target < this.nTargets) { return this.h.target_len[target]; } /// lengths of the reference sequences @property uint[] targetLengths() const { return this.h.target_len[0 .. this.nTargets].dup; } /// names of the reference sequences @property string[] targetNames() const { string[] names; names.length = this.nTargets; foreach (i; 0 .. this.nTargets) { names[i] = fromStringz(this.h.target_name[i]).idup; } return names; } /// reference contig name to integer id int targetId(string name) { return sam_hdr_name2tid(this.h, toStringz(name)); } /// reference contig name to integer id const(char)[] targetName(int tid) { return fromStringz(sam_hdr_tid2name(this.h, tid)); } /* Array-like indexing */ /// 'in' membership operator. /// usage: RecordType.SQ in hdr; => <bool> bool opBinaryRight(string op)(RecordType lhs) if (op == "in") { if (numRecords(lhs)) return true; return false; } /// For position-based lookups of key, /// e.g. a sample-name lookup in Pysam is ["RG"][0]["SM"] , /// while in dhtslib: /// [RecordType.RG, 0, "SN"] const(char)[] opIndex(RecordType rt, size_t pos, const(char)[] key) { return this.valueByPos(rt, pos, key); } /// number of records (lines) of type e.g. SQ, RG, etc. size_t numRecords(RecordType rt) { return sam_hdr_count_lines(this.h, rt.ptr); } /* ==== Line level methods ==== */ /// add multiple \n-terminated full SAM header records, eg "@SQ\tSN:foo\tLN:100" /// (single line or last of multiple does not require terminal \n) auto addLines(const(char)[][] lines) { if (lines.length == 0) return 0; // (sam_hdr_add_lines also returns 0 for nothing added) else if (lines.length == 1) return sam_hdr_add_lines(this.h, lines[0].ptr, lines[0].length); else { char[] buf; foreach(line; lines) buf ~= line ~ '\n'; return sam_hdr_add_lines(this.h, buf.ptr, buf.length); } } /// Add a single line to an existing header auto addLine(T...)(RecordType type, T kvargs) if(kvargs.length > 0 && isSomeString!(T[0])) { static assert (kvargs.length %2 == 0); // K-V pairs => even number of variadic args /* // NOTE: both (runtime) type safe variadic params, and compile-time variadic templates // use dynamic arrays, which cannot be passed to C variadic functions no matter what. // complicating this, we also need to convert to char*. The below won't work period; // the analogous variadic template won't work either without the mixin foolishness below. const(char)*[] varargs; varargs.length = kvargs.length + 1; for(int i=0; i < kvargs.length; i++) varargs[i] = kvargs[i].ptr; varargs[$-1] = null; // last vararg param null signals to sam_hdr_add_line end of list return sam_hdr_add_line(this.h, type.ptr, varargs.ptr); */ string varargMagic(size_t len) { string args = "sam_hdr_add_line(this.h, type.ptr, "; for(int i=0; i<len; i++) args ~= "toStringz(kvargs[" ~ i.to!string ~ "]), "; args ~= "null)"; return args; } // if mixin result is "toStringz(kvargs[0], ..." error is: // Error: Using the result of a comma expression is not allowed //return sam_hdr_add_line(this.h, type.ptr, mixin(varargMagic(kvargs.length)) ); return mixin(varargMagic(kvargs.length)); } /// Return a complete line of formatted text for a given type and ID, /// or if no ID, first line matching type. /// /// Parameters: /// * type - enum /// * id_key - may be empty, in which case the first line matching type is returned /// * id_val - may be empty IFF id_key empty; otherwise must be value for key const(char)[] lineById(RecordType type, string id_key = "", string id_val = "") in (id_key.length == 0 ? id_val.length == 0 : id_val.length > 0) { kstring_t ks_line; // looking at samtools header.c sam_hrecs_Find_type_id (called by sam_hdr_find_line_id), // passing non-null terminated two-char char* appears safe auto res = sam_hdr_find_line_id(this.h, type.ptr, id_key == "" ? null : id_key.ptr, id_val == "" ? null : id_val.ptr, &ks_line); // 0: success, -1: no match found, -2: error if (res < 0) return ""; char[] line; line.length = ks_line.l; memcpy(line.ptr, ks_line.s, ks_line.l); free(ks_line.s); return line; } /* int sam_hdr_find_line_pos(sam_hdr_t *h, const char *type, int pos, kstring_t *ks); */ /* int sam_hdr_remove_line_id(sam_hdr_t *h, const char *type, const char *ID_key, const char *ID_value); */ /* int sam_hdr_remove_line_pos(sam_hdr_t *h, const char *type, int position); */ /* int sam_hdr_update_line(sam_hdr_t *h, const char *type, const char *ID_key, const char *ID_value, ...); */ /* int sam_hdr_remove_except(sam_hdr_t *h, const char *type, const char *ID_key, const char *ID_value); */ /* int sam_hdr_remove_lines(sam_hdr_t *h, const char *type, const char *id, void *rh); */ /+ int sam_hdr_count_lines(sam_hdr_t *h, const char *type); int sam_hdr_line_index(sam_hdr_t *bh, const char *type, const char *key); const char *sam_hdr_line_name(sam_hdr_t *bh, const char *type, int pos); +/ //// //// int sam_hdr_find_tag_id(sam_hdr_t *h, const char *type, const char *ID_key, const char *ID_value, const char *key, kstring_t *ks); /// Return the value associated with a key for a header line identified by position const(char)[] valueByPos(RecordType type, size_t pos, const(char)[] key) in (pos <= int.max) in (key.length > 0) { kstring_t ks; auto res = sam_hdr_find_tag_pos(this.h, type.ptr, cast(int)pos, toStringz(key), &ks); // 0: success, -1: tag DNE, -2: error if (res < 0) return ""; char[] ret; ret.length = ks.l; memcpy(ret.ptr, ks.s, ks.l); free(ks.s); return ret; } } /// Example debug (dhtslib_unittest) unittest { import std; auto h = sam_hdr_init(); auto hdr = SAMHeader(h); assert(!(RecordType.RG in hdr)); //sam_hdr_add_line(h, RecordType.RG.ptr, "ID".ptr, "001".ptr, "SM".ptr, "sample1".ptr, null); hdr.addLine(RecordType.RG, "ID", "001", "SM", "sample1"); assert(RecordType.RG in hdr); auto line = hdr.lineById(RecordType.RG, "ID", "001"); assert(line == "@RG ID:001 SM:sample1"); auto val = hdr.valueByPos(RecordType.RG, 0, "SM"); assert(val == "sample1"); assert(hdr[RecordType.RG, 0, "SM"] == "sample1"); assert(hdr[RecordType.RG, 0, "XX"] == ""); }
D
/Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Intermediates/FareDeal.build/Debug-iphonesimulator/FareDeal.build/Objects-normal/x86_64/RegisterRestaurantVC.o : /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/RestaurantDealsVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/StoreVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/ProfileModel.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/FavoriteVenue.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/RestaurantDealDetaislVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/FavoriteHeaderCell.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/DealDetailsVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/FavoritesTVController.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/ProfileVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/RegisterRestaurantVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/ForgotPasswordUserVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/RegisterUserVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/DataSaving.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/FoodCategories.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/CardOverlayView.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/GradientView.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/DealsVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/RestaurantDetailController.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/ForgotPasswordVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/SignInVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/SavedDeal.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/VenueDeal.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/InitialScreenVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/APICalls.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/FavoritesCell.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/DealsCell.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/Deals.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/Restaurant.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/BusinessDeal.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/Venue.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/RegisterRestaurantVC2.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/HomeSwipeViewController.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/CustomActivityView.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/BusinessHome.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/AuthenticationCalls.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/AppDelegate.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/CardContentView.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/SignInUserVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/DealHeaderCell.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/Constants.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/Validation.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/DealCardCell.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/RegisterRestaurantVC3.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/Reachability.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Swift.swiftmodule /Users/angelasmith/Desktop/Develop/FareDeal/FareDeal/FareDeal-Bridging-Header.h /Users/angelasmith/Desktop/Develop/FareDeal/FareDeal/TTTAttributedLabel.h /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Security.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/CoreImage.swiftmodule /Users/angelasmith/Desktop/Develop/FareDeal/FareDeal/TTCounterLabel.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/RealmSwift.framework/Modules/RealmSwift.swiftmodule/x86_64.swiftmodule /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMSchema_Private.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMResults_Private.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMRealm_Private.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMRealm_Dynamic.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMRealmUtil.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMProperty_Private.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMObject_Private.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMObjectStore.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMObjectSchema_Private.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMMigration_Private.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMListBase.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMArray_Private.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMSchema.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMResults.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMRealm.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMConstants.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMProperty.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMPlatform.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMObjectSchema.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMObjectBase.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMObject.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMMigration.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMDefines.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMCollection.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMArray.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/Realm.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Modules/module.modulemap /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/RealmSwift.framework/Headers/RealmSwift-Swift.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/RealmSwift.framework/Headers/RealmSwift-umbrella.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/RealmSwift.framework/Modules/module.modulemap /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/SwiftyJSON.framework/Modules/SwiftyJSON.swiftmodule/x86_64.swiftmodule /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/SwiftyJSON.framework/Headers/SwiftyJSON-Swift.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/SwiftyJSON.framework/Headers/SwiftyJSON-umbrella.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/SwiftyJSON.framework/Modules/module.modulemap /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/SWActionSheet.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/ActionSheetStringPicker.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/ActionSheetPicker.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/ActionSheetLocalePicker.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/DistancePickerView.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/ActionSheetDistancePicker.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/ActionSheetDatePicker.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/ActionSheetCustomPickerDelegate.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/ActionSheetCustomPicker.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/AbstractActionSheetPicker.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/ActionSheetPicker-3.0-umbrella.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/AssetsLibrary.swiftmodule /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Koloda.framework/Modules/Koloda.swiftmodule/x86_64.swiftmodule /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Koloda.framework/Headers/Koloda-Swift.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Koloda.framework/Headers/Koloda-umbrella.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Koloda.framework/Modules/module.modulemap /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPLayerExtras.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPDecayAnimation.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPCustomAnimation.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPBasicAnimation.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPAnimator.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPPropertyAnimation.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPSpringAnimation.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPDefines.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPAnimationExtras.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPGeometry.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPAnimationEvent.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPAnimationTracer.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPAnimation.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPAnimatableProperty.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POP.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/pop-umbrella.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Modules/module.modulemap /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/KeyboardManager.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQUIView+IQKeyboardToolbar.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQToolbar.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQTitleBarButtonItem.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQBarButtonItem.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQTextView.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQSegmentedNextPrevious.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQKeyboardReturnKeyHandler.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQKeyboardManager.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQKeyboardManagerConstantsInternal.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQUIWindow+Hierarchy.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQUIViewController+Additions.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQKeyboardManagerConstants.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQUIView+Hierarchy.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQUITextFieldView+Additions.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQNSArray+Sort.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQKeyboardManager-umbrella.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Modules/module.modulemap /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Intermediates/FareDeal.build/Debug-iphonesimulator/FareDeal.build/Objects-normal/x86_64/RegisterRestaurantVC~partial.swiftmodule : /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/RestaurantDealsVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/StoreVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/ProfileModel.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/FavoriteVenue.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/RestaurantDealDetaislVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/FavoriteHeaderCell.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/DealDetailsVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/FavoritesTVController.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/ProfileVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/RegisterRestaurantVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/ForgotPasswordUserVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/RegisterUserVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/DataSaving.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/FoodCategories.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/CardOverlayView.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/GradientView.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/DealsVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/RestaurantDetailController.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/ForgotPasswordVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/SignInVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/SavedDeal.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/VenueDeal.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/InitialScreenVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/APICalls.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/FavoritesCell.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/DealsCell.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/Deals.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/Restaurant.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/BusinessDeal.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/Venue.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/RegisterRestaurantVC2.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/HomeSwipeViewController.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/CustomActivityView.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/BusinessHome.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/AuthenticationCalls.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/AppDelegate.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/CardContentView.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/SignInUserVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/DealHeaderCell.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/Constants.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/Validation.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/DealCardCell.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/RegisterRestaurantVC3.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/Reachability.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Swift.swiftmodule /Users/angelasmith/Desktop/Develop/FareDeal/FareDeal/FareDeal-Bridging-Header.h /Users/angelasmith/Desktop/Develop/FareDeal/FareDeal/TTTAttributedLabel.h /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Security.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/CoreImage.swiftmodule /Users/angelasmith/Desktop/Develop/FareDeal/FareDeal/TTCounterLabel.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/RealmSwift.framework/Modules/RealmSwift.swiftmodule/x86_64.swiftmodule /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMSchema_Private.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMResults_Private.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMRealm_Private.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMRealm_Dynamic.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMRealmUtil.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMProperty_Private.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMObject_Private.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMObjectStore.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMObjectSchema_Private.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMMigration_Private.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMListBase.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMArray_Private.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMSchema.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMResults.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMRealm.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMConstants.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMProperty.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMPlatform.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMObjectSchema.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMObjectBase.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMObject.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMMigration.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMDefines.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMCollection.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMArray.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/Realm.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Modules/module.modulemap /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/RealmSwift.framework/Headers/RealmSwift-Swift.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/RealmSwift.framework/Headers/RealmSwift-umbrella.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/RealmSwift.framework/Modules/module.modulemap /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/SwiftyJSON.framework/Modules/SwiftyJSON.swiftmodule/x86_64.swiftmodule /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/SwiftyJSON.framework/Headers/SwiftyJSON-Swift.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/SwiftyJSON.framework/Headers/SwiftyJSON-umbrella.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/SwiftyJSON.framework/Modules/module.modulemap /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/SWActionSheet.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/ActionSheetStringPicker.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/ActionSheetPicker.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/ActionSheetLocalePicker.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/DistancePickerView.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/ActionSheetDistancePicker.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/ActionSheetDatePicker.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/ActionSheetCustomPickerDelegate.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/ActionSheetCustomPicker.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/AbstractActionSheetPicker.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/ActionSheetPicker-3.0-umbrella.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/AssetsLibrary.swiftmodule /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Koloda.framework/Modules/Koloda.swiftmodule/x86_64.swiftmodule /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Koloda.framework/Headers/Koloda-Swift.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Koloda.framework/Headers/Koloda-umbrella.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Koloda.framework/Modules/module.modulemap /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPLayerExtras.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPDecayAnimation.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPCustomAnimation.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPBasicAnimation.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPAnimator.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPPropertyAnimation.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPSpringAnimation.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPDefines.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPAnimationExtras.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPGeometry.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPAnimationEvent.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPAnimationTracer.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPAnimation.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPAnimatableProperty.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POP.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/pop-umbrella.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Modules/module.modulemap /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/KeyboardManager.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQUIView+IQKeyboardToolbar.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQToolbar.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQTitleBarButtonItem.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQBarButtonItem.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQTextView.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQSegmentedNextPrevious.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQKeyboardReturnKeyHandler.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQKeyboardManager.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQKeyboardManagerConstantsInternal.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQUIWindow+Hierarchy.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQUIViewController+Additions.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQKeyboardManagerConstants.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQUIView+Hierarchy.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQUITextFieldView+Additions.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQNSArray+Sort.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQKeyboardManager-umbrella.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Modules/module.modulemap /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Intermediates/FareDeal.build/Debug-iphonesimulator/FareDeal.build/Objects-normal/x86_64/RegisterRestaurantVC~partial.swiftdoc : /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/RestaurantDealsVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/StoreVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/ProfileModel.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/FavoriteVenue.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/RestaurantDealDetaislVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/FavoriteHeaderCell.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/DealDetailsVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/FavoritesTVController.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/ProfileVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/RegisterRestaurantVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/ForgotPasswordUserVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/RegisterUserVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/DataSaving.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/FoodCategories.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/CardOverlayView.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/GradientView.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/DealsVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/RestaurantDetailController.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/ForgotPasswordVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/SignInVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/SavedDeal.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/VenueDeal.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/InitialScreenVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/APICalls.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/FavoritesCell.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/DealsCell.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/Deals.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/Restaurant.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/BusinessDeal.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/Venue.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/RegisterRestaurantVC2.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/HomeSwipeViewController.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/CustomActivityView.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/BusinessHome.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/AuthenticationCalls.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/AppDelegate.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/CardContentView.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/SignInUserVC.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/DealHeaderCell.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/Constants.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/Validation.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/DealCardCell.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/RegisterRestaurantVC3.swift /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/FareDeal/Reachability.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Swift.swiftmodule /Users/angelasmith/Desktop/Develop/FareDeal/FareDeal/FareDeal-Bridging-Header.h /Users/angelasmith/Desktop/Develop/FareDeal/FareDeal/TTTAttributedLabel.h /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/Security.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/CoreImage.swiftmodule /Users/angelasmith/Desktop/Develop/FareDeal/FareDeal/TTCounterLabel.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/RealmSwift.framework/Modules/RealmSwift.swiftmodule/x86_64.swiftmodule /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMSchema_Private.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMResults_Private.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMRealm_Private.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMRealm_Dynamic.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMRealmUtil.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMProperty_Private.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMObject_Private.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMObjectStore.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMObjectSchema_Private.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMMigration_Private.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMListBase.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/PrivateHeaders/RLMArray_Private.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMSchema.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMResults.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMRealm.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMConstants.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMProperty.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMPlatform.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMObjectSchema.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMObjectBase.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMObject.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMMigration.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMDefines.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMCollection.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/RLMArray.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Headers/Realm.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Realm.framework/Modules/module.modulemap /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/RealmSwift.framework/Headers/RealmSwift-Swift.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/RealmSwift.framework/Headers/RealmSwift-umbrella.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/RealmSwift.framework/Modules/module.modulemap /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/SwiftyJSON.framework/Modules/SwiftyJSON.swiftmodule/x86_64.swiftmodule /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/SwiftyJSON.framework/Headers/SwiftyJSON-Swift.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/SwiftyJSON.framework/Headers/SwiftyJSON-umbrella.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/SwiftyJSON.framework/Modules/module.modulemap /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/SWActionSheet.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/ActionSheetStringPicker.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/ActionSheetPicker.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/ActionSheetLocalePicker.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/DistancePickerView.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/ActionSheetDistancePicker.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/ActionSheetDatePicker.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/ActionSheetCustomPickerDelegate.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/ActionSheetCustomPicker.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/AbstractActionSheetPicker.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Headers/ActionSheetPicker-3.0-umbrella.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/ActionSheetPicker_3_0.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/AssetsLibrary.swiftmodule /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Koloda.framework/Modules/Koloda.swiftmodule/x86_64.swiftmodule /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Koloda.framework/Headers/Koloda-Swift.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Koloda.framework/Headers/Koloda-umbrella.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/Koloda.framework/Modules/module.modulemap /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPLayerExtras.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPDecayAnimation.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPCustomAnimation.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPBasicAnimation.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPAnimator.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPPropertyAnimation.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPSpringAnimation.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPDefines.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPAnimationExtras.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPGeometry.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPAnimationEvent.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPAnimationTracer.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPAnimation.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POPAnimatableProperty.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/POP.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Headers/pop-umbrella.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/pop.framework/Modules/module.modulemap /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/KeyboardManager.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQUIView+IQKeyboardToolbar.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQToolbar.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQTitleBarButtonItem.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQBarButtonItem.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQTextView.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQSegmentedNextPrevious.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQKeyboardReturnKeyHandler.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQKeyboardManager.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQKeyboardManagerConstantsInternal.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQUIWindow+Hierarchy.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQUIViewController+Additions.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQKeyboardManagerConstants.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQUIView+Hierarchy.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQUITextFieldView+Additions.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQNSArray+Sort.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Headers/IQKeyboardManager-umbrella.h /Users/angelasmith/Desktop/SourceTree/Develop2/FareDeal/Build/Intermediates/IBDesignables/Products/Debug-iphonesimulator/IQKeyboardManager.framework/Modules/module.modulemap
D
/** Simple tests that serve as an example. Copyright: Copyright Boris-Barboris 2017-2020. License: MIT Authors: Boris-Barboris */ import core.thread; import core.time; import std.algorithm: map; import std.array: array; import std.ascii: isAlphaNum; import std.conv: to; import std.string: strip; import std.exception: assumeWontThrow; import std.typecons: Nullable, scoped; import std.process: environment; import std.stdio; import std.uuid: UUID, randomUUID; import dunit; import dpeq; final class DebugSocket: StdSocketTransport { this(StdConnectParameters params) { super(params); } override void send(const(ubyte)[] buf) { writeln("sending ", buf.length, " bytes: ", buf); super.send(buf); } override void receive(ubyte[] dest) { writeln("receiving ", dest.length, " bytes..."); super.receive(dest); } } final class DebugPSQLConnection: PSQLConnection { this(ITransport transport, SSLPolicy sslPolicy) { super(transport, sslPolicy); } override RawBackendMessage receiveMessage() { RawBackendMessage msg = super.receiveMessage(); writeln("received " ~ msg.toString); return msg; } } class PSQLConnectionTests { mixin UnitTest; DebugPSQLConnection connection; DebugSocket transport; PasswordAuthenticator password; string[string] startupParams; bool isCockroach; @BeforeEach public void setUp() { isCockroach = environment.get("IS_COCKROACH", "false").to!bool; transport = new DebugSocket( StdConnectParameters( environment.get("TEST_DATABASE_HOST", "localhost"), environment.get("TEST_DATABASE_PORT", "5432").to!ushort )); transport.receiveTimeout = seconds(1); transport.sendTimeout = seconds(1); transport.connect(); connection = new DebugPSQLConnection(transport, SSLPolicy.NEVER); startupParams.clear(); startupParams["user"] = environment.get("TEST_USER", "postgres"); startupParams["database"] = environment.get("TEST_DATABASE", "postgres"); password = new PasswordAuthenticator(environment.get("TEST_PASSWORD", "postgres")); passwordAuth(); } private void passwordAuth() { connection.handshakeAndAuthenticate(startupParams, password); assertTrue(!connection.closed); assertTrue(connection.authenticated); assertTrue(connection.isOpen); if (!isCockroach) { assertTrue(connection.backendKeyData.processId != 0); assertTrue(connection.backendKeyData.cancellationKey != 0); } assertEquals(TransactionStatus.IDLE, connection.lastTransactionStatus); writeln("Parameter statuses: ", connection.parameterStatuses); } @AfterEach public void tearDown() { if (connection) connection.close(); } @Test void testSimpleQuerySelectVersion() { RawFrontendMessage query = buildQueryMessage("SELECT version()"); connection.sendMessage(query); CommandComplete commandComplele; RowDescription rowDescription; DataRow dataRow; PollCallback poller = (PSQLConnection con, RawBackendMessage msg) { assert(con is connection); switch (msg.type) { case BackendMessageType.CommandComplete: commandComplele = CommandComplete.parse(msg.data); break; case BackendMessageType.RowDescription: rowDescription = RowDescription.parse(msg.data); break; case BackendMessageType.DataRow: dataRow = DataRow.parse(msg.data); break; default: } return PollAction.CONTINUE; }; assertEquals(PollResult.RFQ_RECEIVED, connection.pollMessages(poller)); assertEquals(TransactionStatus.IDLE, connection.lastTransactionStatus); assertEquals("SELECT 1", commandComplele.commandTag); assertEquals(KnownTypeOID.TEXT, rowDescription.fieldDescriptions[0].type); assertEquals(FormatCode.TEXT, rowDescription.fieldDescriptions[0].formatCode); assertTrue(!dataRow.columns[0].isNull); string returnedVersion; deserializeByteArrayField( dataRow.columns[0].isNull, dataRow.columns[0].value, cast(ubyte[]*) &returnedVersion); writeln("version() returned: ", returnedVersion); } @Test void testSimpleQueryErrorResponse() { RawFrontendMessage query = buildQueryMessage("SELECT nonexistingFunction()"); connection.sendMessage(query); PollResult pr = connection.pollMessages((con, msg) { if (msg.type == BackendMessageType.ErrorResponse) { NoticeOrError error = NoticeOrError.parse(msg.data); assertEquals("ERROR", error.severity); assertEquals("42883", error.code[]); return PollAction.BREAK; } return PollAction.CONTINUE; }); assertEquals(PollResult.POLL_CALLBACK_BREAK, pr); } @Test void testSimpleQueryEmptyQueryResponse() { RawFrontendMessage query = buildQueryMessage(""); connection.sendMessage(query); bool receivedEmptyQuery; PollCallback poller = (PSQLConnection con, RawBackendMessage msg) { switch (msg.type) { case BackendMessageType.CommandComplete: assert(0, "should not have been received"); case BackendMessageType.EmptyQueryResponse: receivedEmptyQuery = true; break; default: } return PollAction.CONTINUE; }; assertEquals(PollResult.RFQ_RECEIVED, connection.pollMessages(poller)); assertEquals(TransactionStatus.IDLE, connection.lastTransactionStatus); assertTrue(receivedEmptyQuery); } @Test void testSimpleQueryTransaction() { RawFrontendMessage query = buildQueryMessage( "BEGIN; CREATE TABLE temptable (pk integer PRIMARY KEY);"); connection.sendMessage(query); CommandComplete commandComplele; int commandsCompleted; PollCallback poller = (PSQLConnection con, RawBackendMessage msg) { assert(con is connection); switch (msg.type) { case BackendMessageType.CommandComplete: commandComplele = CommandComplete.parse(msg.data); if (commandsCompleted == 0) assertEquals("BEGIN", commandComplele.commandTag); if (commandsCompleted == 1) assertEquals("CREATE TABLE", commandComplele.commandTag); if (++commandsCompleted > 2) assert(0, "unexpected CommandComplete message"); break; default: } return PollAction.CONTINUE; }; assertEquals(PollResult.RFQ_RECEIVED, connection.pollMessages(poller)); assertEquals(2, commandsCompleted); assertEquals(TransactionStatus.INSIDE, connection.lastTransactionStatus); connection.sendMessage(buildQueryMessage("ROLLBACK")); poller = (PSQLConnection con, RawBackendMessage msg) { assert(con is connection); switch (msg.type) { case BackendMessageType.CommandComplete: commandComplele = CommandComplete.parse(msg.data); if (commandsCompleted == 2) assertEquals("ROLLBACK", commandComplele.commandTag); if (++commandsCompleted > 3) assert(0, "unexpected CommandComplete message"); break; default: } return PollAction.CONTINUE; }; assertEquals(PollResult.RFQ_RECEIVED, connection.pollMessages(poller)); assertEquals(3, commandsCompleted); assertEquals(TransactionStatus.IDLE, connection.lastTransactionStatus); } @Test void testQueryCancellation() { if (isCockroach) return; RawFrontendMessage query = buildQueryMessage("SELECT pg_sleep(10)"); connection.sendMessage(query); Thread.sleep(msecs(50)); connection.cancelRequest(); PollResult pr = connection.pollMessages((con, msg) { if (msg.type == BackendMessageType.ErrorResponse) { NoticeOrError error = NoticeOrError.parse(msg.data); assertEquals("57014", error.code[]); assertEquals("canceling statement due to user request", error.message); return PollAction.BREAK; } return PollAction.CONTINUE; }); assertEquals(PollResult.POLL_CALLBACK_BREAK, pr); } @Test void testUnprovokedQueryCancellation() { connection.cancelRequest(); } @Test void testExtendedQueryUnnamed() { int[] paramTypes = [KnownTypeOID.INT, KnownTypeOID.REAL, KnownTypeOID.BIGINT, KnownTypeOID.UUID, KnownTypeOID.TEXT]; int[] returnTypes = paramTypes.dup; if (isCockroach) { // cockroachdb integer is bigint, and read->double is unexplainable. returnTypes[0] = KnownTypeOID.BIGINT; returnTypes[1] = KnownTypeOID.DOUBLE_PRECISION; } RawFrontendMessage fmsg = buildParseMessage( "", "SELECT $1::integer, $2::real, $3::bigint, $4::uuid, $5::text", paramTypes); connection.sendMessage(fmsg); connection.sendMessage(buildFlushMessage()); PollCallback poller = (PSQLConnection con, RawBackendMessage msg) { switch (msg.type) { case BackendMessageType.ParseComplete: return PollAction.BREAK; default: return PollAction.CONTINUE; } }; assertEquals(PollResult.POLL_CALLBACK_BREAK, connection.pollMessages(poller)); connection.sendMessage(buildDescribeMessage( PreparedStatementOrPortal.PREPARED_STATEMENT, "")); connection.sendMessage(buildFlushMessage()); ParameterDescription paramDescr; RowDescription rowDescr; poller = (PSQLConnection con, RawBackendMessage msg) { switch (msg.type) { case BackendMessageType.ParameterDescription: paramDescr = ParameterDescription.parse(msg.data); return PollAction.CONTINUE; case BackendMessageType.RowDescription: rowDescr = RowDescription.parse(msg.data); return PollAction.BREAK; default: return PollAction.CONTINUE; } }; assertEquals(PollResult.POLL_CALLBACK_BREAK, connection.pollMessages(poller)); assertEquals(paramTypes, paramDescr.paramTypeOIDs); assertEquals(returnTypes, rowDescr.fieldDescriptions.map!(fd => fd.type).array); int p1 = 42; float p2 = float.infinity; long p3 = long.max; UUID p4 = UUID("beefb950-6c85-4ec6-b448-4ab38fa40825"); string p5 = "some string с юникодом"; fmsg = buildBindMessage("", "", [BindParam(&p1, FormatCode.BINARY, cast(FieldSerializingFunction) &serializePrimitiveFieldBinary!int), BindParam(&p2, FormatCode.BINARY, cast(FieldSerializingFunction) &serializePrimitiveFieldBinary!float), BindParam(&p3, FormatCode.BINARY, cast(FieldSerializingFunction) &serializePrimitiveFieldBinary!long), BindParam(&p4, FormatCode.BINARY, cast(FieldSerializingFunction) &serializeUUIDFieldBinary), BindParam(&p5, FormatCode.BINARY, cast(FieldSerializingFunction) &serializeByteArrayField)], [FormatCode.BINARY]); connection.sendMessage(fmsg); connection.sendMessage(buildExecuteMessage("")); connection.sendMessage(buildSyncMessage()); DataRow[] rows; bool bindCompleteReceived; CommandComplete comCmpl; poller = (PSQLConnection con, RawBackendMessage msg) { switch (msg.type) { case BackendMessageType.BindComplete: bindCompleteReceived = true; return PollAction.CONTINUE; case BackendMessageType.DataRow: rows ~= DataRow.parse(msg.data); return PollAction.CONTINUE; case BackendMessageType.CommandComplete: comCmpl = CommandComplete.parse(msg.data); return PollAction.CONTINUE; default: return PollAction.CONTINUE; } }; assertEquals(PollResult.RFQ_RECEIVED, connection.pollMessages(poller)); assertTrue(bindCompleteReceived); assertEquals(1, rows.length); assertEquals("SELECT 1", comCmpl.commandTag); int r1; float r2; long r3; UUID r4; string r5; if (!isCockroach) { // postgres deserializePrimitiveField!(int, FormatCode.BINARY)( rows[0].columns[0].isNull, rows[0].columns[0].value, &r1); deserializePrimitiveField!(float, FormatCode.BINARY)( rows[0].columns[1].isNull, rows[0].columns[1].value, &r2); } else { long r1cdb; deserializePrimitiveField!(long, FormatCode.BINARY)( rows[0].columns[0].isNull, rows[0].columns[0].value, &r1cdb); r1 = r1cdb.to!int; double r2cdb; deserializePrimitiveField!(double, FormatCode.BINARY)( rows[0].columns[1].isNull, rows[0].columns[1].value, &r2cdb); r2 = r2cdb.to!float; } deserializePrimitiveField!(long, FormatCode.BINARY)( rows[0].columns[2].isNull, rows[0].columns[2].value, &r3); deserializeUUIDField!(FormatCode.BINARY)( rows[0].columns[3].isNull, rows[0].columns[3].value, &r4); deserializeByteArrayField( rows[0].columns[4].isNull, rows[0].columns[4].value, cast(ubyte[]*) &r5); assertEquals(p1, r1); assertEquals(p2, r2); assertEquals(p3, r3); assertEquals(p4, r4); assertEquals(p5, r5); } @Test void testListenNotify() { if (isCockroach) return; DebugPSQLConnection connection2; ITransport transport2; transport2 = transport.duplicate(); connection2 = new DebugPSQLConnection(transport2, SSLPolicy.NEVER); scope(exit) connection2.close(); connection2.handshakeAndAuthenticate(startupParams, password); RawFrontendMessage query = buildQueryMessage("LISTEN channel"); connection.sendMessage(query); assertEquals(PollResult.RFQ_RECEIVED, connection.pollMessages(null)); query = buildQueryMessage("NOTIFY channel, 'payload'"); connection2.sendMessage(query); connection.notificationCallback = (PSQLConnection receiver, NotificationResponse message) { assertEquals(connection2.backendKeyData.processId, message.procId); assertEquals("channel", message.channel); assertEquals("payload", message.payload); return PollAction.BREAK; }; assertEquals(PollResult.RFQ_RECEIVED, connection2.pollMessages(null)); assertEquals( PollResult.NOTIFICATION_CALLBACK_BREAK, connection.pollMessages(null)); } @Test void testCopyMode() { if (isCockroach) return; RawFrontendMessage query = buildQueryMessage( "CREATE TABLE IF NOT EXISTS raw_ints(row1 integer); DELETE FROM raw_ints; COPY raw_ints (row1) FROM STDIN;"); connection.sendMessage(query); PollCallback poller = (PSQLConnection con, RawBackendMessage msg) { switch (msg.type) { case BackendMessageType.CopyInResponse: CopyResponse cr = CopyResponse.parse(msg.data); assertEquals(0, cr.overallFormat); assertEquals([short(0)], cr.formatCodes); return PollAction.BREAK; default: return PollAction.CONTINUE; } }; assertEquals(PollResult.POLL_CALLBACK_BREAK, connection.pollMessages(poller)); for (int i = 0; i < 50; i++) connection.sendMessage( buildCopyDataMessage(cast(ubyte[]) (i.to!string ~ "\n"))); connection.sendMessage(buildCopyDoneMessage()); poller = (PSQLConnection con, RawBackendMessage msg) { switch (msg.type) { case BackendMessageType.CommandComplete: CommandComplete cc = CommandComplete.parse(msg.data); assertEquals("COPY 50", cc.commandTag); return PollAction.BREAK; default: return PollAction.CONTINUE; } }; assertEquals(PollResult.POLL_CALLBACK_BREAK, connection.pollMessages(poller)); assertEquals(PollResult.RFQ_RECEIVED, connection.pollMessages(null)); query = buildQueryMessage(" COPY raw_ints (row1) TO STDOUT"); connection.sendMessage(query); poller = (PSQLConnection con, RawBackendMessage msg) { switch (msg.type) { case BackendMessageType.CopyOutResponse: CopyResponse cr = CopyResponse.parse(msg.data); assertEquals(0, cr.overallFormat); assertEquals([cast(short) FormatCode.TEXT], cr.formatCodes); return PollAction.BREAK; default: return PollAction.CONTINUE; } }; assertEquals(PollResult.POLL_CALLBACK_BREAK, connection.pollMessages(poller)); CopyData[] rows; poller = (PSQLConnection con, RawBackendMessage msg) { switch (msg.type) { case BackendMessageType.CopyData: CopyData cd = CopyData.parse(msg.data); rows ~= cd; return PollAction.CONTINUE; case BackendMessageType.CopyDone: return PollAction.BREAK; default: return PollAction.CONTINUE; } }; assertEquals(PollResult.POLL_CALLBACK_BREAK, connection.pollMessages(poller)); assertEquals(50, rows.length); assertEquals(PollResult.RFQ_RECEIVED, connection.pollMessages(null)); for (int i = 0; i < 50; i++) assertEquals(i, (cast(string) rows[i].data).strip.to!int); } } mixin Main;
D
module systems.healthSystem; import systems.system; import systems.systemType; import components.component; import components.healthComponent; import components.componentType; import entities.entity; import entities.entityType; import std.conv : to; import std.stdio : writeln; import std.algorithm : canFind; class HealthSystem : System { private HealthComponent health; public this() { super(HEALTH_S); } override public void update() { foreach(_entity; entities) { set(to!(HealthComponent)(_entity.getComponent(HEALTH))); if (health.isActive) { healthCheck(_entity); } } } private void set(HealthComponent _health) { health = _health; } private HealthComponent get() { return health; } public void healthCheck(Entity _entity) { if (canFind(_entity.getTypes, HERO) && health.getCurHp <= 0) { _entity.getGame.gameOver; } else if (health.getCurHp > health.getMaxHp) { health.setCurHp(health.getMaxHp); } } } unittest { import components.healthComponent; HealthSystem health = new HealthSystem(); HealthComponent hc = new HealthComponent(2, 20); health.set(hc); assert(health.get == hc); } unittest { import entities.hero; import game; Hero hero = new Hero(); HealthSystem health = new HealthSystem(); Game _game = new Game(); hero.addSystem(health); assert(hero.getSystem(HEALTH_S) == health); assert(canFind(health.getEntities, hero)); (to!(HealthComponent)(hero.getComponent(HEALTH))).setCurHp(22); // max health is 20 and current is 22 assert((to!(HealthComponent)(hero.getComponent(HEALTH))).getCurHp == 22); health.update; // current health is set to 20 assert((to!(HealthComponent)(hero.getComponent(HEALTH))).getCurHp == 20); hero.setGame(_game); (to!(HealthComponent)(hero.getComponent(HEALTH))).setCurHp(0); // hero's current health is 0 but game continues assert((to!(HealthComponent)(hero.getComponent(HEALTH))).getCurHp == 0); assert(!_game.isOver); health.update; // now the game is over assert(_game.isOver); }
D
/*==================================================================== This file is part of SimpleXMLD. SimpleXMLD is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SimpleXMLD 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 SimpleXMLD. If not, see <http://www.gnu.org/licenses/>. ==================================================================*/ /** * This module defined SimpleXML specfic exception, XMLAttributesNotFound * and XMLNode not found. * * Copyright: Copyright (C) 2007 Brian Hsu. All rights reserved. * License: <a href="http://www.gnu.org/licenses/lgpl-3.0.txt">GNU LGPL</a>. * * Authors: Brian Hsu * Version: 0.0.2 * * See_Also: <a href="SimpleXML.html">SimpleXML</a>, * <a href="XMLAttributes.html">XMLAttributes</a> * */ module SimpleXMLD.XMLException; private import tango.text.convert.Sprint; /** * This exception will be throw when you try to read an attributes * which does not exist in current node. */ class XMLAttributeNotFound: Exception { public this (char [] key) { super ("Attribute '" ~ key ~ "' not found."); } public this (dchar [] key) { super ("Attribute '" ~ cast(char [])key ~ "' not found."); } public this (wchar [] key) { super ("Attribute '" ~ cast(char [])key ~ "' not found."); } } /** * This exception will be throw when you try to access an XML node * which does not exist. */ class XMLNodeNotFound: Exception { public this (char [] tag) { super ("Node '" ~ tag ~ "' not found."); } public this (dchar [] tag) { super ("Node '" ~ cast(char [])tag ~ "' not found."); } public this (wchar [] tag) { super ("Node '" ~ cast(char [])tag ~ "' not found."); } } /** * This exception will be throw when parsing XML file or XML * literal is faild. */ public class XMLParseException : Exception { public this (char [] msg) { super (msg); } }
D
import std.stdio; import std.file; import ddmd.parse; import ddmd.astbase; import examples.impvisitor; import ddmd.id; import ddmd.globals; import ddmd.identifier; import core.memory; void main() { GC.disable(); string path = "../../phobos/std/"; string regex = "*.d"; auto dFiles = dirEntries(path, regex, SpanMode.depth); foreach (f; dFiles) { string fn = f.name; //writeln("Processing ", fn); Id.initialize(); global._init(); global.params.isLinux = true; global.params.is64bit = (size_t.sizeof == 8); global.params.useUnitTests = true; ASTBase.Type._init(); auto id = Identifier.idPool(fn); auto m = new ASTBase.Module(&(fn.dup)[0], id, false, false); auto input = readText(fn); //writeln("Started parsing..."); scope p = new Parser!ASTBase(m, input, false); p.nextToken(); m.members = p.parseModule(); //writeln("Finished parsing. Starting transitive visitor"); scope vis = new ImportVisitor2!ASTBase(); m.accept(vis); //writeln("Finished!"); } }
D
module UnrealScript.TribesGame.TrPlayerVoice_T2_Fem03; import ScriptClasses; import UnrealScript.Helpers; import UnrealScript.TribesGame.TrPlayerVoice; extern(C++) interface TrPlayerVoice_T2_Fem03 : TrPlayerVoice { public extern(D): private static __gshared ScriptClass mStaticClass; @property final static ScriptClass StaticClass() { mixin(MGSCC("Class TribesGame.TrPlayerVoice_T2_Fem03")); } private static __gshared TrPlayerVoice_T2_Fem03 mDefaultProperties; @property final static TrPlayerVoice_T2_Fem03 DefaultProperties() { mixin(MGDPC("TrPlayerVoice_T2_Fem03", "TrPlayerVoice_T2_Fem03 TribesGame.Default__TrPlayerVoice_T2_Fem03")); } }
D
<?xml version="1.0" encoding="ASCII" standalone="no"?> <di:SashWindowsMngr xmlns:di="http://www.eclipse.org/papyrus/0.7.0/sashdi" xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmi:version="2.0"> <pageList> <availablePage> <emfPageIdentifier href="VAR_18_BeT-2612347634.notation#_copSALmGEeKQQp7P9cQvNQ"/> </availablePage> </pageList> <sashModel currentSelection="//@sashModel/@windows.0/@children.0"> <windows> <children xsi:type="di:TabFolder"> <children> <emfPageIdentifier href="VAR_18_BeT-2612347634.notation#_copSALmGEeKQQp7P9cQvNQ"/> </children> </children> </windows> </sashModel> </di:SashWindowsMngr>
D
module java.io.FileNotFoundException; import java.lang.String; import java.lang.StringBuilder; import java.io.IOException; public class FileNotFoundException : IOException { public this() { } public this(String paramString) { super(paramString); } private this(String paramString1, String paramString2) { super(paramString1 ~ (paramString2 == null ? "" : (new StringBuilder()).append(" (").append(paramString2).append(")").toString())); } }
D
/Users/elizabethgentile/Desktop/safe_steps_1.0/DerivedData/MapsDirection/Build/Intermediates/Pods.build/Debug-iphonesimulator/ObjectMapper.build/Objects-normal/x86_64/DictionaryTransform.o : /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Core/FromJSON.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Core/ToJSON.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Core/Mappable.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/TransformType.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/TransformOf.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/URLTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/DataTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/DateTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/ISO8601DateTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/EnumTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/NSDecimalNumberTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/DateFormatterTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/CustomDateFormatTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/DictionaryTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Core/Map.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Core/Mapper.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Core/Operators.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreText.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/Target\ Support\ Files/ObjectMapper/ObjectMapper-umbrella.h /Users/elizabethgentile/Desktop/safe_steps_1.0/DerivedData/MapsDirection/Build/Intermediates/Pods.build/Debug-iphonesimulator/ObjectMapper.build/unextended-module.modulemap /Users/elizabethgentile/Desktop/safe_steps_1.0/DerivedData/MapsDirection/Build/Intermediates/Pods.build/Debug-iphonesimulator/ObjectMapper.build/Objects-normal/x86_64/DictionaryTransform~partial.swiftmodule : /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Core/FromJSON.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Core/ToJSON.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Core/Mappable.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/TransformType.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/TransformOf.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/URLTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/DataTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/DateTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/ISO8601DateTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/EnumTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/NSDecimalNumberTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/DateFormatterTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/CustomDateFormatTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/DictionaryTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Core/Map.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Core/Mapper.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Core/Operators.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreText.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/Target\ Support\ Files/ObjectMapper/ObjectMapper-umbrella.h /Users/elizabethgentile/Desktop/safe_steps_1.0/DerivedData/MapsDirection/Build/Intermediates/Pods.build/Debug-iphonesimulator/ObjectMapper.build/unextended-module.modulemap /Users/elizabethgentile/Desktop/safe_steps_1.0/DerivedData/MapsDirection/Build/Intermediates/Pods.build/Debug-iphonesimulator/ObjectMapper.build/Objects-normal/x86_64/DictionaryTransform~partial.swiftdoc : /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Core/FromJSON.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Core/ToJSON.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Core/Mappable.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/TransformType.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/TransformOf.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/URLTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/DataTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/DateTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/ISO8601DateTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/EnumTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/NSDecimalNumberTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/DateFormatterTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/CustomDateFormatTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Transforms/DictionaryTransform.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Core/Map.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Core/Mapper.swift /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/ObjectMapper/ObjectMapper/Core/Operators.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreText.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/elizabethgentile/Desktop/safe_steps_1.0/Pods/Target\ Support\ Files/ObjectMapper/ObjectMapper-umbrella.h /Users/elizabethgentile/Desktop/safe_steps_1.0/DerivedData/MapsDirection/Build/Intermediates/Pods.build/Debug-iphonesimulator/ObjectMapper.build/unextended-module.modulemap
D
import std.stdio; import std.algorithm; import std.range; void main() { writeln("Hello, World!"); int[] arr1 = [4, 9, 7]; int[] arr2 = [5, 2, 1, 10]; int[] arr3 = [6, 8, 3]; sort(chain(arr1, arr2, arr3)); writefln("%s\n%s\n%s\n", arr1, arr2, arr3); }
D
/* DFLAGS: TEST_OUTPUT: --- fail_compilation/fail19911c.d(14): Error: function `object.fun` `object.TypeInfo` could not be found, but is implicitly used in D-style variadic functions --- */ module object; class Object { } class TypeInfo_Tuple { } void fun(...) { }
D
module org.serviio.UPnPServerStatus; public enum UPnPServerStatus { INITIALIZING, STARTED, STOPPED } /* Location: D:\Program Files\Serviio\lib\serviio.jar * Qualified Name: org.serviio.UPnPServerStatus * JD-Core Version: 0.6.2 */
D
/Users/Matt/iOS/RoadInfo/DerivedData/RoadInfo/Build/Intermediates/RoadInfo.build/Debug-iphonesimulator/RoadInfo.build/Objects-normal/i386/URLConnection.o : /Users/Matt/iOS/RoadInfo/RoadInfo/ChristchurchEvent.swift /Users/Matt/iOS/RoadInfo/RoadInfo/URLConnection.swift /Users/Matt/iOS/RoadInfo/RoadInfo/EventViewController.swift /Users/Matt/iOS/RoadInfo/RoadInfo/XMLParser.swift /Users/Matt/iOS/RoadInfo/RoadInfo/MapController.swift /Users/Matt/iOS/RoadInfo/RoadInfo/Complex.swift /Users/Matt/iOS/RoadInfo/RoadInfo/NZMGConverter.swift /Users/Matt/iOS/RoadInfo/RoadInfo/Location.swift /Users/Matt/iOS/RoadInfo/RoadInfo/ChristchurchXML.swift /Users/Matt/iOS/RoadInfo/RoadInfo/RoadEvent.swift /Users/Matt/iOS/RoadInfo/RoadInfo/Annotation.swift /Users/Matt/iOS/RoadInfo/RoadInfo/AppDelegate.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/CoreLocation.swiftmodule /Users/Matt/iOS/RoadInfo/DerivedData/RoadInfo/Build/Intermediates/RoadInfo.build/Debug-iphonesimulator/RoadInfo.build/Objects-normal/i386/URLConnection~partial.swiftmodule : /Users/Matt/iOS/RoadInfo/RoadInfo/ChristchurchEvent.swift /Users/Matt/iOS/RoadInfo/RoadInfo/URLConnection.swift /Users/Matt/iOS/RoadInfo/RoadInfo/EventViewController.swift /Users/Matt/iOS/RoadInfo/RoadInfo/XMLParser.swift /Users/Matt/iOS/RoadInfo/RoadInfo/MapController.swift /Users/Matt/iOS/RoadInfo/RoadInfo/Complex.swift /Users/Matt/iOS/RoadInfo/RoadInfo/NZMGConverter.swift /Users/Matt/iOS/RoadInfo/RoadInfo/Location.swift /Users/Matt/iOS/RoadInfo/RoadInfo/ChristchurchXML.swift /Users/Matt/iOS/RoadInfo/RoadInfo/RoadEvent.swift /Users/Matt/iOS/RoadInfo/RoadInfo/Annotation.swift /Users/Matt/iOS/RoadInfo/RoadInfo/AppDelegate.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/CoreLocation.swiftmodule /Users/Matt/iOS/RoadInfo/DerivedData/RoadInfo/Build/Intermediates/RoadInfo.build/Debug-iphonesimulator/RoadInfo.build/Objects-normal/i386/URLConnection~partial.swiftdoc : /Users/Matt/iOS/RoadInfo/RoadInfo/ChristchurchEvent.swift /Users/Matt/iOS/RoadInfo/RoadInfo/URLConnection.swift /Users/Matt/iOS/RoadInfo/RoadInfo/EventViewController.swift /Users/Matt/iOS/RoadInfo/RoadInfo/XMLParser.swift /Users/Matt/iOS/RoadInfo/RoadInfo/MapController.swift /Users/Matt/iOS/RoadInfo/RoadInfo/Complex.swift /Users/Matt/iOS/RoadInfo/RoadInfo/NZMGConverter.swift /Users/Matt/iOS/RoadInfo/RoadInfo/Location.swift /Users/Matt/iOS/RoadInfo/RoadInfo/ChristchurchXML.swift /Users/Matt/iOS/RoadInfo/RoadInfo/RoadEvent.swift /Users/Matt/iOS/RoadInfo/RoadInfo/Annotation.swift /Users/Matt/iOS/RoadInfo/RoadInfo/AppDelegate.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/i386/CoreLocation.swiftmodule
D
/Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Build/Intermediates/Pods.build/Debug-iphonesimulator/Alamofire.build/Objects-normal/x86_64/RedirectHandler.o : /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/MultipartFormData.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/MultipartUpload.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/AlamofireExtended.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Protected.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/HTTPMethod.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Combine.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/OperationQueue+Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/StringEncoding+Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Result+Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/URLRequest+Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Response.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/SessionDelegate.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/ParameterEncoding.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Session.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Validation.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/ServerTrustEvaluation.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/ResponseSerialization.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/RequestTaskMap.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/URLEncodedFormEncoder.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/ParameterEncoder.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/NetworkReachabilityManager.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/CachedResponseHandler.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/RedirectHandler.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/AFError.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/EventMonitor.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/AuthenticationInterceptor.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/RequestInterceptor.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Notifications.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/HTTPHeaders.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Request.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/RetryPolicy.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/ObjectiveC.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreImage.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/QuartzCore.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Dispatch.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Metal.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Darwin.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Foundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreFoundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreGraphics.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Swift.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/UIKit.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Target\ Support\ Files/Alamofire/Alamofire-umbrella.h /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Build/Intermediates/Pods.build/Debug-iphonesimulator/Alamofire.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/UserNotifications.framework/Headers/UserNotifications.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Build/Intermediates/Pods.build/Debug-iphonesimulator/Alamofire.build/Objects-normal/x86_64/RedirectHandler~partial.swiftmodule : /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/MultipartFormData.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/MultipartUpload.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/AlamofireExtended.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Protected.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/HTTPMethod.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Combine.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/OperationQueue+Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/StringEncoding+Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Result+Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/URLRequest+Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Response.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/SessionDelegate.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/ParameterEncoding.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Session.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Validation.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/ServerTrustEvaluation.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/ResponseSerialization.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/RequestTaskMap.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/URLEncodedFormEncoder.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/ParameterEncoder.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/NetworkReachabilityManager.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/CachedResponseHandler.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/RedirectHandler.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/AFError.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/EventMonitor.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/AuthenticationInterceptor.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/RequestInterceptor.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Notifications.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/HTTPHeaders.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Request.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/RetryPolicy.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/ObjectiveC.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreImage.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/QuartzCore.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Dispatch.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Metal.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Darwin.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Foundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreFoundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreGraphics.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Swift.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/UIKit.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Target\ Support\ Files/Alamofire/Alamofire-umbrella.h /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Build/Intermediates/Pods.build/Debug-iphonesimulator/Alamofire.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/UserNotifications.framework/Headers/UserNotifications.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Build/Intermediates/Pods.build/Debug-iphonesimulator/Alamofire.build/Objects-normal/x86_64/RedirectHandler~partial.swiftdoc : /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/MultipartFormData.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/MultipartUpload.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/AlamofireExtended.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Protected.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/HTTPMethod.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Combine.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/OperationQueue+Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/StringEncoding+Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Result+Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/URLRequest+Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Response.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/SessionDelegate.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/ParameterEncoding.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Session.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Validation.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/ServerTrustEvaluation.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/ResponseSerialization.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/RequestTaskMap.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/URLEncodedFormEncoder.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/ParameterEncoder.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/NetworkReachabilityManager.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/CachedResponseHandler.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/RedirectHandler.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/AFError.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/EventMonitor.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/AuthenticationInterceptor.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/RequestInterceptor.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Notifications.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/HTTPHeaders.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Request.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/RetryPolicy.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/ObjectiveC.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreImage.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/QuartzCore.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Dispatch.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Metal.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Darwin.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Foundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreFoundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreGraphics.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Swift.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/UIKit.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Target\ Support\ Files/Alamofire/Alamofire-umbrella.h /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Build/Intermediates/Pods.build/Debug-iphonesimulator/Alamofire.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/UserNotifications.framework/Headers/UserNotifications.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Build/Intermediates/Pods.build/Debug-iphonesimulator/Alamofire.build/Objects-normal/x86_64/RedirectHandler~partial.swiftsourceinfo : /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/MultipartFormData.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/MultipartUpload.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/AlamofireExtended.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Protected.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/HTTPMethod.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Combine.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/OperationQueue+Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/StringEncoding+Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Result+Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/URLRequest+Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Alamofire.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Response.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/SessionDelegate.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/ParameterEncoding.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Session.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Validation.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/ServerTrustEvaluation.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/ResponseSerialization.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/RequestTaskMap.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/URLEncodedFormEncoder.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/ParameterEncoder.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/NetworkReachabilityManager.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/CachedResponseHandler.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/RedirectHandler.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/AFError.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/EventMonitor.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/AuthenticationInterceptor.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/RequestInterceptor.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Notifications.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/HTTPHeaders.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/Request.swift /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Alamofire/Source/RetryPolicy.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/ObjectiveC.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreImage.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/QuartzCore.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Dispatch.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Metal.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Darwin.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Foundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreFoundation.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/CoreGraphics.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Swift.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/UIKit.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/prebuilt-modules/Combine.swiftmodule/x86_64-apple-ios-simulator.swiftmodule /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Pods/Target\ Support\ Files/Alamofire/Alamofire-umbrella.h /Users/GuoYanjun/Desktop/TestDemo/WanAndroid_IOS/Build/Intermediates/Pods.build/Debug-iphonesimulator/Alamofire.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/UserNotifications.framework/Headers/UserNotifications.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.4.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
D
import std.stdio; int sum_div(int n){ int sum = 0; for(int i = 1; i<n;++i) if(!(n%i)) sum+=i; return sum; } void main(){ int[10000] a; for(auto i = 0;i<a.length;++i){ if(!a[i] && i+1 !=sum_div(i+1) && i+1 == sum_div(sum_div(i+1))){ a[i] = 1; a[sum_div(i+1)-1]=1; } } int sum = 0; for(int i = 0; i<a.length;++i) if(a[i]) sum+=i+1; writeln(sum); }
D
/** * Compiler implementation of the * $(LINK2 http://www.dlang.org, D programming language). * * Copyright: Copyright (C) 1999-2018 by The D Language Foundation, All Rights Reserved * Authors: $(LINK2 http://www.digitalmars.com, Walter Bright) * License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0) * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/mtype.d, _mtype.d) * Documentation: https://dlang.org/phobos/dmd_mtype.html * Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/mtype.d */ module dmd.mtype; import core.checkedint; import core.stdc.stdarg; import core.stdc.stdio; import core.stdc.stdlib; import core.stdc.string; import dmd.access; import dmd.aggregate; import dmd.arraytypes; import dmd.gluelayer; import dmd.complex; import dmd.dclass; import dmd.declaration; import dmd.denum; import dmd.dimport; import dmd.dmangle; import dmd.dscope; import dmd.dstruct; import dmd.dsymbol; import dmd.dsymbolsem; import dmd.dtemplate; import dmd.errors; import dmd.expression; import dmd.expressionsem; import dmd.func; import dmd.globals; import dmd.hdrgen; import dmd.id; import dmd.identifier; import dmd.imphint; import dmd.init; import dmd.opover; import dmd.root.ctfloat; import dmd.root.outbuffer; import dmd.root.rmem; import dmd.root.rootobject; import dmd.root.stringtable; import dmd.target; import dmd.tokens; import dmd.typesem; import dmd.visitor; enum LOGDOTEXP = 0; // log ::dotExp() enum LOGDEFAULTINIT = 0; // log ::defaultInit() extern (C++) __gshared int Tsize_t = Tuns32; extern (C++) __gshared int Tptrdiff_t = Tint32; enum SIZE_INVALID = (~cast(d_uns64)0); // error return from size() functions /*************************** * Return !=0 if modfrom can be implicitly converted to modto */ bool MODimplicitConv(MOD modfrom, MOD modto) pure nothrow @nogc @safe { if (modfrom == modto) return true; //printf("MODimplicitConv(from = %x, to = %x)\n", modfrom, modto); auto X(T, U)(T m, U n) { return ((m << 4) | n); } switch (X(modfrom & ~MODFlags.shared_, modto & ~MODFlags.shared_)) { case X(0, MODFlags.const_): case X(MODFlags.wild, MODFlags.const_): case X(MODFlags.wild, MODFlags.wildconst): case X(MODFlags.wildconst, MODFlags.const_): return (modfrom & MODFlags.shared_) == (modto & MODFlags.shared_); case X(MODFlags.immutable_, MODFlags.const_): case X(MODFlags.immutable_, MODFlags.wildconst): return true; default: return false; } } /*************************** * Return MATCH.exact or MATCH.constant if a method of type '() modfrom' can call a method of type '() modto'. */ MATCH MODmethodConv(MOD modfrom, MOD modto) pure nothrow @nogc @safe { if (modfrom == modto) return MATCH.exact; if (MODimplicitConv(modfrom, modto)) return MATCH.constant; auto X(T, U)(T m, U n) { return ((m << 4) | n); } switch (X(modfrom, modto)) { case X(0, MODFlags.wild): case X(MODFlags.immutable_, MODFlags.wild): case X(MODFlags.const_, MODFlags.wild): case X(MODFlags.wildconst, MODFlags.wild): case X(MODFlags.shared_, MODFlags.shared_ | MODFlags.wild): case X(MODFlags.shared_ | MODFlags.immutable_, MODFlags.shared_ | MODFlags.wild): case X(MODFlags.shared_ | MODFlags.const_, MODFlags.shared_ | MODFlags.wild): case X(MODFlags.shared_ | MODFlags.wildconst, MODFlags.shared_ | MODFlags.wild): return MATCH.constant; default: return MATCH.nomatch; } } /*************************** * Merge mod bits to form common mod. */ MOD MODmerge(MOD mod1, MOD mod2) pure nothrow @nogc @safe { if (mod1 == mod2) return mod1; //printf("MODmerge(1 = %x, 2 = %x)\n", mod1, mod2); MOD result = 0; if ((mod1 | mod2) & MODFlags.shared_) { // If either type is shared, the result will be shared result |= MODFlags.shared_; mod1 &= ~MODFlags.shared_; mod2 &= ~MODFlags.shared_; } if (mod1 == 0 || mod1 == MODFlags.mutable || mod1 == MODFlags.const_ || mod2 == 0 || mod2 == MODFlags.mutable || mod2 == MODFlags.const_) { // If either type is mutable or const, the result will be const. result |= MODFlags.const_; } else { // MODFlags.immutable_ vs MODFlags.wild // MODFlags.immutable_ vs MODFlags.wildconst // MODFlags.wild vs MODFlags.wildconst assert(mod1 & MODFlags.wild || mod2 & MODFlags.wild); result |= MODFlags.wildconst; } return result; } /********************************* * Store modifier name into buf. */ void MODtoBuffer(OutBuffer* buf, MOD mod) nothrow { switch (mod) { case 0: break; case MODFlags.immutable_: buf.writestring(Token.toString(TOK.immutable_)); break; case MODFlags.shared_: buf.writestring(Token.toString(TOK.shared_)); break; case MODFlags.shared_ | MODFlags.const_: buf.writestring(Token.toString(TOK.shared_)); buf.writeByte(' '); goto case; /+ fall through +/ case MODFlags.const_: buf.writestring(Token.toString(TOK.const_)); break; case MODFlags.shared_ | MODFlags.wild: buf.writestring(Token.toString(TOK.shared_)); buf.writeByte(' '); goto case; /+ fall through +/ case MODFlags.wild: buf.writestring(Token.toString(TOK.inout_)); break; case MODFlags.shared_ | MODFlags.wildconst: buf.writestring(Token.toString(TOK.shared_)); buf.writeByte(' '); goto case; /+ fall through +/ case MODFlags.wildconst: buf.writestring(Token.toString(TOK.inout_)); buf.writeByte(' '); buf.writestring(Token.toString(TOK.const_)); break; default: assert(0); } } /********************************* * Return modifier name. */ char* MODtoChars(MOD mod) nothrow { OutBuffer buf; buf.reserve(16); MODtoBuffer(&buf, mod); return buf.extractString(); } /************************************ * Convert MODxxxx to STCxxx */ StorageClass ModToStc(uint mod) pure nothrow @nogc @safe { StorageClass stc = 0; if (mod & MODFlags.immutable_) stc |= STC.immutable_; if (mod & MODFlags.const_) stc |= STC.const_; if (mod & MODFlags.wild) stc |= STC.wild; if (mod & MODFlags.shared_) stc |= STC.shared_; return stc; } private enum TFlags { integral = 1, floating = 2, unsigned = 4, real_ = 8, imaginary = 0x10, complex = 0x20, } Expression semanticLength(Scope* sc, TupleDeclaration tup, Expression exp) { ScopeDsymbol sym = new ArrayScopeSymbol(sc, tup); sym.parent = sc.scopesym; sc = sc.push(sym); sc = sc.startCTFE(); exp = exp.expressionSemantic(sc); sc = sc.endCTFE(); sc.pop(); return exp; } /************************** * This evaluates exp while setting length to be the number * of elements in the tuple t. */ Expression semanticLength(Scope* sc, Type t, Expression exp) { if (t.ty == Ttuple) { ScopeDsymbol sym = new ArrayScopeSymbol(sc, cast(TypeTuple)t); sym.parent = sc.scopesym; sc = sc.push(sym); sc = sc.startCTFE(); exp = exp.expressionSemantic(sc); sc = sc.endCTFE(); sc.pop(); } else { sc = sc.startCTFE(); exp = exp.expressionSemantic(sc); sc = sc.endCTFE(); } return exp; } enum ENUMTY : int { Tarray, // slice array, aka T[] Tsarray, // static array, aka T[dimension] Taarray, // associative array, aka T[type] Tpointer, Treference, Tfunction, Tident, Tclass, Tstruct, Tenum, Tdelegate, Tnone, Tvoid, Tint8, Tuns8, Tint16, Tuns16, Tint32, Tuns32, Tint64, Tuns64, Tfloat32, Tfloat64, Tfloat80, Timaginary32, Timaginary64, Timaginary80, Tcomplex32, Tcomplex64, Tcomplex80, Tbool, Tchar, Twchar, Tdchar, Terror, Tinstance, Ttypeof, Ttuple, Tslice, Treturn, Tnull, Tvector, Tint128, Tuns128, TMAX, } alias Tarray = ENUMTY.Tarray; alias Tsarray = ENUMTY.Tsarray; alias Taarray = ENUMTY.Taarray; alias Tpointer = ENUMTY.Tpointer; alias Treference = ENUMTY.Treference; alias Tfunction = ENUMTY.Tfunction; alias Tident = ENUMTY.Tident; alias Tclass = ENUMTY.Tclass; alias Tstruct = ENUMTY.Tstruct; alias Tenum = ENUMTY.Tenum; alias Tdelegate = ENUMTY.Tdelegate; alias Tnone = ENUMTY.Tnone; alias Tvoid = ENUMTY.Tvoid; alias Tint8 = ENUMTY.Tint8; alias Tuns8 = ENUMTY.Tuns8; alias Tint16 = ENUMTY.Tint16; alias Tuns16 = ENUMTY.Tuns16; alias Tint32 = ENUMTY.Tint32; alias Tuns32 = ENUMTY.Tuns32; alias Tint64 = ENUMTY.Tint64; alias Tuns64 = ENUMTY.Tuns64; alias Tfloat32 = ENUMTY.Tfloat32; alias Tfloat64 = ENUMTY.Tfloat64; alias Tfloat80 = ENUMTY.Tfloat80; alias Timaginary32 = ENUMTY.Timaginary32; alias Timaginary64 = ENUMTY.Timaginary64; alias Timaginary80 = ENUMTY.Timaginary80; alias Tcomplex32 = ENUMTY.Tcomplex32; alias Tcomplex64 = ENUMTY.Tcomplex64; alias Tcomplex80 = ENUMTY.Tcomplex80; alias Tbool = ENUMTY.Tbool; alias Tchar = ENUMTY.Tchar; alias Twchar = ENUMTY.Twchar; alias Tdchar = ENUMTY.Tdchar; alias Terror = ENUMTY.Terror; alias Tinstance = ENUMTY.Tinstance; alias Ttypeof = ENUMTY.Ttypeof; alias Ttuple = ENUMTY.Ttuple; alias Tslice = ENUMTY.Tslice; alias Treturn = ENUMTY.Treturn; alias Tnull = ENUMTY.Tnull; alias Tvector = ENUMTY.Tvector; alias Tint128 = ENUMTY.Tint128; alias Tuns128 = ENUMTY.Tuns128; alias TMAX = ENUMTY.TMAX; alias TY = ubyte; enum MODFlags : int { const_ = 1, // type is const immutable_ = 4, // type is immutable shared_ = 2, // type is shared wild = 8, // type is wild wildconst = (MODFlags.wild | MODFlags.const_), // type is wild const mutable = 0x10, // type is mutable (only used in wildcard matching) } alias MOD = ubyte; /*********************************************************** */ extern (C++) abstract class Type : RootObject { TY ty; MOD mod; // modifiers MODxxxx char* deco; /* These are cached values that are lazily evaluated by constOf(), immutableOf(), etc. * They should not be referenced by anybody but mtype.c. * They can be NULL if not lazily evaluated yet. * Note that there is no "shared immutable", because that is just immutable * Naked == no MOD bits */ Type cto; // MODFlags.const_ ? naked version of this type : const version Type ito; // MODFlags.immutable_ ? naked version of this type : immutable version Type sto; // MODFlags.shared_ ? naked version of this type : shared mutable version Type scto; // MODFlags.shared_ | MODFlags.const_ ? naked version of this type : shared const version Type wto; // MODFlags.wild ? naked version of this type : wild version Type wcto; // MODFlags.wildconst ? naked version of this type : wild const version Type swto; // MODFlags.shared_ | MODFlags.wild ? naked version of this type : shared wild version Type swcto; // MODFlags.shared_ | MODFlags.wildconst ? naked version of this type : shared wild const version Type pto; // merged pointer to this type Type rto; // reference to this type Type arrayof; // array of this type TypeInfoDeclaration vtinfo; // TypeInfo object for this Type type* ctype; // for back end extern (C++) static __gshared Type tvoid; extern (C++) static __gshared Type tint8; extern (C++) static __gshared Type tuns8; extern (C++) static __gshared Type tint16; extern (C++) static __gshared Type tuns16; extern (C++) static __gshared Type tint32; extern (C++) static __gshared Type tuns32; extern (C++) static __gshared Type tint64; extern (C++) static __gshared Type tuns64; extern (C++) static __gshared Type tint128; extern (C++) static __gshared Type tuns128; extern (C++) static __gshared Type tfloat32; extern (C++) static __gshared Type tfloat64; extern (C++) static __gshared Type tfloat80; extern (C++) static __gshared Type timaginary32; extern (C++) static __gshared Type timaginary64; extern (C++) static __gshared Type timaginary80; extern (C++) static __gshared Type tcomplex32; extern (C++) static __gshared Type tcomplex64; extern (C++) static __gshared Type tcomplex80; extern (C++) static __gshared Type tbool; extern (C++) static __gshared Type tchar; extern (C++) static __gshared Type twchar; extern (C++) static __gshared Type tdchar; // Some special types extern (C++) static __gshared Type tshiftcnt; extern (C++) static __gshared Type tvoidptr; // void* extern (C++) static __gshared Type tstring; // immutable(char)[] extern (C++) static __gshared Type twstring; // immutable(wchar)[] extern (C++) static __gshared Type tdstring; // immutable(dchar)[] extern (C++) static __gshared Type tvalist; // va_list alias extern (C++) static __gshared Type terror; // for error recovery extern (C++) static __gshared Type tnull; // for null type extern (C++) static __gshared Type tsize_t; // matches size_t alias extern (C++) static __gshared Type tptrdiff_t; // matches ptrdiff_t alias extern (C++) static __gshared Type thash_t; // matches hash_t alias extern (C++) static __gshared ClassDeclaration dtypeinfo; extern (C++) static __gshared ClassDeclaration typeinfoclass; extern (C++) static __gshared ClassDeclaration typeinfointerface; extern (C++) static __gshared ClassDeclaration typeinfostruct; extern (C++) static __gshared ClassDeclaration typeinfopointer; extern (C++) static __gshared ClassDeclaration typeinfoarray; extern (C++) static __gshared ClassDeclaration typeinfostaticarray; extern (C++) static __gshared ClassDeclaration typeinfoassociativearray; extern (C++) static __gshared ClassDeclaration typeinfovector; extern (C++) static __gshared ClassDeclaration typeinfoenum; extern (C++) static __gshared ClassDeclaration typeinfofunction; extern (C++) static __gshared ClassDeclaration typeinfodelegate; extern (C++) static __gshared ClassDeclaration typeinfotypelist; extern (C++) static __gshared ClassDeclaration typeinfoconst; extern (C++) static __gshared ClassDeclaration typeinfoinvariant; extern (C++) static __gshared ClassDeclaration typeinfoshared; extern (C++) static __gshared ClassDeclaration typeinfowild; extern (C++) static __gshared TemplateDeclaration rtinfo; extern (C++) static __gshared Type[TMAX] basic; extern (C++) static __gshared StringTable stringtable; extern (C++) static __gshared ubyte[TMAX] sizeTy = () { ubyte[TMAX] sizeTy = __traits(classInstanceSize, TypeBasic); sizeTy[Tsarray] = __traits(classInstanceSize, TypeSArray); sizeTy[Tarray] = __traits(classInstanceSize, TypeDArray); sizeTy[Taarray] = __traits(classInstanceSize, TypeAArray); sizeTy[Tpointer] = __traits(classInstanceSize, TypePointer); sizeTy[Treference] = __traits(classInstanceSize, TypeReference); sizeTy[Tfunction] = __traits(classInstanceSize, TypeFunction); sizeTy[Tdelegate] = __traits(classInstanceSize, TypeDelegate); sizeTy[Tident] = __traits(classInstanceSize, TypeIdentifier); sizeTy[Tinstance] = __traits(classInstanceSize, TypeInstance); sizeTy[Ttypeof] = __traits(classInstanceSize, TypeTypeof); sizeTy[Tenum] = __traits(classInstanceSize, TypeEnum); sizeTy[Tstruct] = __traits(classInstanceSize, TypeStruct); sizeTy[Tclass] = __traits(classInstanceSize, TypeClass); sizeTy[Ttuple] = __traits(classInstanceSize, TypeTuple); sizeTy[Tslice] = __traits(classInstanceSize, TypeSlice); sizeTy[Treturn] = __traits(classInstanceSize, TypeReturn); sizeTy[Terror] = __traits(classInstanceSize, TypeError); sizeTy[Tnull] = __traits(classInstanceSize, TypeNull); sizeTy[Tvector] = __traits(classInstanceSize, TypeVector); return sizeTy; }(); final extern (D) this(TY ty) { this.ty = ty; } const(char)* kind() const nothrow pure @nogc @safe { assert(false); // should be overridden } final Type copy() nothrow { Type t = cast(Type)mem.xmalloc(sizeTy[ty]); memcpy(cast(void*)t, cast(void*)this, sizeTy[ty]); return t; } Type syntaxCopy() { print(); fprintf(stderr, "ty = %d\n", ty); assert(0); } override bool equals(RootObject o) { Type t = cast(Type)o; //printf("Type::equals(%s, %s)\n", toChars(), t.toChars()); // deco strings are unique // and semantic() has been run if (this == o || ((t && deco == t.deco) && deco !is null)) { //printf("deco = '%s', t.deco = '%s'\n", deco, t.deco); return true; } //if (deco && t && t.deco) printf("deco = '%s', t.deco = '%s'\n", deco, t.deco); return false; } final bool equivalent(Type t) { return immutableOf().equals(t.immutableOf()); } // kludge for template.isType() override final DYNCAST dyncast() const { return DYNCAST.type; } /******************************* * Covariant means that 'this' can substitute for 't', * i.e. a pure function is a match for an impure type. * Params: * t = type 'this' is covariant with * pstc = if not null, store STCxxxx which would make it covariant * fix17349 = enable fix https://issues.dlang.org/show_bug.cgi?id=17349 * Returns: * 0 types are distinct * 1 this is covariant with t * 2 arguments match as far as overloading goes, * but types are not covariant * 3 cannot determine covariance because of forward references * *pstc STCxxxx which would make it covariant */ final int covariant(Type t, StorageClass* pstc = null, bool fix17349 = true) { version (none) { printf("Type::covariant(t = %s) %s\n", t.toChars(), toChars()); printf("deco = %p, %p\n", deco, t.deco); // printf("ty = %d\n", next.ty); printf("mod = %x, %x\n", mod, t.mod); } if (pstc) *pstc = 0; StorageClass stc = 0; bool notcovariant = false; TypeFunction t1; TypeFunction t2; if (equals(t)) return 1; // covariant if (ty != Tfunction || t.ty != Tfunction) goto Ldistinct; t1 = cast(TypeFunction)this; t2 = cast(TypeFunction)t; if (t1.varargs != t2.varargs) goto Ldistinct; if (t1.parameters && t2.parameters) { size_t dim = Parameter.dim(t1.parameters); if (dim != Parameter.dim(t2.parameters)) goto Ldistinct; for (size_t i = 0; i < dim; i++) { Parameter fparam1 = Parameter.getNth(t1.parameters, i); Parameter fparam2 = Parameter.getNth(t2.parameters, i); if (!fparam1.type.equals(fparam2.type)) { if (!fix17349) goto Ldistinct; Type tp1 = fparam1.type; Type tp2 = fparam2.type; if (tp1.ty == tp2.ty) { if (tp1.ty == Tclass) { if ((cast(TypeClass)tp1).sym == (cast(TypeClass)tp2).sym && MODimplicitConv(tp2.mod, tp1.mod)) goto Lcov; } else if (tp1.ty == Tstruct) { if ((cast(TypeStruct)tp1).sym == (cast(TypeStruct)tp2).sym && MODimplicitConv(tp2.mod, tp1.mod)) goto Lcov; } else if (tp1.ty == Tpointer) { if (tp2.implicitConvTo(tp1)) goto Lcov; } else if (tp1.ty == Tarray) { if (tp2.implicitConvTo(tp1)) goto Lcov; } else if (tp1.ty == Tdelegate) { if (tp1.implicitConvTo(tp2)) goto Lcov; } } goto Ldistinct; } Lcov: notcovariant |= !fparam1.isCovariant(t1.isref, fparam2); } } else if (t1.parameters != t2.parameters) { size_t dim1 = !t1.parameters ? 0 : t1.parameters.dim; size_t dim2 = !t2.parameters ? 0 : t2.parameters.dim; if (dim1 || dim2) goto Ldistinct; } // The argument lists match if (notcovariant) goto Lnotcovariant; if (t1.linkage != t2.linkage) goto Lnotcovariant; { // Return types Type t1n = t1.next; Type t2n = t2.next; if (!t1n || !t2n) // happens with return type inference goto Lnotcovariant; if (t1n.equals(t2n)) goto Lcovariant; if (t1n.ty == Tclass && t2n.ty == Tclass) { /* If same class type, but t2n is const, then it's * covariant. Do this test first because it can work on * forward references. */ if ((cast(TypeClass)t1n).sym == (cast(TypeClass)t2n).sym && MODimplicitConv(t1n.mod, t2n.mod)) goto Lcovariant; // If t1n is forward referenced: ClassDeclaration cd = (cast(TypeClass)t1n).sym; if (cd.semanticRun < PASS.semanticdone && !cd.isBaseInfoComplete()) cd.dsymbolSemantic(null); if (!cd.isBaseInfoComplete()) { return 3; // forward references } } if (t1n.ty == Tstruct && t2n.ty == Tstruct) { if ((cast(TypeStruct)t1n).sym == (cast(TypeStruct)t2n).sym && MODimplicitConv(t1n.mod, t2n.mod)) goto Lcovariant; } else if (t1n.ty == t2n.ty && t1n.implicitConvTo(t2n)) goto Lcovariant; else if (t1n.ty == Tnull && t1n.implicitConvTo(t2n) && t1n.size() == t2n.size()) goto Lcovariant; } goto Lnotcovariant; Lcovariant: if (t1.isref != t2.isref) goto Lnotcovariant; if (!t1.isref && (t1.isscope || t2.isscope)) { StorageClass stc1 = t1.isscope ? STC.scope_ : 0; StorageClass stc2 = t2.isscope ? STC.scope_ : 0; if (t1.isreturn) { stc1 |= STC.return_; if (!t1.isscope) stc1 |= STC.ref_; } if (t2.isreturn) { stc2 |= STC.return_; if (!t2.isscope) stc2 |= STC.ref_; } if (!Parameter.isCovariantScope(t1.isref, stc1, stc2)) goto Lnotcovariant; } // We can subtract 'return ref' from 'this', but cannot add it else if (t1.isreturn && !t2.isreturn) goto Lnotcovariant; /* Can convert mutable to const */ if (!MODimplicitConv(t2.mod, t1.mod)) { version (none) { //stop attribute inference with const // If adding 'const' will make it covariant if (MODimplicitConv(t2.mod, MODmerge(t1.mod, MODFlags.const_))) stc |= STC.const_; else goto Lnotcovariant; } else { goto Ldistinct; } } /* Can convert pure to impure, nothrow to throw, and nogc to gc */ if (!t1.purity && t2.purity) stc |= STC.pure_; if (!t1.isnothrow && t2.isnothrow) stc |= STC.nothrow_; if (!t1.isnogc && t2.isnogc) stc |= STC.nogc; /* Can convert safe/trusted to system */ if (t1.trust <= TRUST.system && t2.trust >= TRUST.trusted) { // Should we infer trusted or safe? Go with safe. stc |= STC.safe; } if (stc) { if (pstc) *pstc = stc; goto Lnotcovariant; } //printf("\tcovaraint: 1\n"); return 1; Ldistinct: //printf("\tcovaraint: 0\n"); return 0; Lnotcovariant: //printf("\tcovaraint: 2\n"); return 2; } /******************************** * For pretty-printing a type. */ final override const(char)* toChars() { OutBuffer buf; buf.reserve(16); HdrGenState hgs; hgs.fullQual = (ty == Tclass && !mod); .toCBuffer(this, &buf, null, &hgs); return buf.extractString(); } /// ditto final char* toPrettyChars(bool QualifyTypes = false) { OutBuffer buf; buf.reserve(16); HdrGenState hgs; hgs.fullQual = QualifyTypes; .toCBuffer(this, &buf, null, &hgs); return buf.extractString(); } static void _init() { stringtable._init(14000); // Set basic types static __gshared TY* basetab = [ Tvoid, Tint8, Tuns8, Tint16, Tuns16, Tint32, Tuns32, Tint64, Tuns64, Tint128, Tuns128, Tfloat32, Tfloat64, Tfloat80, Timaginary32, Timaginary64, Timaginary80, Tcomplex32, Tcomplex64, Tcomplex80, Tbool, Tchar, Twchar, Tdchar, Terror ]; for (size_t i = 0; basetab[i] != Terror; i++) { Type t = new TypeBasic(basetab[i]); t = t.merge(); basic[basetab[i]] = t; } basic[Terror] = new TypeError(); tvoid = basic[Tvoid]; tint8 = basic[Tint8]; tuns8 = basic[Tuns8]; tint16 = basic[Tint16]; tuns16 = basic[Tuns16]; tint32 = basic[Tint32]; tuns32 = basic[Tuns32]; tint64 = basic[Tint64]; tuns64 = basic[Tuns64]; tint128 = basic[Tint128]; tuns128 = basic[Tuns128]; tfloat32 = basic[Tfloat32]; tfloat64 = basic[Tfloat64]; tfloat80 = basic[Tfloat80]; timaginary32 = basic[Timaginary32]; timaginary64 = basic[Timaginary64]; timaginary80 = basic[Timaginary80]; tcomplex32 = basic[Tcomplex32]; tcomplex64 = basic[Tcomplex64]; tcomplex80 = basic[Tcomplex80]; tbool = basic[Tbool]; tchar = basic[Tchar]; twchar = basic[Twchar]; tdchar = basic[Tdchar]; tshiftcnt = tint32; terror = basic[Terror]; tnull = basic[Tnull]; tnull = new TypeNull(); tnull.deco = tnull.merge().deco; tvoidptr = tvoid.pointerTo(); tstring = tchar.immutableOf().arrayOf(); twstring = twchar.immutableOf().arrayOf(); tdstring = tdchar.immutableOf().arrayOf(); tvalist = Target.va_listType(); if (global.params.isLP64) { Tsize_t = Tuns64; Tptrdiff_t = Tint64; } else { Tsize_t = Tuns32; Tptrdiff_t = Tint32; } tsize_t = basic[Tsize_t]; tptrdiff_t = basic[Tptrdiff_t]; thash_t = tsize_t; } final d_uns64 size() { return size(Loc.initial); } d_uns64 size(const ref Loc loc) { error(loc, "no size for type `%s`", toChars()); return SIZE_INVALID; } uint alignsize() { return cast(uint)size(Loc.initial); } final Type trySemantic(const ref Loc loc, Scope* sc) { //printf("+trySemantic(%s) %d\n", toChars(), global.errors); uint errors = global.startGagging(); Type t = typeSemantic(this, loc, sc); if (global.endGagging(errors) || t.ty == Terror) // if any errors happened { t = null; } //printf("-trySemantic(%s) %d\n", toChars(), global.errors); return t; } /************************************* * This version does a merge even if the deco is already computed. * Necessary for types that have a deco, but are not merged. */ final Type merge2() { //printf("merge2(%s)\n", toChars()); Type t = this; assert(t); if (!t.deco) return t.merge(); StringValue* sv = stringtable.lookup(t.deco, strlen(t.deco)); if (sv && sv.ptrvalue) { t = cast(Type)sv.ptrvalue; assert(t.deco); } else assert(0); return t; } /********************************* * Store this type's modifier name into buf. */ final void modToBuffer(OutBuffer* buf) nothrow { if (mod) { buf.writeByte(' '); MODtoBuffer(buf, mod); } } /********************************* * Return this type's modifier name. */ final char* modToChars() nothrow { OutBuffer buf; buf.reserve(16); modToBuffer(&buf); return buf.extractString(); } /** For each active modifier (MODFlags.const_, MODFlags.immutable_, etc) call fp with a void* for the work param and a string representation of the attribute. */ final int modifiersApply(void* param, int function(void*, const(char)*) fp) { immutable ubyte[4] modsArr = [MODFlags.const_, MODFlags.immutable_, MODFlags.wild, MODFlags.shared_]; foreach (modsarr; modsArr) { if (mod & modsarr) { if (int res = fp(param, MODtoChars(modsarr))) return res; } } return 0; } bool isintegral() { return false; } // real, imaginary, or complex bool isfloating() { return false; } bool isreal() { return false; } bool isimaginary() { return false; } bool iscomplex() { return false; } bool isscalar() { return false; } bool isunsigned() { return false; } bool isscope() { return false; } bool isString() { return false; } /************************** * When T is mutable, * Given: * T a, b; * Can we bitwise assign: * a = b; * ? */ bool isAssignable() { return true; } /************************** * Returns true if T can be converted to boolean value. */ bool isBoolean() { return isscalar(); } /********************************* * Check type to see if it is based on a deprecated symbol. */ void checkDeprecated(const ref Loc loc, Scope* sc) { if (Dsymbol s = toDsymbol(sc)) { s.checkDeprecated(loc, sc); } } final bool isConst() const nothrow pure @nogc @safe { return (mod & MODFlags.const_) != 0; } final bool isImmutable() const nothrow pure @nogc @safe { return (mod & MODFlags.immutable_) != 0; } final bool isMutable() const nothrow pure @nogc @safe { return (mod & (MODFlags.const_ | MODFlags.immutable_ | MODFlags.wild)) == 0; } final bool isShared() const nothrow pure @nogc @safe { return (mod & MODFlags.shared_) != 0; } final bool isSharedConst() const nothrow pure @nogc @safe { return (mod & (MODFlags.shared_ | MODFlags.const_)) == (MODFlags.shared_ | MODFlags.const_); } final bool isWild() const nothrow pure @nogc @safe { return (mod & MODFlags.wild) != 0; } final bool isWildConst() const nothrow pure @nogc @safe { return (mod & MODFlags.wildconst) == MODFlags.wildconst; } final bool isSharedWild() const nothrow pure @nogc @safe { return (mod & (MODFlags.shared_ | MODFlags.wild)) == (MODFlags.shared_ | MODFlags.wild); } final bool isNaked() const nothrow pure @nogc @safe { return mod == 0; } /******************************** * Return a copy of this type with all attributes null-initialized. * Useful for creating a type with different modifiers. */ final Type nullAttributes() nothrow { uint sz = sizeTy[ty]; Type t = cast(Type)mem.xmalloc(sz); memcpy(cast(void*)t, cast(void*)this, sz); // t.mod = NULL; // leave mod unchanged t.deco = null; t.arrayof = null; t.pto = null; t.rto = null; t.cto = null; t.ito = null; t.sto = null; t.scto = null; t.wto = null; t.wcto = null; t.swto = null; t.swcto = null; t.vtinfo = null; t.ctype = null; if (t.ty == Tstruct) (cast(TypeStruct)t).att = AliasThisRec.fwdref; if (t.ty == Tclass) (cast(TypeClass)t).att = AliasThisRec.fwdref; return t; } /******************************** * Convert to 'const'. */ final Type constOf() { //printf("Type::constOf() %p %s\n", this, toChars()); if (mod == MODFlags.const_) return this; if (cto) { assert(cto.mod == MODFlags.const_); return cto; } Type t = makeConst(); t = t.merge(); t.fixTo(this); //printf("-Type::constOf() %p %s\n", t, t.toChars()); return t; } /******************************** * Convert to 'immutable'. */ final Type immutableOf() { //printf("Type::immutableOf() %p %s\n", this, toChars()); if (isImmutable()) return this; if (ito) { assert(ito.isImmutable()); return ito; } Type t = makeImmutable(); t = t.merge(); t.fixTo(this); //printf("\t%p\n", t); return t; } /******************************** * Make type mutable. */ final Type mutableOf() { //printf("Type::mutableOf() %p, %s\n", this, toChars()); Type t = this; if (isImmutable()) { t = ito; // immutable => naked assert(!t || (t.isMutable() && !t.isShared())); } else if (isConst()) { if (isShared()) { if (isWild()) t = swcto; // shared wild const -> shared else t = sto; // shared const => shared } else { if (isWild()) t = wcto; // wild const -> naked else t = cto; // const => naked } assert(!t || t.isMutable()); } else if (isWild()) { if (isShared()) t = sto; // shared wild => shared else t = wto; // wild => naked assert(!t || t.isMutable()); } if (!t) { t = makeMutable(); t = t.merge(); t.fixTo(this); } else t = t.merge(); assert(t.isMutable()); return t; } final Type sharedOf() { //printf("Type::sharedOf() %p, %s\n", this, toChars()); if (mod == MODFlags.shared_) return this; if (sto) { assert(sto.mod == MODFlags.shared_); return sto; } Type t = makeShared(); t = t.merge(); t.fixTo(this); //printf("\t%p\n", t); return t; } final Type sharedConstOf() { //printf("Type::sharedConstOf() %p, %s\n", this, toChars()); if (mod == (MODFlags.shared_ | MODFlags.const_)) return this; if (scto) { assert(scto.mod == (MODFlags.shared_ | MODFlags.const_)); return scto; } Type t = makeSharedConst(); t = t.merge(); t.fixTo(this); //printf("\t%p\n", t); return t; } /******************************** * Make type unshared. * 0 => 0 * const => const * immutable => immutable * shared => 0 * shared const => const * wild => wild * wild const => wild const * shared wild => wild * shared wild const => wild const */ final Type unSharedOf() { //printf("Type::unSharedOf() %p, %s\n", this, toChars()); Type t = this; if (isShared()) { if (isWild()) { if (isConst()) t = wcto; // shared wild const => wild const else t = wto; // shared wild => wild } else { if (isConst()) t = cto; // shared const => const else t = sto; // shared => naked } assert(!t || !t.isShared()); } if (!t) { t = this.nullAttributes(); t.mod = mod & ~MODFlags.shared_; t.ctype = ctype; t = t.merge(); t.fixTo(this); } else t = t.merge(); assert(!t.isShared()); return t; } /******************************** * Convert to 'wild'. */ final Type wildOf() { //printf("Type::wildOf() %p %s\n", this, toChars()); if (mod == MODFlags.wild) return this; if (wto) { assert(wto.mod == MODFlags.wild); return wto; } Type t = makeWild(); t = t.merge(); t.fixTo(this); //printf("\t%p %s\n", t, t.toChars()); return t; } final Type wildConstOf() { //printf("Type::wildConstOf() %p %s\n", this, toChars()); if (mod == MODFlags.wildconst) return this; if (wcto) { assert(wcto.mod == MODFlags.wildconst); return wcto; } Type t = makeWildConst(); t = t.merge(); t.fixTo(this); //printf("\t%p %s\n", t, t.toChars()); return t; } final Type sharedWildOf() { //printf("Type::sharedWildOf() %p, %s\n", this, toChars()); if (mod == (MODFlags.shared_ | MODFlags.wild)) return this; if (swto) { assert(swto.mod == (MODFlags.shared_ | MODFlags.wild)); return swto; } Type t = makeSharedWild(); t = t.merge(); t.fixTo(this); //printf("\t%p %s\n", t, t.toChars()); return t; } final Type sharedWildConstOf() { //printf("Type::sharedWildConstOf() %p, %s\n", this, toChars()); if (mod == (MODFlags.shared_ | MODFlags.wildconst)) return this; if (swcto) { assert(swcto.mod == (MODFlags.shared_ | MODFlags.wildconst)); return swcto; } Type t = makeSharedWildConst(); t = t.merge(); t.fixTo(this); //printf("\t%p %s\n", t, t.toChars()); return t; } /********************************** * For our new type 'this', which is type-constructed from t, * fill in the cto, ito, sto, scto, wto shortcuts. */ final void fixTo(Type t) { // If fixing this: immutable(T*) by t: immutable(T)*, // cache t to this.xto won't break transitivity. Type mto = null; Type tn = nextOf(); if (!tn || ty != Tsarray && tn.mod == t.nextOf().mod) { switch (t.mod) { case 0: mto = t; break; case MODFlags.const_: cto = t; break; case MODFlags.wild: wto = t; break; case MODFlags.wildconst: wcto = t; break; case MODFlags.shared_: sto = t; break; case MODFlags.shared_ | MODFlags.const_: scto = t; break; case MODFlags.shared_ | MODFlags.wild: swto = t; break; case MODFlags.shared_ | MODFlags.wildconst: swcto = t; break; case MODFlags.immutable_: ito = t; break; default: break; } } assert(mod != t.mod); auto X(T, U)(T m, U n) { return ((m << 4) | n); } switch (mod) { case 0: break; case MODFlags.const_: cto = mto; t.cto = this; break; case MODFlags.wild: wto = mto; t.wto = this; break; case MODFlags.wildconst: wcto = mto; t.wcto = this; break; case MODFlags.shared_: sto = mto; t.sto = this; break; case MODFlags.shared_ | MODFlags.const_: scto = mto; t.scto = this; break; case MODFlags.shared_ | MODFlags.wild: swto = mto; t.swto = this; break; case MODFlags.shared_ | MODFlags.wildconst: swcto = mto; t.swcto = this; break; case MODFlags.immutable_: t.ito = this; if (t.cto) t.cto.ito = this; if (t.sto) t.sto.ito = this; if (t.scto) t.scto.ito = this; if (t.wto) t.wto.ito = this; if (t.wcto) t.wcto.ito = this; if (t.swto) t.swto.ito = this; if (t.swcto) t.swcto.ito = this; break; default: assert(0); } check(); t.check(); //printf("fixTo: %s, %s\n", toChars(), t.toChars()); } /*************************** * Look for bugs in constructing types. */ final void check() { switch (mod) { case 0: if (cto) assert(cto.mod == MODFlags.const_); if (ito) assert(ito.mod == MODFlags.immutable_); if (sto) assert(sto.mod == MODFlags.shared_); if (scto) assert(scto.mod == (MODFlags.shared_ | MODFlags.const_)); if (wto) assert(wto.mod == MODFlags.wild); if (wcto) assert(wcto.mod == MODFlags.wildconst); if (swto) assert(swto.mod == (MODFlags.shared_ | MODFlags.wild)); if (swcto) assert(swcto.mod == (MODFlags.shared_ | MODFlags.wildconst)); break; case MODFlags.const_: if (cto) assert(cto.mod == 0); if (ito) assert(ito.mod == MODFlags.immutable_); if (sto) assert(sto.mod == MODFlags.shared_); if (scto) assert(scto.mod == (MODFlags.shared_ | MODFlags.const_)); if (wto) assert(wto.mod == MODFlags.wild); if (wcto) assert(wcto.mod == MODFlags.wildconst); if (swto) assert(swto.mod == (MODFlags.shared_ | MODFlags.wild)); if (swcto) assert(swcto.mod == (MODFlags.shared_ | MODFlags.wildconst)); break; case MODFlags.wild: if (cto) assert(cto.mod == MODFlags.const_); if (ito) assert(ito.mod == MODFlags.immutable_); if (sto) assert(sto.mod == MODFlags.shared_); if (scto) assert(scto.mod == (MODFlags.shared_ | MODFlags.const_)); if (wto) assert(wto.mod == 0); if (wcto) assert(wcto.mod == MODFlags.wildconst); if (swto) assert(swto.mod == (MODFlags.shared_ | MODFlags.wild)); if (swcto) assert(swcto.mod == (MODFlags.shared_ | MODFlags.wildconst)); break; case MODFlags.wildconst: assert(!cto || cto.mod == MODFlags.const_); assert(!ito || ito.mod == MODFlags.immutable_); assert(!sto || sto.mod == MODFlags.shared_); assert(!scto || scto.mod == (MODFlags.shared_ | MODFlags.const_)); assert(!wto || wto.mod == MODFlags.wild); assert(!wcto || wcto.mod == 0); assert(!swto || swto.mod == (MODFlags.shared_ | MODFlags.wild)); assert(!swcto || swcto.mod == (MODFlags.shared_ | MODFlags.wildconst)); break; case MODFlags.shared_: if (cto) assert(cto.mod == MODFlags.const_); if (ito) assert(ito.mod == MODFlags.immutable_); if (sto) assert(sto.mod == 0); if (scto) assert(scto.mod == (MODFlags.shared_ | MODFlags.const_)); if (wto) assert(wto.mod == MODFlags.wild); if (wcto) assert(wcto.mod == MODFlags.wildconst); if (swto) assert(swto.mod == (MODFlags.shared_ | MODFlags.wild)); if (swcto) assert(swcto.mod == (MODFlags.shared_ | MODFlags.wildconst)); break; case MODFlags.shared_ | MODFlags.const_: if (cto) assert(cto.mod == MODFlags.const_); if (ito) assert(ito.mod == MODFlags.immutable_); if (sto) assert(sto.mod == MODFlags.shared_); if (scto) assert(scto.mod == 0); if (wto) assert(wto.mod == MODFlags.wild); if (wcto) assert(wcto.mod == MODFlags.wildconst); if (swto) assert(swto.mod == (MODFlags.shared_ | MODFlags.wild)); if (swcto) assert(swcto.mod == (MODFlags.shared_ | MODFlags.wildconst)); break; case MODFlags.shared_ | MODFlags.wild: if (cto) assert(cto.mod == MODFlags.const_); if (ito) assert(ito.mod == MODFlags.immutable_); if (sto) assert(sto.mod == MODFlags.shared_); if (scto) assert(scto.mod == (MODFlags.shared_ | MODFlags.const_)); if (wto) assert(wto.mod == MODFlags.wild); if (wcto) assert(wcto.mod == MODFlags.wildconst); if (swto) assert(swto.mod == 0); if (swcto) assert(swcto.mod == (MODFlags.shared_ | MODFlags.wildconst)); break; case MODFlags.shared_ | MODFlags.wildconst: assert(!cto || cto.mod == MODFlags.const_); assert(!ito || ito.mod == MODFlags.immutable_); assert(!sto || sto.mod == MODFlags.shared_); assert(!scto || scto.mod == (MODFlags.shared_ | MODFlags.const_)); assert(!wto || wto.mod == MODFlags.wild); assert(!wcto || wcto.mod == MODFlags.wildconst); assert(!swto || swto.mod == (MODFlags.shared_ | MODFlags.wild)); assert(!swcto || swcto.mod == 0); break; case MODFlags.immutable_: if (cto) assert(cto.mod == MODFlags.const_); if (ito) assert(ito.mod == 0); if (sto) assert(sto.mod == MODFlags.shared_); if (scto) assert(scto.mod == (MODFlags.shared_ | MODFlags.const_)); if (wto) assert(wto.mod == MODFlags.wild); if (wcto) assert(wcto.mod == MODFlags.wildconst); if (swto) assert(swto.mod == (MODFlags.shared_ | MODFlags.wild)); if (swcto) assert(swcto.mod == (MODFlags.shared_ | MODFlags.wildconst)); break; default: assert(0); } Type tn = nextOf(); if (tn && ty != Tfunction && tn.ty != Tfunction && ty != Tenum) { // Verify transitivity switch (mod) { case 0: case MODFlags.const_: case MODFlags.wild: case MODFlags.wildconst: case MODFlags.shared_: case MODFlags.shared_ | MODFlags.const_: case MODFlags.shared_ | MODFlags.wild: case MODFlags.shared_ | MODFlags.wildconst: case MODFlags.immutable_: assert(tn.mod == MODFlags.immutable_ || (tn.mod & mod) == mod); break; default: assert(0); } tn.check(); } } /************************************* * Apply STCxxxx bits to existing type. * Use *before* semantic analysis is run. */ final Type addSTC(StorageClass stc) { Type t = this; if (t.isImmutable()) { } else if (stc & STC.immutable_) { t = t.makeImmutable(); } else { if ((stc & STC.shared_) && !t.isShared()) { if (t.isWild()) { if (t.isConst()) t = t.makeSharedWildConst(); else t = t.makeSharedWild(); } else { if (t.isConst()) t = t.makeSharedConst(); else t = t.makeShared(); } } if ((stc & STC.const_) && !t.isConst()) { if (t.isShared()) { if (t.isWild()) t = t.makeSharedWildConst(); else t = t.makeSharedConst(); } else { if (t.isWild()) t = t.makeWildConst(); else t = t.makeConst(); } } if ((stc & STC.wild) && !t.isWild()) { if (t.isShared()) { if (t.isConst()) t = t.makeSharedWildConst(); else t = t.makeSharedWild(); } else { if (t.isConst()) t = t.makeWildConst(); else t = t.makeWild(); } } } return t; } /************************************ * Apply MODxxxx bits to existing type. */ final Type castMod(MOD mod) { Type t; switch (mod) { case 0: t = unSharedOf().mutableOf(); break; case MODFlags.const_: t = unSharedOf().constOf(); break; case MODFlags.wild: t = unSharedOf().wildOf(); break; case MODFlags.wildconst: t = unSharedOf().wildConstOf(); break; case MODFlags.shared_: t = mutableOf().sharedOf(); break; case MODFlags.shared_ | MODFlags.const_: t = sharedConstOf(); break; case MODFlags.shared_ | MODFlags.wild: t = sharedWildOf(); break; case MODFlags.shared_ | MODFlags.wildconst: t = sharedWildConstOf(); break; case MODFlags.immutable_: t = immutableOf(); break; default: assert(0); } return t; } /************************************ * Add MODxxxx bits to existing type. * We're adding, not replacing, so adding const to * a shared type => "shared const" */ final Type addMod(MOD mod) { /* Add anything to immutable, and it remains immutable */ Type t = this; if (!t.isImmutable()) { //printf("addMod(%x) %s\n", mod, toChars()); switch (mod) { case 0: break; case MODFlags.const_: if (isShared()) { if (isWild()) t = sharedWildConstOf(); else t = sharedConstOf(); } else { if (isWild()) t = wildConstOf(); else t = constOf(); } break; case MODFlags.wild: if (isShared()) { if (isConst()) t = sharedWildConstOf(); else t = sharedWildOf(); } else { if (isConst()) t = wildConstOf(); else t = wildOf(); } break; case MODFlags.wildconst: if (isShared()) t = sharedWildConstOf(); else t = wildConstOf(); break; case MODFlags.shared_: if (isWild()) { if (isConst()) t = sharedWildConstOf(); else t = sharedWildOf(); } else { if (isConst()) t = sharedConstOf(); else t = sharedOf(); } break; case MODFlags.shared_ | MODFlags.const_: if (isWild()) t = sharedWildConstOf(); else t = sharedConstOf(); break; case MODFlags.shared_ | MODFlags.wild: if (isConst()) t = sharedWildConstOf(); else t = sharedWildOf(); break; case MODFlags.shared_ | MODFlags.wildconst: t = sharedWildConstOf(); break; case MODFlags.immutable_: t = immutableOf(); break; default: assert(0); } } return t; } /************************************ * Add storage class modifiers to type. */ Type addStorageClass(StorageClass stc) { /* Just translate to MOD bits and let addMod() do the work */ MOD mod = 0; if (stc & STC.immutable_) mod = MODFlags.immutable_; else { if (stc & (STC.const_ | STC.in_)) mod |= MODFlags.const_; if (stc & STC.wild) mod |= MODFlags.wild; if (stc & STC.shared_) mod |= MODFlags.shared_; } return addMod(mod); } final Type pointerTo() { if (ty == Terror) return this; if (!pto) { Type t = new TypePointer(this); if (ty == Tfunction) { t.deco = t.merge().deco; pto = t; } else pto = t.merge(); } return pto; } final Type referenceTo() { if (ty == Terror) return this; if (!rto) { Type t = new TypeReference(this); rto = t.merge(); } return rto; } final Type arrayOf() { if (ty == Terror) return this; if (!arrayof) { Type t = new TypeDArray(this); arrayof = t.merge(); } return arrayof; } // Make corresponding static array type without semantic final Type sarrayOf(dinteger_t dim) { assert(deco); Type t = new TypeSArray(this, new IntegerExp(Loc.initial, dim, Type.tsize_t)); // according to TypeSArray::semantic() t = t.addMod(mod); t = t.merge(); return t; } final Type aliasthisOf() { auto ad = isAggregate(this); if (!ad || !ad.aliasthis) return null; auto s = ad.aliasthis; if (s.isAliasDeclaration()) s = s.toAlias(); if (s.isTupleDeclaration()) return null; if (auto vd = s.isVarDeclaration()) { auto t = vd.type; if (vd.needThis()) t = t.addMod(this.mod); return t; } if (auto fd = s.isFuncDeclaration()) { fd = resolveFuncCall(Loc.initial, null, fd, null, this, null, 1); if (!fd || fd.errors || !fd.functionSemantic()) return Type.terror; auto t = fd.type.nextOf(); if (!t) // issue 14185 return Type.terror; t = t.substWildTo(mod == 0 ? MODFlags.mutable : mod); return t; } if (auto d = s.isDeclaration()) { assert(d.type); return d.type; } if (auto ed = s.isEnumDeclaration()) { return ed.type; } if (auto td = s.isTemplateDeclaration()) { assert(td._scope); auto fd = resolveFuncCall(Loc.initial, null, td, null, this, null, 1); if (!fd || fd.errors || !fd.functionSemantic()) return Type.terror; auto t = fd.type.nextOf(); if (!t) return Type.terror; t = t.substWildTo(mod == 0 ? MODFlags.mutable : mod); return t; } //printf("%s\n", s.kind()); return null; } final bool checkAliasThisRec() { Type tb = toBasetype(); AliasThisRec* pflag; if (tb.ty == Tstruct) pflag = &(cast(TypeStruct)tb).att; else if (tb.ty == Tclass) pflag = &(cast(TypeClass)tb).att; else return false; AliasThisRec flag = cast(AliasThisRec)(*pflag & AliasThisRec.typeMask); if (flag == AliasThisRec.fwdref) { Type att = aliasthisOf(); flag = att && att.implicitConvTo(this) ? AliasThisRec.yes : AliasThisRec.no; } *pflag = cast(AliasThisRec)(flag | (*pflag & ~AliasThisRec.typeMask)); return flag == AliasThisRec.yes; } Type makeConst() { //printf("Type::makeConst() %p, %s\n", this, toChars()); if (cto) return cto; Type t = this.nullAttributes(); t.mod = MODFlags.const_; //printf("-Type::makeConst() %p, %s\n", t, toChars()); return t; } Type makeImmutable() { if (ito) return ito; Type t = this.nullAttributes(); t.mod = MODFlags.immutable_; return t; } Type makeShared() { if (sto) return sto; Type t = this.nullAttributes(); t.mod = MODFlags.shared_; return t; } Type makeSharedConst() { if (scto) return scto; Type t = this.nullAttributes(); t.mod = MODFlags.shared_ | MODFlags.const_; return t; } Type makeWild() { if (wto) return wto; Type t = this.nullAttributes(); t.mod = MODFlags.wild; return t; } Type makeWildConst() { if (wcto) return wcto; Type t = this.nullAttributes(); t.mod = MODFlags.wildconst; return t; } Type makeSharedWild() { if (swto) return swto; Type t = this.nullAttributes(); t.mod = MODFlags.shared_ | MODFlags.wild; return t; } Type makeSharedWildConst() { if (swcto) return swcto; Type t = this.nullAttributes(); t.mod = MODFlags.shared_ | MODFlags.wildconst; return t; } Type makeMutable() { Type t = this.nullAttributes(); t.mod = mod & MODFlags.shared_; return t; } Dsymbol toDsymbol(Scope* sc) { return null; } /******************************* * If this is a shell around another type, * get that other type. */ Type toBasetype() { return this; } bool isBaseOf(Type t, int* poffset) { return 0; // assume not } /******************************** * Determine if 'this' can be implicitly converted * to type 'to'. * Returns: * MATCH.nomatch, MATCH.convert, MATCH.constant, MATCH.exact */ MATCH implicitConvTo(Type to) { //printf("Type::implicitConvTo(this=%p, to=%p)\n", this, to); //printf("from: %s\n", toChars()); //printf("to : %s\n", to.toChars()); if (this.equals(to)) return MATCH.exact; return MATCH.nomatch; } /******************************* * Determine if converting 'this' to 'to' is an identity operation, * a conversion to const operation, or the types aren't the same. * Returns: * MATCH.exact 'this' == 'to' * MATCH.constant 'to' is const * MATCH.nomatch conversion to mutable or invariant */ MATCH constConv(Type to) { //printf("Type::constConv(this = %s, to = %s)\n", toChars(), to.toChars()); if (equals(to)) return MATCH.exact; if (ty == to.ty && MODimplicitConv(mod, to.mod)) return MATCH.constant; return MATCH.nomatch; } /*************************************** * Return MOD bits matching this type to wild parameter type (tprm). */ ubyte deduceWild(Type t, bool isRef) { //printf("Type::deduceWild this = '%s', tprm = '%s'\n", toChars(), tprm.toChars()); if (t.isWild()) { if (isImmutable()) return MODFlags.immutable_; else if (isWildConst()) { if (t.isWildConst()) return MODFlags.wild; else return MODFlags.wildconst; } else if (isWild()) return MODFlags.wild; else if (isConst()) return MODFlags.const_; else if (isMutable()) return MODFlags.mutable; else assert(0); } return 0; } Type substWildTo(uint mod) { //printf("+Type::substWildTo this = %s, mod = x%x\n", toChars(), mod); Type t; if (Type tn = nextOf()) { // substitution has no effect on function pointer type. if (ty == Tpointer && tn.ty == Tfunction) { t = this; goto L1; } t = tn.substWildTo(mod); if (t == tn) t = this; else { if (ty == Tpointer) t = t.pointerTo(); else if (ty == Tarray) t = t.arrayOf(); else if (ty == Tsarray) t = new TypeSArray(t, (cast(TypeSArray)this).dim.syntaxCopy()); else if (ty == Taarray) { t = new TypeAArray(t, (cast(TypeAArray)this).index.syntaxCopy()); (cast(TypeAArray)t).sc = (cast(TypeAArray)this).sc; // duplicate scope } else if (ty == Tdelegate) { t = new TypeDelegate(t); } else assert(0); t = t.merge(); } } else t = this; L1: if (isWild()) { if (mod == MODFlags.immutable_) { t = t.immutableOf(); } else if (mod == MODFlags.wildconst) { t = t.wildConstOf(); } else if (mod == MODFlags.wild) { if (isWildConst()) t = t.wildConstOf(); else t = t.wildOf(); } else if (mod == MODFlags.const_) { t = t.constOf(); } else { if (isWildConst()) t = t.constOf(); else t = t.mutableOf(); } } if (isConst()) t = t.addMod(MODFlags.const_); if (isShared()) t = t.addMod(MODFlags.shared_); //printf("-Type::substWildTo t = %s\n", t.toChars()); return t; } final Type unqualify(uint m) { Type t = mutableOf().unSharedOf(); Type tn = ty == Tenum ? null : nextOf(); if (tn && tn.ty != Tfunction) { Type utn = tn.unqualify(m); if (utn != tn) { if (ty == Tpointer) t = utn.pointerTo(); else if (ty == Tarray) t = utn.arrayOf(); else if (ty == Tsarray) t = new TypeSArray(utn, (cast(TypeSArray)this).dim); else if (ty == Taarray) { t = new TypeAArray(utn, (cast(TypeAArray)this).index); (cast(TypeAArray)t).sc = (cast(TypeAArray)this).sc; // duplicate scope } else assert(0); t = t.merge(); } } t = t.addMod(mod & ~m); return t; } /************************** * Return type with the top level of it being mutable. */ Type toHeadMutable() { if (!mod) return this; return mutableOf(); } ClassDeclaration isClassHandle() { return null; } /**************** * dotExp() bit flags */ enum DotExpFlag { gag = 1, // don't report "not a property" error and just return null noDeref = 2, // the use of the expression will not attempt a dereference } /************************************ * Return alignment to use for this type. */ structalign_t alignment() { return STRUCTALIGN_DEFAULT; } Expression defaultInit(const ref Loc loc) { static if (LOGDEFAULTINIT) { printf("Type::defaultInit() '%s'\n", toChars()); } return null; } /*************************************** * Use when we prefer the default initializer to be a literal, * rather than a global immutable variable. */ Expression defaultInitLiteral(const ref Loc loc) { static if (LOGDEFAULTINIT) { printf("Type::defaultInitLiteral() '%s'\n", toChars()); } return defaultInit(loc); } // if initializer is 0 bool isZeroInit(const ref Loc loc) { return false; // assume not } final Identifier getTypeInfoIdent() { // _init_10TypeInfo_%s OutBuffer buf; buf.reserve(32); mangleToBuffer(this, &buf); const slice = buf.peekSlice(); // Allocate buffer on stack, fail over to using malloc() char[128] namebuf; const namelen = 19 + size_t.sizeof * 3 + slice.length + 1; auto name = namelen <= namebuf.length ? namebuf.ptr : cast(char*)malloc(namelen); assert(name); const length = sprintf(name, "_D%lluTypeInfo_%.*s6__initZ", cast(ulong)(9 + slice.length), cast(int)slice.length, slice.ptr); //printf("%p %s, deco = %s, name = %s\n", this, toChars(), deco, name); assert(0 < length && length < namelen); // don't overflow the buffer auto id = Identifier.idPool(name, length); if (name != namebuf.ptr) free(name); return id; } /*************************************** * Normalize `e` as the result of Type.resolve() process. */ final void resolveExp(Expression e, Type *pt, Expression *pe, Dsymbol* ps) { *pt = null; *pe = null; *ps = null; Dsymbol s; switch (e.op) { case TOK.error: *pt = Type.terror; return; case TOK.type: *pt = e.type; return; case TOK.variable: s = (cast(VarExp)e).var; if (s.isVarDeclaration()) goto default; //if (s.isOverDeclaration()) // todo; break; case TOK.template_: // TemplateDeclaration s = (cast(TemplateExp)e).td; break; case TOK.scope_: s = (cast(ScopeExp)e).sds; // TemplateDeclaration, TemplateInstance, Import, Package, Module break; case TOK.function_: s = getDsymbol(e); break; case TOK.dotTemplateDeclaration: s = (cast(DotTemplateExp)e).td; break; //case TOK.this_: //case TOK.super_: //case TOK.tuple: //case TOK.overloadSet: //case TOK.dotVariable: //case TOK.dotTemplateInstance: //case TOK.dotType: //case TOK.dotIdentifier: default: *pe = e; return; } *ps = s; } /*************************************** * Return !=0 if the type or any of its subtypes is wild. */ int hasWild() const { return mod & MODFlags.wild; } /*************************************** * Return !=0 if type has pointers that need to * be scanned by the GC during a collection cycle. */ bool hasPointers() { //printf("Type::hasPointers() %s, %d\n", toChars(), ty); return false; } /************************************* * Detect if type has pointer fields that are initialized to void. * Local stack variables with such void fields can remain uninitialized, * leading to pointer bugs. * Returns: * true if so */ bool hasVoidInitPointers() { return false; } /************************************* * If this is a type of something, return that something. */ Type nextOf() { return null; } /************************************* * If this is a type of static array, return its base element type. */ final Type baseElemOf() { Type t = toBasetype(); while (t.ty == Tsarray) t = (cast(TypeSArray)t).next.toBasetype(); return t; } /**************************************** * Return the mask that an integral type will * fit into. */ final uinteger_t sizemask() { uinteger_t m; switch (toBasetype().ty) { case Tbool: m = 1; break; case Tchar: case Tint8: case Tuns8: m = 0xFF; break; case Twchar: case Tint16: case Tuns16: m = 0xFFFFU; break; case Tdchar: case Tint32: case Tuns32: m = 0xFFFFFFFFU; break; case Tint64: case Tuns64: m = 0xFFFFFFFFFFFFFFFFUL; break; default: assert(0); } return m; } /******************************** * true if when type goes out of scope, it needs a destructor applied. * Only applies to value types, not ref types. */ bool needsDestruction() { return false; } /********************************* * */ bool needsNested() { return false; } /************************************* * https://issues.dlang.org/show_bug.cgi?id=14488 * Check if the inner most base type is complex or imaginary. * Should only give alerts when set to emit transitional messages. * Params: * loc = The source location. * sc = scope of the type */ final bool checkComplexTransition(const ref Loc loc, Scope* sc) { if (sc.isDeprecated()) return false; Type t = baseElemOf(); while (t.ty == Tpointer || t.ty == Tarray) t = t.nextOf().baseElemOf(); // Basetype is an opaque enum, nothing to check. if (t.ty == Tenum && !(cast(TypeEnum)t).sym.memtype) return false; if (t.isimaginary() || t.iscomplex()) { Type rt; switch (t.ty) { case Tcomplex32: case Timaginary32: rt = Type.tfloat32; break; case Tcomplex64: case Timaginary64: rt = Type.tfloat64; break; case Tcomplex80: case Timaginary80: rt = Type.tfloat80; break; default: assert(0); } if (t.iscomplex()) { deprecation(loc, "use of complex type `%s` is deprecated, use `std.complex.Complex!(%s)` instead", toChars(), rt.toChars()); return true; } else { deprecation(loc, "use of imaginary type `%s` is deprecated, use `%s` instead", toChars(), rt.toChars()); return true; } } return false; } static void error(const ref Loc loc, const(char)* format, ...) { va_list ap; va_start(ap, format); .verror(loc, format, ap); va_end(ap); } static void warning(const ref Loc loc, const(char)* format, ...) { va_list ap; va_start(ap, format); .vwarning(loc, format, ap); va_end(ap); } // For eliminating dynamic_cast TypeBasic isTypeBasic() { return null; } void accept(Visitor v) { v.visit(this); } final TypeFunction toTypeFunction() { if (ty != Tfunction) assert(0); return cast(TypeFunction)this; } } /*********************************************************** */ extern (C++) final class TypeError : Type { extern (D) this() { super(Terror); } override Type syntaxCopy() { // No semantic analysis done, no need to copy return this; } override d_uns64 size(const ref Loc loc) { return SIZE_INVALID; } override Expression defaultInit(const ref Loc loc) { return new ErrorExp(); } override Expression defaultInitLiteral(const ref Loc loc) { return new ErrorExp(); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) abstract class TypeNext : Type { Type next; final extern (D) this(TY ty, Type next) { super(ty); this.next = next; } override final void checkDeprecated(const ref Loc loc, Scope* sc) { Type.checkDeprecated(loc, sc); if (next) // next can be NULL if TypeFunction and auto return type next.checkDeprecated(loc, sc); } override final int hasWild() const { if (ty == Tfunction) return 0; if (ty == Tdelegate) return Type.hasWild(); return mod & MODFlags.wild || (next && next.hasWild()); } /******************************* * For TypeFunction, nextOf() can return NULL if the function return * type is meant to be inferred, and semantic() hasn't yet ben run * on the function. After semantic(), it must no longer be NULL. */ override final Type nextOf() { return next; } override final Type makeConst() { //printf("TypeNext::makeConst() %p, %s\n", this, toChars()); if (cto) { assert(cto.mod == MODFlags.const_); return cto; } TypeNext t = cast(TypeNext)Type.makeConst(); if (ty != Tfunction && next.ty != Tfunction && !next.isImmutable()) { if (next.isShared()) { if (next.isWild()) t.next = next.sharedWildConstOf(); else t.next = next.sharedConstOf(); } else { if (next.isWild()) t.next = next.wildConstOf(); else t.next = next.constOf(); } } //printf("TypeNext::makeConst() returns %p, %s\n", t, t.toChars()); return t; } override final Type makeImmutable() { //printf("TypeNext::makeImmutable() %s\n", toChars()); if (ito) { assert(ito.isImmutable()); return ito; } TypeNext t = cast(TypeNext)Type.makeImmutable(); if (ty != Tfunction && next.ty != Tfunction && !next.isImmutable()) { t.next = next.immutableOf(); } return t; } override final Type makeShared() { //printf("TypeNext::makeShared() %s\n", toChars()); if (sto) { assert(sto.mod == MODFlags.shared_); return sto; } TypeNext t = cast(TypeNext)Type.makeShared(); if (ty != Tfunction && next.ty != Tfunction && !next.isImmutable()) { if (next.isWild()) { if (next.isConst()) t.next = next.sharedWildConstOf(); else t.next = next.sharedWildOf(); } else { if (next.isConst()) t.next = next.sharedConstOf(); else t.next = next.sharedOf(); } } //printf("TypeNext::makeShared() returns %p, %s\n", t, t.toChars()); return t; } override final Type makeSharedConst() { //printf("TypeNext::makeSharedConst() %s\n", toChars()); if (scto) { assert(scto.mod == (MODFlags.shared_ | MODFlags.const_)); return scto; } TypeNext t = cast(TypeNext)Type.makeSharedConst(); if (ty != Tfunction && next.ty != Tfunction && !next.isImmutable()) { if (next.isWild()) t.next = next.sharedWildConstOf(); else t.next = next.sharedConstOf(); } //printf("TypeNext::makeSharedConst() returns %p, %s\n", t, t.toChars()); return t; } override final Type makeWild() { //printf("TypeNext::makeWild() %s\n", toChars()); if (wto) { assert(wto.mod == MODFlags.wild); return wto; } TypeNext t = cast(TypeNext)Type.makeWild(); if (ty != Tfunction && next.ty != Tfunction && !next.isImmutable()) { if (next.isShared()) { if (next.isConst()) t.next = next.sharedWildConstOf(); else t.next = next.sharedWildOf(); } else { if (next.isConst()) t.next = next.wildConstOf(); else t.next = next.wildOf(); } } //printf("TypeNext::makeWild() returns %p, %s\n", t, t.toChars()); return t; } override final Type makeWildConst() { //printf("TypeNext::makeWildConst() %s\n", toChars()); if (wcto) { assert(wcto.mod == MODFlags.wildconst); return wcto; } TypeNext t = cast(TypeNext)Type.makeWildConst(); if (ty != Tfunction && next.ty != Tfunction && !next.isImmutable()) { if (next.isShared()) t.next = next.sharedWildConstOf(); else t.next = next.wildConstOf(); } //printf("TypeNext::makeWildConst() returns %p, %s\n", t, t.toChars()); return t; } override final Type makeSharedWild() { //printf("TypeNext::makeSharedWild() %s\n", toChars()); if (swto) { assert(swto.isSharedWild()); return swto; } TypeNext t = cast(TypeNext)Type.makeSharedWild(); if (ty != Tfunction && next.ty != Tfunction && !next.isImmutable()) { if (next.isConst()) t.next = next.sharedWildConstOf(); else t.next = next.sharedWildOf(); } //printf("TypeNext::makeSharedWild() returns %p, %s\n", t, t.toChars()); return t; } override final Type makeSharedWildConst() { //printf("TypeNext::makeSharedWildConst() %s\n", toChars()); if (swcto) { assert(swcto.mod == (MODFlags.shared_ | MODFlags.wildconst)); return swcto; } TypeNext t = cast(TypeNext)Type.makeSharedWildConst(); if (ty != Tfunction && next.ty != Tfunction && !next.isImmutable()) { t.next = next.sharedWildConstOf(); } //printf("TypeNext::makeSharedWildConst() returns %p, %s\n", t, t.toChars()); return t; } override final Type makeMutable() { //printf("TypeNext::makeMutable() %p, %s\n", this, toChars()); TypeNext t = cast(TypeNext)Type.makeMutable(); if (ty == Tsarray) { t.next = next.mutableOf(); } //printf("TypeNext::makeMutable() returns %p, %s\n", t, t.toChars()); return t; } override MATCH constConv(Type to) { //printf("TypeNext::constConv from = %s, to = %s\n", toChars(), to.toChars()); if (equals(to)) return MATCH.exact; if (!(ty == to.ty && MODimplicitConv(mod, to.mod))) return MATCH.nomatch; Type tn = to.nextOf(); if (!(tn && next.ty == tn.ty)) return MATCH.nomatch; MATCH m; if (to.isConst()) // whole tail const conversion { // Recursive shared level check m = next.constConv(tn); if (m == MATCH.exact) m = MATCH.constant; } else { //printf("\tnext => %s, to.next => %s\n", next.toChars(), tn.toChars()); m = next.equals(tn) ? MATCH.constant : MATCH.nomatch; } return m; } override final ubyte deduceWild(Type t, bool isRef) { if (ty == Tfunction) return 0; ubyte wm; Type tn = t.nextOf(); if (!isRef && (ty == Tarray || ty == Tpointer) && tn) { wm = next.deduceWild(tn, true); if (!wm) wm = Type.deduceWild(t, true); } else { wm = Type.deduceWild(t, isRef); if (!wm && tn) wm = next.deduceWild(tn, true); } return wm; } final void transitive() { /* Invoke transitivity of type attributes */ next = next.addMod(mod); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class TypeBasic : Type { const(char)* dstring; uint flags; extern (D) this(TY ty) { super(ty); const(char)* d; uint flags = 0; switch (ty) { case Tvoid: d = Token.toChars(TOK.void_); break; case Tint8: d = Token.toChars(TOK.int8); flags |= TFlags.integral; break; case Tuns8: d = Token.toChars(TOK.uns8); flags |= TFlags.integral | TFlags.unsigned; break; case Tint16: d = Token.toChars(TOK.int16); flags |= TFlags.integral; break; case Tuns16: d = Token.toChars(TOK.uns16); flags |= TFlags.integral | TFlags.unsigned; break; case Tint32: d = Token.toChars(TOK.int32); flags |= TFlags.integral; break; case Tuns32: d = Token.toChars(TOK.uns32); flags |= TFlags.integral | TFlags.unsigned; break; case Tfloat32: d = Token.toChars(TOK.float32); flags |= TFlags.floating | TFlags.real_; break; case Tint64: d = Token.toChars(TOK.int64); flags |= TFlags.integral; break; case Tuns64: d = Token.toChars(TOK.uns64); flags |= TFlags.integral | TFlags.unsigned; break; case Tint128: d = Token.toChars(TOK.int128); flags |= TFlags.integral; break; case Tuns128: d = Token.toChars(TOK.uns128); flags |= TFlags.integral | TFlags.unsigned; break; case Tfloat64: d = Token.toChars(TOK.float64); flags |= TFlags.floating | TFlags.real_; break; case Tfloat80: d = Token.toChars(TOK.float80); flags |= TFlags.floating | TFlags.real_; break; case Timaginary32: d = Token.toChars(TOK.imaginary32); flags |= TFlags.floating | TFlags.imaginary; break; case Timaginary64: d = Token.toChars(TOK.imaginary64); flags |= TFlags.floating | TFlags.imaginary; break; case Timaginary80: d = Token.toChars(TOK.imaginary80); flags |= TFlags.floating | TFlags.imaginary; break; case Tcomplex32: d = Token.toChars(TOK.complex32); flags |= TFlags.floating | TFlags.complex; break; case Tcomplex64: d = Token.toChars(TOK.complex64); flags |= TFlags.floating | TFlags.complex; break; case Tcomplex80: d = Token.toChars(TOK.complex80); flags |= TFlags.floating | TFlags.complex; break; case Tbool: d = "bool"; flags |= TFlags.integral | TFlags.unsigned; break; case Tchar: d = Token.toChars(TOK.char_); flags |= TFlags.integral | TFlags.unsigned; break; case Twchar: d = Token.toChars(TOK.wchar_); flags |= TFlags.integral | TFlags.unsigned; break; case Tdchar: d = Token.toChars(TOK.dchar_); flags |= TFlags.integral | TFlags.unsigned; break; default: assert(0); } this.dstring = d; this.flags = flags; merge(this); } override const(char)* kind() const { return dstring; } override Type syntaxCopy() { // No semantic analysis done on basic types, no need to copy return this; } override d_uns64 size(const ref Loc loc) const { uint size; //printf("TypeBasic::size()\n"); switch (ty) { case Tint8: case Tuns8: size = 1; break; case Tint16: case Tuns16: size = 2; break; case Tint32: case Tuns32: case Tfloat32: case Timaginary32: size = 4; break; case Tint64: case Tuns64: case Tfloat64: case Timaginary64: size = 8; break; case Tfloat80: case Timaginary80: size = Target.realsize; break; case Tcomplex32: size = 8; break; case Tcomplex64: case Tint128: case Tuns128: size = 16; break; case Tcomplex80: size = Target.realsize * 2; break; case Tvoid: //size = Type::size(); // error message size = 1; break; case Tbool: size = 1; break; case Tchar: size = 1; break; case Twchar: size = 2; break; case Tdchar: size = 4; break; default: assert(0); } //printf("TypeBasic::size() = %d\n", size); return size; } override uint alignsize() { return Target.alignsize(this); } override bool isintegral() { //printf("TypeBasic::isintegral('%s') x%x\n", toChars(), flags); return (flags & TFlags.integral) != 0; } override bool isfloating() const { return (flags & TFlags.floating) != 0; } override bool isreal() const { return (flags & TFlags.real_) != 0; } override bool isimaginary() const { return (flags & TFlags.imaginary) != 0; } override bool iscomplex() const { return (flags & TFlags.complex) != 0; } override bool isscalar() const { return (flags & (TFlags.integral | TFlags.floating)) != 0; } override bool isunsigned() const { return (flags & TFlags.unsigned) != 0; } override MATCH implicitConvTo(Type to) { //printf("TypeBasic::implicitConvTo(%s) from %s\n", to.toChars(), toChars()); if (this == to) return MATCH.exact; if (ty == to.ty) { if (mod == to.mod) return MATCH.exact; else if (MODimplicitConv(mod, to.mod)) return MATCH.constant; else if (!((mod ^ to.mod) & MODFlags.shared_)) // for wild matching return MATCH.constant; else return MATCH.convert; } if (ty == Tvoid || to.ty == Tvoid) return MATCH.nomatch; if (to.ty == Tbool) return MATCH.nomatch; TypeBasic tob; if (to.ty == Tvector && to.deco) { TypeVector tv = cast(TypeVector)to; tob = tv.elementType(); } else tob = to.isTypeBasic(); if (!tob) return MATCH.nomatch; if (flags & TFlags.integral) { // Disallow implicit conversion of integers to imaginary or complex if (tob.flags & (TFlags.imaginary | TFlags.complex)) return MATCH.nomatch; // If converting from integral to integral if (tob.flags & TFlags.integral) { d_uns64 sz = size(Loc.initial); d_uns64 tosz = tob.size(Loc.initial); /* Can't convert to smaller size */ if (sz > tosz) return MATCH.nomatch; /* Can't change sign if same size */ //if (sz == tosz && (flags ^ tob.flags) & TFlags.unsigned) // return MATCH.nomatch; } } else if (flags & TFlags.floating) { // Disallow implicit conversion of floating point to integer if (tob.flags & TFlags.integral) return MATCH.nomatch; assert(tob.flags & TFlags.floating || to.ty == Tvector); // Disallow implicit conversion from complex to non-complex if (flags & TFlags.complex && !(tob.flags & TFlags.complex)) return MATCH.nomatch; // Disallow implicit conversion of real or imaginary to complex if (flags & (TFlags.real_ | TFlags.imaginary) && tob.flags & TFlags.complex) return MATCH.nomatch; // Disallow implicit conversion to-from real and imaginary if ((flags & (TFlags.real_ | TFlags.imaginary)) != (tob.flags & (TFlags.real_ | TFlags.imaginary))) return MATCH.nomatch; } return MATCH.convert; } override Expression defaultInit(const ref Loc loc) { static if (LOGDEFAULTINIT) { printf("TypeBasic::defaultInit() '%s'\n", toChars()); } dinteger_t value = 0; switch (ty) { case Tchar: value = 0xFF; break; case Twchar: case Tdchar: value = 0xFFFF; break; case Timaginary32: case Timaginary64: case Timaginary80: case Tfloat32: case Tfloat64: case Tfloat80: return new RealExp(loc, Target.RealProperties.snan, this); case Tcomplex32: case Tcomplex64: case Tcomplex80: { // Can't use fvalue + I*fvalue (the im part becomes a quiet NaN). const cvalue = complex_t(Target.RealProperties.snan, Target.RealProperties.snan); return new ComplexExp(loc, cvalue, this); } case Tvoid: error(loc, "`void` does not have a default initializer"); return new ErrorExp(); default: break; } return new IntegerExp(loc, value, this); } override bool isZeroInit(const ref Loc loc) const { switch (ty) { case Tchar: case Twchar: case Tdchar: case Timaginary32: case Timaginary64: case Timaginary80: case Tfloat32: case Tfloat64: case Tfloat80: case Tcomplex32: case Tcomplex64: case Tcomplex80: return false; // no default: return true; // yes } } // For eliminating dynamic_cast override TypeBasic isTypeBasic() { return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * The basetype must be one of: * byte[16],ubyte[16],short[8],ushort[8],int[4],uint[4],long[2],ulong[2],float[4],double[2] * For AVX: * byte[32],ubyte[32],short[16],ushort[16],int[8],uint[8],long[4],ulong[4],float[8],double[4] */ extern (C++) final class TypeVector : Type { Type basetype; extern (D) this(Type basetype) { super(Tvector); this.basetype = basetype; } static TypeVector create(Type basetype) { return new TypeVector(basetype); } override const(char)* kind() const { return "vector"; } override Type syntaxCopy() { return new TypeVector(basetype.syntaxCopy()); } override d_uns64 size(const ref Loc loc) { return basetype.size(); } override uint alignsize() { return cast(uint)basetype.size(); } override bool isintegral() { //printf("TypeVector::isintegral('%s') x%x\n", toChars(), flags); return basetype.nextOf().isintegral(); } override bool isfloating() { return basetype.nextOf().isfloating(); } override bool isscalar() { return basetype.nextOf().isscalar(); } override bool isunsigned() { return basetype.nextOf().isunsigned(); } override bool isBoolean() const { return false; } override MATCH implicitConvTo(Type to) { //printf("TypeVector::implicitConvTo(%s) from %s\n", to.toChars(), toChars()); if (this == to) return MATCH.exact; if (ty == to.ty) return MATCH.convert; return MATCH.nomatch; } override Expression defaultInit(const ref Loc loc) { //printf("TypeVector::defaultInit()\n"); assert(basetype.ty == Tsarray); Expression e = basetype.defaultInit(loc); auto ve = new VectorExp(loc, e, this); ve.type = this; ve.dim = cast(int)(basetype.size(loc) / elementType().size(loc)); return ve; } override Expression defaultInitLiteral(const ref Loc loc) { //printf("TypeVector::defaultInitLiteral()\n"); assert(basetype.ty == Tsarray); Expression e = basetype.defaultInitLiteral(loc); auto ve = new VectorExp(loc, e, this); ve.type = this; ve.dim = cast(int)(basetype.size(loc) / elementType().size(loc)); return ve; } TypeBasic elementType() { assert(basetype.ty == Tsarray); TypeSArray t = cast(TypeSArray)basetype; TypeBasic tb = t.nextOf().isTypeBasic(); assert(tb); return tb; } override bool isZeroInit(const ref Loc loc) { return basetype.isZeroInit(loc); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) class TypeArray : TypeNext { final extern (D) this(TY ty, Type next) { super(ty, next); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * Static array, one with a fixed dimension */ extern (C++) final class TypeSArray : TypeArray { Expression dim; extern (D) this(Type t, Expression dim) { super(Tsarray, t); //printf("TypeSArray(%s)\n", dim.toChars()); this.dim = dim; } override const(char)* kind() const { return "sarray"; } override Type syntaxCopy() { Type t = next.syntaxCopy(); Expression e = dim.syntaxCopy(); t = new TypeSArray(t, e); t.mod = mod; return t; } override d_uns64 size(const ref Loc loc) { //printf("TypeSArray::size()\n"); dinteger_t sz; if (!dim) return Type.size(loc); sz = dim.toInteger(); { bool overflow = false; sz = mulu(next.size(), sz, overflow); if (overflow) goto Loverflow; } if (sz > uint.max) goto Loverflow; return sz; Loverflow: error(loc, "static array `%s` size overflowed to %lld", toChars(), cast(long)sz); return SIZE_INVALID; } override uint alignsize() { return next.alignsize(); } override bool isString() { TY nty = next.toBasetype().ty; return nty == Tchar || nty == Twchar || nty == Tdchar; } override bool isZeroInit(const ref Loc loc) { return next.isZeroInit(loc); } override structalign_t alignment() { return next.alignment(); } override MATCH constConv(Type to) { if (to.ty == Tsarray) { TypeSArray tsa = cast(TypeSArray)to; if (!dim.equals(tsa.dim)) return MATCH.nomatch; } return TypeNext.constConv(to); } override MATCH implicitConvTo(Type to) { //printf("TypeSArray::implicitConvTo(to = %s) this = %s\n", to.toChars(), toChars()); if (to.ty == Tarray) { TypeDArray ta = cast(TypeDArray)to; if (!MODimplicitConv(next.mod, ta.next.mod)) return MATCH.nomatch; /* Allow conversion to void[] */ if (ta.next.ty == Tvoid) { return MATCH.convert; } MATCH m = next.constConv(ta.next); if (m > MATCH.nomatch) { return MATCH.convert; } return MATCH.nomatch; } if (to.ty == Tsarray) { if (this == to) return MATCH.exact; TypeSArray tsa = cast(TypeSArray)to; if (dim.equals(tsa.dim)) { /* Since static arrays are value types, allow * conversions from const elements to non-const * ones, just like we allow conversion from const int * to int. */ MATCH m = next.implicitConvTo(tsa.next); if (m >= MATCH.constant) { if (mod != to.mod) m = MATCH.constant; return m; } } } return MATCH.nomatch; } override Expression defaultInit(const ref Loc loc) { static if (LOGDEFAULTINIT) { printf("TypeSArray::defaultInit() '%s'\n", toChars()); } if (next.ty == Tvoid) return tuns8.defaultInit(loc); else return next.defaultInit(loc); } override Expression defaultInitLiteral(const ref Loc loc) { static if (LOGDEFAULTINIT) { printf("TypeSArray::defaultInitLiteral() '%s'\n", toChars()); } size_t d = cast(size_t)dim.toInteger(); Expression elementinit; if (next.ty == Tvoid) elementinit = tuns8.defaultInitLiteral(loc); else elementinit = next.defaultInitLiteral(loc); auto elements = new Expressions(); elements.setDim(d); for (size_t i = 0; i < d; i++) (*elements)[i] = null; auto ae = new ArrayLiteralExp(Loc.initial, elementinit, elements); ae.type = this; return ae; } override bool hasPointers() { /* Don't want to do this, because: * struct S { T* array[0]; } * may be a variable length struct. */ //if (dim.toInteger() == 0) // return false; if (next.ty == Tvoid) { // Arrays of void contain arbitrary data, which may include pointers return true; } else return next.hasPointers(); } override bool needsDestruction() { return next.needsDestruction(); } /********************************* * */ override bool needsNested() { return next.needsNested(); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * Dynamic array, no dimension */ extern (C++) final class TypeDArray : TypeArray { extern (D) this(Type t) { super(Tarray, t); //printf("TypeDArray(t = %p)\n", t); } override const(char)* kind() const { return "darray"; } override Type syntaxCopy() { Type t = next.syntaxCopy(); if (t == next) t = this; else { t = new TypeDArray(t); t.mod = mod; } return t; } override d_uns64 size(const ref Loc loc) const { //printf("TypeDArray::size()\n"); return Target.ptrsize * 2; } override uint alignsize() const { // A DArray consists of two ptr-sized values, so align it on pointer size // boundary return Target.ptrsize; } override bool isString() { TY nty = next.toBasetype().ty; return nty == Tchar || nty == Twchar || nty == Tdchar; } override bool isZeroInit(const ref Loc loc) const { return true; } override bool isBoolean() const { return true; } override MATCH implicitConvTo(Type to) { //printf("TypeDArray::implicitConvTo(to = %s) this = %s\n", to.toChars(), toChars()); if (equals(to)) return MATCH.exact; if (to.ty == Tarray) { TypeDArray ta = cast(TypeDArray)to; if (!MODimplicitConv(next.mod, ta.next.mod)) return MATCH.nomatch; // not const-compatible /* Allow conversion to void[] */ if (next.ty != Tvoid && ta.next.ty == Tvoid) { return MATCH.convert; } MATCH m = next.constConv(ta.next); if (m > MATCH.nomatch) { if (m == MATCH.exact && mod != to.mod) m = MATCH.constant; return m; } } return Type.implicitConvTo(to); } override Expression defaultInit(const ref Loc loc) { static if (LOGDEFAULTINIT) { printf("TypeDArray::defaultInit() '%s'\n", toChars()); } return new NullExp(loc, this); } override bool hasPointers() const { return true; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class TypeAArray : TypeArray { Type index; // key type Loc loc; Scope* sc; extern (D) this(Type t, Type index) { super(Taarray, t); this.index = index; } static TypeAArray create(Type t, Type index) { return new TypeAArray(t, index); } override const(char)* kind() const { return "aarray"; } override Type syntaxCopy() { Type t = next.syntaxCopy(); Type ti = index.syntaxCopy(); if (t == next && ti == index) t = this; else { t = new TypeAArray(t, ti); t.mod = mod; } return t; } override d_uns64 size(const ref Loc loc) { return Target.ptrsize; } override Expression defaultInit(const ref Loc loc) { static if (LOGDEFAULTINIT) { printf("TypeAArray::defaultInit() '%s'\n", toChars()); } return new NullExp(loc, this); } override bool isZeroInit(const ref Loc loc) const { return true; } override bool isBoolean() const { return true; } override bool hasPointers() const { return true; } override MATCH implicitConvTo(Type to) { //printf("TypeAArray::implicitConvTo(to = %s) this = %s\n", to.toChars(), toChars()); if (equals(to)) return MATCH.exact; if (to.ty == Taarray) { TypeAArray ta = cast(TypeAArray)to; if (!MODimplicitConv(next.mod, ta.next.mod)) return MATCH.nomatch; // not const-compatible if (!MODimplicitConv(index.mod, ta.index.mod)) return MATCH.nomatch; // not const-compatible MATCH m = next.constConv(ta.next); MATCH mi = index.constConv(ta.index); if (m > MATCH.nomatch && mi > MATCH.nomatch) { return MODimplicitConv(mod, to.mod) ? MATCH.constant : MATCH.nomatch; } } return Type.implicitConvTo(to); } override MATCH constConv(Type to) { if (to.ty == Taarray) { TypeAArray taa = cast(TypeAArray)to; MATCH mindex = index.constConv(taa.index); MATCH mkey = next.constConv(taa.next); // Pick the worst match return mkey < mindex ? mkey : mindex; } return Type.constConv(to); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class TypePointer : TypeNext { extern (D) this(Type t) { super(Tpointer, t); } static TypePointer create(Type t) { return new TypePointer(t); } override const(char)* kind() const { return "pointer"; } override Type syntaxCopy() { Type t = next.syntaxCopy(); if (t == next) t = this; else { t = new TypePointer(t); t.mod = mod; } return t; } override d_uns64 size(const ref Loc loc) const { return Target.ptrsize; } override MATCH implicitConvTo(Type to) { //printf("TypePointer::implicitConvTo(to = %s) %s\n", to.toChars(), toChars()); if (equals(to)) return MATCH.exact; if (next.ty == Tfunction) { if (to.ty == Tpointer) { TypePointer tp = cast(TypePointer)to; if (tp.next.ty == Tfunction) { if (next.equals(tp.next)) return MATCH.constant; if (next.covariant(tp.next) == 1) { Type tret = this.next.nextOf(); Type toret = tp.next.nextOf(); if (tret.ty == Tclass && toret.ty == Tclass) { /* https://issues.dlang.org/show_bug.cgi?id=10219 * Check covariant interface return with offset tweaking. * interface I {} * class C : Object, I {} * I function() dg = function C() {} // should be error */ int offset = 0; if (toret.isBaseOf(tret, &offset) && offset != 0) return MATCH.nomatch; } return MATCH.convert; } } else if (tp.next.ty == Tvoid) { // Allow conversions to void* return MATCH.convert; } } return MATCH.nomatch; } else if (to.ty == Tpointer) { TypePointer tp = cast(TypePointer)to; assert(tp.next); if (!MODimplicitConv(next.mod, tp.next.mod)) return MATCH.nomatch; // not const-compatible /* Alloc conversion to void* */ if (next.ty != Tvoid && tp.next.ty == Tvoid) { return MATCH.convert; } MATCH m = next.constConv(tp.next); if (m > MATCH.nomatch) { if (m == MATCH.exact && mod != to.mod) m = MATCH.constant; return m; } } return MATCH.nomatch; } override MATCH constConv(Type to) { if (next.ty == Tfunction) { if (to.nextOf() && next.equals((cast(TypeNext)to).next)) return Type.constConv(to); else return MATCH.nomatch; } return TypeNext.constConv(to); } override bool isscalar() const { return true; } override Expression defaultInit(const ref Loc loc) { static if (LOGDEFAULTINIT) { printf("TypePointer::defaultInit() '%s'\n", toChars()); } return new NullExp(loc, this); } override bool isZeroInit(const ref Loc loc) const { return true; } override bool hasPointers() const { return true; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class TypeReference : TypeNext { extern (D) this(Type t) { super(Treference, t); // BUG: what about references to static arrays? } override const(char)* kind() const { return "reference"; } override Type syntaxCopy() { Type t = next.syntaxCopy(); if (t == next) t = this; else { t = new TypeReference(t); t.mod = mod; } return t; } override d_uns64 size(const ref Loc loc) const { return Target.ptrsize; } override Expression defaultInit(const ref Loc loc) { static if (LOGDEFAULTINIT) { printf("TypeReference::defaultInit() '%s'\n", toChars()); } return new NullExp(loc, this); } override bool isZeroInit(const ref Loc loc) const { return true; } override void accept(Visitor v) { v.visit(this); } } enum RET : int { regs = 1, // returned in registers stack = 2, // returned on stack } enum TRUST : int { default_ = 0, system = 1, // @system (same as TRUST.default) trusted = 2, // @trusted safe = 3, // @safe } enum TRUSTformat : int { TRUSTformatDefault, // do not emit @system when trust == TRUST.default_ TRUSTformatSystem, // emit @system when trust == TRUST.default_ } alias TRUSTformatDefault = TRUSTformat.TRUSTformatDefault; alias TRUSTformatSystem = TRUSTformat.TRUSTformatSystem; enum PURE : int { impure = 0, // not pure at all fwdref = 1, // it's pure, but not known which level yet weak = 2, // no mutable globals are read or written const_ = 3, // parameters are values or const strong = 4, // parameters are values or immutable } /*********************************************************** */ extern (C++) final class TypeFunction : TypeNext { // .next is the return type Parameters* parameters; // function parameters int varargs; // 1: T t, ...) style for variable number of arguments // 2: T t ...) style for variable number of arguments bool isnothrow; // true: nothrow bool isnogc; // true: is @nogc bool isproperty; // can be called without parentheses bool isref; // true: returns a reference bool isreturn; // true: 'this' is returned by ref bool isscope; // true: 'this' is scope bool isscopeinferred; // true: 'this' is scope from inference LINK linkage; // calling convention TRUST trust; // level of trust PURE purity = PURE.impure; ubyte iswild; // bit0: inout on params, bit1: inout on qualifier Expressions* fargs; // function arguments int inuse; extern (D) this(Parameters* parameters, Type treturn, int varargs, LINK linkage, StorageClass stc = 0) { super(Tfunction, treturn); //if (!treturn) *(char*)0=0; // assert(treturn); assert(0 <= varargs && varargs <= 2); this.parameters = parameters; this.varargs = varargs; this.linkage = linkage; if (stc & STC.pure_) this.purity = PURE.fwdref; if (stc & STC.nothrow_) this.isnothrow = true; if (stc & STC.nogc) this.isnogc = true; if (stc & STC.property) this.isproperty = true; if (stc & STC.ref_) this.isref = true; if (stc & STC.return_) this.isreturn = true; if (stc & STC.scope_) this.isscope = true; if (stc & STC.scopeinferred) this.isscopeinferred = true; this.trust = TRUST.default_; if (stc & STC.safe) this.trust = TRUST.safe; if (stc & STC.system) this.trust = TRUST.system; if (stc & STC.trusted) this.trust = TRUST.trusted; } static TypeFunction create(Parameters* parameters, Type treturn, int varargs, LINK linkage, StorageClass stc = 0) { return new TypeFunction(parameters, treturn, varargs, linkage, stc); } override const(char)* kind() const { return "function"; } override Type syntaxCopy() { Type treturn = next ? next.syntaxCopy() : null; Parameters* params = Parameter.arraySyntaxCopy(parameters); auto t = new TypeFunction(params, treturn, varargs, linkage); t.mod = mod; t.isnothrow = isnothrow; t.isnogc = isnogc; t.purity = purity; t.isproperty = isproperty; t.isref = isref; t.isreturn = isreturn; t.isscope = isscope; t.isscopeinferred = isscopeinferred; t.iswild = iswild; t.trust = trust; t.fargs = fargs; return t; } /******************************************** * Set 'purity' field of 'this'. * Do this lazily, as the parameter types might be forward referenced. */ void purityLevel() { TypeFunction tf = this; if (tf.purity != PURE.fwdref) return; /* Determine purity level based on mutability of t * and whether it is a 'ref' type or not. */ static PURE purityOfType(bool isref, Type t) { if (isref) { if (t.mod & MODFlags.immutable_) return PURE.strong; if (t.mod & (MODFlags.const_ | MODFlags.wild)) return PURE.const_; return PURE.weak; } t = t.baseElemOf(); if (!t.hasPointers() || t.mod & MODFlags.immutable_) return PURE.strong; /* Accept immutable(T)[] and immutable(T)* as being strongly pure */ if (t.ty == Tarray || t.ty == Tpointer) { Type tn = t.nextOf().toBasetype(); if (tn.mod & MODFlags.immutable_) return PURE.strong; if (tn.mod & (MODFlags.const_ | MODFlags.wild)) return PURE.const_; } /* The rest of this is too strict; fix later. * For example, the only pointer members of a struct may be immutable, * which would maintain strong purity. * (Just like for dynamic arrays and pointers above.) */ if (t.mod & (MODFlags.const_ | MODFlags.wild)) return PURE.const_; /* Should catch delegates and function pointers, and fold in their purity */ return PURE.weak; } purity = PURE.strong; // assume strong until something weakens it /* Evaluate what kind of purity based on the modifiers for the parameters */ const dim = Parameter.dim(tf.parameters); Lloop: foreach (i; 0 .. dim) { Parameter fparam = Parameter.getNth(tf.parameters, i); Type t = fparam.type; if (!t) continue; if (fparam.storageClass & (STC.lazy_ | STC.out_)) { purity = PURE.weak; break; } switch (purityOfType((fparam.storageClass & STC.ref_) != 0, t)) { case PURE.weak: purity = PURE.weak; break Lloop; // since PURE.weak, no need to check further case PURE.const_: purity = PURE.const_; continue; case PURE.strong: continue; default: assert(0); } } if (purity > PURE.weak && tf.nextOf()) { /* Adjust purity based on mutability of return type. * https://issues.dlang.org/show_bug.cgi?id=15862 */ const purity2 = purityOfType(tf.isref, tf.nextOf()); if (purity2 < purity) purity = purity2; } tf.purity = purity; } /******************************************** * Return true if there are lazy parameters. */ bool hasLazyParameters() { size_t dim = Parameter.dim(parameters); for (size_t i = 0; i < dim; i++) { Parameter fparam = Parameter.getNth(parameters, i); if (fparam.storageClass & STC.lazy_) return true; } return false; } /*************************** * Examine function signature for parameter p and see if * the value of p can 'escape' the scope of the function. * This is useful to minimize the needed annotations for the parameters. * Params: * p = parameter to this function * Returns: * true if escapes via assignment to global or through a parameter */ bool parameterEscapes(Parameter p) { /* Scope parameters do not escape. * Allow 'lazy' to imply 'scope' - * lazy parameters can be passed along * as lazy parameters to the next function, but that isn't * escaping. */ if (parameterStorageClass(p) & (STC.scope_ | STC.lazy_)) return false; return true; } /************************************ * Take the specified storage class for p, * and use the function signature to infer whether * STC.scope_ and STC.return_ should be OR'd in. * (This will not affect the name mangling.) * Params: * p = one of the parameters to 'this' * Returns: * storage class with STC.scope_ or STC.return_ OR'd in */ final StorageClass parameterStorageClass(Parameter p) { //printf("parameterStorageClass(p: %s)\n", p.toChars()); auto stc = p.storageClass; if (!global.params.vsafe) return stc; if (stc & (STC.scope_ | STC.return_ | STC.lazy_) || purity == PURE.impure) return stc; /* If haven't inferred the return type yet, can't infer storage classes */ if (!nextOf()) return stc; purityLevel(); // See if p can escape via any of the other parameters if (purity == PURE.weak) { const dim = Parameter.dim(parameters); foreach (const i; 0 .. dim) { Parameter fparam = Parameter.getNth(parameters, i); if (fparam == p) continue; Type t = fparam.type; if (!t) continue; t = t.baseElemOf(); if (t.isMutable() && t.hasPointers()) { if (fparam.storageClass & (STC.ref_ | STC.out_)) { } else if (t.ty == Tarray || t.ty == Tpointer) { Type tn = t.nextOf().toBasetype(); if (!(tn.isMutable() && tn.hasPointers())) continue; } return stc; } } } stc |= STC.scope_; /* Inferring STC.return_ here has false positives * for pure functions, producing spurious error messages * about escaping references. * Give up on it for now. */ version (none) { Type tret = nextOf().toBasetype(); if (isref || tret.hasPointers()) { /* The result has references, so p could be escaping * that way. */ stc |= STC.return_; } } return stc; } override Type addStorageClass(StorageClass stc) { //printf("addStorageClass(%llx) %d\n", stc, (stc & STC.scope_) != 0); TypeFunction t = Type.addStorageClass(stc).toTypeFunction(); if ((stc & STC.pure_ && !t.purity) || (stc & STC.nothrow_ && !t.isnothrow) || (stc & STC.nogc && !t.isnogc) || (stc & STC.scope_ && !t.isscope) || (stc & STC.safe && t.trust < TRUST.trusted)) { // Klunky to change these auto tf = new TypeFunction(t.parameters, t.next, t.varargs, t.linkage, 0); tf.mod = t.mod; tf.fargs = fargs; tf.purity = t.purity; tf.isnothrow = t.isnothrow; tf.isnogc = t.isnogc; tf.isproperty = t.isproperty; tf.isref = t.isref; tf.isreturn = t.isreturn; tf.isscope = t.isscope; tf.isscopeinferred = t.isscopeinferred; tf.trust = t.trust; tf.iswild = t.iswild; if (stc & STC.pure_) tf.purity = PURE.fwdref; if (stc & STC.nothrow_) tf.isnothrow = true; if (stc & STC.nogc) tf.isnogc = true; if (stc & STC.safe) tf.trust = TRUST.safe; if (stc & STC.scope_) { tf.isscope = true; if (stc & STC.scopeinferred) tf.isscopeinferred = true; } tf.deco = tf.merge().deco; t = tf; } return t; } /** For each active attribute (ref/const/nogc/etc) call fp with a void* for the work param and a string representation of the attribute. */ int attributesApply(void* param, int function(void*, const(char)*) fp, TRUSTformat trustFormat = TRUSTformatDefault) { int res = 0; if (purity) res = fp(param, "pure"); if (res) return res; if (isnothrow) res = fp(param, "nothrow"); if (res) return res; if (isnogc) res = fp(param, "@nogc"); if (res) return res; if (isproperty) res = fp(param, "@property"); if (res) return res; if (isref) res = fp(param, "ref"); if (res) return res; if (isreturn) res = fp(param, "return"); if (res) return res; if (isscope && !isscopeinferred) res = fp(param, "scope"); if (res) return res; TRUST trustAttrib = trust; if (trustAttrib == TRUST.default_) { // Print out "@system" when trust equals TRUST.default_ (if desired). if (trustFormat == TRUSTformatSystem) trustAttrib = TRUST.system; else return res; // avoid calling with an empty string } return fp(param, trustToChars(trustAttrib)); } override Type substWildTo(uint) { if (!iswild && !(mod & MODFlags.wild)) return this; // Substitude inout qualifier of function type to mutable or immutable // would break type system. Instead substitude inout to the most weak // qualifer - const. uint m = MODFlags.const_; assert(next); Type tret = next.substWildTo(m); Parameters* params = parameters; if (mod & MODFlags.wild) params = parameters.copy(); for (size_t i = 0; i < params.dim; i++) { Parameter p = (*params)[i]; Type t = p.type.substWildTo(m); if (t == p.type) continue; if (params == parameters) params = parameters.copy(); (*params)[i] = new Parameter(p.storageClass, t, null, null); } if (next == tret && params == parameters) return this; // Similar to TypeFunction::syntaxCopy; auto t = new TypeFunction(params, tret, varargs, linkage); t.mod = ((mod & MODFlags.wild) ? (mod & ~MODFlags.wild) | MODFlags.const_ : mod); t.isnothrow = isnothrow; t.isnogc = isnogc; t.purity = purity; t.isproperty = isproperty; t.isref = isref; t.isreturn = isreturn; t.isscope = isscope; t.isscopeinferred = isscopeinferred; t.iswild = 0; t.trust = trust; t.fargs = fargs; return t.merge(); } // arguments get specially formatted private const(char)* getParamError(const(char)* format, Expression arg, Parameter par) { // show qualification when toChars() is the same but types are different auto at = arg.type.toChars(); bool qual = !arg.type.equals(par.type) && strcmp(at, par.type.toChars()) == 0; if (qual) at = arg.type.toPrettyChars(true); OutBuffer as; as.printf("`%s` of type `%s`", arg.toChars(), at); OutBuffer ps; ps.printf("`%s`", parameterToChars(par, this, qual)); OutBuffer buf; buf.printf(format, as.peekString(), ps.peekString()); return buf.extractString(); } /******************************** * 'args' are being matched to function 'this' * Determine match level. * Input: * flag 1 performing a partial ordering match * pMessage address to store error message, or null * Returns: * MATCHxxxx */ MATCH callMatch(Type tthis, Expressions* args, int flag = 0, const(char)** pMessage = null) { //printf("TypeFunction::callMatch() %s\n", toChars()); MATCH match = MATCH.exact; // assume exact match ubyte wildmatch = 0; if (tthis) { Type t = tthis; if (t.toBasetype().ty == Tpointer) t = t.toBasetype().nextOf(); // change struct* to struct if (t.mod != mod) { if (MODimplicitConv(t.mod, mod)) match = MATCH.constant; else if ((mod & MODFlags.wild) && MODimplicitConv(t.mod, (mod & ~MODFlags.wild) | MODFlags.const_)) { match = MATCH.constant; } else return MATCH.nomatch; } if (isWild()) { if (t.isWild()) wildmatch |= MODFlags.wild; else if (t.isConst()) wildmatch |= MODFlags.const_; else if (t.isImmutable()) wildmatch |= MODFlags.immutable_; else wildmatch |= MODFlags.mutable; } } size_t nparams = Parameter.dim(parameters); size_t nargs = args ? args.dim : 0; if (nparams == nargs) { } else if (nargs > nparams) { if (varargs == 0) goto Nomatch; // too many args; no match match = MATCH.convert; // match ... with a "conversion" match level } for (size_t u = 0; u < nargs; u++) { if (u >= nparams) break; Parameter p = Parameter.getNth(parameters, u); Expression arg = (*args)[u]; assert(arg); Type tprm = p.type; Type targ = arg.type; if (!(p.storageClass & STC.lazy_ && tprm.ty == Tvoid && targ.ty != Tvoid)) { bool isRef = (p.storageClass & (STC.ref_ | STC.out_)) != 0; wildmatch |= targ.deduceWild(tprm, isRef); } } if (wildmatch) { /* Calculate wild matching modifier */ if (wildmatch & MODFlags.const_ || wildmatch & (wildmatch - 1)) wildmatch = MODFlags.const_; else if (wildmatch & MODFlags.immutable_) wildmatch = MODFlags.immutable_; else if (wildmatch & MODFlags.wild) wildmatch = MODFlags.wild; else { assert(wildmatch & MODFlags.mutable); wildmatch = MODFlags.mutable; } } for (size_t u = 0; u < nparams; u++) { MATCH m; Parameter p = Parameter.getNth(parameters, u); assert(p); if (u >= nargs) { if (p.defaultArg) continue; goto L1; // try typesafe variadics } { Expression arg = (*args)[u]; assert(arg); //printf("arg: %s, type: %s\n", arg.toChars(), arg.type.toChars()); Type targ = arg.type; Type tprm = wildmatch ? p.type.substWildTo(wildmatch) : p.type; if (p.storageClass & STC.lazy_ && tprm.ty == Tvoid && targ.ty != Tvoid) m = MATCH.convert; else { //printf("%s of type %s implicitConvTo %s\n", arg.toChars(), targ.toChars(), tprm.toChars()); if (flag) { // for partial ordering, value is an irrelevant mockup, just look at the type m = targ.implicitConvTo(tprm); } else m = arg.implicitConvTo(tprm); //printf("match %d\n", m); } // Non-lvalues do not match ref or out parameters if (p.storageClass & (STC.ref_ | STC.out_)) { // https://issues.dlang.org/show_bug.cgi?id=13783 // Don't use toBasetype() to handle enum types. Type ta = targ; Type tp = tprm; //printf("fparam[%d] ta = %s, tp = %s\n", u, ta.toChars(), tp.toChars()); if (m && !arg.isLvalue()) { if (p.storageClass & STC.out_) { if (pMessage) *pMessage = getParamError("cannot pass rvalue argument %s to parameter %s", arg, p); goto Nomatch; } if (arg.op == TOK.string_ && tp.ty == Tsarray) { if (ta.ty != Tsarray) { Type tn = tp.nextOf().castMod(ta.nextOf().mod); dinteger_t dim = (cast(StringExp)arg).len; ta = tn.sarrayOf(dim); } } else if (arg.op == TOK.slice && tp.ty == Tsarray) { // Allow conversion from T[lwr .. upr] to ref T[upr-lwr] if (ta.ty != Tsarray) { Type tn = ta.nextOf(); dinteger_t dim = (cast(TypeSArray)tp).dim.toUInteger(); ta = tn.sarrayOf(dim); } } else { if (pMessage) *pMessage = getParamError("cannot pass rvalue argument %s to parameter %s", arg, p); goto Nomatch; } } /* Find most derived alias this type being matched. * https://issues.dlang.org/show_bug.cgi?id=15674 * Allow on both ref and out parameters. */ while (1) { Type tab = ta.toBasetype(); Type tat = tab.aliasthisOf(); if (!tat || !tat.implicitConvTo(tprm)) break; if (tat == tab) break; ta = tat; } /* A ref variable should work like a head-const reference. * e.g. disallows: * ref T <- an lvalue of const(T) argument * ref T[dim] <- an lvalue of const(T[dim]) argument */ if (!ta.constConv(tp)) { if (pMessage) *pMessage = getParamError( arg.isLvalue() ? "cannot pass argument %s to parameter %s" : "cannot pass rvalue argument %s to parameter %s", arg, p); goto Nomatch; } } } /* prefer matching the element type rather than the array * type when more arguments are present with T[]... */ if (varargs == 2 && u + 1 == nparams && nargs > nparams) goto L1; //printf("\tm = %d\n", m); if (m == MATCH.nomatch) // if no match { L1: if (varargs == 2 && u + 1 == nparams) // if last varargs param { Type tb = p.type.toBasetype(); TypeSArray tsa; dinteger_t sz; switch (tb.ty) { case Tsarray: tsa = cast(TypeSArray)tb; sz = tsa.dim.toInteger(); if (sz != nargs - u) goto Nomatch; goto case Tarray; case Tarray: { TypeArray ta = cast(TypeArray)tb; for (; u < nargs; u++) { Expression arg = (*args)[u]; assert(arg); /* If lazy array of delegates, * convert arg(s) to delegate(s) */ Type tret = p.isLazyArray(); if (tret) { if (ta.next.equals(arg.type)) m = MATCH.exact; else if (tret.toBasetype().ty == Tvoid) m = MATCH.convert; else { m = arg.implicitConvTo(tret); if (m == MATCH.nomatch) m = arg.implicitConvTo(ta.next); } } else m = arg.implicitConvTo(ta.next); if (m == MATCH.nomatch) { if (pMessage) *pMessage = getParamError("cannot pass argument %s to parameter %s", arg, p); goto Nomatch; } if (m < match) match = m; } goto Ldone; } case Tclass: // Should see if there's a constructor match? // Or just leave it ambiguous? goto Ldone; default: break; } } if (pMessage && u < nargs) *pMessage = getParamError("cannot pass argument %s to parameter %s", (*args)[u], p); goto Nomatch; } if (m < match) match = m; // pick worst match } Ldone: //printf("match = %d\n", match); return match; Nomatch: //printf("no match\n"); return MATCH.nomatch; } bool checkRetType(const ref Loc loc) { Type tb = next.toBasetype(); if (tb.ty == Tfunction) { error(loc, "functions cannot return a function"); next = Type.terror; } if (tb.ty == Ttuple) { error(loc, "functions cannot return a tuple"); next = Type.terror; } if (!isref && (tb.ty == Tstruct || tb.ty == Tsarray)) { Type tb2 = tb.baseElemOf(); if (tb2.ty == Tstruct && !(cast(TypeStruct)tb2).sym.members) { error(loc, "functions cannot return opaque type `%s` by value", tb.toChars()); next = Type.terror; } } if (tb.ty == Terror) return true; return false; } override Expression defaultInit(const ref Loc loc) const { error(loc, "`function` does not have a default initializer"); return new ErrorExp(); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class TypeDelegate : TypeNext { // .next is a TypeFunction extern (D) this(Type t) { super(Tfunction, t); ty = Tdelegate; } static TypeDelegate create(Type t) { return new TypeDelegate(t); } override const(char)* kind() const { return "delegate"; } override Type syntaxCopy() { Type t = next.syntaxCopy(); if (t == next) t = this; else { t = new TypeDelegate(t); t.mod = mod; } return t; } override Type addStorageClass(StorageClass stc) { TypeDelegate t = cast(TypeDelegate)Type.addStorageClass(stc); if (!global.params.vsafe) return t; /* The rest is meant to add 'scope' to a delegate declaration if it is of the form: * alias dg_t = void* delegate(); * scope dg_t dg = ...; */ if(stc & STC.scope_) { auto n = t.next.addStorageClass(STC.scope_ | STC.scopeinferred); if (n != t.next) { t.next = n; t.deco = t.merge().deco; // mangling supposed to not be changed due to STC.scope_inferrred } } return t; } override d_uns64 size(const ref Loc loc) const { return Target.ptrsize * 2; } override uint alignsize() const { return Target.ptrsize; } override MATCH implicitConvTo(Type to) { //printf("TypeDelegate.implicitConvTo(this=%p, to=%p)\n", this, to); //printf("from: %s\n", toChars()); //printf("to : %s\n", to.toChars()); if (this == to) return MATCH.exact; version (all) { // not allowing covariant conversions because it interferes with overriding if (to.ty == Tdelegate && this.nextOf().covariant(to.nextOf()) == 1) { Type tret = this.next.nextOf(); Type toret = (cast(TypeDelegate)to).next.nextOf(); if (tret.ty == Tclass && toret.ty == Tclass) { /* https://issues.dlang.org/show_bug.cgi?id=10219 * Check covariant interface return with offset tweaking. * interface I {} * class C : Object, I {} * I delegate() dg = delegate C() {} // should be error */ int offset = 0; if (toret.isBaseOf(tret, &offset) && offset != 0) return MATCH.nomatch; } return MATCH.convert; } } return MATCH.nomatch; } override Expression defaultInit(const ref Loc loc) { static if (LOGDEFAULTINIT) { printf("TypeDelegate::defaultInit() '%s'\n", toChars()); } return new NullExp(loc, this); } override bool isZeroInit(const ref Loc loc) const { return true; } override bool isBoolean() const { return true; } override bool hasPointers() const { return true; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) abstract class TypeQualified : Type { Loc loc; // array of Identifier and TypeInstance, // representing ident.ident!tiargs.ident. ... etc. Objects idents; final extern (D) this(TY ty, Loc loc) { super(ty); this.loc = loc; } final void syntaxCopyHelper(TypeQualified t) { //printf("TypeQualified::syntaxCopyHelper(%s) %s\n", t.toChars(), toChars()); idents.setDim(t.idents.dim); for (size_t i = 0; i < idents.dim; i++) { RootObject id = t.idents[i]; if (id.dyncast() == DYNCAST.dsymbol) { TemplateInstance ti = cast(TemplateInstance)id; ti = cast(TemplateInstance)ti.syntaxCopy(null); id = ti; } else if (id.dyncast() == DYNCAST.expression) { Expression e = cast(Expression)id; e = e.syntaxCopy(); id = e; } else if (id.dyncast() == DYNCAST.type) { Type tx = cast(Type)id; tx = tx.syntaxCopy(); id = tx; } idents[i] = id; } } final void addIdent(Identifier ident) { idents.push(ident); } final void addInst(TemplateInstance inst) { idents.push(inst); } final void addIndex(RootObject e) { idents.push(e); } override d_uns64 size(const ref Loc loc) { error(this.loc, "size of type `%s` is not known", toChars()); return SIZE_INVALID; } /************************************* * Resolve a tuple index. */ final void resolveTupleIndex(const ref Loc loc, Scope* sc, Dsymbol s, Expression* pe, Type* pt, Dsymbol* ps, RootObject oindex) { *pt = null; *ps = null; *pe = null; auto tup = s.isTupleDeclaration(); auto eindex = isExpression(oindex); auto tindex = isType(oindex); auto sindex = isDsymbol(oindex); if (!tup) { // It's really an index expression if (tindex) eindex = new TypeExp(loc, tindex); else if (sindex) eindex = .resolve(loc, sc, sindex, false); Expression e = new IndexExp(loc, .resolve(loc, sc, s, false), eindex); e = e.expressionSemantic(sc); resolveExp(e, pt, pe, ps); return; } // Convert oindex to Expression, then try to resolve to constant. if (tindex) tindex.resolve(loc, sc, &eindex, &tindex, &sindex); if (sindex) eindex = .resolve(loc, sc, sindex, false); if (!eindex) { .error(loc, "index `%s` is not an expression", oindex.toChars()); *pt = Type.terror; return; } eindex = semanticLength(sc, tup, eindex); eindex = eindex.ctfeInterpret(); if (eindex.op == TOK.error) { *pt = Type.terror; return; } const(uinteger_t) d = eindex.toUInteger(); if (d >= tup.objects.dim) { .error(loc, "tuple index `%llu` exceeds length %u", d, tup.objects.dim); *pt = Type.terror; return; } RootObject o = (*tup.objects)[cast(size_t)d]; *pt = isType(o); *ps = isDsymbol(o); *pe = isExpression(o); if (*pt) *pt = (*pt).typeSemantic(loc, sc); if (*pe) resolveExp(*pe, pt, pe, ps); } /************************************* * Takes an array of Identifiers and figures out if * it represents a Type or an Expression. * Output: * if expression, *pe is set * if type, *pt is set */ final void resolveHelper(const ref Loc loc, Scope* sc, Dsymbol s, Dsymbol scopesym, Expression* pe, Type* pt, Dsymbol* ps, bool intypeid = false) { version (none) { printf("TypeQualified::resolveHelper(sc = %p, idents = '%s')\n", sc, toChars()); if (scopesym) printf("\tscopesym = '%s'\n", scopesym.toChars()); } *pe = null; *pt = null; *ps = null; if (s) { //printf("\t1: s = '%s' %p, kind = '%s'\n",s.toChars(), s, s.kind()); Declaration d = s.isDeclaration(); if (d && (d.storage_class & STC.templateparameter)) s = s.toAlias(); else { // check for deprecated or disabled aliases s.checkDeprecated(loc, sc); if (d) d.checkDisabled(loc, sc, true); } s = s.toAlias(); //printf("\t2: s = '%s' %p, kind = '%s'\n",s.toChars(), s, s.kind()); for (size_t i = 0; i < idents.dim; i++) { RootObject id = idents[i]; if (id.dyncast() == DYNCAST.expression || id.dyncast() == DYNCAST.type) { Type tx; Expression ex; Dsymbol sx; resolveTupleIndex(loc, sc, s, &ex, &tx, &sx, id); if (sx) { s = sx.toAlias(); continue; } if (tx) ex = new TypeExp(loc, tx); assert(ex); ex = typeToExpressionHelper(this, ex, i + 1); ex = ex.expressionSemantic(sc); resolveExp(ex, pt, pe, ps); return; } Type t = s.getType(); // type symbol, type alias, or type tuple? uint errorsave = global.errors; int flags = t is null ? SearchLocalsOnly : IgnorePrivateImports; Dsymbol sm = s.searchX(loc, sc, id, flags); if (sm && !(sc.flags & SCOPE.ignoresymbolvisibility) && !symbolIsVisible(sc, sm)) { .deprecation(loc, "`%s` is not visible from module `%s`", sm.toPrettyChars(), sc._module.toChars()); // sm = null; } if (global.errors != errorsave) { *pt = Type.terror; return; } //printf("\t3: s = %p %s %s, sm = %p\n", s, s.kind(), s.toChars(), sm); if (intypeid && !t && sm && sm.needThis()) goto L3; if (VarDeclaration v = s.isVarDeclaration()) { if (v.storage_class & (STC.const_ | STC.immutable_ | STC.manifest) || v.type.isConst() || v.type.isImmutable()) { // https://issues.dlang.org/show_bug.cgi?id=13087 // this.field is not constant always if (!v.isThisDeclaration()) goto L3; } } if (!sm) { if (!t) { if (s.isDeclaration()) // var, func, or tuple declaration? { t = s.isDeclaration().type; if (!t && s.isTupleDeclaration()) // expression tuple? goto L3; } else if (s.isTemplateInstance() || s.isImport() || s.isPackage() || s.isModule()) { goto L3; } } if (t) { sm = t.toDsymbol(sc); if (sm && id.dyncast() == DYNCAST.identifier) { sm = sm.search(loc, cast(Identifier)id /*, IgnorePrivateImports*/); // Deprecated in 2018-01. // Change to error by deleting the deprecation line and uncommenting // the above parameter. The error will be issued in Type.getProperty. // The deprecation is highlighted here to avoid a redundant call to // ScopeDsymbol.search. // @@@DEPRECATED_2019-01@@@. if (sm) { .deprecation(loc, "`%s` is not visible from module `%s`", sm.toPrettyChars(), sc._module.toChars()); goto L2; } } L3: Expression e; VarDeclaration v = s.isVarDeclaration(); FuncDeclaration f = s.isFuncDeclaration(); if (intypeid || !v && !f) e = .resolve(loc, sc, s, true); else e = new VarExp(loc, s.isDeclaration(), true); e = typeToExpressionHelper(this, e, i); e = e.expressionSemantic(sc); resolveExp(e, pt, pe, ps); return; } else { if (id.dyncast() == DYNCAST.dsymbol) { // searchX already handles errors for template instances assert(global.errors); } else { assert(id.dyncast() == DYNCAST.identifier); sm = s.search_correct(cast(Identifier)id); if (sm) error(loc, "identifier `%s` of `%s` is not defined, did you mean %s `%s`?", id.toChars(), toChars(), sm.kind(), sm.toChars()); else error(loc, "identifier `%s` of `%s` is not defined", id.toChars(), toChars()); } *pe = new ErrorExp(); } return; } L2: s = sm.toAlias(); } if (auto em = s.isEnumMember()) { // It's not a type, it's an expression *pe = em.getVarExp(loc, sc); return; } if (auto v = s.isVarDeclaration()) { /* This is mostly same with DsymbolExp::semantic(), but we cannot use it * because some variables used in type context need to prevent lowering * to a literal or contextful expression. For example: * * enum a = 1; alias b = a; * template X(alias e){ alias v = e; } alias x = X!(1); * struct S { int v; alias w = v; } * // TypeIdentifier 'a', 'e', and 'v' should be TOK.variable, * // because getDsymbol() need to work in AliasDeclaration::semantic(). */ if (!v.type || !v.type.deco && v.inuse) { if (v.inuse) // https://issues.dlang.org/show_bug.cgi?id=9494 error(loc, "circular reference to %s `%s`", v.kind(), v.toPrettyChars()); else error(loc, "forward reference to %s `%s`", v.kind(), v.toPrettyChars()); *pt = Type.terror; return; } if (v.type.ty == Terror) *pt = Type.terror; else *pe = new VarExp(loc, v); return; } if (auto fld = s.isFuncLiteralDeclaration()) { //printf("'%s' is a function literal\n", fld.toChars()); *pe = new FuncExp(loc, fld); *pe = (*pe).expressionSemantic(sc); return; } version (none) { if (FuncDeclaration fd = s.isFuncDeclaration()) { *pe = new DsymbolExp(loc, fd); return; } } L1: Type t = s.getType(); if (!t) { // If the symbol is an import, try looking inside the import if (Import si = s.isImport()) { s = si.search(loc, s.ident); if (s && s != si) goto L1; s = si; } *ps = s; return; } if (t.ty == Tinstance && t != this && !t.deco) { if (!(cast(TypeInstance)t).tempinst.errors) error(loc, "forward reference to `%s`", t.toChars()); *pt = Type.terror; return; } if (t.ty == Ttuple) *pt = t; else *pt = t.merge(); } if (!s) { /* Look for what user might have intended */ const p = mutableOf().unSharedOf().toChars(); auto id = Identifier.idPool(p, strlen(p)); if (const n = importHint(p)) error(loc, "`%s` is not defined, perhaps `import %s;` ?", p, n); else if (auto s2 = sc.search_correct(id)) error(loc, "undefined identifier `%s`, did you mean %s `%s`?", p, s2.kind(), s2.toChars()); else if (const q = Scope.search_correct_C(id)) error(loc, "undefined identifier `%s`, did you mean `%s`?", p, q); else error(loc, "undefined identifier `%s`", p); *pt = Type.terror; } } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class TypeIdentifier : TypeQualified { Identifier ident; // The symbol representing this identifier, before alias resolution Dsymbol originalSymbol; extern (D) this(const ref Loc loc, Identifier ident) { super(Tident, loc); this.ident = ident; } override const(char)* kind() const { return "identifier"; } override Type syntaxCopy() { auto t = new TypeIdentifier(loc, ident); t.syntaxCopyHelper(this); t.mod = mod; return t; } /***************************************** * See if type resolves to a symbol, if so, * return that symbol. */ override Dsymbol toDsymbol(Scope* sc) { //printf("TypeIdentifier::toDsymbol('%s')\n", toChars()); if (!sc) return null; Type t; Expression e; Dsymbol s; resolve(this, loc, sc, &e, &t, &s); if (t && t.ty != Tident) s = t.toDsymbol(sc); if (e) s = getDsymbol(e); return s; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * Similar to TypeIdentifier, but with a TemplateInstance as the root */ extern (C++) final class TypeInstance : TypeQualified { TemplateInstance tempinst; extern (D) this(const ref Loc loc, TemplateInstance tempinst) { super(Tinstance, loc); this.tempinst = tempinst; } override const(char)* kind() const { return "instance"; } override Type syntaxCopy() { //printf("TypeInstance::syntaxCopy() %s, %d\n", toChars(), idents.dim); auto t = new TypeInstance(loc, cast(TemplateInstance)tempinst.syntaxCopy(null)); t.syntaxCopyHelper(this); t.mod = mod; return t; } override Dsymbol toDsymbol(Scope* sc) { Type t; Expression e; Dsymbol s; //printf("TypeInstance::semantic(%s)\n", toChars()); resolve(this, loc, sc, &e, &t, &s); if (t && t.ty != Tinstance) s = t.toDsymbol(sc); return s; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class TypeTypeof : TypeQualified { Expression exp; int inuse; extern (D) this(const ref Loc loc, Expression exp) { super(Ttypeof, loc); this.exp = exp; } override const(char)* kind() const { return "typeof"; } override Type syntaxCopy() { //printf("TypeTypeof::syntaxCopy() %s\n", toChars()); auto t = new TypeTypeof(loc, exp.syntaxCopy()); t.syntaxCopyHelper(this); t.mod = mod; return t; } override Dsymbol toDsymbol(Scope* sc) { //printf("TypeTypeof::toDsymbol('%s')\n", toChars()); Expression e; Type t; Dsymbol s; resolve(this, loc, sc, &e, &t, &s); return s; } override d_uns64 size(const ref Loc loc) { if (exp.type) return exp.type.size(loc); else return TypeQualified.size(loc); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class TypeReturn : TypeQualified { extern (D) this(const ref Loc loc) { super(Treturn, loc); } override const(char)* kind() const { return "return"; } override Type syntaxCopy() { auto t = new TypeReturn(loc); t.syntaxCopyHelper(this); t.mod = mod; return t; } override Dsymbol toDsymbol(Scope* sc) { Expression e; Type t; Dsymbol s; resolve(this, loc, sc, &e, &t, &s); return s; } override void accept(Visitor v) { v.visit(this); } } // Whether alias this dependency is recursive or not. enum AliasThisRec : int { no = 0, // no alias this recursion yes = 1, // alias this has recursive dependency fwdref = 2, // not yet known typeMask = 3, // mask to read no/yes/fwdref tracing = 0x4, // mark in progress of implicitConvTo/deduceWild tracingDT = 0x8, // mark in progress of deduceType } /*********************************************************** */ extern (C++) final class TypeStruct : Type { StructDeclaration sym; AliasThisRec att = AliasThisRec.fwdref; CPPMANGLE cppmangle = CPPMANGLE.def; extern (D) this(StructDeclaration sym) { super(Tstruct); this.sym = sym; } static TypeStruct create(StructDeclaration sym) { return new TypeStruct(sym); } override const(char)* kind() const { return "struct"; } override d_uns64 size(const ref Loc loc) { return sym.size(loc); } override uint alignsize() { sym.size(Loc.initial); // give error for forward references return sym.alignsize; } override Type syntaxCopy() { return this; } override Dsymbol toDsymbol(Scope* sc) { return sym; } override structalign_t alignment() { if (sym.alignment == 0) sym.size(sym.loc); return sym.alignment; } override Expression defaultInit(const ref Loc loc) { static if (LOGDEFAULTINIT) { printf("TypeStruct::defaultInit() '%s'\n", toChars()); } Declaration d = new SymbolDeclaration(sym.loc, sym); assert(d); d.type = this; d.storage_class |= STC.rvalue; // https://issues.dlang.org/show_bug.cgi?id=14398 return new VarExp(sym.loc, d); } /*************************************** * Use when we prefer the default initializer to be a literal, * rather than a global immutable variable. */ override Expression defaultInitLiteral(const ref Loc loc) { static if (LOGDEFAULTINIT) { printf("TypeStruct::defaultInitLiteral() '%s'\n", toChars()); } sym.size(loc); if (sym.sizeok != Sizeok.done) return new ErrorExp(); auto structelems = new Expressions(); structelems.setDim(sym.fields.dim - sym.isNested()); uint offset = 0; for (size_t j = 0; j < structelems.dim; j++) { VarDeclaration vd = sym.fields[j]; Expression e; if (vd.inuse) { error(loc, "circular reference to `%s`", vd.toPrettyChars()); return new ErrorExp(); } if (vd.offset < offset || vd.type.size() == 0) e = null; else if (vd._init) { if (vd._init.isVoidInitializer()) e = null; else e = vd.getConstInitializer(false); } else e = vd.type.defaultInitLiteral(loc); if (e && e.op == TOK.error) return e; if (e) offset = vd.offset + cast(uint)vd.type.size(); (*structelems)[j] = e; } auto structinit = new StructLiteralExp(loc, sym, structelems); /* Copy from the initializer symbol for larger symbols, * otherwise the literals expressed as code get excessively large. */ if (size(loc) > Target.ptrsize * 4 && !needsNested()) structinit.useStaticInit = true; structinit.type = this; return structinit; } override bool isZeroInit(const ref Loc loc) const { return sym.zeroInit; } override bool isAssignable() { bool assignable = true; uint offset = ~0; // dead-store initialize to prevent spurious warning /* If any of the fields are const or immutable, * then one cannot assign this struct. */ for (size_t i = 0; i < sym.fields.dim; i++) { VarDeclaration v = sym.fields[i]; //printf("%s [%d] v = (%s) %s, v.offset = %d, v.parent = %s", sym.toChars(), i, v.kind(), v.toChars(), v.offset, v.parent.kind()); if (i == 0) { } else if (v.offset == offset) { /* If any fields of anonymous union are assignable, * then regard union as assignable. * This is to support unsafe things like Rebindable templates. */ if (assignable) continue; } else { if (!assignable) return false; } assignable = v.type.isMutable() && v.type.isAssignable(); offset = v.offset; //printf(" -> assignable = %d\n", assignable); } return assignable; } override bool isBoolean() const { return false; } override bool needsDestruction() const { return sym.dtor !is null; } override bool needsNested() { if (sym.isNested()) return true; for (size_t i = 0; i < sym.fields.dim; i++) { VarDeclaration v = sym.fields[i]; if (!v.isDataseg() && v.type.needsNested()) return true; } return false; } override bool hasPointers() { // Probably should cache this information in sym rather than recompute StructDeclaration s = sym; sym.size(Loc.initial); // give error for forward references foreach (VarDeclaration v; s.fields) { if (v.storage_class & STC.ref_ || v.hasPointers()) return true; } return false; } override bool hasVoidInitPointers() { // Probably should cache this information in sym rather than recompute StructDeclaration s = sym; sym.size(Loc.initial); // give error for forward references foreach (VarDeclaration v; s.fields) { if (v._init && v._init.isVoidInitializer() && v.type.hasPointers()) return true; if (!v._init && v.type.hasVoidInitPointers()) return true; } return false; } override MATCH implicitConvTo(Type to) { MATCH m; //printf("TypeStruct::implicitConvTo(%s => %s)\n", toChars(), to.toChars()); if (ty == to.ty && sym == (cast(TypeStruct)to).sym) { m = MATCH.exact; // exact match if (mod != to.mod) { m = MATCH.constant; if (MODimplicitConv(mod, to.mod)) { } else { /* Check all the fields. If they can all be converted, * allow the conversion. */ uint offset = ~0; // dead-store to prevent spurious warning for (size_t i = 0; i < sym.fields.dim; i++) { VarDeclaration v = sym.fields[i]; if (i == 0) { } else if (v.offset == offset) { if (m > MATCH.nomatch) continue; } else { if (m <= MATCH.nomatch) return m; } // 'from' type Type tvf = v.type.addMod(mod); // 'to' type Type tv = v.type.addMod(to.mod); // field match MATCH mf = tvf.implicitConvTo(tv); //printf("\t%s => %s, match = %d\n", v.type.toChars(), tv.toChars(), mf); if (mf <= MATCH.nomatch) return mf; if (mf < m) // if field match is worse m = mf; offset = v.offset; } } } } else if (sym.aliasthis && !(att & AliasThisRec.tracing)) { if (auto ato = aliasthisOf()) { att = cast(AliasThisRec)(att | AliasThisRec.tracing); m = ato.implicitConvTo(to); att = cast(AliasThisRec)(att & ~AliasThisRec.tracing); } else m = MATCH.nomatch; // no match } else m = MATCH.nomatch; // no match return m; } override MATCH constConv(Type to) { if (equals(to)) return MATCH.exact; if (ty == to.ty && sym == (cast(TypeStruct)to).sym && MODimplicitConv(mod, to.mod)) return MATCH.constant; return MATCH.nomatch; } override ubyte deduceWild(Type t, bool isRef) { if (ty == t.ty && sym == (cast(TypeStruct)t).sym) return Type.deduceWild(t, isRef); ubyte wm = 0; if (t.hasWild() && sym.aliasthis && !(att & AliasThisRec.tracing)) { if (auto ato = aliasthisOf()) { att = cast(AliasThisRec)(att | AliasThisRec.tracing); wm = ato.deduceWild(t, isRef); att = cast(AliasThisRec)(att & ~AliasThisRec.tracing); } } return wm; } override Type toHeadMutable() { return this; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class TypeEnum : Type { EnumDeclaration sym; extern (D) this(EnumDeclaration sym) { super(Tenum); this.sym = sym; } override const(char)* kind() const { return "enum"; } override Type syntaxCopy() { return this; } override d_uns64 size(const ref Loc loc) { return sym.getMemtype(loc).size(loc); } override uint alignsize() { Type t = sym.getMemtype(Loc.initial); if (t.ty == Terror) return 4; return t.alignsize(); } override Dsymbol toDsymbol(Scope* sc) { return sym; } override bool isintegral() { return sym.getMemtype(Loc.initial).isintegral(); } override bool isfloating() { return sym.getMemtype(Loc.initial).isfloating(); } override bool isreal() { return sym.getMemtype(Loc.initial).isreal(); } override bool isimaginary() { return sym.getMemtype(Loc.initial).isimaginary(); } override bool iscomplex() { return sym.getMemtype(Loc.initial).iscomplex(); } override bool isscalar() { return sym.getMemtype(Loc.initial).isscalar(); } override bool isunsigned() { return sym.getMemtype(Loc.initial).isunsigned(); } override bool isBoolean() { return sym.getMemtype(Loc.initial).isBoolean(); } override bool isString() { return sym.getMemtype(Loc.initial).isString(); } override bool isAssignable() { return sym.getMemtype(Loc.initial).isAssignable(); } override bool needsDestruction() { return sym.getMemtype(Loc.initial).needsDestruction(); } override bool needsNested() { return sym.getMemtype(Loc.initial).needsNested(); } override MATCH implicitConvTo(Type to) { MATCH m; //printf("TypeEnum::implicitConvTo()\n"); if (ty == to.ty && sym == (cast(TypeEnum)to).sym) m = (mod == to.mod) ? MATCH.exact : MATCH.constant; else if (sym.getMemtype(Loc.initial).implicitConvTo(to)) m = MATCH.convert; // match with conversions else m = MATCH.nomatch; // no match return m; } override MATCH constConv(Type to) { if (equals(to)) return MATCH.exact; if (ty == to.ty && sym == (cast(TypeEnum)to).sym && MODimplicitConv(mod, to.mod)) return MATCH.constant; return MATCH.nomatch; } override Type toBasetype() { if (!sym.members && !sym.memtype) return this; auto tb = sym.getMemtype(Loc.initial).toBasetype(); return tb.castMod(mod); // retain modifier bits from 'this' } override Expression defaultInit(const ref Loc loc) { static if (LOGDEFAULTINIT) { printf("TypeEnum::defaultInit() '%s'\n", toChars()); } // Initialize to first member of enum Expression e = sym.getDefaultValue(loc); e = e.copy(); e.loc = loc; e.type = this; // to deal with const, immutable, etc., variants return e; } override bool isZeroInit(const ref Loc loc) { return sym.getDefaultValue(loc).isBool(false); } override bool hasPointers() { return sym.getMemtype(Loc.initial).hasPointers(); } override bool hasVoidInitPointers() { return sym.getMemtype(Loc.initial).hasVoidInitPointers(); } override Type nextOf() { return sym.getMemtype(Loc.initial).nextOf(); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class TypeClass : Type { ClassDeclaration sym; AliasThisRec att = AliasThisRec.fwdref; CPPMANGLE cppmangle = CPPMANGLE.def; extern (D) this(ClassDeclaration sym) { super(Tclass); this.sym = sym; } override const(char)* kind() const { return "class"; } override d_uns64 size(const ref Loc loc) const { return Target.ptrsize; } override Type syntaxCopy() { return this; } override Dsymbol toDsymbol(Scope* sc) { return sym; } override ClassDeclaration isClassHandle() { return sym; } override bool isBaseOf(Type t, int* poffset) { if (t && t.ty == Tclass) { ClassDeclaration cd = (cast(TypeClass)t).sym; if (sym.isBaseOf(cd, poffset)) return true; } return false; } override MATCH implicitConvTo(Type to) { //printf("TypeClass::implicitConvTo(to = '%s') %s\n", to.toChars(), toChars()); MATCH m = constConv(to); if (m > MATCH.nomatch) return m; ClassDeclaration cdto = to.isClassHandle(); if (cdto) { //printf("TypeClass::implicitConvTo(to = '%s') %s, isbase = %d %d\n", to.toChars(), toChars(), cdto.isBaseInfoComplete(), sym.isBaseInfoComplete()); if (cdto.semanticRun < PASS.semanticdone && !cdto.isBaseInfoComplete()) cdto.dsymbolSemantic(null); if (sym.semanticRun < PASS.semanticdone && !sym.isBaseInfoComplete()) sym.dsymbolSemantic(null); if (cdto.isBaseOf(sym, null) && MODimplicitConv(mod, to.mod)) { //printf("'to' is base\n"); return MATCH.convert; } } m = MATCH.nomatch; if (sym.aliasthis && !(att & AliasThisRec.tracing)) { if (auto ato = aliasthisOf()) { att = cast(AliasThisRec)(att | AliasThisRec.tracing); m = ato.implicitConvTo(to); att = cast(AliasThisRec)(att & ~AliasThisRec.tracing); } } return m; } override MATCH constConv(Type to) { if (equals(to)) return MATCH.exact; if (ty == to.ty && sym == (cast(TypeClass)to).sym && MODimplicitConv(mod, to.mod)) return MATCH.constant; /* Conversion derived to const(base) */ int offset = 0; if (to.isBaseOf(this, &offset) && offset == 0 && MODimplicitConv(mod, to.mod)) { // Disallow: // derived to base // inout(derived) to inout(base) if (!to.isMutable() && !to.isWild()) return MATCH.convert; } return MATCH.nomatch; } override ubyte deduceWild(Type t, bool isRef) { ClassDeclaration cd = t.isClassHandle(); if (cd && (sym == cd || cd.isBaseOf(sym, null))) return Type.deduceWild(t, isRef); ubyte wm = 0; if (t.hasWild() && sym.aliasthis && !(att & AliasThisRec.tracing)) { if (auto ato = aliasthisOf()) { att = cast(AliasThisRec)(att | AliasThisRec.tracing); wm = ato.deduceWild(t, isRef); att = cast(AliasThisRec)(att & ~AliasThisRec.tracing); } } return wm; } override Type toHeadMutable() { return this; } override Expression defaultInit(const ref Loc loc) { static if (LOGDEFAULTINIT) { printf("TypeClass::defaultInit() '%s'\n", toChars()); } return new NullExp(loc, this); } override bool isZeroInit(const ref Loc loc) const { return true; } override bool isscope() const { return sym.stack; } override bool isBoolean() const { return true; } override bool hasPointers() const { return true; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class TypeTuple : Type { Parameters* arguments; // types making up the tuple extern (D) this(Parameters* arguments) { super(Ttuple); //printf("TypeTuple(this = %p)\n", this); this.arguments = arguments; //printf("TypeTuple() %p, %s\n", this, toChars()); debug { if (arguments) { for (size_t i = 0; i < arguments.dim; i++) { Parameter arg = (*arguments)[i]; assert(arg && arg.type); } } } } /**************** * Form TypeTuple from the types of the expressions. * Assume exps[] is already tuple expanded. */ extern (D) this(Expressions* exps) { super(Ttuple); auto arguments = new Parameters(); if (exps) { arguments.setDim(exps.dim); for (size_t i = 0; i < exps.dim; i++) { Expression e = (*exps)[i]; if (e.type.ty == Ttuple) e.error("cannot form tuple of tuples"); auto arg = new Parameter(STC.undefined_, e.type, null, null); (*arguments)[i] = arg; } } this.arguments = arguments; //printf("TypeTuple() %p, %s\n", this, toChars()); } static TypeTuple create(Parameters* arguments) { return new TypeTuple(arguments); } /******************************************* * Type tuple with 0, 1 or 2 types in it. */ extern (D) this() { super(Ttuple); arguments = new Parameters(); } extern (D) this(Type t1) { super(Ttuple); arguments = new Parameters(); arguments.push(new Parameter(0, t1, null, null)); } extern (D) this(Type t1, Type t2) { super(Ttuple); arguments = new Parameters(); arguments.push(new Parameter(0, t1, null, null)); arguments.push(new Parameter(0, t2, null, null)); } override const(char)* kind() const { return "tuple"; } override Type syntaxCopy() { Parameters* args = Parameter.arraySyntaxCopy(arguments); Type t = new TypeTuple(args); t.mod = mod; return t; } override bool equals(RootObject o) { Type t = cast(Type)o; //printf("TypeTuple::equals(%s, %s)\n", toChars(), t.toChars()); if (this == t) return true; if (t.ty == Ttuple) { TypeTuple tt = cast(TypeTuple)t; if (arguments.dim == tt.arguments.dim) { for (size_t i = 0; i < tt.arguments.dim; i++) { Parameter arg1 = (*arguments)[i]; Parameter arg2 = (*tt.arguments)[i]; if (!arg1.type.equals(arg2.type)) return false; } return true; } } return false; } override Expression defaultInit(const ref Loc loc) { auto exps = new Expressions(); exps.setDim(arguments.dim); for (size_t i = 0; i < arguments.dim; i++) { Parameter p = (*arguments)[i]; assert(p.type); Expression e = p.type.defaultInitLiteral(loc); if (e.op == TOK.error) return e; (*exps)[i] = e; } return new TupleExp(loc, exps); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** * This is so we can slice a TypeTuple */ extern (C++) final class TypeSlice : TypeNext { Expression lwr; Expression upr; extern (D) this(Type next, Expression lwr, Expression upr) { super(Tslice, next); //printf("TypeSlice[%s .. %s]\n", lwr.toChars(), upr.toChars()); this.lwr = lwr; this.upr = upr; } override const(char)* kind() const { return "slice"; } override Type syntaxCopy() { Type t = new TypeSlice(next.syntaxCopy(), lwr.syntaxCopy(), upr.syntaxCopy()); t.mod = mod; return t; } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class TypeNull : Type { extern (D) this() { //printf("TypeNull %p\n", this); super(Tnull); } override const(char)* kind() const { return "null"; } override Type syntaxCopy() { // No semantic analysis done, no need to copy return this; } override MATCH implicitConvTo(Type to) { //printf("TypeNull::implicitConvTo(this=%p, to=%p)\n", this, to); //printf("from: %s\n", toChars()); //printf("to : %s\n", to.toChars()); MATCH m = Type.implicitConvTo(to); if (m != MATCH.nomatch) return m; // NULL implicitly converts to any pointer type or dynamic array //if (type.ty == Tpointer && type.nextOf().ty == Tvoid) { Type tb = to.toBasetype(); if (tb.ty == Tnull || tb.ty == Tpointer || tb.ty == Tarray || tb.ty == Taarray || tb.ty == Tclass || tb.ty == Tdelegate) return MATCH.constant; } return MATCH.nomatch; } override bool isBoolean() const { return true; } override d_uns64 size(const ref Loc loc) const { return tvoidptr.size(loc); } override Expression defaultInit(const ref Loc loc) const { return new NullExp(Loc.initial, Type.tnull); } override void accept(Visitor v) { v.visit(this); } } /*********************************************************** */ extern (C++) final class Parameter : RootObject { StorageClass storageClass; Type type; Identifier ident; Expression defaultArg; extern (D) this(StorageClass storageClass, Type type, Identifier ident, Expression defaultArg) { this.type = type; this.ident = ident; this.storageClass = storageClass; this.defaultArg = defaultArg; } static Parameter create(StorageClass storageClass, Type type, Identifier ident, Expression defaultArg) { return new Parameter(storageClass, type, ident, defaultArg); } Parameter syntaxCopy() { return new Parameter(storageClass, type ? type.syntaxCopy() : null, ident, defaultArg ? defaultArg.syntaxCopy() : null); } /**************************************************** * Determine if parameter is a lazy array of delegates. * If so, return the return type of those delegates. * If not, return NULL. * * Returns T if the type is one of the following forms: * T delegate()[] * T delegate()[dim] */ Type isLazyArray() { Type tb = type.toBasetype(); if (tb.ty == Tsarray || tb.ty == Tarray) { Type tel = (cast(TypeArray)tb).next.toBasetype(); if (tel.ty == Tdelegate) { TypeDelegate td = cast(TypeDelegate)tel; TypeFunction tf = td.next.toTypeFunction(); if (!tf.varargs && Parameter.dim(tf.parameters) == 0) { return tf.next; // return type of delegate } } } return null; } // kludge for template.isType() override DYNCAST dyncast() const { return DYNCAST.parameter; } void accept(Visitor v) { v.visit(this); } static Parameters* arraySyntaxCopy(Parameters* parameters) { Parameters* params = null; if (parameters) { params = new Parameters(); params.setDim(parameters.dim); for (size_t i = 0; i < params.dim; i++) (*params)[i] = (*parameters)[i].syntaxCopy(); } return params; } /*************************************** * Determine number of arguments, folding in tuples. */ static size_t dim(Parameters* parameters) { size_t nargs = 0; int dimDg(size_t n, Parameter p) { ++nargs; return 0; } _foreach(parameters, &dimDg); return nargs; } /*************************************** * Get nth Parameter, folding in tuples. * Returns: * Parameter* nth Parameter * NULL not found, *pn gets incremented by the number * of Parameters */ static Parameter getNth(Parameters* parameters, size_t nth, size_t* pn = null) { Parameter param; int getNthParamDg(size_t n, Parameter p) { if (n == nth) { param = p; return 1; } return 0; } int res = _foreach(parameters, &getNthParamDg); return res ? param : null; } alias ForeachDg = extern (D) int delegate(size_t paramidx, Parameter param); /*************************************** * Expands tuples in args in depth first order. Calls * dg(void *ctx, size_t argidx, Parameter *arg) for each Parameter. * If dg returns !=0, stops and returns that value else returns 0. * Use this function to avoid the O(N + N^2/2) complexity of * calculating dim and calling N times getNth. */ extern (D) static int _foreach(Parameters* parameters, scope ForeachDg dg, size_t* pn = null) { assert(dg); if (!parameters) return 0; size_t n = pn ? *pn : 0; // take over index int result = 0; foreach (i; 0 .. parameters.dim) { Parameter p = (*parameters)[i]; Type t = p.type.toBasetype(); if (t.ty == Ttuple) { TypeTuple tu = cast(TypeTuple)t; result = _foreach(tu.arguments, dg, &n); } else result = dg(n++, p); if (result) break; } if (pn) *pn = n; // update index return result; } override const(char)* toChars() const { return ident ? ident.toChars() : "__anonymous_param"; } /********************************* * Compute covariance of parameters `this` and `p` * as determined by the storage classes of both. * Params: * returnByRef = true if the function returns by ref * p = Parameter to compare with * Returns: * true = `this` can be used in place of `p` * false = nope */ final bool isCovariant(bool returnByRef, const Parameter p) const pure nothrow @nogc @safe { enum stc = STC.ref_ | STC.in_ | STC.out_ | STC.lazy_; if ((this.storageClass & stc) != (p.storageClass & stc)) return false; return isCovariantScope(returnByRef, this.storageClass, p.storageClass); } static bool isCovariantScope(bool returnByRef, StorageClass from, StorageClass to) pure nothrow @nogc @safe { if (from == to) return true; /* Shrinking the representation is necessary because StorageClass is so wide * Params: * returnByRef = true if the function returns by ref * stc = storage class of parameter */ static uint buildSR(bool returnByRef, StorageClass stc) pure nothrow @nogc @safe { uint result; final switch (stc & (STC.ref_ | STC.scope_ | STC.return_)) { case 0: result = SR.None; break; case STC.ref_: result = SR.Ref; break; case STC.scope_: result = SR.Scope; break; case STC.return_ | STC.ref_: result = SR.ReturnRef; break; case STC.return_ | STC.scope_: result = SR.ReturnScope; break; case STC.ref_ | STC.scope_: result = SR.RefScope; break; case STC.return_ | STC.ref_ | STC.scope_: result = returnByRef ? SR.ReturnRef_Scope : SR.Ref_ReturnScope; break; } return result; } /* result is true if the 'from' can be used as a 'to' */ if ((from ^ to) & STC.ref_) // differing in 'ref' means no covariance return false; return covariant[buildSR(returnByRef, from)][buildSR(returnByRef, to)]; } /* Classification of 'scope-return-ref' possibilities */ enum SR { None, Scope, ReturnScope, Ref, ReturnRef, RefScope, ReturnRef_Scope, Ref_ReturnScope, } static bool[SR.max + 1][SR.max + 1] covariantInit() pure nothrow @nogc @safe { /* Initialize covariant[][] with this: From\To n rs s None X ReturnScope X X Scope X X X From\To r rr rs rr-s r-rs Ref X X ReturnRef X RefScope X X X X X ReturnRef-Scope X X Ref-ReturnScope X X X */ bool[SR.max + 1][SR.max + 1] covariant; foreach (i; 0 .. SR.max + 1) { covariant[i][i] = true; covariant[SR.RefScope][i] = true; } covariant[SR.ReturnScope][SR.None] = true; covariant[SR.Scope ][SR.None] = true; covariant[SR.Scope ][SR.ReturnScope] = true; covariant[SR.Ref ][SR.ReturnRef] = true; covariant[SR.ReturnRef_Scope][SR.ReturnRef] = true; covariant[SR.Ref_ReturnScope][SR.Ref ] = true; covariant[SR.Ref_ReturnScope][SR.ReturnRef] = true; return covariant; } extern (D) static immutable bool[SR.max + 1][SR.max + 1] covariant = covariantInit(); } /************************************************************* * For printing two types with qualification when necessary. * Params: * t1 = The first type to receive the type name for * t2 = The second type to receive the type name for * Returns: * The fully-qualified names of both types if the two type names are not the same, * or the unqualified names of both types if the two type names are the same. */ const(char*)[2] toAutoQualChars(Type t1, Type t2) { auto s1 = t1.toChars(); auto s2 = t2.toChars(); // show qualification only if it's different if (!t1.equals(t2) && strcmp(s1, s2) == 0) { s1 = t1.toPrettyChars(true); s2 = t2.toPrettyChars(true); } return [s1, s2]; }
D
a state of poor nutrition
D
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ module flow.common.db.EngineDatabaseConfiguration; //import javax.sql.DataSource; // //import flow.common.AbstractEngineConfiguration; // ///** // * @author Filip Hrisafov // */ //class EngineDatabaseConfiguration implements LiquibaseDatabaseConfiguration { // // protected final AbstractEngineConfiguration engineConfiguration; // // public EngineDatabaseConfiguration(AbstractEngineConfiguration engineConfiguration) { // this.engineConfiguration = engineConfiguration; // } // // @Override // public DataSource getDataSource() { // return engineConfiguration.getDataSource(); // } // // @Override // public String getDatabaseSchema() { // return engineConfiguration.getDatabaseSchema(); // } // // @Override // public String getDatabaseCatalog() { // return engineConfiguration.getDatabaseCatalog(); // } //}
D
# FIXED uartstdio.obj: C:/TI/TivaWare_C_Series-2.1.4.178/utils/uartstdio.c uartstdio.obj: C:/TI/ccsv6/tools/compiler/ti-cgt-arm_16.12.0.STS/include/stdbool.h uartstdio.obj: C:/TI/ccsv6/tools/compiler/ti-cgt-arm_16.12.0.STS/include/stdint.h uartstdio.obj: C:/TI/ccsv6/tools/compiler/ti-cgt-arm_16.12.0.STS/include/stdarg.h uartstdio.obj: C:/TI/TivaWare_C_Series-2.1.4.178/inc/hw_ints.h uartstdio.obj: C:/TI/TivaWare_C_Series-2.1.4.178/inc/hw_memmap.h uartstdio.obj: C:/TI/TivaWare_C_Series-2.1.4.178/inc/hw_types.h uartstdio.obj: C:/TI/TivaWare_C_Series-2.1.4.178/inc/hw_uart.h uartstdio.obj: C:/TI/TivaWare_C_Series-2.1.4.178/driverlib/debug.h uartstdio.obj: C:/TI/TivaWare_C_Series-2.1.4.178/driverlib/interrupt.h uartstdio.obj: C:/TI/TivaWare_C_Series-2.1.4.178/driverlib/rom.h uartstdio.obj: C:/TI/TivaWare_C_Series-2.1.4.178/driverlib/rom_map.h uartstdio.obj: C:/TI/TivaWare_C_Series-2.1.4.178/driverlib/sysctl.h uartstdio.obj: C:/TI/TivaWare_C_Series-2.1.4.178/driverlib/uart.h uartstdio.obj: C:/TI/TivaWare_C_Series-2.1.4.178/utils/uartstdio.h uartstdio.obj: C:/TI/ccsv6/tools/compiler/ti-cgt-arm_16.12.0.STS/include/stdarg.h C:/TI/TivaWare_C_Series-2.1.4.178/utils/uartstdio.c: C:/TI/ccsv6/tools/compiler/ti-cgt-arm_16.12.0.STS/include/stdbool.h: C:/TI/ccsv6/tools/compiler/ti-cgt-arm_16.12.0.STS/include/stdint.h: C:/TI/ccsv6/tools/compiler/ti-cgt-arm_16.12.0.STS/include/stdarg.h: C:/TI/TivaWare_C_Series-2.1.4.178/inc/hw_ints.h: C:/TI/TivaWare_C_Series-2.1.4.178/inc/hw_memmap.h: C:/TI/TivaWare_C_Series-2.1.4.178/inc/hw_types.h: C:/TI/TivaWare_C_Series-2.1.4.178/inc/hw_uart.h: C:/TI/TivaWare_C_Series-2.1.4.178/driverlib/debug.h: C:/TI/TivaWare_C_Series-2.1.4.178/driverlib/interrupt.h: C:/TI/TivaWare_C_Series-2.1.4.178/driverlib/rom.h: C:/TI/TivaWare_C_Series-2.1.4.178/driverlib/rom_map.h: C:/TI/TivaWare_C_Series-2.1.4.178/driverlib/sysctl.h: C:/TI/TivaWare_C_Series-2.1.4.178/driverlib/uart.h: C:/TI/TivaWare_C_Series-2.1.4.178/utils/uartstdio.h: C:/TI/ccsv6/tools/compiler/ti-cgt-arm_16.12.0.STS/include/stdarg.h:
D
module DTest.Tests.Sizeof; import DTest.TestFramework; import ez.Foundation.Types.Delegate; mixin TestGroup!("Sizeof"); extern(C++) size_t SizeOfDelegate(); @Test("Sizeof") void SizeofTest() { if(EZ_TEST_BLOCK(ezTestBlock.Enabled, "Delegate")) { EZ_TEST_INT(ezDelegate!(Signature!(void function())).sizeof, SizeOfDelegate()); } }
D
module directx.d2d1_2helper; /*=========================================================================*\ Copyright (c) Microsoft Corporation. All rights reserved. File: D2D1_2Helper.h Module Name: D2D Description: Helper files over the D2D interfaces and APIs. \*=========================================================================*/ public import directx.d2d1_2; // TODO:
D
import std.stdio; import std.string; import bcd.libxml2.parser; import bcd.libxml2.tree; void print_element_names(char[] prefix, _xmlNode * a_node) { _xmlNode *cur_node = null; for (cur_node = a_node; cur_node; cur_node = cur_node.next) { if (cur_node.type == xmlElementType.XML_ELEMENT_NODE) { writefln("%s%s", prefix, toString(cur_node.name)); print_element_names(prefix ~ " ", cur_node.children); } } } /** * Simple example to parse a file called "file.xml", * walk down the DOM, and print the name of the * xml elements nodes. */ int main(char[][] args) { _xmlDoc *doc = null; _xmlNode *root_element = null; if (args.length != 2) return(1); /* * this initialize the library and check potential ABI mismatches * between the version it was compiled for and the actual shared * library used. */ xmlCheckVersion(20621); /*parse the file and get the DOM */ doc = xmlReadFile(args[1], null, 0); if (doc == null) { printf("error: could not parse file %s\n", args[1]); } /*Get the root element node */ root_element = xmlDocGetRootElement(doc); print_element_names("", root_element); /*free the document */ xmlFreeDoc(doc); /* *Free the global variables that may *have been allocated by the parser. */ xmlCleanupParser(); return 0; }
D
/* Copyright (c) 2013-2020 Timur Gafarov Boost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * Copyright: Timur Gafarov 2013-2020. * License: $(LINK2 boost.org/LICENSE_1_0.txt, Boost License 1.0). * Authors: Timur Gafarov */ module dlib.geometry.trimesh; import std.stdio; import std.math; import dlib.core.memory; import dlib.container.array; import dlib.math.vector; import dlib.geometry.triangle; struct Index { uint a, b, c; } struct FaceGroup { Array!Index indicesArray; int materialIndex; @property Index[] indices() { return indicesArray.data; } void addFace(uint a, uint b, uint c) { indicesArray.insertBack(Index(a, b, c)); } void addFaces(Index[] inds) { indicesArray.insertBack(inds); } } /// Triangle mesh class TriMesh { Array!(Vector3f) verticesArray; Array!(Vector3f) normalsArray; Array!(Vector3f) tangentsArray; Array!(Vector2f) texcoordsArray; Array!FaceGroup facegroupsArray; @property Vector3f[] vertices() { return verticesArray.data; } @property Vector3f[] normals() { return normalsArray.data; } @property Vector3f[] tangents() { return tangentsArray.data; } @property Vector2f[] texcoords() { return texcoordsArray.data; } @property FaceGroup[] facegroups() { return facegroupsArray.data; } this() { } ~this() { verticesArray.free(); normalsArray.free(); tangentsArray.free(); texcoordsArray.free(); foreach(fc; facegroupsArray) fc.indicesArray.free(); facegroupsArray.free(); } void addVertex(Vector3f v) { verticesArray.insertBack(v); } void addNormal(Vector3f n) { normalsArray.insertBack(n); } void addTangent(Vector3f t) { tangentsArray.insertBack(t); } void addTexcoord(Vector2f t) { texcoordsArray.insertBack(t); } void addVertices(Vector3f[] verts) { verticesArray.insertBack(verts); } void addNormals(Vector3f[] norms) { normalsArray.insertBack(norms); } void addTangents(Vector3f[] tans) { tangentsArray.insertBack(tans); } void addTexcoords(Vector2f[] texs) { texcoordsArray.insertBack(texs); } FaceGroup* addFacegroup() { FaceGroup fg; facegroupsArray.insertBack(fg); return &facegroupsArray.data[$-1]; } Triangle getTriangle(uint facegroupIndex, uint triIndex) { Triangle tri; Index triIdx = facegroupsArray[facegroupIndex].indicesArray[triIndex]; tri.v[0] = verticesArray[triIdx.a]; tri.v[1] = verticesArray[triIdx.b]; tri.v[2] = verticesArray[triIdx.c]; tri.n[0] = normalsArray[triIdx.a]; tri.n[1] = normalsArray[triIdx.b]; tri.n[2] = normalsArray[triIdx.c]; if (texcoordsArray.length == verticesArray.length) { tri.t1[0] = texcoordsArray[triIdx.a]; tri.t1[1] = texcoordsArray[triIdx.b]; tri.t1[2] = texcoordsArray[triIdx.c]; } tri.normal = planeNormal(tri.v[0], tri.v[1], tri.v[2]); tri.barycenter = (tri.v[0] + tri.v[1] + tri.v[2]) / 3; tri.d = (tri.v[0].x * tri.normal.x + tri.v[0].y * tri.normal.y + tri.v[0].z * tri.normal.z); tri.edges[0] = tri.v[1] - tri.v[0]; tri.edges[1] = tri.v[2] - tri.v[1]; tri.edges[2] = tri.v[0] - tri.v[2]; tri.materialIndex = facegroupsArray[facegroupIndex].materialIndex; return tri; } /** * Read-only triangle aggregate */ int opApply(scope int delegate(ref Triangle) dg) { int result = 0; for (uint fgi = 0; fgi < facegroupsArray.length; fgi++) for (uint i = 0; i < facegroupsArray[fgi].indices.length; i++) { Triangle tri = getTriangle(fgi, i); result = dg(tri); if (result) break; } return result; } void genTangents() { tangentsArray.free(); Vector3f[] sTan = New!(Vector3f[])(verticesArray.length); Vector3f[] tTan = New!(Vector3f[])(verticesArray.length); foreach(i, v; sTan) { sTan[i] = Vector3f(0.0f, 0.0f, 0.0f); tTan[i] = Vector3f(0.0f, 0.0f, 0.0f); } foreach(ref fg; facegroupsArray) foreach(ref index; fg.indicesArray) { uint i0 = index.a; uint i1 = index.b; uint i2 = index.c; Vector3f v0 = verticesArray[i0]; Vector3f v1 = verticesArray[i1]; Vector3f v2 = verticesArray[i2]; Vector2f w0 = texcoordsArray[i0]; Vector2f w1 = texcoordsArray[i1]; Vector2f w2 = texcoordsArray[i2]; float x1 = v1.x - v0.x; float x2 = v2.x - v0.x; float y1 = v1.y - v0.y; float y2 = v2.y - v0.y; float z1 = v1.z - v0.z; float z2 = v2.z - v0.z; float s1 = w1[0] - w0[0]; float s2 = w2[0] - w0[0]; float t1 = w1[1] - w0[1]; float t2 = w2[1] - w0[1]; float r = (s1 * t2) - (s2 * t1); // Prevent division by zero if (r == 0.0f) r = 1.0f; float oneOverR = 1.0f / r; Vector3f sDir = Vector3f((t2 * x1 - t1 * x2) * oneOverR, (t2 * y1 - t1 * y2) * oneOverR, (t2 * z1 - t1 * z2) * oneOverR); Vector3f tDir = Vector3f((s1 * x2 - s2 * x1) * oneOverR, (s1 * y2 - s2 * y1) * oneOverR, (s1 * z2 - s2 * z1) * oneOverR); sTan[i0] += sDir; tTan[i0] += tDir; sTan[i1] += sDir; tTan[i1] += tDir; sTan[i2] += sDir; tTan[i2] += tDir; } tangentsArray.resize(vertices.length, Vector3f(0.0f, 0.0f, 0.0f)); // Calculate vertex tangent foreach(i, v; tangents) { Vector3f n = normalsArray[i]; Vector3f t = sTan[i]; // Gram-Schmidt orthogonalize Vector3f tangent = (t - n * dot(n, t)); tangent.normalize(); tangentsArray[i] = tangent; } Delete(sTan); Delete(tTan); } }
D
// ************************************************** // ************************************************************ // EXIT // ************************************************************ INSTANCE DIA_BaalKagan_EXIT(C_INFO) { npc = rbl_1332_baalkagan; nr = 999; condition = DIA_BaalKagan_EXIT_Condition; information = DIA_BaalKagan_EXIT_Info; permanent = 1; description = DIALOG_ENDE; }; FUNC INT DIA_BaalKagan_EXIT_Condition() { return 1; }; FUNC VOID DIA_BaalKagan_EXIT_Info() { B_StopProcessInfos (self); }; // ************************************************************ // Hallo // ************************************************************ INSTANCE DIA_BaalKagan_Hello(C_INFO) { npc = rbl_1332_baalkagan; nr = 1; condition = DIA_BaalKagan_Hello_Condition; information = DIA_BaalKagan_Hello_Info; permanent = 0; description = "Jesteś z obozu Sekty, nieprawdaż?"; }; FUNC INT DIA_BaalKagan_Hello_Condition() { return 1; }; FUNC VOID DIA_BaalKagan_Hello_Info() { AI_Output (other, self,"DIA_BaalKagan_Hello_15_00"); //Jesteś z obozu Sekty, nieprawdaż? AI_Output (self, other,"DIA_BaalKagan_Hello1_13_01"); //Byłem, ale już nie należę do świrów z bagna. AI_Output (self, other,"DIA_BaalKagan_Hello1_13_02"); //Jestem Baal Kagan, znaczy bez tego Baal. A Śniący to kawałek cuchnącego gówna. }; // ************************************************************ // Warum hier // ************************************************************ //TODO: Sher, albo poprawic tresc dialogu albo zostawic wywalony, logiczna calosc to to narazie nie jest INSTANCE DIA_BaalKagan_WhyHere(C_INFO) { npc = rbl_1332_baalkagan; nr = 1; condition = DIA_BaalKagan_WhyHere_Condition; information = DIA_BaalKagan_WhyHere_Info; permanent = 0; description = "Co tu robisz?"; }; FUNC INT DIA_BaalKagan_WhyHere_Condition() { if (Npc_KnowsInfo(hero,DIA_BaalKagan_Hello)) { return 1; }; }; FUNC VOID DIA_BaalKagan_WhyHere_Info() { AI_Output (other, self,"DIA_BaalKagan_WhyHere_15_00"); //Co tu robisz? AI_Output (self, other,"DIA_BaalKagan_WhyHere_13_01"); //Kiedyś werbowałem nowych do Bractwa. AI_Output (self, other,"DIA_BaalKagan_WhyHere_13_02"); //Ale to dawne dzieje. Teraz zajmuję się wyłącznie sprzedażą ziela. AI_Output (self, other,"DIA_BaalKagan_WhyHere_13_03"); //Palenie ziela to dość popularne zajęcie w tych stronach. Może nawet zbyt popularne. Ledwie nadążam z kolejnymi dostawami. Log_CreateTopic (GE_TraderOR, LOG_NOTE); B_LogEntry (GE_TraderOR, "Baal Kagan sprzedaje małe porcje ziela w obozie."); }; // ************************************************************ // TRADE // ************************************************************ INSTANCE DIA_BaalKagan_TRADE (C_INFO) { npc = rbl_1332_baalkagan; nr = 800; condition = DIA_BaalKagan_TRADE_Condition; information = DIA_BaalKagan_TRADE_Info; permanent = 1; description = "Pokaż mi co masz do zaoferowania."; trade = 1; }; FUNC INT DIA_BaalKagan_TRADE_Condition() { if (Npc_KnowsInfo(hero,DIA_BaalKagan_WhyHere)) { return 1; }; }; FUNC VOID DIA_BaalKagan_TRADE_Info() { AI_Output (other, self,"DIA_BaalKagan_TRADE_15_00"); //Pokaż, co masz do zaoferowania. AI_Output (self, other,"DIA_BaalKagan_TRADE_13_01"); //Jak sobie życzysz. }; // ************************************************************ // Hilfe anfordern // ************************************************************ INSTANCE DIA_BaalKagan_OrderHelp(C_INFO) { npc = rbl_1332_baalkagan; nr = 2; condition = DIA_BaalKagan_OrderHelp_Condition; information = DIA_BaalKagan_OrderHelp_Info; important = 1; permanent = 0; description = ""; }; FUNC INT DIA_BaalKagan_OrderHelp_Condition() { if (Npc_KnowsInfo(hero,DIA_BaalKagan_Hello)) { return 1; }; }; FUNC VOID DIA_BaalKagan_OrderHelp_Info() { AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_01"); //Zaczekaj chwilkę. Jest coś o czym chciałbym z Tobą porozmawiać. AI_Output (other, self,"DIA_BaalKagan_OrderHelp1_15_02"); //Mów. AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_03"); //To dość delikatna sprawa... AI_PlayAni (self, "T_SEARCH"); AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_04"); //Spotkałeś już Baal Tarana? if (Npc_KnowsInfo(hero,DIA_BaalTaran_Greet)) { AI_Output (other, self,"DIA_BaalKagan_OrderHelp1_15_05"); //Tak. } else { AI_Output (other, self,"DIA_BaalKagan_OrderHelp1_15_06"); //Jeszcze nie. }; AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_07"); //A więc ta menda... AI_Output (other, self,"DIA_BaalKagan_OrderHelp1_15_08"); //Menda? Przecież pochodzicie z tego samego obozu. AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_09"); //To stare dzieje. Teraz liczy się tylko to, żeby przetrwać. AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_10"); //A żeby przetrwać trzeba mieć za co żyć. AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_11"); //A żeby mieć za co żyć trzeba zarabiać. AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_12"); //A żeby zarabiać trzeba coś sprzedać. AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_13"); //A żeby coś... AI_Output (other, self,"DIA_BaalKagan_OrderHelp1_15_14"); //Skończ już z tą wyliczanką. Mów o co chodzi! AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_15"); //Taran robi mi konkurencję. AI_Output (other, self,"DIA_BaalKagan_OrderHelp1_15_16"); //Mówisz o handlu zielem? AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_17"); //Tak, do cholery. Przecież nie o kręceniu tyłkiem! AI_Output (other, self,"DIA_BaalKagan_OrderHelp1_15_18"); //Chyba wiem do czego zmierzasz. Moja odpowiedź brzmi - NIE. Nie wypruję mu flaków tylko dlatego, że sprzedaje ziele. AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_19"); //Spokojnie, wysnułeś zbyt pochopne wnioski. A kto mówi o zabijaniu? AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_20"); //Wystarczy, że Taran zrazi do siebie klientów. Ja już zajmę się resztą. AI_Output (other, self,"DIA_BaalKagan_OrderHelp1_15_21"); //Co miałbym zrobić? AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_22"); //Taran sam nie zbiera ziela. Jego dostawca to pustelnik Gilbert. if (!Npc_KnowsInfo(hero,DIA_Gilbert_First)) { AI_Output (other, self,"DIA_BaalKagan_OrderHelp1_15_23"); //Gdzie go znajdę? AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_24"); //W tym właśnie tkwi problem. Nie mam bladego pojęcia. AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_25"); //Musisz odnaleźć Gilberta. } else { AI_Output (other, self,"DIA_BaalKagan_OrderHelp1_15_26"); //Wiem gdzie mieszka. AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_27"); //To świetnie! }; AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_28"); //Powiesz temu staremu pacanowi, że przyszedłeś po dostawę dla Tarana. AI_Output (other, self,"DIA_BaalKagan_OrderHelp1_15_29"); //Gilbert albo Taran nie będą nic podejrzewać? AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_30"); //Gilbert to już Twój problem. Co do Tarana... Człowieku on jest cały czas zabakany w trupa! Nie odróżniłby w słoneczny dzień gołej dupy od mordy orka. AI_Output (other, self,"DIA_BaalKagan_OrderHelp1_15_31"); //No dobra. I co dalej? AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_32"); //Kiedy dostaniesz paczkę od Gilberta najpierw przyniesiesz ją do mnie, a ja trochę doprawię ziele. AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_33"); //Później zaniesiesz paczkę Taranowi. AI_Output (other, self,"DIA_BaalKagan_OrderHelp1_15_34"); //To wszystko? AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_35"); //Tak, mówiłem, że dla kogoś takiego jak Ty to żaden wysiłek. AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_36"); //Tylko musisz paczkę najpierw przynieść mi. Jeżeli zaniesiesz ją od razu do Tarana to mój misterny plan szlag trafi. AI_Output (other, self,"DIA_BaalKagan_OrderHelp1_15_37"); //No dobra, a co ja będę z tego miał? AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_38"); //Zapłacę Ci... 300 bryłek. AI_Output (other, self,"DIA_BaalKagan_OrderHelp1_15_39"); //To za mało. AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_40"); //No dobra niech będzie 400, ale ani bryłki więcej! AI_Output (other, self,"DIA_BaalKagan_OrderHelp1_15_41"); //Nie o tym myślałem. Dasz mi udział w zyskach. AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_42"); //Chyba za mocno uderzyłeś się w głowę! AI_Output (other, self,"DIA_BaalKagan_OrderHelp1_15_43"); //Udział w zyskach albo Taran o wszystkim się dowie. Ciekawe co wtedy powiedzą rebelianci, którzy kupują ziele? Myślę, że raczej Twoja popularność od tego nie wzrośnie. AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_44"); //Ale z ciebie skurwiel! Niech będzie. Dostaniesz udział w utargu. Powiedzmy... 10 procent. AI_Output (other, self,"DIA_BaalKagan_OrderHelp1_15_45"); //Mam lepszy pomysł. Odpalisz mi 20 procent co 10 dni. AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_46"); //Ty... AI_Output (other, self,"DIA_BaalKagan_OrderHelp1_15_47"); //Uważaj na słowa jeżeli lubisz swój język. AI_Output (self, other,"DIA_BaalKagan_OrderHelp1_13_48"); //Niech Cię szlag! Dobra, przynieś mi tę cholerną paczkę. Zaczynam żałować, że wdałem się z Tobą w interesy... Log_CreateTopic (CH2_RBL_Stuff, LOG_MISSION); Log_SetTopicStatus (CH2_RBL_Stuff, LOG_RUNNING); B_LogEntry (CH2_RBL_Stuff, "A ludzie mówią, że ruda nie leży na ziemi. Pomogę Kaganowi pozbyć się konkurencji, czyli Baal Tarana w zamian za 20-procentowy udział w zyskach. Rudę będę odbierał co 10 dni. Muszę mu tylko dostarczyć paczkę ziela od niejakiego Gilberta."); }; // ************************************************************ INSTANCE DIA_BaalKagan_StuffHave (C_INFO) { npc = rbl_1332_baalkagan; nr = 3; condition = DIA_BaalKagan_StuffHave_Condition; information = DIA_BaalKagan_StuffHave_Info; important = 0; permanent = 0; description = "Mam przesyłkę od Gilberta."; }; FUNC INT DIA_BaalKagan_StuffHave_Condition() { if (Npc_KnowsInfo(hero,DIA_Gilbert_Stuff1))&&(Npc_KnowsInfo(hero,DIA_BaalKagan_OrderHelp))&&(NPC_HasItems(other,package_stuff)>=1) { return 1; }; }; FUNC VOID DIA_BaalKagan_StuffHave_Info() { AI_Output (other, self,"DIA_BaalKagan_StuffHave_15_01"); //Mam przesyłkę od Gilberta. AI_Output (self, other,"DIA_BaalKagan_StuffHave_13_02"); //Nareszcie. Daj ziele to je doprawię... B_GiveInvItems (other, self, package_stuff, 1); Ai_Wait (self,2); B_GiveInvItems (self, other, package_stuff, 1); AI_Output (self, other,"DIA_BaalKagan_StuffHave_13_03"); //W porządku, gotowe. Zanieś paczkę Baal Taranowi z pozdrowieniami od Gilberta. AI_Output (other, self,"DIA_BaalKagan_StuffHave_15_04"); //Bez obaw. Zaraz po tym wrócę po swój udział. B_LogEntry (CH2_RBL_Stuff, "Mam już doprawioną paczkę ziela. Czas oddać ją Baal Taranowi."); }; var int kagan_pay; // ************************************************************ INSTANCE DIA_BaalKagan_StuffHave1 (C_INFO) { npc = rbl_1332_baalkagan; nr = 4; condition = DIA_BaalKagan_StuffHave1_Condition; information = DIA_BaalKagan_StuffHave1_Info; important = 0; permanent = 0; description = "Zrobiłem swoje, czas odebrać zapłatę."; }; FUNC INT DIA_BaalKagan_StuffHave1_Condition() { if (Npc_KnowsInfo(hero,DIA_BaalTaran_Stuff)) { return 1; }; }; FUNC VOID DIA_BaalKagan_StuffHave1_Info() { AI_Output (other, self,"DIA_BaalKagan_StuffHave1_15_01"); //Zrobiłem swoje, czas odebrać zapłatę. AI_Output (self, other,"DIA_BaalKagan_StuffHave1_13_02"); //Nie tak szybko. Wróć za 10 dni, wtedy dostaniesz swoją dolę. AI_Output (other, self,"DIA_BaalKagan_StuffHave1_15_03"); //Możesz być pewien, że o tym nie zapomnę. kagan_pay = B_SetDayTolerance()+10; Log_SetTopicStatus (CH2_RBL_Stuff, LOG_SUCCESS); B_LogEntry (CH2_RBL_Stuff, "Sprawa załatwiona. Muszę tylko pamiętać, żeby wracać co tydzień po swoją dolę."); }; // ************************************************************ INSTANCE DIA_BaalKagan_StuffHave2 (C_INFO) { npc = rbl_1332_baalkagan; nr = 5; condition = DIA_BaalKagan_StuffHave2_Condition; information = DIA_BaalKagan_StuffHave2_Info; important = 0; permanent = 1; description = "Chyba coś mi się należy."; }; FUNC INT DIA_BaalKagan_StuffHave2_Condition() { //TODO: Kiedys trzeba zatrzymać ta nieustanna machine zarabiania kasy if (Npc_KnowsInfo(hero,DIA_BaalTaran_Stuff))&&(kagan_pay <= (Wld_GetDay()))&&(kagan_pay!=0) { return 1; }; }; FUNC VOID DIA_BaalKagan_StuffHave2_Info() { //Jako ze zmniejszona zostala zaplata dla Tarana z 800 na 300 //to zmniejszam rownież troche kase ktora wypłaca Kagan. AI_Output (other, self,"DIA_BaalKagan_StuffHave2_15_01"); //Chyba coś mi się należy. if(Aloes_Creation==TRUE)&&(Taran_300ore) { AI_Output (self, other,"DIA_BaalKagan_StuffHave2_13_02"); //Taran przejął ostatnio większość moich klientów, ledwo starcza mi rudy na jedzenie. AI_Output (self, other,"DIA_BaalKagan_StuffHave2_13_03"); //Nie mam nic dla Ciebie. kagan_pay=0; } else { AI_Output (self, other,"DIA_BaalKagan_StuffHave2_13_02"); //Zabieraj swoją dolę i zejdź mi z oczu, krwiopijco! CreateInvItems (self, ItMiNugget, 100); B_GiveInvItems (self, other, ItMiNugget, 100); }; kagan_pay = B_SetDayTolerance()+10; }; // ************************************************************ INSTANCE DIA_BaalKagan_Hanis (C_INFO) { npc = rbl_1332_baalkagan; nr = 6; condition = DIA_BaalKagan_Hanis_Condition; information = DIA_BaalKagan_Hanis_Info; important = 0; permanent = 0; description = "Mam pytanie."; }; FUNC INT DIA_BaalKagan_Hanis_Condition() { if (Npc_KnowsInfo(hero,DIA_Quentin_Hanis1))&&(Npc_KnowsInfo(hero,DIA_BaalKagan_Hello)) { return 1; }; }; FUNC VOID DIA_BaalKagan_Hanis_Info() { AI_Output (other, self,"DIA_BaalKagan_Hanis_15_01"); //Mam pytanie. AI_Output (self, other,"DIA_BaalKagan_Hanis_13_02"); //Jakie? AI_Output (other, self,"DIA_BaalKagan_Hanis_15_03"); //Masz na sprzedaż jakiś specyfik, po którym człowiek wpada w szał? AI_Output (self, other,"DIA_BaalKagan_Hanis_13_04"); //Hmm. Znam tylko jedną taką roślinę. To klątwa berserkera. AI_Output (self, other,"DIA_BaalKagan_Hanis_13_05"); //Bardzo rzadkie ziele. AI_Output (other, self,"DIA_BaalKagan_Hanis_15_06"); //Komuś je sprzedałeś? AI_Output (self, other,"DIA_BaalKagan_Hanis_13_07"); //Jakiś czas temu Kharim pytał mnie o podobny specyfik. Akurat znalazłem ziele na orkowym cmentarzu. Sporo za nie zapłacił więc o nic więcej nie pytałem. AI_Output (other, self,"DIA_BaalKagan_Hanis_15_08"); //Bardzo mi pomogłeś. Bywaj. B_LogEntry (CH2_RBL_Mem, "To Baal Kagan sprzedał Kharimowi klątwę berserkera - ziele, po którym człowiek wpada w szał. W końcu mam dowody na to, że Gor Hanis jest niewinny. Muszę porozmawiać z Ratfordem."); }; // ************************************************** INSTANCE DIA_rbl_1332_baalkagan_Stew (C_INFO) { npc = rbl_1332_baalkagan; nr = 12; condition = DIA_rbl_1332_baalkagan_Stew_Condition; information = DIA_rbl_1332_baalkagan_Stew_Info; permanent = 0; important = 0; description = "Twoja porcja pysznego gulaszu, smacznego."; }; FUNC INT DIA_rbl_1332_baalkagan_Stew_Condition() { if (Npc_KnowsInfo (hero, DIA_Fox_Camp))&&(NPC_HasItems(other,ItFo_Stew)>=1) { return 1; }; }; FUNC VOID DIA_rbl_1332_baalkagan_Stew_Info() { fox_stew = fox_stew + 1; //TODO: Sher FIX Needed. anotha' crappy dialog created by orc AI_Output (other, self, "DIA_rbl_1332_baalkagan_Stew_15_01"); //Twoja porcja pysznego gulaszu, smacznego. AI_Output (self, other, "DIA_rbl_1332_baalkagan_Stew_11_02"); //Słuchaj no, dawaj swoją porcje, bo inaczej to będą ostatnie słowa w twoim życiu. AI_Output (other, self, "DIA_rbl_1332_baalkagan_Stew_15_03"); //Och, Doprawdy? AI_Output (self, other, "DIA_rbl_1332_baalkagan_Stew_11_04"); //Nie cholera, żartowałem, dwie porcje to dawka śmiertelna. B_GiveInvItems (other, self, ItFo_Stew, 1); B_LogEntry (CH2_Rbl_Food, "Kagana trzymają się żarty, mimo tego że musiał zjeść swoją porcje."); }; // ************************************************** INSTANCE DIA_rbl_1332_baalkagan_Aloes (C_INFO) { npc = rbl_1332_baalkagan; nr = 12; condition = DIA_rbl_1332_baalkagan_Aloes_Condition; information = DIA_rbl_1332_baalkagan_Aloes_Info; permanent = 0; important = 0; description = "Potrafisz przyrządzić miksturę z aloesu?"; }; FUNC INT DIA_rbl_1332_baalkagan_Aloes_Condition() { if (NPC_HasItems(other,aloes)>=1)&&(aloes_find)&& (!Npc_KnowsInfo (hero, DIA_rbl_1331_baaltaran_Aloes)) { return 1; }; }; FUNC VOID DIA_rbl_1332_baalkagan_Aloes_Info() { //crappy dialog created by orc AI_Output (other, self, "DIA_rbl_1332_baalkagan_Aloes_15_01"); //Potrafisz przyrządzić miksturę z aloesu? AI_Output (self, other, "DIA_rbl_1332_baalkagan_Aloes_11_02"); //Nie, ale Taran na pewno da sobie radę, pomagał kiedyś przygotowywać guru mikstury pozwalające na kontakt ze Śniącym. };
D
/** * This module contains a minimal garbage collector implementation according to * published requirements. This library is mostly intended to serve as an * example, but it is usable in applications which do not rely on a garbage * collector to clean up memory (ie. when dynamic array resizing is not used, * and all memory allocated with 'new' is freed deterministically with * 'delete'). * * Please note that block attribute data must be tracked, or at a minimum, the * FINALIZE bit must be tracked for any allocated memory block because calling * rt_finalize on a non-object block can result in an access violation. In the * allocator below, this tracking is done via a leading uint bitmask. A real * allocator may do better to store this data separately, similar to the basic * GC. * * Copyright: Copyright Sean Kelly 2005 - 2009. * License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>. * Authors: Sean Kelly */ /* Copyright Sean Kelly 2005 - 2009. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ module gc.gc; private { import core.stdc.stdlib; import core.stdc.stdio; enum BlkAttr : uint { FINALIZE = 0b0000_0001, NO_SCAN = 0b0000_0010, NO_MOVE = 0b0000_0100, APPENDABLE = 0b0000_1000, ALL_BITS = 0b1111_1111 } struct BlkInfo { void* base; size_t size; uint attr; } extern (C) void thread_init(); extern (C) void onOutOfMemoryError(); struct Proxy { extern (C) void function() gc_enable; extern (C) void function() gc_disable; extern (C) void function() gc_collect; extern (C) void function() gc_minimize; extern (C) uint function(void*) gc_getAttr; extern (C) uint function(void*, uint) gc_setAttr; extern (C) uint function(void*, uint) gc_clrAttr; extern (C) void* function(size_t, uint) gc_malloc; extern (C) BlkInfo function(size_t, uint) gc_qalloc; extern (C) void* function(size_t, uint) gc_calloc; extern (C) void* function(void*, size_t, uint ba) gc_realloc; extern (C) size_t function(void*, size_t, size_t) gc_extend; extern (C) size_t function(size_t) gc_reserve; extern (C) void function(void*) gc_free; extern (C) void* function(void*) gc_addrOf; extern (C) size_t function(void*) gc_sizeOf; extern (C) BlkInfo function(void*) gc_query; extern (C) void function(void*) gc_addRoot; extern (C) void function(void*, size_t) gc_addRange; extern (C) void function(void*) gc_removeRoot; extern (C) void function(void*) gc_removeRange; } __gshared Proxy pthis; __gshared Proxy* proxy; void initProxy() { pthis.gc_enable = &gc_enable; pthis.gc_disable = &gc_disable; pthis.gc_collect = &gc_collect; pthis.gc_minimize = &gc_minimize; pthis.gc_getAttr = &gc_getAttr; pthis.gc_setAttr = &gc_setAttr; pthis.gc_clrAttr = &gc_clrAttr; pthis.gc_malloc = &gc_malloc; pthis.gc_qalloc = &gc_qalloc; pthis.gc_calloc = &gc_calloc; pthis.gc_realloc = &gc_realloc; pthis.gc_extend = &gc_extend; pthis.gc_reserve = &gc_reserve; pthis.gc_free = &gc_free; pthis.gc_addrOf = &gc_addrOf; pthis.gc_sizeOf = &gc_sizeOf; pthis.gc_query = &gc_query; pthis.gc_addRoot = &gc_addRoot; pthis.gc_addRange = &gc_addRange; pthis.gc_removeRoot = &gc_removeRoot; pthis.gc_removeRange = &gc_removeRange; } __gshared void** roots = null; __gshared size_t nroots = 0; struct Range { void* pos; size_t len; } __gshared Range* ranges = null; __gshared size_t nranges = 0; } extern (C) void gc_init() { // NOTE: The GC must initialize the thread library before its first // collection, and always before returning from gc_init(). thread_init(); initProxy(); } extern (C) void gc_term() { free( roots ); free( ranges ); } extern (C) void gc_enable() { if( proxy is null ) return; return proxy.gc_enable(); } extern (C) void gc_disable() { if( proxy is null ) return; return proxy.gc_disable(); } extern (C) void gc_collect() { if( proxy is null ) return; return proxy.gc_collect(); } extern (C) void gc_minimize() { if( proxy is null ) return; return proxy.gc_minimize(); } extern (C) uint gc_getAttr( void* p ) { if( proxy is null ) return 0; return proxy.gc_getAttr( p ); } extern (C) uint gc_setAttr( void* p, uint a ) { if( proxy is null ) return 0; return proxy.gc_setAttr( p, a ); } extern (C) uint gc_clrAttr( void* p, uint a ) { if( proxy is null ) return 0; return proxy.gc_clrAttr( p, a ); } extern (C) void* gc_malloc( size_t sz, uint ba = 0 ) { if( proxy is null ) { void* p = malloc( sz ); if( sz && p is null ) onOutOfMemoryError(); return p; } return proxy.gc_malloc( sz, ba ); } extern (C) BlkInfo gc_qalloc( size_t sz, uint ba = 0 ) { if( proxy is null ) { BlkInfo retval; retval.base = gc_malloc(sz, ba); retval.size = sz; retval.attr = ba; return retval; } return proxy.gc_qalloc( sz, ba ); } extern (C) void* gc_calloc( size_t sz, uint ba = 0 ) { if( proxy is null ) { void* p = calloc( 1, sz ); if( sz && p is null ) onOutOfMemoryError(); return p; } return proxy.gc_calloc( sz, ba ); } extern (C) void* gc_realloc( void* p, size_t sz, uint ba = 0 ) { if( proxy is null ) { p = realloc( p, sz ); if( sz && p is null ) onOutOfMemoryError(); return p; } return proxy.gc_realloc( p, sz, ba ); } extern (C) size_t gc_extend( void* p, size_t mx, size_t sz ) { if( proxy is null ) return 0; return proxy.gc_extend( p, mx, sz ); } extern (C) size_t gc_reserve( size_t sz ) { if( proxy is null ) return 0; return proxy.gc_reserve( sz ); } extern (C) void gc_free( void* p ) { if( proxy is null ) return free( p ); return proxy.gc_free( p ); } extern (C) void* gc_addrOf( void* p ) { if( proxy is null ) return null; return proxy.gc_addrOf( p ); } extern (C) size_t gc_sizeOf( void* p ) { if( proxy is null ) return 0; return proxy.gc_sizeOf( p ); } extern (C) BlkInfo gc_query( void* p ) { if( proxy is null ) return BlkInfo.init; return proxy.gc_query( p ); } extern (C) void gc_addRoot( void* p ) { if( proxy is null ) { void** r = cast(void**) realloc( roots, (nroots+1) * roots[0].sizeof ); if( r is null ) onOutOfMemoryError(); r[nroots++] = p; roots = r; return; } return proxy.gc_addRoot( p ); } extern (C) void gc_addRange( void* p, size_t sz ) { //printf("gcstub::gc_addRange() proxy = %p\n", proxy); if( proxy is null ) { Range* r = cast(Range*) realloc( ranges, (nranges+1) * ranges[0].sizeof ); if( r is null ) onOutOfMemoryError(); r[nranges].pos = p; r[nranges].len = sz; ranges = r; ++nranges; return; } return proxy.gc_addRange( p, sz ); } extern (C) void gc_removeRoot( void *p ) { if( proxy is null ) { for( size_t i = 0; i < nroots; ++i ) { if( roots[i] is p ) { roots[i] = roots[--nroots]; return; } } assert( false ); } return proxy.gc_removeRoot( p ); } extern (C) void gc_removeRange( void *p ) { if( proxy is null ) { for( size_t i = 0; i < nranges; ++i ) { if( ranges[i].pos is p ) { ranges[i] = ranges[--nranges]; return; } } assert( false ); } return proxy.gc_removeRange( p ); } extern (C) Proxy* gc_getProxy() { return &pthis; } export extern (C) void gc_setProxy( Proxy* p ) { if( proxy !is null ) { // TODO: Decide if this is an error condition. } proxy = p; foreach( r; roots[0 .. nroots] ) proxy.gc_addRoot( r ); foreach( r; ranges[0 .. nranges] ) proxy.gc_addRange( r.pos, r.len ); } export extern (C) void gc_clrProxy() { foreach( r; ranges[0 .. nranges] ) proxy.gc_removeRange( r.pos ); foreach( r; roots[0 .. nroots] ) proxy.gc_removeRoot( r ); proxy = null; }
D
module lfant.gameobject; import std.signals; import std.path; import std.file; import lfant.properties; import lfant.game; public { import std.algorithm; import std.array; } class GameObject { class EventBase { public: void Clear() { } } class Event(T...) : EventBase { mixin Signal!(T); } class EventVar(T) : EventBase { this(T* var) { this.var = var; } T* var; } void serialize(Properties prop) { } void loadFile(string path) { if(path.empty) return; string rp = game.getAssetPath(path); // string rp = path; if(!exists(rp)) return; Properties prop = new Properties(); prop.loadFile(rp); prop.mode = Properties.Mode.Input; // string type = type::Descope(type::Name(this)); // to_lower(type); if(Properties pc = prop.getChild(0)) { serialize(pc); } } void saveFile(string path) { Properties prop = new Properties; prop.mode = Properties.Mode.Output; this.serialize(prop); prop.saveFile(path); } string typeName()() { return ""; } string typeName(P1)() { return typeid(P1).toString(); } string typeName(P1, P2, P...)() { return typeName!(P1)~","~typeName!(P2, P); } static void connectEvent(P...)(GameObject sender, string name, void delegate() func) { alias event_type = Event!(P); name ~= "("~typeName!(P)~")"; auto evt = &sender.events[name]; event_type evtp = null; if(evt && typeid(*evt) == typeid(event_type)) { evtp = cast(event_type)(evt); evtp.connect(func); } else { evtp = new event_type(); *evt = evtp; } if(evtp) { evtp.connect(func); } } void triggerEvent(P...)(string name, P args) { alias Event!(P) event_type; name ~= "("~typeName!(P)~")"; auto evt = (name in events); if(evt && typeid(*evt) == typeid(event_type)) { auto casted = cast(event_type)(evt); casted.emit(args); } } void initialize() { } void update(in float delta) { } void render() { } void deinit() { } @property abstract Game game() nothrow; private: EventBase[string] events; }
D
/** The action concept is an interface, bridge between the world of cids and dynamic concepts, that knows nothing about the code and the static world, which is a big set of functions, that actually are the code. */ module cpt.cpt_actions; import std.stdio; import std.string, std.typecons; import proj_data, proj_funcs; import chri_types, chri_data; import cpt.cpt_types, cpt.abs.abs_concept, cpt.cpt_stat; import atn.atn_caldron; /// Spirit Action. Runs a static concept function with signature p0Cal. @(1) class SpA: SpiritDynamicConcept { /** Constructor Parameters: cid = predefined concept identifier */ this(Cid cid) { super(cid); } /// Create live wrapper for the holy static concept. override A live_factory() const { return new A(cast(immutable)this); } /// Serialize concept override Serial serialize() const { Serial res = super.serialize; res.stable.length = St.length; // allocate *cast(Cid*)&res.stable[St._statActionCid_ofs] = _statAction; return res; } /// Equality test override bool opEquals(Object sc) const { if(!super.opEquals(sc)) return false; return _statAction == scast!(typeof(this))(sc)._statAction; } override string toString() const { string s = super.toString; s ~= format!"\n _statAction = %s(%s)"(cptName(_statAction), _statAction); return s; } //---***---***---***---***---***--- functions ---***---***---***---***---***-- /** Call static concept function. Parameters: caldron = name space it which static concept function will be working. */ void run(Caldron caldron) { assert((cast(SpStaticConcept)_sm_[_statAction]).callType == StatCallType.p0Cal, "Static concept: %s( cid:%s) in SpAction must have StatCallType none and it has %s.". format(_nm_[_statAction], _statAction, (cast(SpStaticConcept)_sm_[_statAction]).callType)); auto statCpt = (cast(SpStaticConcept)_sm_[_statAction]); (cast(void function(Caldron))statCpt.fp)(caldron); } /// Full setup final void load(Cid statAction) { checkCid!SpStaticConcept(statAction); _statAction = statAction; } /// Getter final @property Cid statAction() { return _statAction; } /// Setter //final @property Cid statAction(Cid statActionCid) { // debug checkCid!SpStaticConcept(statActionCid); // return _statActionCid = statActionCid; //} //~~~$$$~~~$$$~~~$$$~~~$$$~~~$$$~~~$$$~~~$$$~~~$$$~~~$$$~~~$$$~~~$$$~~~$$$~~~$$$~~~$$$ // // Protected // //~~~$$$~~~$$$~~~$$$~~~$$$~~~$$$~~~$$$~~~$$$~~~$$$~~~$$$~~~$$$~~~$$$~~~$$$~~~$$$~~~$$$ //---$$$---$$$---$$$---$$$---$$$--- data ---$$$---$$$---$$$---$$$---$$$-- // Static action. protected Cid _statAction; //---$$$---$$$---$$$---$$$---$$$--- functions ---$$$---$$$---$$$---$$$---$$$--- /** Initialize concept from its serialized form. Parameters: stable = stable part of data transient = unstable part of data Returns: unconsumed slices of the stable and transient byte arrays. */ protected override Tuple!(const byte[], "stable", const byte[], "transient") _deserialize(const byte[] stable, const byte[] transient) { _statAction = *cast(Cid*)&stable[St._statActionCid_ofs]; return tuple!(const byte[], "stable", const byte[], "transient")(stable[St.length..$], transient); } //===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@ // // Private // //===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@ /// Stable offsets. Used by serialize()/_deserialize() private enum St { _statActionCid_ofs = 0, length = _statActionCid_ofs + _statAction.sizeof } /// Tranzient offsets. Used by serialize()/_deserialize() private enum Tr { length = 0 } } unittest { auto a = new SpA(42); a.ver = 5; a.load(43); Serial ser = a.serialize; auto b = cast(SpA)a.deserialize(ser.cid, ser.ver, ser.clid, ser.stable, ser.transient); assert(b.cid == 42 && b.ver == 5 && typeid(b) == typeid(SpA)); assert(a == b); } /// Live. class A: DynamicConcept { /// Private constructor. Use SpiritConcept.live_factory() instead. private this(immutable SpA spAction) { super(spAction); } //---***---***---***---***---***--- functions ---***---***---***---***---***-- /** Call static concept function. Parameters: caldron = name space it which static concept function will be working. */ void run(Caldron caldron) { assert((cast(SpA)spirit).statAction != 0, "Cid: %s, static action must be assigned.".format(this.cid)); (cast(SpA)spirit).run(caldron); } } /// SpA - spirit action, Cid - p0Calp1Cid /// Action, that operate on only one concept. Examples: activate/anactivate concept. @(2) final class SpA_Cid: SpA { /// Constructor this(Cid cid) { super(cid); } /// Create live wrapper for the holy static concept. override A_Cid live_factory() const { return new A_Cid(cast(immutable)this); } /// Serialize concept override Serial serialize() const { Serial res = super.serialize; res.stable.length = St.length; // allocate *cast(Cid*)&res.stable[St._statActionCid_ofs] = _statAction; *cast(Cid*)&res.stable[St._p1Cid_ofs] = _p1Cid; return res; } /// Equality test override bool opEquals(Object sc) const { if(!super.opEquals(sc)) return false; auto o = scast!(typeof(this))(sc); return _p1Cid == o._p1Cid; } override string toString() const { string s = super.toString; s ~= format!"\n _p1Cid = %s(%,?s)"(cptName(_p1Cid), '_', _p1Cid); return s; } //---***---***---***---***---***--- functions ---***---***---***---***---***-- /** Call static concept function. Parameters: caldron = name space it which static concept function will be working. */ override void run(Caldron caldron) { auto statAct = (scast!SpStaticConcept(_sm_[_statAction])); assert(statAct.callType == StatCallType.p0Calp1Cid, "Static concept: %s( cid:%s) in SpAction must have StatCallType p0Calp1Cid and it has %s.". format(typeid(statAct), _statAction, statAct.callType)); checkCid!DynamicConcept(caldron, _p1Cid); (cast(void function(Caldron, Cid))statAct.fp)(caldron, _p1Cid); } /// Allow loading only static action using load(Cid statAction) of the SpA class. alias load = SpA.load; /// Full setup void load(Cid statAction, DcpDsc operand) { checkCid!SpStaticConcept(statAction); _statAction = statAction; checkCid!SpiritDynamicConcept(operand.cid); _p1Cid = operand.cid; } /// Partial setup, only operand void load(DcpDsc operand) { checkCid!SpiritDynamicConcept(operand.cid); _p1Cid = operand.cid; } //---%%%---%%%---%%%---%%%---%%% data ---%%%---%%%---%%%---%%%---%%%---%%% /// Cid of a concept to operate on protected Cid _p1Cid; //---%%%---%%%---%%%---%%%---%%% funcs ---%%%---%%%---%%%---%%%---%%%---%%% /** Initialize concept from its serialized form. Parameters: stable = stable part of data transient = unstable part of data Returns: unconsumed slices of the stable and transient byte arrays. */ protected override Tuple!(const byte[], "stable", const byte[], "transient") _deserialize(const byte[] stable, const byte[] transient) { _statAction = *cast(Cid*)&stable[St._statActionCid_ofs]; _p1Cid = *cast(Cid*)&stable[St._p1Cid_ofs]; return tuple!(const byte[], "stable", const byte[], "transient")(stable[St.length..$], transient); } //===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@ // // Private // //===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@ /// Stable offsets. Used by serialize()/_deserialize() private enum St { _statActionCid_ofs = 0, _p1Cid_ofs = _statActionCid_ofs + _statAction.sizeof, length = _p1Cid_ofs + _p1Cid.sizeof } /// Tranzient offsets. Used by serialize()/_deserialize() private enum Tr { length = 0 } } unittest { auto a = new SpA_Cid(42); a.ver = 5; a._statAction = 43; a._p1Cid = 44; Serial ser = a.serialize; auto b = cast(SpA_Cid)a.deserialize(ser.cid, ser.ver, ser.clid, ser.stable, ser.transient); assert(b.cid == 42 && b.ver == 5 && typeid(b) == typeid(SpA_Cid) && b._statAction == 43 && b._p1Cid == 44); assert(a == b); } /// Live. final class A_Cid: A { /// Private constructor. Use live_factory() instead. private this(immutable SpA_Cid spUnaryAction) { super(spUnaryAction); } } /** SpA - spirit action, CidCid - p0Calp1Cidp2Cid Actions, that operate on two concepts. Examples: sending a message - the first operand breed of the correspondent, the second operand concept object to send. */ @(3) final class SpA_2Cid: SpA { /// Constructor this(Cid cid) { super(cid); } /// Create live wrapper for the holy static concept. override A_2Cid live_factory() const { return new A_2Cid(cast(immutable)this); } /// Serialize concept override Serial serialize() const { Serial res = super.serialize; res.stable.length = St.length; // allocate *cast(Cid*)&res.stable[St._statActionCid_ofs] = _statAction; *cast(Cid*)&res.stable[St._p1Cid_ofs] = _p1Cid; *cast(Cid*)&res.stable[St._p2Cid_ofs] = _p2Cid; return res; } /// Equality test override bool opEquals(Object sc) const { if(!super.opEquals(sc)) return false; auto o = scast!(typeof(this))(sc); return _p1Cid == o._p1Cid && _p2Cid == o._p2Cid; } override string toString() const { string s = super.toString; s ~= format!"\n _p1Cid = %s(%,?s)"(cptName(_p1Cid), '_', _p1Cid); s ~= format!"\n _p2Cid = %s(%,?s)"(cptName(_p2Cid), '_', _p2Cid); return s; } //---***---***---***---***---***--- functions ---***---***---***---***---***-- /** Call static concept function. Parameters: caldron = name space it which static concept function will be working. */ override void run(Caldron caldron) { auto statAct = (scast!SpStaticConcept(_sm_[_statAction])); assert(statAct.callType == StatCallType.p0Calp1Cidp2Cid, "Static concept: %s( cid:%s) in SpAction must have StatCallType p0Calp1Cidp2Cid and it has %s.". format(typeid(statAct), _statAction, statAct.callType)); checkCid!DynamicConcept(caldron, _p1Cid); checkCid!DynamicConcept(caldron, _p2Cid); (cast(void function(Caldron, Cid, Cid))statAct.fp)(caldron, _p1Cid, _p2Cid); } /// Allow loading only static action using load(Cid statAction) of the SpA class. alias load = SpA.load; /// Full setup void load(Cid statAction, DcpDsc firstOperand, DcpDsc secondOperand) { checkCid!SpStaticConcept(statAction); _statAction = statAction; checkCid!SpiritDynamicConcept(firstOperand.cid); _p1Cid = firstOperand.cid; checkCid!SpiritDynamicConcept(secondOperand.cid); _p2Cid = secondOperand.cid; } /// Partial setup, without the static action void load(DcpDsc firstOperand, DcpDsc secondOperand) { checkCid!SpiritDynamicConcept(firstOperand.cid); _p1Cid = firstOperand.cid; checkCid!SpiritDynamicConcept(secondOperand.cid); _p2Cid = secondOperand.cid; } //---%%%---%%%---%%%---%%%---%%% data ---%%%---%%%---%%%---%%%---%%%---%%% /// Cid of the first concept protected Cid _p1Cid; /// Cid of the second concept protected Cid _p2Cid; //---%%%---%%%---%%%---%%%---%%% funcs ---%%%---%%%---%%%---%%%---%%%---%%% /** Initialize concept from its serialized form. Parameters: stable = stable part of data transient = unstable part of data Returns: unconsumed slices of the stable and transient byte arrays. */ protected override Tuple!(const byte[], "stable", const byte[], "transient") _deserialize(const byte[] stable, const byte[] transient) { _statAction = *cast(Cid*)&stable[St._statActionCid_ofs]; _p1Cid = *cast(Cid*)&stable[St._p1Cid_ofs]; _p2Cid = *cast(Cid*)&stable[St._p2Cid_ofs]; return tuple!(const byte[], "stable", const byte[], "transient")(stable[St.length..$], transient); } //===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@ // // Private // //===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@ /// Stable offsets. Used by serialize()/_deserialize() private enum St { _statActionCid_ofs = 0, _p1Cid_ofs = _statActionCid_ofs + _statAction.sizeof, _p2Cid_ofs = _p1Cid_ofs + _p1Cid.sizeof, length = _p2Cid_ofs + _p2Cid.sizeof } /// Tranzient offsets. Used by serialize()/_deserialize() private enum Tr { length = 0 } } unittest { auto a = new SpA_2Cid(42); a.ver = 5; a._statAction = 43; a._p1Cid = 44; a._p2Cid = 45; Serial ser = a.serialize; auto b = cast(SpA_2Cid)a.deserialize(ser.cid, ser.ver, ser.clid, ser.stable, ser.transient); assert(b.cid == 42 && b.ver == 5 && typeid(b) == typeid(SpA_2Cid) && b._statAction == 43 && b._p1Cid == 44 && b._p2Cid == 45); assert(a == b); } /// Live. final class A_2Cid: A { /// Private constructor. Use live_factory() instead. private this(immutable SpA_2Cid spBinaryAction) { super(spBinaryAction); } } /** SpA - spirit action, 3Cid - p0Calp1Cidp2Cidp3Cid Actions, that operate on two concepts. Examples: sending a message - the first operand breed of the correspondent, the second operand concept object to send. */ @(4) final class SpA_3Cid: SpA { /// Constructor this(Cid cid) { super(cid); } /// Create live wrapper for the holy static concept. override A_3Cid live_factory() const { return new A_3Cid(cast(immutable)this); } /// Serialize concept override Serial serialize() const { Serial res = super.serialize; res.stable.length = St.length; // allocate *cast(Cid*)&res.stable[St._statActionCid_ofs] = _statAction; *cast(Cid*)&res.stable[St._p1Cid_ofs] = _p1Cid; *cast(Cid*)&res.stable[St._p2Cid_ofs] = _p2Cid; *cast(Cid*)&res.stable[St._p3Cid_ofs] = _p3Cid; return res; } /// Equality test override bool opEquals(Object sc) const { if(!super.opEquals(sc)) return false; auto o = scast!(typeof(this))(sc); return _p1Cid == o._p1Cid && _p2Cid == o._p2Cid && _p3Cid == o._p3Cid; } override string toString() const { string s = super.toString; s ~= format!"\n _p1Cid = %s(%,?s)"(cptName(_p1Cid), '_', _p1Cid); s ~= format!"\n _p2Cid = %s(%,?s)"(cptName(_p2Cid), '_', _p2Cid); s ~= format!"\n _p3Cid = %s(%,?s)"(cptName(_p3Cid), '_', _p3Cid); return s; } //---***---***---***---***---***--- functions ---***---***---***---***---***-- /** Call static concept function. Parameters: caldron = name space it which static concept function will be working. */ override void run(Caldron caldron) { auto statAct = (scast!SpStaticConcept(_sm_[_statAction])); assert(statAct.callType == StatCallType.p0Calp1Cidp2Cidp3Cid, "Static concept: %s( cid:%s) in SpAction must have StatCallType p0Calp1Cidp2Cid3Cid and it has %s.". format(typeid(statAct), _statAction, statAct.callType)); checkCid!DynamicConcept(caldron, _p1Cid); checkCid!DynamicConcept(caldron, _p2Cid); checkCid!DynamicConcept(caldron, _p3Cid); (cast(void function(Caldron, Cid, Cid, Cid))statAct.fp)(caldron, _p1Cid, _p2Cid, _p3Cid); } /// Allow loading only static action using load(Cid statAction) of the SpA class. alias load = SpA.load; /// Full setup void load(Cid statAction, DcpDsc firstOperand, DcpDsc secondOperand, DcpDsc thirdOperand) { checkCid!SpStaticConcept(statAction); _statAction = statAction; checkCid!SpiritDynamicConcept(firstOperand.cid); _p1Cid = firstOperand.cid; checkCid!SpiritDynamicConcept(secondOperand.cid); _p2Cid = secondOperand.cid; checkCid!SpiritDynamicConcept(thirdOperand.cid); _p3Cid = thirdOperand.cid; } /// Partial setup, without the static action void load(DcpDsc firstOperand, DcpDsc secondOperand, DcpDsc thirdOperand) { checkCid!SpiritDynamicConcept(firstOperand.cid); _p1Cid = firstOperand.cid; checkCid!SpiritDynamicConcept(secondOperand.cid); _p2Cid = secondOperand.cid; checkCid!SpiritDynamicConcept(thirdOperand.cid); _p3Cid = thirdOperand.cid; } //---%%%---%%%---%%%---%%%---%%% data ---%%%---%%%---%%%---%%%---%%%---%%% /// Cid of the first concept protected Cid _p1Cid; /// Cid of the second concept protected Cid _p2Cid; /// Cid of the third concept protected Cid _p3Cid; //---%%%---%%%---%%%---%%%---%%% funcs ---%%%---%%%---%%%---%%%---%%%---%%% /** Initialize concept from its serialized form. Parameters: stable = stable part of data transient = unstable part of data Returns: unconsumed slices of the stable and transient byte arrays. */ protected override Tuple!(const byte[], "stable", const byte[], "transient") _deserialize(const byte[] stable, const byte[] transient) { _statAction = *cast(Cid*)&stable[St._statActionCid_ofs]; _p1Cid = *cast(Cid*)&stable[St._p1Cid_ofs]; _p2Cid = *cast(Cid*)&stable[St._p2Cid_ofs]; _p3Cid = *cast(Cid*)&stable[St._p3Cid_ofs]; return tuple!(const byte[], "stable", const byte[], "transient")(stable[St.length..$], transient); } //===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@ // // Private // //===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@ /// Stable offsets. Used by serialize()/_deserialize() private enum St { _statActionCid_ofs = 0, _p1Cid_ofs = _statActionCid_ofs + _statAction.sizeof, _p2Cid_ofs = _p1Cid_ofs + _p1Cid.sizeof, _p3Cid_ofs = _p2Cid_ofs + _p2Cid.sizeof, length = _p3Cid_ofs + _p3Cid.sizeof } /// Tranzient offsets. Used by serialize()/_deserialize() private enum Tr { length = 0 } } unittest { auto a = new SpA_3Cid(42); a.ver = 5; a._statAction = 43; a._p1Cid = 44; a._p2Cid = 45; a._p3Cid = 46; Serial ser = a.serialize; auto b = cast(SpA_3Cid)a.deserialize(ser.cid, ser.ver, ser.clid, ser.stable, ser.transient); assert(b.cid == 42 && b.ver == 5 && typeid(b) == typeid(SpA_3Cid) && b._statAction == 43 && b._p1Cid == 44 && b._p2Cid == 45 && b._p3Cid == 46); assert(a == b); } /// Live. final class A_3Cid: A { /// Private constructor. Use live_factory() instead. private this(immutable SpA_3Cid spBinaryAction) { super(spBinaryAction); } } /// SpA - spirit action, CidFloat - p0Calp1Cidp2Float /// Action, that works on a concept and a float value @(5) final class SpA_CidFloat: SpA { /// Constructor this(Cid cid) { super(cid); } /// Create live wrapper for the holy static concept. override A_CidFloat live_factory() const { return new A_CidFloat(cast(immutable)this); } /// Serialize concept override Serial serialize() const { Serial res = super.serialize; res.stable.length = St.length; // allocate *cast(Cid*)&res.stable[St._statActionCid_ofs] = _statAction; *cast(Cid*)&res.stable[St._p1Cid_ofs] = _p1Cid; *cast(float*)&res.stable[St._p2Float_ofs] = _p2Float; return res; } /// Equality test override bool opEquals(Object sc) const { if(!super.opEquals(sc)) return false; auto o = scast!(typeof(this))(sc); return _p1Cid == o._p1Cid && _p2Float == o._p2Float; } override string toString() const { string s = super.toString; s ~= format!"\n _p1Cid = %s(%,?s)"(cptName(_p1Cid), '_', _p1Cid); s ~= format!"\n _p2Float = %s"(_p2Float); return s; } //---***---***---***---***---***--- functions ---***---***---***---***---***-- /// Run the static action. override void run(Caldron caldron) { auto statAct = (scast!SpStaticConcept(_sm_[_statAction])); assert(statAct.callType == StatCallType.p0Calp1Cidp2Float, "Static concept: %s( cid:%s) in SpAction must have StatCallType p0Calp1Cidp2Float and it has %s.". format(typeid(statAct), _statAction, statAct.callType)); checkCid!DynamicConcept(caldron, _p1Cid); (cast(void function(Caldron, Cid, float))statAct.fp)(caldron, _p1Cid, _p2Float); } /// Allow loading only static action using load(Cid statAction) of the SpA class. alias load = SpA.load; /** Set float value for a concept in the current namespace. Parameters: statActionCid = static action to perform p1 = concept, that takes the float value p2 = float value */ void load(Cid statActionCid, DcpDsc p1, float p2) { checkCid!SpStaticConcept(statActionCid); checkCid!SpiritDynamicConcept(p1.cid); _statAction = statActionCid; _p1Cid = p1.cid; _p2Float = p2; } /// Partial setup, without the static action void load(DcpDsc p1, float p2) { checkCid!SpiritDynamicConcept(p1.cid); _p1Cid = p1.cid; _p2Float = p2; } //---%%%---%%%---%%%---%%%---%%% data ---%%%---%%%---%%%---%%%---%%%---%%% // Parameter 1 - a concept cid. protected Cid _p1Cid; // Parameter 2 - a float value protected float _p2Float; //---%%%---%%%---%%%---%%%---%%% funcs ---%%%---%%%---%%%---%%%---%%%---%%% /** Initialize concept from its serialized form. Parameters: stable = stable part of data transient = unstable part of data Returns: unconsumed slices of the stable and transient byte arrays. */ protected override Tuple!(const byte[], "stable", const byte[], "transient") _deserialize(const byte[] stable, const byte[] transient) { _statAction = *cast(Cid*)&stable[St._statActionCid_ofs]; _p1Cid = *cast(Cid*)&stable[St._p1Cid_ofs]; _p2Float = *cast(float*)&stable[St._p2Float_ofs]; return tuple!(const byte[], "stable", const byte[], "transient")(stable[St.length..$], transient); } //===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@ // // Private // //===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@ /// Stable offsets. Used by serialize()/_deserialize() private enum St { _statActionCid_ofs = 0, _p1Cid_ofs = _statActionCid_ofs + _statAction.sizeof, _p2Float_ofs = _p1Cid_ofs + _p1Cid.sizeof, length = _p2Float_ofs + _p2Float.sizeof } /// Tranzient offsets. Used by serialize()/_deserialize() private enum Tr { length = 0 } } unittest { auto a = new SpA_CidFloat(42); a.ver = 5; a._statAction = 43; a._p1Cid = 44; a._p2Float = 4.5; Serial ser = a.serialize; auto b = cast(SpA_CidFloat)a.deserialize(ser.cid, ser.ver, ser.clid, ser.stable, ser.transient); assert(b.cid == 42 && b.ver == 5 && typeid(b) == typeid(SpA_CidFloat) && b._statAction == 43 && b._p1Cid == 44 && b._p2Float == 4.5); assert(a == b); } /// Live. final class A_CidFloat: A { /// Private constructor. Use live_factory() instead. private this(immutable SpA_CidFloat spUnaryFloatAction) { super(spUnaryFloatAction); } } /// SpA - spirit action, CidCidFloat stands for p0Calp1Cidp2Cidp3Float /// Action, that involves two concepts and a float value @(6) final class SpA_2CidFloat: SpA { /// Constructor this(Cid cid) { super(cid); } /// Create live wrapper for the holy static concept. override A_2CidFloat live_factory() const { return new A_2CidFloat(cast(immutable)this); } /// Serialize concept override Serial serialize() const { Serial res = super.serialize; res.stable.length = St.length; // allocate *cast(Cid*)&res.stable[St._statActionCid_ofs] = _statAction; *cast(Cid*)&res.stable[St._p1Cid_ofs] = _p1Cid; *cast(Cid*)&res.stable[St._p2Cid_ofs] = _p2Cid; *cast(float*)&res.stable[St._p3Float_ofs] = _p3Float; return res; } /// Equality test override bool opEquals(Object sc) const { if(!super.opEquals(sc)) return false; auto o = scast!(typeof(this))(sc); return _p1Cid == o._p1Cid && _p2Cid == o._p2Cid && _p3Float == o._p3Float; } override string toString() const { string s = super.toString; s ~= format!"\n _p1Cid = %s(%,?s)"(cptName(_p1Cid), '_', _p1Cid); s ~= format!"\n _p2Cid = %s(%,?s)"(cptName(_p2Cid), '_', _p2Cid); s ~= format!"\n _p3Float = %s"(_p3Float); return s; } //---***---***---***---***---***--- functions ---***---***---***---***---***-- /// Run the static action. override void run(Caldron caldron) { auto statAct = (scast!SpStaticConcept(_sm_[_statAction])); assert(statAct.callType == StatCallType.p0Calp1Cidp2Cidp3Float, "Static concept: %s( cid:%s) in SpAction must have StatCallType p0Calp1Cidp2Cidp3Float and it has %s.". format(typeid(statAct), _statAction, statAct.callType)); checkCid!DynamicConcept(caldron, _p1Cid); checkCid!DynamicConcept(caldron, _p2Cid); (cast(void function(Caldron, Cid, Cid, float))statAct.fp)(caldron, _p1Cid, _p2Cid, _p3Float); } /// Allow loading only static action using load(Cid statAction) of the SpA class. alias load = SpA.load; /** Set float value for a concept in the current namespace. Parameters: statActionCid = static action to perform p1 = first concept p2 = second concept p3 = float value */ void load(Cid statActionCid, DcpDsc p1, DcpDsc p2, float p3) { checkCid!SpStaticConcept(statActionCid); checkCid!SpiritDynamicConcept(p1.cid); checkCid!SpiritDynamicConcept(p2.cid); _statAction = statActionCid; _p1Cid = p1.cid; _p2Cid = p2.cid; _p3Float = p3; } /// Partial setup, without the static action void load(DcpDsc p1, DcpDsc p2, float p3) { checkCid!SpiritDynamicConcept(p1.cid); checkCid!SpiritDynamicConcept(p2.cid); _p1Cid = p1.cid; _p2Cid = p2.cid; _p3Float = p3; } //---%%%---%%%---%%%---%%%---%%% data ---%%%---%%%---%%%---%%%---%%%---%%% // Parameter 1 - a concept cid. protected Cid _p1Cid; // Parameter 2 - a concept cid. protected Cid _p2Cid; // Parameter 2 - a float value protected float _p3Float; //---%%%---%%%---%%%---%%%---%%% funcs ---%%%---%%%---%%%---%%%---%%%---%%% /** Initialize concept from its serialized form. Parameters: stable = stable part of data transient = unstable part of data Returns: unconsumed slices of the stable and transient byte arrays. */ protected override Tuple!(const byte[], "stable", const byte[], "transient") _deserialize(const byte[] stable, const byte[] transient) { _statAction = *cast(Cid*)&stable[St._statActionCid_ofs]; _p1Cid = *cast(Cid*)&stable[St._p1Cid_ofs]; _p2Cid = *cast(Cid*)&stable[St._p2Cid_ofs]; _p3Float = *cast(float*)&stable[St._p3Float_ofs]; return tuple!(const byte[], "stable", const byte[], "transient")(stable[St.length..$], transient); } //===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@ // // Private // //===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@ /// Stable offsets. Used by serialize()/_deserialize() private enum St { _statActionCid_ofs = 0, _p1Cid_ofs = _statActionCid_ofs + _statAction.sizeof, _p2Cid_ofs = _p1Cid_ofs + _p1Cid.sizeof, _p3Float_ofs = _p2Cid_ofs + _p2Cid.sizeof, length = _p3Float_ofs + _p3Float.sizeof } /// Tranzient offsets. Used by serialize()/_deserialize() private enum Tr { length = 0 } } unittest { auto a = new SpA_2CidFloat(42); a.ver = 5; a._statAction = 43; a._p1Cid = 44; a._p2Cid = 45; a._p3Float = 4.5; Serial ser = a.serialize; auto b = cast(SpA_2CidFloat)a.deserialize(ser.cid, ser.ver, ser.clid, ser.stable, ser.transient); assert(b.cid == 42 && b.ver == 5 && typeid(b) == typeid(SpA_2CidFloat) && b._statAction == 43 && b._p1Cid == 44 && b._p2Cid == 45 && b._p3Float == 4.5); assert(a == b); } /// Live. final class A_2CidFloat: A { /// Private constructor. Use live_factory() instead. private this(immutable SpA_2CidFloat spBinaryFloatAction) { super(spBinaryFloatAction); } } /// SpA - spirit action, CidInt - p0Calp1Cidp2Int /// Action, that involves a concept and a float value @(7) final class SpA_CidInt: SpA { /// Constructor this(Cid cid) { super(cid); } /// Create live wrapper for the holy static concept. override A_CidInt live_factory() const { return new A_CidInt(cast(immutable)this); } /// Serialize concept override Serial serialize() const { Serial res = super.serialize; res.stable.length = St.length; // allocate *cast(Cid*)&res.stable[St._statActionCid_ofs] = _statAction; *cast(Cid*)&res.stable[St._p1Cid_ofs] = _p1Cid; *cast(int*)&res.stable[St._p2Int_ofs] = _p2Int; return res; } /// Equality test override bool opEquals(Object sc) const { if(!super.opEquals(sc)) return false; auto o = scast!(typeof(this))(sc); return _p1Cid == o._p1Cid && _p2Int == o._p2Int; } override string toString() const { string s = super.toString; s ~= format!"\n _p1Cid = %s(%,?s)"(cptName(_p1Cid), '_', _p1Cid); s ~= format!"\n _p2Int = %s"(_p2Int); return s; } //---***---***---***---***---***--- functions ---***---***---***---***---***-- /// Run the static action. override void run(Caldron caldron) { auto statAct = (scast!SpStaticConcept(_sm_[_statAction])); assert(statAct.callType == StatCallType.p0Calp1Cidp2Int, "Static concept: %s( cid:%s) in SpAction must have StatCallType p0Calp1Cidp2Int and it has %s.". format(typeid(statAct), _statAction, statAct.callType)); checkCid!DynamicConcept(caldron, _p1Cid); (cast(void function(Caldron, Cid, int))statAct.fp)(caldron, _p1Cid, _p2Int); } /// Allow loading only static action using load(Cid statAction) of the SpA class. alias load = SpA.load; /** Set int value for a concept in the current namespace. Parameters: statActionCid = static action to perform p1 = concept, that takes the int value p2 = int value */ void load(Cid statActionCid, DcpDsc p1, int p2) { checkCid!SpStaticConcept(statActionCid); checkCid!SpiritDynamicConcept(p1.cid); _statAction = statActionCid; _p1Cid = p1.cid; _p2Int = p2; } /// Partial setup, without the static action void load(DcpDsc p1, int p2) { checkCid!SpiritDynamicConcept(p1.cid); _p1Cid = p1.cid; _p2Int = p2; } //---%%%---%%%---%%%---%%%---%%% data ---%%%---%%%---%%%---%%%---%%%---%%% // Parameter 1 - a concept cid. protected Cid _p1Cid; // Parameter 2 - a float value protected int _p2Int; //---%%%---%%%---%%%---%%%---%%% funcs ---%%%---%%%---%%%---%%%---%%%---%%% /** Initialize concept from its serialized form. Parameters: stable = stable part of data transient = unstable part of data Returns: unconsumed slices of the stable and transient byte arrays. */ protected override Tuple!(const byte[], "stable", const byte[], "transient") _deserialize(const byte[] stable, const byte[] transient) { _statAction = *cast(Cid*)&stable[St._statActionCid_ofs]; _p1Cid = *cast(Cid*)&stable[St._p1Cid_ofs]; _p2Int = *cast(int*)&stable[St._p2Int_ofs]; return tuple!(const byte[], "stable", const byte[], "transient")(stable[St.length..$], transient); } //===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@ // // Private // //===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@===@@@ /// Stable offsets. Used by serialize()/_deserialize() private enum St { _statActionCid_ofs = 0, _p1Cid_ofs = _statActionCid_ofs + _statAction.sizeof, _p2Int_ofs = _p1Cid_ofs + _p1Cid.sizeof, length = _p2Int_ofs + _p2Int.sizeof } /// Tranzient offsets. Used by serialize()/_deserialize() private enum Tr { length = 0 } } unittest { auto a = new SpA_CidInt(42); a.ver = 5; a._statAction = 43; a._p1Cid = 44; a._p2Int = 45; Serial ser = a.serialize; auto b = cast(SpA_CidInt)a.deserialize(ser.cid, ser.ver, ser.clid, ser.stable, ser.transient); assert(b.cid == 42 && b.ver == 5 && typeid(b) == typeid(SpA_CidInt) && b._statAction == 43 && b._p1Cid == 44 && b._p2Int == 45); assert(a == b); } /// Live. final class A_CidInt: A { /// Private constructor. Use live_factory() instead. private this(immutable SpA_CidInt spUnaryIntAction) { super(spUnaryIntAction); } }
D
// Written in the D programming language. /** <script type="text/javascript">inhibitQuickIndex = 1</script> $(BOOKTABLE , $(TR $(TH Category) $(TH Functions) ) $(TR $(TDNW Searching) $(TD $(MYREF balancedParens) $(MYREF boyerMooreFinder) $(MYREF canFind) $(MYREF count) $(MYREF countUntil) $(MYREF endsWith) $(MYREF find) $(MYREF findAdjacent) $(MYREF findAmong) $(MYREF findSkip) $(MYREF findSplit) $(MYREF findSplitAfter) $(MYREF findSplitBefore) $(MYREF indexOf) $(MYREF minCount) $(MYREF minPos) $(MYREF mismatch) $(MYREF skipOver) $(MYREF startsWith) $(MYREF until) ) ) $(TR $(TDNW Comparison) $(TD $(MYREF cmp) $(MYREF equal) $(MYREF levenshteinDistance) $(MYREF levenshteinDistanceAndPath) $(MYREF max) $(MYREF min) $(MYREF mismatch) ) ) $(TR $(TDNW Iteration) $(TD $(MYREF filter) $(MYREF filterBidirectional) $(MYREF group) $(MYREF joiner) $(MYREF map) $(MYREF reduce) $(MYREF splitter) $(MYREF uniq) ) ) $(TR $(TDNW Sorting) $(TD $(MYREF completeSort) $(MYREF isPartitioned) $(MYREF isSorted) $(MYREF makeIndex) $(MYREF partialSort) $(MYREF partition) $(MYREF partition3) $(MYREF schwartzSort) $(MYREF sort) $(MYREF topN) $(MYREF topNCopy) ) ) $(TR $(TDNW Set&nbsp;operations) $(TD $(MYREF largestPartialIntersection) $(MYREF largestPartialIntersectionWeighted) $(MYREF nWayUnion) $(MYREF setDifference) $(MYREF setIntersection) $(MYREF setSymmetricDifference) $(MYREF setUnion) ) ) $(TR $(TDNW Mutation) $(TD $(MYREF bringToFront) $(MYREF copy) $(MYREF fill) $(MYREF initializeAll) $(MYREF move) $(MYREF moveAll) $(MYREF moveSome) $(MYREF remove) $(MYREF reverse) $(MYREF swap) $(MYREF swapRanges) $(MYREF uninitializedFill) )) ) Implements algorithms oriented mainly towards processing of sequences. Some functions are semantic equivalents or supersets of those found in the $(D $(LESS)_algorithm$(GREATER)) header in $(WEB sgi.com/tech/stl/, Alexander Stepanov's Standard Template Library) for C++. Many functions in this module are parameterized with a function or a $(GLOSSARY predicate). The predicate may be passed either as a function name, a delegate name, a $(GLOSSARY functor) name, or a compile-time string. The string may consist of $(B any) legal D expression that uses the symbol $(D a) (for unary functions) or the symbols $(D a) and $(D b) (for binary functions). These names will NOT interfere with other homonym symbols in user code because they are evaluated in a different context. The default for all binary comparison predicates is $(D "a == b") for unordered operations and $(D "a < b") for ordered operations. Example: ---- int[] a = ...; static bool greater(int a, int b) { return a > b; } sort!(greater)(a); // predicate as alias sort!("a > b")(a); // predicate as string // (no ambiguity with array name) sort(a); // no predicate, "a < b" is implicit ---- $(BOOKTABLE Cheat Sheet, $(TR $(TH Function Name) $(TH Description) ) $(LEADINGROW Searching ) $(TR $(TDNW $(LREF balancedParens)) $(TD $(D balancedParens("((1 + 1) / 2)")) returns $(D true) because the string has balanced parentheses.) ) $(TR $(TDNW $(LREF boyerMooreFinder)) $(TD $(D find("hello world", boyerMooreFinder("or"))) returns $(D "orld") using the $(LUCKY Boyer-Moore _algorithm).) ) $(TR $(TDNW $(LREF canFind)) $(TD $(D canFind("hello world", "or")) returns $(D true).) ) $(TR $(TDNW $(LREF count)) $(TD Counts elements that are equal to a specified value or satisfy a predicate. $(D count([1, 2, 1], 1)) returns $(D 2) and $(D count!"a < 0"([1, -3, 0])) returns $(D 1).) ) $(TR $(TDNW $(LREF countUntil)) $(TD $(D countUntil(a, b)) returns the number of steps taken in $(D a) to reach $(D b); for example, $(D countUntil("hello!", "o")) returns $(D 4).) ) $(TR $(TDNW $(LREF endsWith)) $(TD $(D endsWith("rocks", "ks")) returns $(D true).) ) $(TR $(TD $(LREF find)) $(TD $(D find("hello world", "or")) returns $(D "orld") using linear search.) ) $(TR $(TDNW $(LREF findAdjacent)) $(TD $(D findAdjacent([1, 2, 3, 3, 4])) returns the subrange starting with two equal adjacent elements, i.e. $(D [3, 3, 4]).) ) $(TR $(TDNW $(LREF findAmong)) $(TD $(D findAmong("abcd", "qcx")) returns $(D "cd") because $(D 'c') is among $(D "qcx").) ) $(TR $(TDNW $(LREF findSkip)) $(TD If $(D a = "abcde"), then $(D findSkip(a, "x")) returns $(D false) and leaves $(D a) unchanged, whereas $(D findSkip(a, 'c')) advances $(D a) to $(D "cde") and returns $(D true).) ) $(TR $(TDNW $(LREF findSplit)) $(TD $(D findSplit("abcdefg", "de")) returns the three ranges $(D "abc"), $(D "de"), and $(D "fg").) ) $(TR $(TDNW $(LREF findSplitAfter)) $(TD $(D findSplitAfter("abcdefg", "de")) returns the two ranges $(D "abcde") and $(D "fg").) ) $(TR $(TDNW $(LREF findSplitBefore)) $(TD $(D findSplitBefore("abcdefg", "de")) returns the two ranges $(D "abc") and $(D "defg").) ) $(TR $(TDNW $(LREF minCount)) $(TD $(D minCount([2, 1, 1, 4, 1])) returns $(D tuple(1, 3)).) ) $(TR $(TDNW $(LREF minPos)) $(TD $(D minPos([2, 3, 1, 3, 4, 1])) returns the subrange $(D [1, 3, 4, 1]), i.e., positions the range at the first occurrence of its minimal element.) ) $(TR $(TDNW $(LREF skipOver)) $(TD Assume $(D a = "blah"). Then $(D skipOver(a, "bi")) leaves $(D a) unchanged and returns $(D false), whereas $(D skipOver(a, "bl")) advances $(D a) to refer to $(D "ah") and returns $(D true).) ) $(TR $(TDNW $(LREF startsWith)) $(TD $(D startsWith("hello, world", "hello")) returns $(D true).) ) $(TR $(TDNW $(LREF until)) $(TD Lazily iterates a range until a specific value is found.) ) $(LEADINGROW Comparison ) $(TR $(TDNW $(LREF cmp)) $(TD $(D cmp("abc", "abcd")) is $(D -1), $(D cmp("abc", aba")) is $(D 1), and $(D cmp("abc", "abc")) is $(D 0).) ) $(TR $(TDNW $(LREF equal)) $(TD Compares ranges for element-by-element equality, e.g. $(D equal([1, 2, 3], [1.0, 2.0, 3.0])) returns $(D true).) ) $(TR $(TDNW $(LREF levenshteinDistance)) $(TD $(D levenshteinDistance("kitten", "sitting")) returns $(D 3) by using the $(LUCKY Levenshtein distance _algorithm).) ) $(TR $(TDNW $(LREF levenshteinDistanceAndPath)) $(TD $(D levenshteinDistanceAndPath("kitten", "sitting")) returns $(D tuple(3, "snnnsni")) by using the $(LUCKY Levenshtein distance _algorithm).) ) $(TR $(TDNW $(LREF max)) $(TD $(D max(3, 4, 2)) returns $(D 4).) ) $(TR $(TDNW $(LREF min)) $(TD $(D min(3, 4, 2)) returns $(D 2).) ) $(TR $(TDNW $(LREF mismatch)) $(TD $(D mismatch("oh hi", "ohayo")) returns $(D tuple(" hi", "ayo")).) ) $(LEADINGROW Iteration ) $(TR $(TDNW $(LREF filter)) $(TD $(D filter!"a > 0"([1, -1, 2, 0, -3])) iterates over elements $(D 1), $(D 2), and $(D 0).) ) $(TR $(TDNW $(LREF filterBidirectional)) $(TD Similar to $(D filter), but also provides $(D back) and $(D popBack) at a small increase in cost.) ) $(TR $(TDNW $(LREF group)) $(TD $(D group([5, 2, 2, 3, 3])) returns a range containing the tuples $(D tuple(5, 1)), $(D tuple(2, 2)), and $(D tuple(3, 2)).) ) $(TR $(TDNW $(LREF joiner)) $(TD $(D joiner(["hello", "world!"], ";")) returns a range that iterates over the characters $(D "hello; world!"). No new string is created - the existing inputs are iterated.) ) $(TR $(TDNW $(LREF map)) $(TD $(D map!"2 * a"([1, 2, 3])) lazily returns a range with the numbers $(D 2), $(D 4), $(D 6).) ) $(TR $(TDNW $(LREF reduce)) $(TD $(D reduce!"a + b"([1, 2, 3, 4])) returns $(D 10).) ) $(TR $(TDNW $(LREF splitter)) $(TD Lazily splits a range by a separator.) ) $(TR $(TDNW $(LREF uniq)) $(TD Iterates over the unique elements in a range, which is assumed sorted.) ) $(LEADINGROW Sorting ) $(TR $(TDNW $(LREF completeSort)) $(TD If $(D a = [10, 20, 30]) and $(D b = [40, 6, 15]), then $(D completeSort(a, b)) leaves $(D a = [6, 10, 15]) and $(D b = [20, 30, 40]). The range $(D a) must be sorted prior to the call, and as a result the combination $(D $(XREF range,chain)(a, b)) is sorted.) ) $(TR $(TDNW $(LREF isPartitioned)) $(TD $(D isPartitioned!"a < 0"([-1, -2, 1, 0, 2])) returns $(D true) because the predicate is $(D true) for a portion of the range and $(D false) afterwards.) ) $(TR $(TDNW $(LREF isSorted)) $(TD $(D isSorted([1, 1, 2, 3])) returns $(D true).) ) $(TR $(TDNW $(LREF makeIndex)) $(TD Creates a separate index for a range.) ) $(TR $(TDNW $(LREF partialSort)) $(TD If $(D a = [5, 4, 3, 2, 1]), then $(D partialSort(a, 3)) leaves $(D a[0 .. 3] = [1, 2, 3]). The other elements of $(D a) are left in an unspecified order.) ) $(TR $(TDNW $(LREF partition)) $(TD Partitions a range according to a predicate.) ) $(TR $(TDNW $(LREF schwartzSort)) $(TD Sorts with the help of the $(LUCKY Schwartzian transform).) ) $(TR $(TDNW $(LREF sort)) $(TD Sorts.) ) $(TR $(TDNW $(LREF topN)) $(TD Separates the top elements in a range.) ) $(TR $(TDNW $(LREF topNCopy)) $(TD Copies out the top elements of a range.) ) $(LEADINGROW Set operations ) $(TR $(TDNW $(LREF largestPartialIntersection)) $(TD Copies out the values that occur most frequently in a range of ranges.) ) $(TR $(TDNW $(LREF largestPartialIntersectionWeighted)) $(TD Copies out the values that occur most frequently (multiplied by per-value weights) in a range of ranges.) ) $(TR $(TDNW $(LREF nWayUnion)) $(TD Computes the union of a set of sets implemented as a range of sorted ranges.) ) $(TR $(TDNW $(LREF setDifference)) $(TD Lazily computes the set difference of two or more sorted ranges.) ) $(TR $(TDNW $(LREF setIntersection)) $(TD Lazily computes the set difference of two or more sorted ranges.) ) $(TR $(TDNW $(LREF setSymmetricDifference)) $(TD Lazily computes the symmetric set difference of two or more sorted ranges.) ) $(TR $(TDNW $(LREF setUnion)) $(TD Lazily computes the set union of two or more sorted ranges.) ) $(LEADINGROW Mutation ) $(TR $(TDNW $(LREF bringToFront)) $(TD If $(D a = [1, 2, 3]) and $(D b = [4, 5, 6, 7]), $(D bringToFront(a, b)) leaves $(D a = [4, 5, 6]) and $(D b = [7, 1, 2, 3]).) ) $(TR $(TDNW $(LREF copy)) $(TD Copies a range to another. If $(D a = [1, 2, 3]) and $(D b = new int[5]), then $(D copy(a, b)) leaves $(D b = [1, 2, 3, 0, 0]) and returns $(D b[3 .. $]).) ) $(TR $(TDNW $(LREF fill)) $(TD Fills a range with a pattern, e.g., if $(D a = new int[3]), then $(D fill(a, 4)) leaves $(D a = [4, 4, 4]) and $(D fill(a, [3, 4])) leaves $(D a = [3, 4, 3]).) ) $(TR $(TDNW $(LREF initializeAll)) $(TD If $(D a = [1.2, 3.4]), then $(D initializeAll(a)) leaves $(D a = [double.init, double.init]).) ) $(TR $(TDNW $(LREF move)) $(TD $(D move(a, b)) moves $(D a) into $(D b). $(D move(a)) reads $(D a) destructively.) ) $(TR $(TDNW $(LREF moveAll)) $(TD Moves all elements from one range to another.) ) $(TR $(TDNW $(LREF moveSome)) $(TD Moves as many elements as possible from one range to another.) ) $(TR $(TDNW $(LREF reverse)) $(TD If $(D a = [1, 2, 3]), $(D reverse(a)) changes it to $(D [3, 2, 1]).) ) $(TR $(TDNW $(LREF swap)) $(TD Swaps two values.) ) $(TR $(TDNW $(LREF swapRanges)) $(TD Swaps all elements of two ranges.) ) $(TR $(TDNW $(LREF uninitializedFill)) $(TD Fills a range (assumed uninitialized) with a value.) ) ) Macros: WIKI = Phobos/StdAlgorithm MYREF = <font face='Consolas, "Bitstream Vera Sans Mono", "Andale Mono", Monaco, "DejaVu Sans Mono", "Lucida Console", monospace'><a href="#$1">$1</a>&nbsp;</font> Copyright: Andrei Alexandrescu 2008-. License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0). Authors: $(WEB erdani.com, Andrei Alexandrescu) Source: $(PHOBOSSRC std/_algorithm.d) */ module std.algorithm; //debug = std_algorithm; import std.c.string; import std.array, std.ascii, std.container, std.conv, std.exception, std.functional, std.math, std.metastrings, std.range, std.string, std.traits, std.typecons, std.typetuple, std.uni; version(unittest) { import std.random, std.stdio, std.string; mixin(dummyRanges); } /** Implements the homonym function (also known as $(D transform)) present in many languages of functional flavor. The call $(D map!(fun)(range)) returns a range of which elements are obtained by applying $(D fun(x)) left to right for all $(D x) in $(D range). The original ranges are not changed. Evaluation is done lazily. The range returned by $(D map) caches the last value such that evaluating $(D front) multiple times does not result in multiple calls to $(D fun). Example: ---- int[] arr1 = [ 1, 2, 3, 4 ]; int[] arr2 = [ 5, 6 ]; auto squares = map!("a * a")(chain(arr1, arr2)); assert(equal(squares, [ 1, 4, 9, 16, 25, 36 ])); ---- Multiple functions can be passed to $(D map). In that case, the element type of $(D map) is a tuple containing one element for each function. Example: ---- auto arr1 = [ 1, 2, 3, 4 ]; foreach (e; map!("a + a", "a * a")(arr1)) { writeln(e[0], " ", e[1]); } ---- You may alias $(D map) with some function(s) to a symbol and use it separately: ---- alias map!(to!string) stringize; assert(equal(stringize([ 1, 2, 3, 4 ]), [ "1", "2", "3", "4" ])); ---- */ template map(fun...) if (fun.length >= 1) { auto map(Range)(Range r) if (isInputRange!(Unqual!Range)) { static if (fun.length > 1) { alias adjoin!(staticMap!(unaryFun, fun)) _fun; } else { alias unaryFun!fun _fun; } struct Result { alias Unqual!Range R; alias typeof(_fun(.ElementType!R.init)) ElementType; R _input; static if (isBidirectionalRange!R) { @property auto ref back() { return _fun(_input.back); } void popBack() { _input.popBack(); } } this(R input) { _input = input; } static if (isInfinite!R) { // Propagate infinite-ness. enum bool empty = false; } else { @property bool empty() { return _input.empty; } } void popFront() { _input.popFront(); } @property auto ref front() { return _fun(_input.front); } static if (isRandomAccessRange!R) { auto ref opIndex(size_t index) { return _fun(_input[index]); } } static if (hasLength!R || isSomeString!R) { @property auto length() { return _input.length; } } static if (hasSlicing!R) { auto opSlice(size_t lowerBound, size_t upperBound) { return typeof(this)(_input[lowerBound..upperBound]); } } static if (isForwardRange!R) @property auto save() { auto result = this; result._input = result._input.save; return result; } } return Result(r); } } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); alias map!(to!string) stringize; assert(equal(stringize([ 1, 2, 3, 4 ]), [ "1", "2", "3", "4" ])); uint counter; alias map!((a) { return counter++; }) count; assert(equal(count([ 10, 2, 30, 4 ]), [ 0, 1, 2, 3 ])); counter = 0; adjoin!((a) { return counter++; }, (a) { return counter++; })(1); alias map!((a) { return counter++; }, (a) { return counter++; }) countAndSquare; //assert(equal(countAndSquare([ 10, 2 ]), [ tuple(0u, 100), tuple(1u, 4) ])); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] arr1 = [ 1, 2, 3, 4 ]; const int[] arr1Const = arr1; int[] arr2 = [ 5, 6 ]; auto squares = map!("a * a")(arr1Const); assert(equal(squares, [ 1, 4, 9, 16 ][])); assert(equal(map!("a * a")(chain(arr1, arr2)), [ 1, 4, 9, 16, 25, 36 ][])); // Test the caching stuff. assert(squares.back == 16); auto squares2 = squares.save; assert(squares2.back == 16); assert(squares2.front == 1); squares2.popFront; assert(squares2.front == 4); squares2.popBack; assert(squares2.front == 4); assert(squares2.back == 9); assert(equal(map!("a * a")(chain(arr1, arr2)), [ 1, 4, 9, 16, 25, 36 ][])); uint i; foreach (e; map!("a", "a * a")(arr1)) { assert(e[0] == ++i); assert(e[1] == i * i); } // Test length. assert(squares.length == 4); assert(map!"a * a"(chain(arr1, arr2)).length == 6); // Test indexing. assert(squares[0] == 1); assert(squares[1] == 4); assert(squares[2] == 9); assert(squares[3] == 16); // Test slicing. auto squareSlice = squares[1..squares.length - 1]; assert(equal(squareSlice, [4, 9][])); assert(squareSlice.back == 9); assert(squareSlice[1] == 9); // Test on a forward range to make sure it compiles when all the fancy // stuff is disabled. auto fibsSquares = map!"a * a"(recurrence!("a[n-1] + a[n-2]")(1, 1)); assert(fibsSquares.front == 1); fibsSquares.popFront; fibsSquares.popFront; assert(fibsSquares.front == 4); fibsSquares.popFront; assert(fibsSquares.front == 9); auto repeatMap = map!"a"(repeat(1)); static assert(isInfinite!(typeof(repeatMap))); auto intRange = map!"a"([1,2,3]); static assert(isRandomAccessRange!(typeof(intRange))); foreach(DummyType; AllDummyRanges) { DummyType d; auto m = map!"a * a"(d); static assert(propagatesRangeType!(typeof(m), DummyType)); assert(equal(m, [1,4,9,16,25,36,49,64,81,100])); } } unittest { auto LL = iota(1L, 4L); auto m = map!"a*a"(LL); assert(equal(m, [1L, 4L, 9L])); } // reduce /** Implements the homonym function (also known as $(D accumulate), $(D compress), $(D inject), or $(D foldl)) present in various programming languages of functional flavor. The call $(D reduce!(fun)(seed, range)) first assigns $(D seed) to an internal variable $(D result), also called the accumulator. Then, for each element $(D x) in $(D range), $(D result = fun(result, x)) gets evaluated. Finally, $(D result) is returned. The one-argument version $(D reduce!(fun)(range)) works similarly, but it uses the first element of the range as the seed (the range must be non-empty). Many aggregate range operations turn out to be solved with $(D reduce) quickly and easily. The example below illustrates $(D reduce)'s remarkable power and flexibility. Example: ---- int[] arr = [ 1, 2, 3, 4, 5 ]; // Sum all elements auto sum = reduce!("a + b")(0, arr); assert(sum == 15); // Compute the maximum of all elements auto largest = reduce!(max)(arr); assert(largest == 5); // Compute the number of odd elements auto odds = reduce!("a + (b & 1)")(0, arr); assert(odds == 3); // Compute the sum of squares auto ssquares = reduce!("a + b * b")(0, arr); assert(ssquares == 55); // Chain multiple ranges into seed int[] a = [ 3, 4 ]; int[] b = [ 100 ]; auto r = reduce!("a + b")(chain(a, b)); assert(r == 107); // Mixing convertible types is fair game, too double[] c = [ 2.5, 3.0 ]; auto r1 = reduce!("a + b")(chain(a, b, c)); assert(r1 == 112.5); ---- $(DDOC_SECTION_H Multiple functions:) Sometimes it is very useful to compute multiple aggregates in one pass. One advantage is that the computation is faster because the looping overhead is shared. That's why $(D reduce) accepts multiple functions. If two or more functions are passed, $(D reduce) returns a $(XREF typecons, Tuple) object with one member per passed-in function. The number of seeds must be correspondingly increased. Example: ---- double[] a = [ 3.0, 4, 7, 11, 3, 2, 5 ]; // Compute minimum and maximum in one pass auto r = reduce!(min, max)(a); // The type of r is Tuple!(double, double) assert(r[0] == 2); // minimum assert(r[1] == 11); // maximum // Compute sum and sum of squares in one pass r = reduce!("a + b", "a + b * b")(tuple(0.0, 0.0), a); assert(r[0] == 35); // sum assert(r[1] == 233); // sum of squares // Compute average and standard deviation from the above auto avg = r[0] / a.length; auto stdev = sqrt(r[1] / a.length - avg * avg); ---- */ template reduce(fun...) if (fun.length >= 1) { auto reduce(Args...)(Args args) if (Args.length > 0 && Args.length <= 2 && isIterable!(Args[$ - 1])) { static if(isInputRange!(Args[$ - 1])) { static if (Args.length == 2) { alias args[0] seed; alias args[1] r; Unqual!(Args[0]) result = seed; for (; !r.empty; r.popFront) { static if (fun.length == 1) { result = binaryFun!(fun[0])(result, r.front); } else { foreach (i, Unused; Args[0].Types) { result[i] = binaryFun!(fun[i])(result[i], r.front); } } } return result; } else { enforce(!args[$ - 1].empty, "Cannot reduce an empty range w/o an explicit seed value."); alias args[0] r; static if (fun.length == 1) { auto seed = r.front; r.popFront(); return reduce(seed, r); } else { static assert(fun.length > 1); typeof(adjoin!(staticMap!(binaryFun, fun))(r.front, r.front)) result = void; foreach (i, T; result.Types) { emplace(&result[i], r.front); } r.popFront(); return reduce(result, r); } } } else { // opApply case. Coded as a separate case because efficiently // handling all of the small details like avoiding unnecessary // copying, iterating by dchar over strings, and dealing with the // no explicit start value case would become an unreadable mess // if these were merged. alias args[$ - 1] r; alias Args[$ - 1] R; alias ForeachType!R E; static if(args.length == 2) { static if(fun.length == 1) { auto result = Tuple!(Unqual!(Args[0]))(args[0]); } else { Unqual!(Args[0]) result = args[0]; } enum bool initialized = true; } else static if(fun.length == 1) { Tuple!(typeof(binaryFun!fun(E.init, E.init))) result = void; bool initialized = false; } else { typeof(adjoin!(staticMap!(binaryFun, fun))(E.init, E.init)) result = void; bool initialized = false; } // For now, just iterate using ref to avoid unnecessary copying. // When Bug 2443 is fixed, this may need to change. foreach(ref elem; r) { if(initialized) { foreach(i, T; result.Types) { result[i] = binaryFun!(fun[i])(result[i], elem); } } else { static if(is(typeof(&initialized))) { initialized = true; } foreach (i, T; result.Types) { emplace(&result[i], elem); } } } enforce(initialized, "Cannot reduce an empty iterable w/o an explicit seed value."); static if(fun.length == 1) { return result[0]; } else { return result; } } } } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); double[] a = [ 3, 4 ]; auto r = reduce!("a + b")(0.0, a); assert(r == 7); r = reduce!("a + b")(a); assert(r == 7); r = reduce!(min)(a); assert(r == 3); double[] b = [ 100 ]; auto r1 = reduce!("a + b")(chain(a, b)); assert(r1 == 107); // two funs auto r2 = reduce!("a + b", "a - b")(tuple(0., 0.), a); assert(r2[0] == 7 && r2[1] == -7); auto r3 = reduce!("a + b", "a - b")(a); assert(r3[0] == 7 && r3[1] == -1); a = [ 1, 2, 3, 4, 5 ]; // Stringize with commas string rep = reduce!("a ~ `, ` ~ to!(string)(b)")("", a); assert(rep[2 .. $] == "1, 2, 3, 4, 5", "["~rep[2 .. $]~"]"); // Test the opApply case. struct OpApply { bool actEmpty; int opApply(int delegate(ref int) dg) { int res; if(actEmpty) return res; foreach(i; 0..100) { res = dg(i); if(res) break; } return res; } } OpApply oa; auto hundredSum = reduce!"a + b"(iota(100)); assert(reduce!"a + b"(5, oa) == hundredSum + 5); assert(reduce!"a + b"(oa) == hundredSum); assert(reduce!("a + b", max)(oa) == tuple(hundredSum, 99)); assert(reduce!("a + b", max)(tuple(5, 0), oa) == tuple(hundredSum + 5, 99)); // Test for throwing on empty range plus no seed. try { reduce!"a + b"([1, 2][0..0]); assert(0); } catch(Exception) {} oa.actEmpty = true; try { reduce!"a + b"(oa); assert(0); } catch(Exception) {} } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); const float a = 0.0; const float[] b = [ 1.2, 3, 3.3 ]; float[] c = [ 1.2, 3, 3.3 ]; auto r = reduce!"a + b"(a, b); r = reduce!"a + b"(a, c); } /** Fills a range with a value. Example: ---- int[] a = [ 1, 2, 3, 4 ]; fill(a, 5); assert(a == [ 5, 5, 5, 5 ]); ---- */ void fill(Range, Value)(Range range, Value filler) if (isForwardRange!Range && is(typeof(range.front = filler))) { alias ElementType!Range T; static if (hasElaborateCopyConstructor!T || !isDynamicArray!Range) { for (; !range.empty; range.popFront) { range.front = filler; } } else { if (range.empty) return; // Range is a dynamic array of bald values, just fill memory // Can't use memcpy or memmove coz ranges overlap range.front = filler; auto bytesToFill = T.sizeof * (range.length - 1); auto bytesFilled = T.sizeof; while (bytesToFill) { auto fillNow = min(bytesToFill, bytesFilled); memcpy(cast(void*) range.ptr + bytesFilled, cast(void*) range.ptr, fillNow); bytesToFill -= fillNow; bytesFilled += fillNow; } } } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 1, 2, 3 ]; fill(a, 6); assert(a == [ 6, 6, 6 ], text(a)); void fun0() { foreach (i; 0 .. 1000) { foreach (ref e; a) e = 6; } } void fun1() { foreach (i; 0 .. 1000) fill(a, 6); } //void fun2() { foreach (i; 0 .. 1000) fill2(a, 6); } //writeln(benchmark!(fun0, fun1, fun2)(10000)); } /** Fills $(D range) with a pattern copied from $(D filler). The length of $(D range) does not have to be a multiple of the length of $(D filler). If $(D filler) is empty, an exception is thrown. Example: ---- int[] a = [ 1, 2, 3, 4, 5 ]; int[] b = [ 8, 9 ]; fill(a, b); assert(a == [ 8, 9, 8, 9, 8 ]); ---- */ void fill(Range1, Range2)(Range1 range, Range2 filler) if (isForwardRange!Range1 && isForwardRange!Range2 && is(typeof(Range1.init.front = Range2.init.front))) { enforce(!filler.empty); auto t = filler.save; for (; !range.empty; range.popFront, t.popFront) { if (t.empty) t = filler; range.front = t.front; } } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 1, 2, 3, 4, 5 ]; int[] b = [1, 2]; fill(a, b); assert(a == [ 1, 2, 1, 2, 1 ]); } /** Fills a range with a value. Assumes that the range does not currently contain meaningful content. This is of interest for structs that define copy constructors (for all other types, fill and uninitializedFill are equivalent). Example: ---- struct S { ... } S[] s = (cast(S*) malloc(5 * S.sizeof))[0 .. 5]; uninitializedFill(s, 42); assert(s == [ 42, 42, 42, 42, 42 ]); ---- */ void uninitializedFill(Range, Value)(Range range, Value filler) if (isForwardRange!Range && is(typeof(range.front = filler))) { alias ElementType!Range T; static if (hasElaborateCopyConstructor!T) { // Must construct stuff by the book for (; !range.empty; range.popFront) { emplace(&range.front, filler); } } else { // Doesn't matter whether fill is initialized or not return fill(range, filler); } } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 1, 2, 3 ]; uninitializedFill(a, 6); assert(a == [ 6, 6, 6 ]); void fun0() { foreach (i; 0 .. 1000) { foreach (ref e; a) e = 6; } } void fun1() { foreach (i; 0 .. 1000) fill(a, 6); } //void fun2() { foreach (i; 0 .. 1000) fill2(a, 6); } //writeln(benchmark!(fun0, fun1, fun2)(10000)); } /** Initializes all elements of a range with their $(D .init) value. Assumes that the range does not currently contain meaningful content. Example: ---- struct S { ... } S[] s = (cast(S*) malloc(5 * S.sizeof))[0 .. 5]; initializeAll(s); assert(s == [ 0, 0, 0, 0, 0 ]); ---- */ void initializeAll(Range)(Range range) if (isForwardRange!Range && is(typeof(range.front = range.front))) { alias ElementType!Range T; static assert(is(typeof(&(range.front()))) || !hasElaborateAssign!T, "Cannot initialize a range that does not expose" " references to its elements"); static if (!isDynamicArray!Range) { static if (is(typeof(&(range.front())))) { // Range exposes references for (; !range.empty; range.popFront) { memcpy(&(range.front()), &T.init, T.sizeof); } } else { // Go the slow route for (; !range.empty; range.popFront) { range.front = filler; } } } else { fill(range, T.init); } } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 1, 2, 3 ]; uninitializedFill(a, 6); assert(a == [ 6, 6, 6 ]); initializeAll(a); assert(a == [ 0, 0, 0 ]); void fun0() { foreach (i; 0 .. 1000) { foreach (ref e; a) e = 6; } } void fun1() { foreach (i; 0 .. 1000) fill(a, 6); } //void fun2() { foreach (i; 0 .. 1000) fill2(a, 6); } //writeln(benchmark!(fun0, fun1, fun2)(10000)); } // filter /** Implements the homonym function present in various programming languages of functional flavor. The call $(D filter!(fun)(range)) returns a new range only containing elements $(D x) in $(D r) for which $(D predicate(x)) is $(D true). Example: ---- int[] arr = [ 1, 2, 3, 4, 5 ]; // Sum all elements auto small = filter!("a < 3")(arr); assert(equal(small, [ 1, 2 ])); // In combination with chain() to span multiple ranges int[] a = [ 3, -2, 400 ]; int[] b = [ 100, -101, 102 ]; auto r = filter!("a > 0")(chain(a, b)); assert(equal(r, [ 3, 400, 100, 102 ])); // Mixing convertible types is fair game, too double[] c = [ 2.5, 3.0 ]; auto r1 = filter!("cast(int) a != a")(chain(c, a, b)); assert(equal(r1, [ 2.5 ])); ---- */ template filter(alias pred) if (is(typeof(unaryFun!pred))) { auto filter(Range)(Range rs) if (isInputRange!(Unqual!Range)) { struct Result { alias Unqual!Range R; R _input; this(R r) { _input = r; while (!_input.empty && !unaryFun!pred(_input.front)) { _input.popFront(); } } auto opSlice() { return this; } static if (isInfinite!Range) { enum bool empty = false; } else { @property bool empty() { return _input.empty; } } void popFront() { do { _input.popFront; } while (!_input.empty && !unaryFun!pred(_input.front)); } @property auto ref front() { return _input.front; } static if(isForwardRange!R) { @property auto save() { return Result(_input); } } } return Result(rs); } } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 3, 4, 2 ]; auto r = filter!("a > 3")(a); static assert(isForwardRange!(typeof(r))); assert(equal(r, [ 4 ][])); a = [ 1, 22, 3, 42, 5 ]; auto under10 = filter!("a < 10")(a); assert(equal(under10, [1, 3, 5][])); static assert(isForwardRange!(typeof(under10))); under10.front() = 4; assert(equal(under10, [4, 3, 5][])); under10.front() = 40; assert(equal(under10, [40, 3, 5][])); under10.front() = 1; auto infinite = filter!"a > 2"(repeat(3)); static assert(isInfinite!(typeof(infinite))); static assert(isForwardRange!(typeof(infinite))); foreach(DummyType; AllDummyRanges) { DummyType d; auto f = filter!"a & 1"(d); assert(equal(f, [1,3,5,7,9])); static if (isForwardRange!DummyType) { static assert(isForwardRange!(typeof(f))); } } // With delegates int x = 10; int overX(int a) { return a > x; } typeof(filter!overX(a)) getFilter() { return filter!overX(a); } auto r1 = getFilter(); assert(equal(r1, [22, 42])); // With chain auto nums = [0,1,2,3,4]; assert(equal(filter!overX(chain(a, nums)), [22, 42])); // With copying of inner struct Filter to Map auto arr = [1,2,3,4,5]; auto m = map!"a + 1"(filter!"a < 4"(arr)); } unittest { int[] a = [ 3, 4 ]; const aConst = a; auto r = filter!("a > 3")(aConst); assert(equal(r, [ 4 ][])); a = [ 1, 22, 3, 42, 5 ]; auto under10 = filter!("a < 10")(a); assert(equal(under10, [1, 3, 5][])); assert(equal(under10.save, [1, 3, 5][])); assert(equal(under10.save, under10)); // With copying of inner struct Filter to Map auto arr = [1,2,3,4,5]; auto m = map!"a + 1"(filter!"a < 4"(arr)); } unittest { assert(equal(compose!(map!"2 * a", filter!"a & 1")([1,2,3,4,5]), [2,6,10])); assert(equal(pipe!(filter!"a & 1", map!"2 * a")([1,2,3,4,5]), [2,6,10])); } unittest { int x = 10; int underX(int a) { return a < x; } const(int)[] list = [ 1, 2, 10, 11, 3, 4 ]; assert(equal(filter!underX(list), [ 1, 2, 3, 4 ])); } // filterBidirectional /** * Similar to $(D filter), except it defines a bidirectional * range. There is a speed disadvantage - the constructor spends time * finding the last element in the range that satisfies the filtering * condition (in addition to finding the first one). The advantage is * that the filtered range can be spanned from both directions. Also, * $(XREF range, retro) can be applied against the filtered range. * Example: ---- int[] arr = [ 1, 2, 3, 4, 5 ]; auto small = filterBidirectional!("a < 3")(arr); assert(small.back == 2); assert(equal(small, [ 1, 2 ])); assert(equal(retro(small), [ 2, 1 ])); // In combination with chain() to span multiple ranges int[] a = [ 3, -2, 400 ]; int[] b = [ 100, -101, 102 ]; auto r = filterBidirectional!("a > 0")(chain(a, b)); assert(r.back == 102); ---- */ template filterBidirectional(alias pred) { auto filterBidirectional(Range)(Range r) if (isBidirectionalRange!(Unqual!Range)) { static struct Result { alias Unqual!Range R; alias unaryFun!pred predFun; R _input; this(R r) { _input = r; while (!_input.empty && !predFun(_input.front)) _input.popFront(); while (!_input.empty && !predFun(_input.back)) _input.popBack(); } @property bool empty() { return _input.empty; } void popFront() { do { _input.popFront; } while (!_input.empty && !predFun(_input.front)); } @property auto ref front() { return _input.front; } void popBack() { do { _input.popBack; } while (!_input.empty && !predFun(_input.back)); } @property auto ref back() { return _input.back; } @property auto save() { Result result; result._input = _input.save; return result; } } return Result(r); } } unittest { int[] arr = [ 1, 2, 3, 4, 5 ]; auto small = filterBidirectional!("a < 3")(arr); static assert(isBidirectionalRange!(typeof(small))); assert(small.back == 2); assert(equal(small, [ 1, 2 ])); assert(equal(retro(small), [ 2, 1 ])); // In combination with chain() to span multiple ranges int[] a = [ 3, -2, 400 ]; int[] b = [ 100, -101, 102 ]; auto r = filterBidirectional!("a > 0")(chain(a, b)); assert(r.back == 102); } // move /** Moves $(D source) into $(D target) via a destructive copy. Specifically: $(UL $(LI If $(D hasAliasing!T) is true (see $(XREF traits, hasAliasing)), then the representation of $(D source) is bitwise copied into $(D target) and then $(D source = T.init) is evaluated.) $(LI Otherwise, $(D target = source) is evaluated.)) See also $(XREF contracts, pointsTo). Preconditions: $(D &source == &target || !pointsTo(source, source)) */ void move(T)(ref T source, ref T target) { if (&source == &target) return; assert(!pointsTo(source, source)); static if (is(T == struct)) { // Most complicated case. Destroy whatever target had in it // and bitblast source over it static if (hasElaborateDestructor!T) typeid(T).destroy(&target); memcpy(&target, &source, T.sizeof); // If the source defines a destructor or a postblit hook, we must obliterate the // object in order to avoid double freeing and undue aliasing static if (hasElaborateDestructor!T || hasElaborateCopyConstructor!T) { static T empty; memcpy(&source, &empty, T.sizeof); } } else { // Primitive data (including pointers and arrays) or class - // assignment works great target = source; // static if (is(typeof(source = null))) // { // // Nullify the source to help the garbage collector // source = null; // } } } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); Object obj1 = new Object; Object obj2 = obj1; Object obj3; move(obj2, obj3); assert(obj3 is obj1); struct S1 { int a = 1, b = 2; } S1 s11 = { 10, 11 }; S1 s12; move(s11, s12); assert(s11.a == 10 && s11.b == 11 && s12.a == 10 && s12.b == 11); struct S2 { int a = 1; int * b; } S2 s21 = { 10, null }; s21.b = new int; S2 s22; move(s21, s22); assert(s21 == s22); // Issue 5661 test(1) struct S3 { struct X { int n = 0; ~this(){n = 0;} } X x; } static assert(hasElaborateDestructor!S3); S3 s31, s32; s31.x.n = 1; move(s31, s32); assert(s31.x.n == 0); assert(s32.x.n == 1); // Issue 5661 test(2) struct S4 { struct X { int n = 0; this(this){n = 0;} } X x; } static assert(hasElaborateCopyConstructor!S4); S4 s41, s42; s41.x.n = 1; move(s41, s42); assert(s41.x.n == 0); assert(s42.x.n == 1); } /// Ditto T move(T)(ref T src) { T result; move(src, result); return result; } // moveAll /** For each element $(D a) in $(D src) and each element $(D b) in $(D tgt) in lockstep in increasing order, calls $(D move(a, b)). Returns the leftover portion of $(D tgt). Throws an exeption if there is not enough room in $(D tgt) to acommodate all of $(D src). Preconditions: $(D walkLength(src) >= walkLength(tgt)) */ Range2 moveAll(Range1, Range2)(Range1 src, Range2 tgt) if (isInputRange!Range1 && isInputRange!Range2 && is(typeof(move(src.front, tgt.front)))) { for (; !src.empty; src.popFront, tgt.popFront) { enforce(!tgt.empty); move(src.front, tgt.front); } return tgt; } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 1, 2, 3 ]; int[] b = new int[5]; assert(moveAll(a, b) is b[3 .. $]); assert(a == b[0 .. 3]); assert(a == [ 1, 2, 3 ]); } // moveSome /** For each element $(D a) in $(D src) and each element $(D b) in $(D tgt) in lockstep in increasing order, calls $(D move(a, b)). Stops when either $(D src) or $(D tgt) have been exhausted. Returns the leftover portions of the two ranges. */ Tuple!(Range1, Range2) moveSome(Range1, Range2)(Range1 src, Range2 tgt) if (isInputRange!Range1 && isInputRange!Range2 && is(typeof(move(src.front, tgt.front)))) { for (; !src.empty && !tgt.empty; src.popFront, tgt.popFront) { enforce(!tgt.empty); move(src.front, tgt.front); } return tuple(src, tgt); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 1, 2, 3, 4, 5 ]; int[] b = new int[3]; assert(moveSome(a, b)[0] is a[3 .. $]); assert(a[0 .. 3] == b); assert(a == [ 1, 2, 3, 4, 5 ]); } // swap /** Swaps $(D lhs) and $(D rhs). See also $(XREF exception, pointsTo). Preconditions: $(D !pointsTo(lhs, lhs) && !pointsTo(lhs, rhs) && !pointsTo(rhs, lhs) && !pointsTo(rhs, rhs)) */ void swap(T)(ref T lhs, ref T rhs) @trusted pure nothrow if (isMutable!T && !is(typeof(T.init.proxySwap(T.init)))) { static if (hasElaborateAssign!T) { if (&lhs != &rhs) { // For structs with non-trivial assignment, move memory directly // First check for undue aliasing assert(!pointsTo(lhs, rhs) && !pointsTo(rhs, lhs) && !pointsTo(lhs, lhs) && !pointsTo(rhs, rhs)); // Swap bits ubyte[T.sizeof] t = void; auto a = (cast(ubyte*) &lhs)[0 .. T.sizeof]; auto b = (cast(ubyte*) &rhs)[0 .. T.sizeof]; t[] = a[]; a[] = b[]; b[] = t[]; } } else { // Temporary fix Bug 4789. Wor around the fact that assigning a static // array to itself doesn't work properly. static if(isStaticArray!T) { if(lhs.ptr is rhs.ptr) { return; } } // For non-struct types, suffice to do the classic swap auto tmp = lhs; lhs = rhs; rhs = tmp; } } // Not yet documented void swap(T)(T lhs, T rhs) if (is(typeof(T.init.proxySwap(T.init)))) { lhs.proxySwap(rhs); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int a = 42, b = 34; swap(a, b); assert(a == 34 && b == 42); struct S { int x; char c; int[] y; } S s1 = { 0, 'z', [ 1, 2 ] }; S s2 = { 42, 'a', [ 4, 6 ] }; //writeln(s2.tupleof.stringof); swap(s1, s2); assert(s1.x == 42); assert(s1.c == 'a'); assert(s1.y == [ 4, 6 ]); assert(s2.x == 0); assert(s2.c == 'z'); assert(s2.y == [ 1, 2 ]); immutable int imm1, imm2; static assert(!__traits(compiles, swap(imm1, imm2))); } unittest { struct NoCopy { this(this) { assert(0); } int n; string s; } NoCopy nc1, nc2; nc1.n = 127; nc1.s = "abc"; nc2.n = 513; nc2.s = "uvwxyz"; swap(nc1, nc2); assert(nc1.n == 513 && nc1.s == "uvwxyz"); assert(nc2.n == 127 && nc2.s == "abc"); swap(nc1, nc1); swap(nc2, nc2); assert(nc1.n == 513 && nc1.s == "uvwxyz"); assert(nc2.n == 127 && nc2.s == "abc"); struct NoCopyHolder { NoCopy noCopy; } NoCopyHolder h1, h2; h1.noCopy.n = 31; h1.noCopy.s = "abc"; h2.noCopy.n = 65; h2.noCopy.s = null; swap(h1, h2); assert(h1.noCopy.n == 65 && h1.noCopy.s == null); assert(h2.noCopy.n == 31 && h2.noCopy.s == "abc"); swap(h1, h1); swap(h2, h2); assert(h1.noCopy.n == 65 && h1.noCopy.s == null); assert(h2.noCopy.n == 31 && h2.noCopy.s == "abc"); const NoCopy const1, const2; static assert(!__traits(compiles, swap(const1, const2))); } void swapFront(R1, R2)(R1 r1, R2 r2) if (isInputRange!R1 && isInputRange!R2) { static if (is(typeof(swap(r1.front, r2.front)))) { swap(r1.front, r2.front); } else { auto t1 = moveFront(r1), t2 = moveFront(r2); r1.front = move(t2); r2.front = move(t1); } } // splitter /** Splits a range using an element as a separator. This can be used with any range type, but is most popular with string types. Two adjacent separators are considered to surround an empty element in the split range. If the empty range is given, the result is a range with one empty element. If a range with one separator is given, the result is a range with two empty elements. Example: --- assert(equal(splitter("hello world", ' '), [ "hello", "", "world" ])); int[] a = [ 1, 2, 0, 0, 3, 0, 4, 5, 0 ]; int[][] w = [ [1, 2], [], [3], [4, 5] ]; assert(equal(splitter(a, 0), w)); a = null; assert(equal(splitter(a, 0), [ (int[]).init ])); a = [ 0 ]; assert(equal(splitter(a, 0), [ (int[]).init, (int[]).init ])); a = [ 0, 1 ]; assert(equal(splitter(a, 0), [ [], [1] ])); ---- */ auto splitter(Range, Separator)(Range r, Separator s) if (is(typeof(ElementType!Range.init == Separator.init)) && (hasSlicing!Range || isNarrowString!Range)) { struct Result { private: Range _input; Separator _separator; // Do we need hasLength!Range? popFront uses _input.length... alias typeof(unsigned(_input.length)) IndexType; enum IndexType _unComputed = IndexType.max - 1, _atEnd = IndexType.max; IndexType _frontLength = _unComputed; IndexType _backLength = _unComputed; static if(isBidirectionalRange!Range) { static IndexType lastIndexOf(Range haystack, Separator needle) { immutable index = countUntil(retro(haystack), needle); return (index == -1) ? -1 : haystack.length - 1 - index; } } public: this(Range input, Separator separator) { _input = input; _separator = separator; } static if (isInfinite!Range) { enum bool empty = false; } else { @property bool empty() { return _frontLength == _atEnd; } } @property Range front() { assert(!empty); if (_frontLength == _unComputed) { _frontLength = countUntil(_input, _separator); if (_frontLength == -1) _frontLength = _input.length; } return _input[0 .. _frontLength]; } void popFront() { assert(!empty); if (_frontLength == _unComputed) { front; } assert(_frontLength <= _input.length); if (_frontLength == _input.length) { // no more input and need to fetch => done _frontLength = _atEnd; // Probably don't need this, but just for consistency: _backLength = _atEnd; } else { _input = _input[_frontLength .. _input.length]; skipOver(_input, _separator) || assert(false); _frontLength = _unComputed; } } static if(isForwardRange!Range) { @property typeof(this) save() { auto ret = this; ret._input = _input.save; return ret; } } static if(isBidirectionalRange!Range) { @property Range back() { assert(!empty); if (_backLength == _unComputed) { immutable lastIndex = lastIndexOf(_input, _separator); if(lastIndex == -1) { _backLength = _input.length; } else { _backLength = _input.length - lastIndex - 1; } } return _input[_input.length - _backLength .. _input.length]; } void popBack() { assert(!empty); if (_backLength == _unComputed) { // evaluate back to make sure it's computed back; } assert(_backLength <= _input.length); if (_backLength == _input.length) { // no more input and need to fetch => done _frontLength = _atEnd; _backLength = _atEnd; } else { _input = _input[0 .. _input.length - _backLength]; if (!_input.empty && _input.back == _separator) { _input.popBack(); } else { assert(false); } _backLength = _unComputed; } } } } return Result(r, s); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); assert(equal(splitter("hello world", ' '), [ "hello", "", "world" ])); int[] a = [ 1, 2, 0, 0, 3, 0, 4, 5, 0 ]; int[][] w = [ [1, 2], [], [3], [4, 5], [] ]; static assert(isForwardRange!(typeof(splitter(a, 0)))); // foreach (x; splitter(a, 0)) { // writeln("[", x, "]"); // } assert(equal(splitter(a, 0), w)); a = null; assert(equal(splitter(a, 0), [ (int[]).init ][])); a = [ 0 ]; assert(equal(splitter(a, 0), [ (int[]).init, (int[]).init ][])); a = [ 0, 1 ]; assert(equal(splitter(a, 0), [ [], [1] ][])); // Thoroughly exercise the bidirectional stuff. auto str = "abc abcd abcde ab abcdefg abcdefghij ab ac ar an at ada"; assert(equal( retro(splitter(str, 'a')), retro(array(splitter(str, 'a'))) )); // Test interleaving front and back. auto split = splitter(str, 'a'); assert(split.front == ""); assert(split.back == ""); split.popBack(); assert(split.back == "d"); split.popFront(); assert(split.front == "bc "); assert(split.back == "d"); split.popFront(); split.popBack(); assert(split.back == "t "); split.popBack(); split.popBack(); split.popFront(); split.popFront(); assert(split.front == "b "); assert(split.back == "r "); foreach(DummyType; AllDummyRanges) { // Bug 4408 static if(isRandomAccessRange!DummyType) { static assert(isBidirectionalRange!DummyType); DummyType d; auto s = splitter(d, 5); assert(equal(s.front, [1,2,3,4])); assert(equal(s.back, [6,7,8,9,10])); auto s2 = splitter(d, [4, 5]); assert(equal(s2.front, [1,2,3])); assert(equal(s2.back, [6,7,8,9,10])); } } } unittest { auto L = retro(iota(1L, 10L)); auto s = splitter(L, 5L); assert(equal(s.front, [9L, 8L, 7L, 6L])); s.popFront(); assert(equal(s.front, [4L, 3L, 2L, 1L])); s.popFront(); assert(s.empty); } /** Splits a range using another range as a separator. This can be used with any range type, but is most popular with string types. */ auto splitter(Range, Separator)(Range r, Separator s) if (is(typeof(Range.init.front == Separator.init.front) : bool)) { struct Result { private: Range _input; Separator _separator; alias typeof(unsigned(_input.length)) RIndexType; // _frontLength == size_t.max means empty RIndexType _frontLength = RIndexType.max; static if (isBidirectionalRange!Range) RIndexType _backLength = RIndexType.max; auto separatorLength() { return _separator.length; } void ensureFrontLength() { if (_frontLength != _frontLength.max) return; assert(!_input.empty); // compute front length _frontLength = _input.length - find(_input, _separator).length; static if (isBidirectionalRange!Range) if (_frontLength == _input.length) _backLength = _frontLength; } void ensureBackLength() { static if (isBidirectionalRange!Range) if (_backLength != _backLength.max) return; assert(!_input.empty); // compute back length static if (isBidirectionalRange!Range) { _backLength = _input.length - find(retro(_input), retro(_separator)).source.length; } } public: this(Range input, Separator separator) { _input = input; _separator = separator; } @property Range front() { assert(!empty); ensureFrontLength(); return _input[0 .. _frontLength]; } static if (isInfinite!Range) { enum bool empty = false; // Propagate infiniteness } else { @property bool empty() { return _frontLength == RIndexType.max && _input.empty; } } void popFront() { assert(!empty); ensureFrontLength; if (_frontLength == _input.length) { // done, there's no separator in sight _input = _input[_frontLength .. _frontLength]; _frontLength = _frontLength.max; static if (isBidirectionalRange!Range) _backLength = _backLength.max; return; } if (_frontLength + separatorLength == _input.length) { // Special case: popping the first-to-last item; there is // an empty item right after this. _input = _input[_input.length .. _input.length]; _frontLength = 0; static if (isBidirectionalRange!Range) _backLength = 0; return; } // Normal case, pop one item and the separator, get ready for // reading the next item _input = _input[_frontLength + separatorLength .. _input.length]; // mark _frontLength as uninitialized _frontLength = _frontLength.max; } static if(isForwardRange!Range) { @property typeof(this) save() { auto ret = this; ret._input = _input.save; return ret; } } // Bidirectional functionality as suggested by Brad Roberts. static if (isBidirectionalRange!Range) { @property Range back() { ensureBackLength; return _input[_input.length - _backLength .. _input.length]; } void popBack() { ensureBackLength; if (_backLength == _input.length) { // done _input = _input[0 .. 0]; _frontLength = _frontLength.max; _backLength = _backLength.max; return; } if (_backLength + separatorLength == _input.length) { // Special case: popping the first-to-first item; there is // an empty item right before this. Leave the separator in. _input = _input[0 .. 0]; _frontLength = 0; _backLength = 0; return; } // Normal case _input = _input[0 .. _input.length - _backLength - separatorLength]; _backLength = _backLength.max; } } } return Result(r, s); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); auto s = ",abc, de, fg,hi,"; auto sp0 = splitter(s, ','); // //foreach (e; sp0) writeln("[", e, "]"); assert(equal(sp0, ["", "abc", " de", " fg", "hi", ""][])); auto s1 = ", abc, de, fg, hi, "; auto sp1 = splitter(s1, ", "); //foreach (e; sp1) writeln("[", e, "]"); assert(equal(sp1, ["", "abc", "de", " fg", "hi", ""][])); static assert(isForwardRange!(typeof(sp1))); int[] a = [ 1, 2, 0, 3, 0, 4, 5, 0 ]; int[][] w = [ [1, 2], [3], [4, 5], [] ]; uint i; foreach (e; splitter(a, 0)) { assert(i < w.length); assert(e == w[i++]); } assert(i == w.length); // // Now go back // auto s2 = splitter(a, 0); // foreach (e; retro(s2)) // { // assert(i > 0); // assert(equal(e, w[--i]), text(e)); // } // assert(i == 0); wstring names = ",peter,paul,jerry,"; auto words = split(names, ","); assert(walkLength(words) == 5, text(walkLength(words))); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); auto s6 = ","; auto sp6 = splitter(s6, ','); foreach (e; sp6) { //writeln("{", e, "}"); } assert(equal(sp6, ["", ""][])); } auto splitter(alias isTerminator, Range)(Range input) if (is(typeof(unaryFun!(isTerminator)(ElementType!(Range).init)))) { struct Result { private Range _input; private size_t _end; private alias unaryFun!isTerminator _isTerminator; this(Range input) { _input = input; if (_input.empty) { _end = _end.max; } else { // Chase first terminator while (_end < _input.length && !_isTerminator(_input[_end])) { ++_end; } } } static if (isInfinite!Range) { enum bool empty = false; // Propagate infiniteness. } else { @property bool empty() { return _end == _end.max; } } @property Range front() { assert(!empty); return _input[0 .. _end]; } void popFront() { assert(!empty); if (_input.empty) { _end = _end.max; return; } // Skip over existing word _input = _input[_end .. _input.length]; // Skip terminator for (;;) { if (_input.empty) { // Nothing following the terminator - done _end = _end.max; return; } if (!_isTerminator(_input.front)) { // Found a legit next field break; } _input.popFront(); } assert(!_input.empty && !_isTerminator(_input.front)); // Prepare _end _end = 1; while (_end < _input.length && !_isTerminator(_input[_end])) { ++_end; } } static if(isForwardRange!Range) { @property typeof(this) save() { auto ret = this; ret._input = _input.save; return ret; } } } return Result(input); } unittest { auto L = iota(1L, 10L); auto s = splitter(L, [5L, 6L]); assert(equal(s.front, [1L, 2L, 3L, 4L])); s.popFront(); assert(equal(s.front, [7L, 8L, 9L])); s.popFront(); assert(s.empty); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); void compare(string sentence, string[] witness) { foreach (word; splitter!"a == ' '"(sentence)) { assert(word == witness.front, word); witness.popFront(); } assert(witness.empty, witness[0]); } compare(" Mary has a little lamb. ", ["", "Mary", "has", "a", "little", "lamb."]); compare("Mary has a little lamb. ", ["Mary", "has", "a", "little", "lamb."]); compare("Mary has a little lamb.", ["Mary", "has", "a", "little", "lamb."]); compare("", []); compare(" ", [""]); static assert(isForwardRange!(typeof(splitter!"a == ' '"("ABC")))); foreach(DummyType; AllDummyRanges) { static if(isRandomAccessRange!DummyType) { auto rangeSplit = splitter!"a == 5"(DummyType.init); assert(equal(rangeSplit.front, [1,2,3,4])); rangeSplit.popFront(); assert(equal(rangeSplit.front, [6,7,8,9,10])); } } } auto splitter(Range)(Range input) if (isSomeString!Range) { return splitter!(std.uni.isWhite)(input); } unittest { // TDPL example, page 8 uint[string] dictionary; char[][3] lines; lines[0] = "line one".dup; lines[1] = "line \ttwo".dup; lines[2] = "yah last line\ryah".dup; foreach (line; lines) { foreach (word; splitter(strip(line))) { if (word in dictionary) continue; // Nothing to do auto newID = dictionary.length; dictionary[to!string(word)] = cast(uint)newID; } } assert(dictionary.length == 5); assert(dictionary["line"]== 0); assert(dictionary["one"]== 1); assert(dictionary["two"]== 2); assert(dictionary["yah"]== 3); assert(dictionary["last"]== 4); } // joiner /** Lazily joins a range of ranges with a separator. The separator itself is a range. Example: ---- assert(equal(joiner([""], "xyz"), "")); assert(equal(joiner(["", ""], "xyz"), "xyz")); assert(equal(joiner(["", "abc"], "xyz"), "xyzabc")); assert(equal(joiner(["abc", ""], "xyz"), "abcxyz")); assert(equal(joiner(["abc", "def"], "xyz"), "abcxyzdef")); assert(equal(joiner(["Mary", "has", "a", "little", "lamb"], "..."), "Mary...has...a...little...lamb")); ---- */ auto joiner(RoR, Separator)(RoR r, Separator sep) if (isInputRange!RoR && isInputRange!(ElementType!RoR) && isForwardRange!Separator && is(ElementType!Separator : ElementType!(ElementType!RoR))) { static struct Result { private RoR _items; private ElementType!RoR _current; private Separator _sep, _currentSep; private void useSeparator() { assert(_currentSep.empty && _current.empty, "joiner: internal error"); if (_sep.empty) { // Advance to the next range in the // input //_items.popFront(); for (;; _items.popFront()) { if (_items.empty) return; if (!_items.front.empty) break; } _current = _items.front; _items.popFront(); } else { // Must make sure something is coming after the // separator - it's a separator, not a terminator! if (_items.empty) return; _currentSep = _sep.save; assert(!_currentSep.empty); } } private void useItem() { assert(_currentSep.empty && _current.empty, "joiner: internal error"); // Use the input if (_items.empty) return; _current = _items.front; _items.popFront(); if (!_current.empty) { return; } // No data in the current item - toggle to use the // separator useSeparator(); } this(RoR items, Separator sep) { _items = items; _sep = sep; useItem(); // We need the separator if the input has at least two // elements if (_current.empty && _items.empty) { // Vacate the whole thing _currentSep = _currentSep.init; } } @property auto empty() { return _current.empty && _currentSep.empty; } @property ElementType!(ElementType!RoR) front() { if (!_currentSep.empty) return _currentSep.front; assert(!_current.empty); return _current.front; } void popFront() { assert(!empty); // Using separator? if (!_currentSep.empty) { _currentSep.popFront(); if (!_currentSep.empty) return; useItem(); } else { // we're using the range _current.popFront(); if (!_current.empty) return; useSeparator(); } } static if (isForwardRange!RoR && isForwardRange!(ElementType!RoR)) { @property auto save() { Result copy; copy._items = _items.save; copy._current = _current.save; copy._sep = _sep.save; copy._currentSep = _currentSep.save; return copy; } } } return Result(r, sep); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); static assert(isInputRange!(typeof(joiner([""], "")))); static assert(isForwardRange!(typeof(joiner([""], "")))); assert(equal(joiner([""], "xyz"), ""), text(joiner([""], "xyz"))); assert(equal(joiner(["", ""], "xyz"), "xyz"), text(joiner(["", ""], "xyz"))); assert(equal(joiner(["", "abc"], "xyz"), "xyzabc")); assert(equal(joiner(["abc", ""], "xyz"), "abcxyz")); assert(equal(joiner(["abc", "def"], "xyz"), "abcxyzdef")); assert(equal(joiner(["Mary", "has", "a", "little", "lamb"], "..."), "Mary...has...a...little...lamb")); } unittest { // joiner() should work for non-forward ranges too. InputRange!string r = inputRangeObject(["abc", "def"]); assert (equal(joiner(r, "xyz"), "abcxyzdef")); } auto joiner(RoR)(RoR r) if (isInputRange!RoR && isInputRange!(ElementType!RoR)) { static struct Result { private: RoR _items; ElementType!RoR _current; void prepare() { for (;; _items.popFront()) { if (_items.empty) return; if (!_items.front.empty) break; } _current = _items.front; _items.popFront(); } public: this(RoR r) { _items = r; prepare(); } static if (isInfinite!(ElementType!RoR)) { enum bool empty = false; } else { @property auto empty() { return _current.empty; } } @property auto ref front() { assert(!empty); return _current.front; } void popFront() { assert(!_current.empty); _current.popFront(); if (_current.empty) prepare(); } static if (isForwardRange!RoR && isForwardRange!(ElementType!RoR)) { @property auto save() { Result copy; copy._items = _items.save; copy._current = _current.save; return copy; } } } return Result(r); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); static assert(isInputRange!(typeof(joiner([""])))); static assert(isForwardRange!(typeof(joiner([""])))); assert(equal(joiner([""]), "")); assert(equal(joiner(["", ""]), "")); assert(equal(joiner(["", "abc"]), "abc")); assert(equal(joiner(["abc", ""]), "abc")); assert(equal(joiner(["abc", "def"]), "abcdef")); assert(equal(joiner(["Mary", "has", "a", "little", "lamb"]), "Maryhasalittlelamb")); assert(equal(joiner(std.range.repeat("abc", 3)), "abcabcabc")); // joiner allows in-place mutation! auto a = [ [1, 2, 3], [42, 43] ]; auto j = joiner(a); j.front() = 44; assert(a == [ [44, 2, 3], [42, 43] ]); } // uniq /** Iterates unique consecutive elements of the given range (functionality akin to the $(WEB wikipedia.org/wiki/_Uniq, _uniq) system utility). Equivalence of elements is assessed by using the predicate $(D pred), by default $(D "a == b"). If the given range is bidirectional, $(D uniq) also yields a bidirectional range. Example: ---- int[] arr = [ 1, 2, 2, 2, 2, 3, 4, 4, 4, 5 ]; assert(equal(uniq(arr), [ 1, 2, 3, 4, 5 ][])); ---- */ auto uniq(alias pred = "a == b", Range)(Range r) if (isInputRange!Range && is(typeof(binaryFun!pred(r.front, r.front)) == bool)) { struct Result { Range _input; this(Range input) { _input = input; } auto opSlice() { return this; } void popFront() { auto last = _input.front; do { _input.popFront; } while (!_input.empty && binaryFun!(pred)(last, _input.front)); } @property ElementType!Range front() { return _input.front; } static if (isBidirectionalRange!Range) { void popBack() { auto last = _input.back; do { _input.popBack; } while (!_input.empty && binaryFun!pred(last, _input.back)); } @property ElementType!Range back() { return _input.back; } } static if (isInfinite!Range) { enum bool empty = false; // Propagate infiniteness. } else { @property bool empty() { return _input.empty; } } static if (isForwardRange!Range) { @property typeof(this) save() { return typeof(this)(_input.save); } } } return Result(r); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] arr = [ 1, 2, 2, 2, 2, 3, 4, 4, 4, 5 ]; auto r = uniq(arr); static assert(isForwardRange!(typeof(r))); assert(equal(r, [ 1, 2, 3, 4, 5 ][])); assert(equal(retro(r), retro([ 1, 2, 3, 4, 5 ][]))); foreach(DummyType; AllDummyRanges) { DummyType d; auto u = uniq(d); assert(equal(u, [1,2,3,4,5,6,7,8,9,10])); static assert(d.rt == RangeType.Input || isForwardRange!(typeof(u))); static if (d.rt >= RangeType.Bidirectional) { assert(equal(retro(u), [10,9,8,7,6,5,4,3,2,1])); } } } // group /** Similarly to $(D uniq), $(D group) iterates unique consecutive elements of the given range. The element type is $(D Tuple!(ElementType!R, uint)) because it includes the count of equivalent elements seen. Equivalence of elements is assessed by using the predicate $(D pred), by default $(D "a == b"). $(D Group) is an input range if $(D R) is an input range, and a forward range in all other cases. Example: ---- int[] arr = [ 1, 2, 2, 2, 2, 3, 4, 4, 4, 5 ]; assert(equal(group(arr), [ tuple(1, 1u), tuple(2, 4u), tuple(3, 1u), tuple(4, 3u), tuple(5, 1u) ][])); ---- */ struct Group(alias pred, R) if (isInputRange!R) { private R _input; private Tuple!(ElementType!R, uint) _current; private alias binaryFun!pred comp; this(R input) { _input = input; if (!_input.empty) popFront; } void popFront() { if (_input.empty) { _current[1] = 0; } else { _current = tuple(_input.front, 1u); _input.popFront; while (!_input.empty && comp(_current[0], _input.front)) { ++_current[1]; _input.popFront; } } } static if (isInfinite!R) { enum bool empty = false; // Propagate infiniteness. } else { @property bool empty() { return _current[1] == 0; } } @property ref Tuple!(ElementType!R, uint) front() { assert(!empty); return _current; } static if (isForwardRange!R) { @property typeof(this) save() { typeof(this) ret; ret._input = this._input.save; ret._current = this._current; return ret; } } } /// Ditto Group!(pred, Range) group(alias pred = "a == b", Range)(Range r) { return typeof(return)(r); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] arr = [ 1, 2, 2, 2, 2, 3, 4, 4, 4, 5 ]; assert(equal(group(arr), [ tuple(1, 1u), tuple(2, 4u), tuple(3, 1u), tuple(4, 3u), tuple(5, 1u) ][])); static assert(isForwardRange!(typeof(group(arr)))); foreach(DummyType; AllDummyRanges) { DummyType d; auto g = group(d); static assert(d.rt == RangeType.Input || isForwardRange!(typeof(g))); assert(equal(g, [tuple(1, 1u), tuple(2, 1u), tuple(3, 1u), tuple(4, 1u), tuple(5, 1u), tuple(6, 1u), tuple(7, 1u), tuple(8, 1u), tuple(9, 1u), tuple(10, 1u)])); } } // overwriteAdjacent /* Reduces $(D r) by shifting it to the left until no adjacent elements $(D a), $(D b) remain in $(D r) such that $(D pred(a, b)). Shifting is performed by evaluating $(D move(source, target)) as a primitive. The algorithm is stable and runs in $(BIGOH r.length) time. Returns the reduced range. The default $(XREF _algorithm, move) performs a potentially destructive assignment of $(D source) to $(D target), so the objects beyond the returned range should be considered "empty". By default $(D pred) compares for equality, in which case $(D overwriteAdjacent) collapses adjacent duplicate elements to one (functionality akin to the $(WEB wikipedia.org/wiki/Uniq, uniq) system utility). Example: ---- int[] arr = [ 1, 2, 2, 2, 2, 3, 4, 4, 4, 5 ]; auto r = overwriteAdjacent(arr); assert(r == [ 1, 2, 3, 4, 5 ]); ---- */ // Range overwriteAdjacent(alias pred, alias move, Range)(Range r) // { // if (r.empty) return r; // //auto target = begin(r), e = end(r); // auto target = r; // auto source = r; // source.popFront; // while (!source.empty) // { // if (!pred(target.front, source.front)) // { // target.popFront; // continue; // } // // found an equal *source and *target // for (;;) // { // //@@@ // //move(source.front, target.front); // target[0] = source[0]; // source.popFront; // if (source.empty) break; // if (!pred(target.front, source.front)) target.popFront; // } // break; // } // return range(begin(r), target + 1); // } // /// Ditto // Range overwriteAdjacent( // string fun = "a == b", // alias move = .move, // Range)(Range r) // { // return .overwriteAdjacent!(binaryFun!(fun), move, Range)(r); // } // unittest // { // int[] arr = [ 1, 2, 2, 2, 2, 3, 4, 4, 4, 5 ]; // auto r = overwriteAdjacent(arr); // assert(r == [ 1, 2, 3, 4, 5 ]); // assert(arr == [ 1, 2, 3, 4, 5, 3, 4, 4, 4, 5 ]); // } // find /** Finds an individual element in an input range. Elements of $(D haystack) are compared with $(D needle) by using predicate $(D pred). Performs $(BIGOH walkLength(haystack)) evaluations of $(D pred). See also $(WEB sgi.com/tech/stl/_find.html, STL's _find). To _find the last occurence of $(D needle) in $(D haystack), call $(D find(retro(haystack), needle)). See also $(XREF range, retro). Params: haystack = The range searched in. needle = The element searched for. Constraints: $(D isInputRange!R && is(typeof(binaryFun!pred(haystack.front, needle) : bool))) Returns: $(D haystack) advanced such that $(D binaryFun!pred(haystack.front, needle)) is $(D true) (if no such position exists, returns $(D haystack) after exhaustion). Example: ---- assert(find("hello, world", ',') == ", world"); assert(find([1, 2, 3, 5], 4) == []); assert(find(SList!int(1, 2, 3, 4, 5)[], 4) == SList!int(4, 5)[]); assert(find!"a > b"([1, 2, 3, 5], 2) == [3, 5]); auto a = [ 1, 2, 3 ]; assert(find(a, 5).empty); // not found assert(!find(a, 2).empty); // found // Case-insensitive find of a string string[] s = [ "Hello", "world", "!" ]; assert(!find!("toLower(a) == b")(s, "hello").empty); ---- */ R find(alias pred = "a == b", R, E)(R haystack, E needle) if (isInputRange!R && is(typeof(binaryFun!pred(haystack.front, needle)) : bool)) { for (; !haystack.empty; haystack.popFront()) { if (binaryFun!pred(haystack.front, needle)) break; } return haystack; } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); auto lst = SList!int(1, 2, 5, 7, 3); assert(lst.front == 1); auto r = find(lst[], 5); assert(equal(r, SList!int(5, 7, 3)[])); assert(find([1, 2, 3, 5], 4).empty); } /** Finds a forward range in another. Elements are compared for equality. Performs $(BIGOH walkLength(haystack) * walkLength(needle)) comparisons in the worst case. Specializations taking advantage of bidirectional or random access (where present) may accelerate search depending on the statistics of the two ranges' content. Params: haystack = The range searched in. needle = The range searched for. Constraints: $(D isForwardRange!R1 && isForwardRange!R2 && is(typeof(binaryFun!pred(haystack.front, needle.front) : bool))) Returns: $(D haystack) advanced such that $(D needle) is a prefix of it (if no such position exists, returns $(D haystack) advanced to termination). ---- assert(find("hello, world", "World").empty); assert(find("hello, world", "wo") == "world"); assert(find([1, 2, 3, 4], SList!(2, 3)[]) == [2, 3, 4]); ---- */ R1 find(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle) if (isForwardRange!R1 && isForwardRange!R2 && is(typeof(binaryFun!pred(haystack.front, needle.front)) : bool) && !isRandomAccessRange!R1) { static if (is(typeof(pred == "a == b")) && pred == "a == b" && isSomeString!R1 && isSomeString!R2 && haystack[0].sizeof == needle[0].sizeof) { //return cast(R1) find(representation(haystack), representation(needle)); // Specialization for simple string search alias Select!(haystack[0].sizeof == 1, ubyte[], Select!(haystack[0].sizeof == 2, ushort[], uint[])) Representation; // Will use the array specialization return cast(R1) .find!(pred, Representation, Representation) (cast(Representation) haystack, cast(Representation) needle); } else { return simpleMindedFind!pred(haystack, needle); } } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); auto lst = SList!int(1, 2, 5, 7, 3); static assert(isForwardRange!(int[])); static assert(isForwardRange!(typeof(lst[]))); auto r = find(lst[], [2, 5]); assert(equal(r, SList!int(2, 5, 7, 3)[])); } // Specialization for searching a random-access range for a // bidirectional range R1 find(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle) if (isRandomAccessRange!R1 && isBidirectionalRange!R2 && is(typeof(binaryFun!pred(haystack.front, needle.front)) : bool)) { if (needle.empty) return haystack; const needleLength = walkLength(needle); if (needleLength > haystack.length) { // @@@BUG@@@ //return haystack[$ .. $]; return haystack[haystack.length .. haystack.length]; } // @@@BUG@@@ // auto needleBack = moveBack(needle); // Stage 1: find the step size_t step = 1; auto needleBack = needle.back; needle.popBack(); for (auto i = needle.save; !i.empty && !binaryFun!pred(i.back, needleBack); i.popBack(), ++step) { } // Stage 2: linear find size_t scout = needleLength - 1; for (;;) { if (scout >= haystack.length) { return haystack[haystack.length .. haystack.length]; } if (!binaryFun!pred(haystack[scout], needleBack)) { ++scout; continue; } // Found a match with the last element in the needle auto cand = haystack[scout + 1 - needleLength .. haystack.length]; if (startsWith!pred(cand, needle)) { // found return cand; } // Continue with the stride scout += step; } } unittest { //scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); // @@@BUG@@@ removing static below makes unittest fail static struct BiRange { int[] payload; @property bool empty() { return payload.empty; } @property BiRange save() { return this; } @property ref int front() { return payload[0]; } @property ref int back() { return payload[$ - 1]; } void popFront() { return payload.popFront(); } void popBack() { return payload.popBack(); } } //static assert(isBidirectionalRange!BiRange); auto r = BiRange([1, 2, 3, 10, 11, 4]); //assert(equal(find(r, [3, 10]), BiRange([3, 10, 11, 4]))); //assert(find("abc", "bc").length == 2); debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); //assert(find!"a == b"("abc", "bc").length == 2); } // Leftover specialization: searching a random-access range for a // non-bidirectional forward range R1 find(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle) if (isRandomAccessRange!R1 && isForwardRange!R2 && !isBidirectionalRange!R2 && is(typeof(binaryFun!pred(haystack.front, needle.front)) : bool)) { static if (!is(ElementType!R1 == ElementType!R2)) { return simpleMindedFind!pred(haystack, needle); } else { // Prepare the search with needle's first element if (needle.empty) return haystack; haystack = .find!pred(haystack, needle.front); if (haystack.empty) return haystack; needle.popFront(); size_t matchLen = 1; // Loop invariant: haystack[0 .. matchLen] matches everything in // the initial needle that was popped out of needle. for (;;) { // Extend matchLength as much as possible for (;;) { if (needle.empty || haystack.empty) return haystack; if (!binaryFun!pred(haystack[matchLen], needle.front)) break; ++matchLen; needle.popFront(); } auto bestMatch = haystack[0 .. matchLen]; haystack.popFront(); haystack = .find!pred(haystack, bestMatch); } } } unittest { assert(find([ 1, 2, 3 ], SList!int(2, 3)[]) == [ 2, 3 ]); assert(find([ 1, 2, 1, 2, 3, 3 ], SList!int(2, 3)[]) == [ 2, 3, 3 ]); } // Internally used by some find() overloads above. Can't make it // private due to bugs in the compiler. /*private*/ R1 simpleMindedFind(alias pred, R1, R2)(R1 haystack, R2 needle) { enum estimateNeedleLength = hasLength!R1 && !hasLength!R2; static if (hasLength!R1) { static if (hasLength!R2) size_t estimatedNeedleLength = 0; else immutable size_t estimatedNeedleLength = needle.length; } bool haystackTooShort() { static if (hasLength!R1) { return haystack.length < estimatedNeedleLength; } else { return haystack.empty; } } searching: for (;; haystack.popFront()) { if (haystackTooShort()) { // Failed search static if (hasLength!R1) { static if (is(typeof(haystack[haystack.length .. haystack.length]) : R1)) return haystack[haystack.length .. haystack.length]; else return R1.init; } else { assert(haystack.empty); return haystack; } } static if (estimateNeedleLength) size_t matchLength = 0; for (auto h = haystack.save, n = needle.save; !n.empty; h.popFront(), n.popFront()) { if (h.empty || !binaryFun!pred(h.front, n.front)) { // Failed searching n in h static if (estimateNeedleLength) { if (estimatedNeedleLength < matchLength) estimatedNeedleLength = matchLength; } continue searching; } static if (estimateNeedleLength) ++matchLength; } break; } return haystack; } /** Finds two or more $(D needles) into a $(D haystack). The predicate $(D pred) is used throughout to compare elements. By default, elements are compared for equality. Params: haystack = The target of the search. Must be an $(GLOSSARY input range). If any of $(D needles) is a range with elements comparable to elements in $(D haystack), then $(D haystack) must be a $(GLOSSARY forward range) such that the search can backtrack. needles = One or more items to search for. Each of $(D needles) must be either comparable to one element in $(D haystack), or be itself a $(GLOSSARY forward range) with elements comparable with elements in $(D haystack). Returns: A tuple containing $(D haystack) positioned to match one of the needles and also the 1-based index of the matching element in $(D needles) (0 if none of $(D needles) matched, 1 if $(D needles[0]) matched, 2 if $(D needles[1]) matched...). The first needle to be found will be the one that matches. If multiple needles are found at the same spot in the range, then the shortest one is the one which matches (if multiple needles of the same length are found at the same spot (e.g $(D "a") and $(D 'a')), then the left-most of them in the argument list matches). The relationship between $(D haystack) and $(D needles) simply means that one can e.g. search for individual $(D int)s or arrays of $(D int)s in an array of $(D int)s. In addition, if elements are individually comparable, searches of heterogeneous types are allowed as well: a $(D double[]) can be searched for an $(D int) or a $(D short[]), and conversely a $(D long) can be searched for a $(D float) or a $(D double[]). This makes for efficient searches without the need to coerce one side of the comparison into the other's side type. Example: ---- int[] a = [ 1, 4, 2, 3 ]; assert(find(a, 4) == [ 4, 2, 3 ]); assert(find(a, [ 1, 4 ]) == [ 1, 4, 2, 3 ]); assert(find(a, [ 1, 3 ], 4) == tuple([ 4, 2, 3 ], 2)); // Mixed types allowed if comparable assert(find(a, 5, [ 1.2, 3.5 ], 2.0, [ 1 ]) == tuple([ 2, 3 ], 3)); ---- The complexity of the search is $(BIGOH haystack.length * max(needles.length)). (For needles that are individual items, length is considered to be 1.) The strategy used in searching several subranges at once maximizes cache usage by moving in $(D haystack) as few times as possible. */ Tuple!(Range, size_t) find(alias pred = "a == b", Range, Ranges...) (Range haystack, Ranges needles) if (Ranges.length > 1 && allSatisfy!(isForwardRange, Ranges)) { for (;; haystack.popFront) { size_t r = startsWith!pred(haystack, needles); if (r || haystack.empty) { return tuple(haystack, r); } } } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); auto s1 = "Mary has a little lamb"; //writeln(find(s1, "has a", "has an")); assert(find(s1, "has a", "has an") == tuple("has a little lamb", 1)); assert(find("abc", "bc").length == 2); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 1, 2, 3 ]; assert(find(a, 5).empty); assert(find(a, 2) == [2, 3]); foreach (T; TypeTuple!(int, double)) { auto b = rndstuff!(T)(); if (!b.length) continue; b[$ / 2] = 200; b[$ / 4] = 200; assert(find(b, 200).length == b.length - b.length / 4); } // Case-insensitive find of a string string[] s = [ "Hello", "world", "!" ]; //writeln(find!("toUpper(a) == toUpper(b)")(s, "hello")); assert(find!("toUpper(a) == toUpper(b)")(s, "hello").length == 3); static bool f(string a, string b) { return toUpper(a) == toUpper(b); } assert(find!(f)(s, "hello").length == 3); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 1, 2, 3, 2, 6 ]; assert(find(std.range.retro(a), 5).empty); assert(equal(find(std.range.retro(a), 2), [ 2, 3, 2, 1 ][])); foreach (T; TypeTuple!(int, double)) { auto b = rndstuff!(T)(); if (!b.length) continue; b[$ / 2] = 200; b[$ / 4] = 200; assert(find(std.range.retro(b), 200).length == b.length - (b.length - 1) / 2); } } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ -1, 0, 1, 2, 3, 4, 5 ]; int[] b = [ 1, 2, 3 ]; assert(find(a, b) == [ 1, 2, 3, 4, 5 ]); assert(find(b, a).empty); foreach(DummyType; AllDummyRanges) { DummyType d; auto findRes = find(d, 5); assert(equal(findRes, [5,6,7,8,9,10])); } } /// Ditto struct BoyerMooreFinder(alias pred, Range) { private: size_t skip[]; sizediff_t[ElementType!(Range)] occ; Range needle; sizediff_t occurrence(ElementType!(Range) c) { auto p = c in occ; return p ? *p : -1; } /* This helper function checks whether the last "portion" bytes of "needle" (which is "nlen" bytes long) exist within the "needle" at offset "offset" (counted from the end of the string), and whether the character preceding "offset" is not a match. Notice that the range being checked may reach beyond the beginning of the string. Such range is ignored. */ static bool needlematch(R)(R needle, size_t portion, size_t offset) { sizediff_t virtual_begin = needle.length - offset - portion; sizediff_t ignore = 0; if (virtual_begin < 0) { ignore = -virtual_begin; virtual_begin = 0; } if (virtual_begin > 0 && needle[virtual_begin - 1] == needle[$ - portion - 1]) return 0; immutable delta = portion - ignore; return equal(needle[needle.length - delta .. needle.length], needle[virtual_begin .. virtual_begin + delta]); } public: this(Range needle) { if (!needle.length) return; this.needle = needle; /* Populate table with the analysis of the needle */ /* But ignoring the last letter */ foreach (i, n ; needle[0 .. $ - 1]) { this.occ[n] = i; } /* Preprocess #2: init skip[] */ /* Note: This step could be made a lot faster. * A simple implementation is shown here. */ this.skip = new size_t[needle.length]; foreach (a; 0 .. needle.length) { size_t value = 0; while (value < needle.length && !needlematch(needle, a, value)) { ++value; } this.skip[needle.length - a - 1] = value; } } Range beFound(Range haystack) { if (!needle.length) return haystack; if (needle.length > haystack.length) return haystack[$ .. $]; /* Search: */ auto limit = haystack.length - needle.length; for (size_t hpos = 0; hpos <= limit; ) { size_t npos = needle.length - 1; while (pred(needle[npos], haystack[npos+hpos])) { if (npos == 0) return haystack[hpos .. $]; --npos; } hpos += max(skip[npos], npos - occurrence(haystack[npos+hpos])); } return haystack[$ .. $]; } @property size_t length() { return needle.length; } } /// Ditto BoyerMooreFinder!(binaryFun!(pred), Range) boyerMooreFinder (alias pred = "a == b", Range) (Range needle) if (isRandomAccessRange!(Range) || isSomeString!Range) { return typeof(return)(needle); } // Oddly this is not disabled by bug 4759 Range1 find(Range1, alias pred, Range2)( Range1 haystack, BoyerMooreFinder!(pred, Range2) needle) { return needle.beFound(haystack); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); string h = "/homes/aalexand/d/dmd/bin/../lib/libphobos.a(dmain2.o)" "(.gnu.linkonce.tmain+0x74): In function `main' undefined reference" " to `_Dmain':"; string[] ns = ["libphobos", "function", " undefined", "`", ":"]; foreach (n ; ns) { auto p = find(h, boyerMooreFinder(n)); assert(!p.empty); } int[] a = [ -1, 0, 1, 2, 3, 4, 5 ]; int[] b = [ 1, 2, 3 ]; //writeln(find(a, boyerMooreFinder(b))); assert(find(a, boyerMooreFinder(b)) == [ 1, 2, 3, 4, 5 ]); assert(find(b, boyerMooreFinder(a)).empty); } /** Advances the input range $(D haystack) by calling $(D haystack.popFront) until either $(D pred(haystack.front)), or $(D haystack.empty). Performs $(BIGOH haystack.length) evaluations of $(D pred). See also $(WEB sgi.com/tech/stl/find_if.html, STL's find_if). To find the last element of a bidirectional $(D haystack) satisfying $(D pred), call $(D find!(pred)(retro(haystack))). See also $(XREF range, retro). Example: ---- auto arr = [ 1, 2, 3, 4, 1 ]; assert(find!("a > 2")(arr) == [ 3, 4, 1 ]); // with predicate alias bool pred(int x) { return x + 1 > 1.5; } assert(find!(pred)(arr) == arr); ---- */ Range find(alias pred, Range)(Range haystack) if (isInputRange!(Range)) { alias unaryFun!(pred) predFun; for (; !haystack.empty && !predFun(haystack.front); haystack.popFront) { } return haystack; } unittest { //scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 1, 2, 3 ]; assert(find!("a > 2")(a) == [3]); bool pred(int x) { return x + 1 > 1.5; } assert(find!(pred)(a) == a); } // findSkip /** * If $(D needle) occurs in $(D haystack), positions $(D haystack) * right after the first occurrence of $(D needle) and returns $(D * true). Otherwise, leaves $(D haystack) as is and returns $(D * false). * * Example: ---- string s = "abcdef"; assert(findSkip(s, "cd") && s == "ef"); s = "abcdef"; assert(!findSkip(s, "cxd") && s == "abcdef"); assert(findSkip(s, "def") && s.empty); ---- */ bool findSkip(alias pred = "a == b", R1, R2)(ref R1 haystack, R2 needle) if (isForwardRange!R1 && isForwardRange!R2 && is(typeof(binaryFun!pred(haystack.front, needle.front)))) { auto parts = findSplit!pred(haystack, needle); if (parts[1].empty) return false; // found haystack = parts[2]; return true; } unittest { string s = "abcdef"; assert(findSkip(s, "cd") && s == "ef"); s = "abcdef"; assert(!findSkip(s, "cxd") && s == "abcdef"); s = "abcdef"; assert(findSkip(s, "def") && s.empty); } /** These functions find the first occurrence of $(D needle) in $(D haystack) and then split $(D haystack) as follows. $(D findSplit) returns a tuple $(D result) containing $(I three) ranges. $(D result[0]) is the portion of $(D haystack) before $(D needle), $(D result[1]) is the portion of $(D haystack) that matches $(D needle), and $(D result[2]) is the portion of $(D haystack) after the match. $(D findSplitBefore) returns a tuple $(D result) containing two ranges. $(D result[0]) is the portion of $(D haystack) before $(D needle), and $(D result[1]) is the balance of $(D haystack) starting with the match. If $(D needle) was not found, $(D result[0]) comprehends $(D haystack) entirely and $(D result[1]) is empty. $(D findSplitAfter) returns a tuple $(D result) containing two ranges. $(D result[0]) is the portion of $(D haystack) up to and including the match, and $(D result[1]) is the balance of $(D haystack) starting after the match. If $(D needle) was not found, $(D result[0]) is empty and $(D result[1]) is $(D haystack). In all cases, the concatenation of the returned ranges spans the entire $(D haystack). If $(D haystack) is a random-access range, all three components of the tuple have the same type as $(D haystack). Otherwise, $(D haystack) must be a forward range and the type of $(D result[0]) and $(D result[1]) is the same as $(XREF range,takeExactly). Example: ---- auto a = [ 1, 2, 3, 4, 5, 6, 7, 8 ]; auto r = findSplit(a, [9, 1]); assert(r[0] == a); assert(r[1].empty); assert(r[2].empty); r = findSplit(a, [ 3, 4 ]); assert(r[0] == a[0 .. 2]); assert(r[1] == a[2 .. 4]); assert(r[2] == a[4 .. $]); auto r1 = findSplitBefore(a, [ 7, 8 ]); assert(r1[0] == a[0 .. 6]); assert(r1[1] == a[6 .. $]); auto r1 = findSplitAfter(a, [ 7, 8 ]); assert(r1[0] == a); assert(r1[1].empty); ---- */ auto findSplit(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle) if (isForwardRange!R1 && isForwardRange!R2) { static if (isSomeString!R1 && isSomeString!R2 || isRandomAccessRange!R1 && hasLength!R2) { auto balance = find!pred(haystack, needle); immutable pos1 = haystack.length - balance.length; immutable pos2 = balance.empty ? pos1 : pos1 + needle.length; return tuple(haystack[0 .. pos1], haystack[pos1 .. pos2], haystack[pos2 .. haystack.length]); } else { auto original = haystack.save; auto h = haystack.save; auto n = needle.save; size_t pos1, pos2; while (!n.empty && !h.empty) { if (binaryFun!pred(h.front, n.front)) { h.popFront(); n.popFront(); ++pos2; } else { haystack.popFront(); n = needle.save; h = haystack.save; pos2 = ++pos1; } } return tuple(takeExactly(original, pos1), takeExactly(haystack, pos2 - pos1), h); } } /// Ditto auto findSplitBefore(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle) if (isForwardRange!R1 && isForwardRange!R2) { static if (isSomeString!R1 && isSomeString!R2 || isRandomAccessRange!R1 && hasLength!R2) { auto balance = find!pred(haystack, needle); immutable pos = haystack.length - balance.length; return tuple(haystack[0 .. pos], haystack[pos .. haystack.length]); } else { auto original = haystack.save; auto h = haystack.save; auto n = needle.save; size_t pos; while (!n.empty && !h.empty) { if (binaryFun!pred(h.front, n.front)) { h.popFront(); n.popFront(); } else { haystack.popFront(); n = needle.save; h = haystack.save; ++pos; } } return tuple(takeExactly(original, pos), haystack); } } /// Ditto auto findSplitAfter(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle) if (isForwardRange!R1 && isForwardRange!R2) { static if (isSomeString!R1 && isSomeString!R2 || isRandomAccessRange!R1 && hasLength!R2) { auto balance = find!pred(haystack, needle); immutable pos = balance.empty ? 0 : haystack.length - balance.length + needle.length; return tuple(haystack[0 .. pos], haystack[pos .. haystack.length]); } else { auto original = haystack.save; auto h = haystack.save; auto n = needle.save; size_t pos1, pos2; while (!n.empty) { if (h.empty) { // Failed search return tuple(takeExactly(original, 0), original); } if (binaryFun!pred(h.front, n.front)) { h.popFront(); n.popFront(); ++pos2; } else { haystack.popFront(); n = needle.save; h = haystack.save; pos2 = ++pos1; } } return tuple(takeExactly(original, pos2), h); } } unittest { auto a = [ 1, 2, 3, 4, 5, 6, 7, 8 ]; auto r = findSplit(a, [9, 1]); assert(r[0] == a); assert(r[1].empty); assert(r[2].empty); r = findSplit(a, [3]); assert(r[0] == a[0 .. 2]); assert(r[1] == a[2 .. 3]); assert(r[2] == a[3 .. $]); auto r1 = findSplitBefore(a, [9, 1]); assert(r1[0] == a); assert(r1[1].empty); r1 = findSplitBefore(a, [3, 4]); assert(r1[0] == a[0 .. 2]); assert(r1[1] == a[2 .. $]); r1 = findSplitAfter(a, [9, 1]); assert(r1[0].empty); assert(r1[1] == a); r1 = findSplitAfter(a, [3, 4]); assert(r1[0] == a[0 .. 4]); assert(r1[1] == a[4 .. $]); } unittest { auto a = [ 1, 2, 3, 4, 5, 6, 7, 8 ]; auto fwd = filter!"a > 0"(a); auto r = findSplit(fwd, [9, 1]); assert(equal(r[0], a)); assert(r[1].empty); assert(r[2].empty); r = findSplit(fwd, [3]); assert(equal(r[0], a[0 .. 2])); assert(equal(r[1], a[2 .. 3])); assert(equal(r[2], a[3 .. $])); auto r1 = findSplitBefore(fwd, [9, 1]); assert(equal(r1[0], a)); assert(r1[1].empty); r1 = findSplitBefore(fwd, [3, 4]); assert(equal(r1[0], a[0 .. 2])); assert(equal(r1[1], a[2 .. $])); r1 = findSplitAfter(fwd, [9, 1]); assert(r1[0].empty); assert(equal(r1[1], a)); r1 = findSplitAfter(fwd, [3, 4]); assert(equal(r1[0], a[0 .. 4])); assert(equal(r1[1], a[4 .. $])); } /++ Returns the number of elements which must be popped from the front of $(D haystack) before reaching an element for which $(D startsWith!pred(haystack, needle)) is $(D true). If $(D startsWith!pred(haystack, needle)) is not $(D true) for any element in $(D haystack), then -1 is returned. $(D needle) may be either an element or a range. Examples: -------------------- assert(countUntil("hello world", "world") == 6); assert(countUntil("hello world", 'r') == 8); assert(countUntil("hello world", "programming") == -1); assert(countUntil([0, 7, 12, 22, 9], [12, 22]) == 2); assert(countUntil([0, 7, 12, 22, 9], 9) == 4); assert(countUntil!"a > b"([0, 7, 12, 22, 9], 20) == 3); -------------------- +/ sizediff_t countUntil(alias pred = "a == b", R, N)(R haystack, N needle) if (is(typeof(startsWith!pred(haystack, needle)))) { static if (isNarrowString!R) { // Narrow strings are handled a bit differently auto length = haystack.length; for (; !haystack.empty; haystack.popFront()) { if (startsWith!pred(haystack, needle)) { return length - haystack.length; } } } else { typeof(return) result; for (; !haystack.empty; ++result, haystack.popFront()) { if (startsWith!pred(haystack, needle)) return result; } } return -1; } //Verify Examples. unittest { assert(countUntil("hello world", "world") == 6); assert(countUntil("hello world", 'r') == 8); assert(countUntil("hello world", "programming") == -1); assert(countUntil([0, 7, 12, 22, 9], [12, 22]) == 2); assert(countUntil([0, 7, 12, 22, 9], 9) == 4); assert(countUntil!"a > b"([0, 7, 12, 22, 9], 20) == 3); } /++ Returns the number of elements which must be popped from $(D haystack) before $(D pred(hastack.front)) is $(D true.). Examples: -------------------- assert(countUntil!(std.uni.isWhite)("hello world") == 5); assert(countUntil!(std.ascii.isDigit)("hello world") == -1); assert(countUntil!"a > 20"([0, 7, 12, 22, 9]) == 3); -------------------- +/ sizediff_t countUntil(alias pred, R)(R haystack) if (isForwardRange!R && is(typeof(unaryFun!pred(haystack.front)) == bool)) { static if (isNarrowString!R) { // Narrow strings are handled a bit differently auto length = haystack.length; for (; !haystack.empty; haystack.popFront()) { if (unaryFun!pred(haystack.front)) { return length - haystack.length; } } } else { typeof(return) result; for (; !haystack.empty; ++result, haystack.popFront()) { if (unaryFun!pred(haystack.front)) return result; } } return -1; } //Verify Examples. unittest { assert(countUntil!(std.uni.isWhite)("hello world") == 5); assert(countUntil!(std.ascii.isDigit)("hello world") == -1); assert(countUntil!"a > 20"([0, 7, 12, 22, 9]) == 3); } /** * $(RED Scheduled for deprecation. Please use $(XREF algorithm, countUntil) * instead.) * * Same as $(D countUntil). This symbol has been scheduled for * deprecation because it is easily confused with the homonym function * in $(D std.string). */ sizediff_t indexOf(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle) if (is(typeof(startsWith!pred(haystack, needle)))) { return countUntil!pred(haystack, needle); } /** Interval option specifier for $(D until) (below) and others. */ enum OpenRight { no, /// Interval is closed to the right (last element included) yes /// Interval is open to the right (last element is not included) } /** Lazily iterates $(D range) until value $(D sentinel) is found, at which point it stops. Example: ---- int[] a = [ 1, 2, 4, 7, 7, 2, 4, 7, 3, 5]; assert(equal(a.until(7), [1, 2, 4][])); assert(equal(a.until(7, OpenRight.no), [1, 2, 4, 7][])); ---- */ struct Until(alias pred, Range, Sentinel) if (isInputRange!Range) { private Range _input; static if (!is(Sentinel == void)) private Sentinel _sentinel; // mixin(bitfields!( // OpenRight, "_openRight", 1, // bool, "_done", 1, // uint, "", 6)); // OpenRight, "_openRight", 1, // bool, "_done", 1, OpenRight _openRight; bool _done; static if (!is(Sentinel == void)) this(Range input, Sentinel sentinel, OpenRight openRight = OpenRight.yes) { _input = input; _sentinel = sentinel; _openRight = openRight; _done = _input.empty || openRight && predSatisfied(); } else this(Range input, OpenRight openRight = OpenRight.yes) { _input = input; _openRight = openRight; _done = _input.empty || openRight && predSatisfied(); } @property bool empty() { return _done; } @property ElementType!Range front() { assert(!empty); return _input.front; } bool predSatisfied() { static if (is(Sentinel == void)) return unaryFun!pred(_input.front); else return startsWith!pred(_input, _sentinel); } void popFront() { assert(!empty); if (!_openRight) { if (predSatisfied()) { _done = true; return; } _input.popFront; _done = _input.empty; } else { _input.popFront; _done = _input.empty || predSatisfied; } } static if (isForwardRange!Range) { static if (!is(Sentinel == void)) @property Until save() { Until result; result._input = _input.save; result._sentinel = _sentinel; result._openRight = _openRight; result._done = _done; return result; } else @property Until save() { Until result; result._input = _input.save; result._openRight = _openRight; result._done = _done; return result; } } } /// Ditto Until!(pred, Range, Sentinel) until(alias pred = "a == b", Range, Sentinel) (Range range, Sentinel sentinel, OpenRight openRight = OpenRight.yes) if (!is(Sentinel == OpenRight)) { return typeof(return)(range, sentinel, openRight); } /// Ditto Until!(pred, Range, void) until(alias pred, Range) (Range range, OpenRight openRight = OpenRight.yes) { return typeof(return)(range, openRight); } unittest { //scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 1, 2, 4, 7, 7, 2, 4, 7, 3, 5]; static assert(isForwardRange!(typeof(a.until(7)))); static assert(isForwardRange!(typeof(until!"a == 2"(a, OpenRight.no)))); assert(equal(a.until(7), [1, 2, 4][])); assert(equal(a.until([7, 2]), [1, 2, 4, 7][])); assert(equal(a.until(7, OpenRight.no), [1, 2, 4, 7][])); assert(equal(until!"a == 2"(a, OpenRight.no), [1, 2][])); } /** If the range $(D doesThisStart) starts with $(I any) of the $(D withOneOfThese) ranges or elements, returns 1 if it starts with $(D withOneOfThese[0]), 2 if it starts with $(D withOneOfThese[1]), and so on. If none match, returns 0. In the case where $(D doesThisStart) starts with multiple of the ranges or elements in $(D withOneOfThese), then the shortest one matches (if there are two which match which are of the same length (e.g. $(D "a") and $(D 'a')), then the left-most of them in the argument list matches). Example: ---- assert(startsWith("abc", "")); assert(startsWith("abc", "a")); assert(!startsWith("abc", "b")); assert(startsWith("abc", 'a', "b") == 1); assert(startsWith("abc", "b", "a") == 2); assert(startsWith("abc", "a", "a") == 1); assert(startsWith("abc", "ab", "a") == 2); assert(startsWith("abc", "x", "a", "b") == 2); assert(startsWith("abc", "x", "aa", "ab") == 3); assert(startsWith("abc", "x", "aaa", "sab") == 0); assert(startsWith("abc", "x", "aaa", "a", "sab") == 3); ---- */ uint startsWith(alias pred = "a == b", Range, Ranges...) (Range doesThisStart, Ranges withOneOfThese) if (isInputRange!Range && Ranges.length > 1 && is(typeof(.startsWith!pred(doesThisStart, withOneOfThese[0])) : bool ) && is(typeof(.startsWith!pred(doesThisStart, withOneOfThese[1 .. $])) : uint)) { alias doesThisStart haystack; alias withOneOfThese needles; // Make one pass looking for empty ranges foreach (i, Unused; Ranges) { // Empty range matches everything static if (!is(typeof(binaryFun!pred(haystack.front, needles[i])) : bool)) { if (needles[i].empty) return i + 1; } } for (; !haystack.empty; haystack.popFront()) { foreach (i, Unused; Ranges) { static if (is(typeof(binaryFun!pred(haystack.front, needles[i])) : bool)) { // Single-element if (binaryFun!pred(haystack.front, needles[i])) { // found, but continue to account for one-element // range matches (consider startsWith("ab", "a", // 'a') should return 1, not 2). continue; } } else { if (binaryFun!pred(haystack.front, needles[i].front)) { continue; } } // This code executed on failure to match // Out with this guy, check for the others uint result = startsWith!pred(haystack, needles[0 .. i], needles[i + 1 .. $]); if (result > i) ++result; return result; } // If execution reaches this point, then the front matches for all // needles ranges. What we need to do now is to lop off the front of // all ranges involved and recurse. foreach (i, Unused; Ranges) { static if (is(typeof(binaryFun!pred(haystack.front, needles[i])) : bool)) { // Test has passed in the previous loop return i + 1; } else { needles[i].popFront(); if (needles[i].empty) return i + 1; } } } return 0; } /// Ditto bool startsWith(alias pred = "a == b", R1, R2) (R1 doesThisStart, R2 withThis) if (isInputRange!R1 && isInputRange!R2 && is(typeof(binaryFun!pred(doesThisStart.front, withThis.front)) : bool)) { alias doesThisStart haystack; alias withThis needle; static if(is(typeof(pred) : string)) enum isDefaultPred = pred == "a == b"; else enum isDefaultPred = false; // Special case for two arrays static if (isArray!R1 && isArray!R2 && ((!isSomeString!R1 && !isSomeString!R2) || (isSomeString!R1 && isSomeString!R2 && is(Unqual!(typeof(haystack[0])) == Unqual!(typeof(needle[0]))) && isDefaultPred))) { if (haystack.length < needle.length) return false; foreach (j; 0 .. needle.length) { if (!binaryFun!pred(needle[j], haystack[j])) // not found return false; } // found! return true; } else { static if (hasLength!R1 && hasLength!R2) { if (haystack.length < needle.length) return false; } if (needle.empty) return true; for (; !haystack.empty; haystack.popFront()) { if (!binaryFun!pred(haystack.front, needle.front)) break; needle.popFront(); if (needle.empty) return true; } return false; } } /// Ditto bool startsWith(alias pred = "a == b", R, E) (R doesThisStart, E withThis) if (isInputRange!R && is(typeof(binaryFun!pred(doesThisStart.front, withThis)) : bool)) { return doesThisStart.empty ? false : binaryFun!pred(doesThisStart.front, withThis); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); //foreach (S; TypeTuple!(char[], wchar[], dchar[], string, wstring, dstring)) foreach (S; TypeTuple!(char[], wstring)) { assert(!startsWith(to!S("abc"), 'c')); assert(startsWith(to!S("abc"), 'a', 'c') == 1); assert(!startsWith(to!S("abc"), 'x', 'n', 'b')); assert(startsWith(to!S("abc"), 'x', 'n', 'a') == 3); assert(startsWith(to!S("\uFF28abc"), 'a', '\uFF28', 'c') == 2); //foreach (T; TypeTuple!(char[], wchar[], dchar[], string, wstring, dstring)) foreach (T; TypeTuple!(dchar[], string)) { assert(startsWith(to!S("abc"), to!T(""))); assert(startsWith(to!S("ab"), to!T("a"))); assert(startsWith(to!S("abc"), to!T("a"))); assert(!startsWith(to!S("abc"), to!T("b"))); assert(!startsWith(to!S("abc"), to!T("b"), "bc", "abcd", "xyz")); assert(startsWith(to!S("abc"), to!T("ab"), 'a') == 2); assert(startsWith(to!S("abc"), to!T("a"), "b") == 1); assert(startsWith(to!S("abc"), to!T("b"), "a") == 2); assert(startsWith(to!S("abc"), to!T("a"), 'a') == 1); assert(startsWith(to!S("abc"), 'a', to!T("a")) == 1); assert(startsWith(to!S("abc"), to!T("x"), "a", "b") == 2); assert(startsWith(to!S("abc"), to!T("x"), "aa", "ab") == 3); assert(startsWith(to!S("abc"), to!T("x"), "aaa", "sab") == 0); assert(startsWith(to!S("abc"), 'a')); assert(!startsWith(to!S("abc"), to!T("sab"))); assert(startsWith(to!S("abc"), 'x', to!T("aaa"), 'a', "sab") == 3); assert(startsWith(to!S("\uFF28el\uFF4co"), to!T("\uFF28el"))); assert(startsWith(to!S("\uFF28el\uFF4co"), to!T("Hel"), to!T("\uFF28el")) == 2); } } assert(startsWith([0, 1, 2, 3, 4, 5], cast(int[])null)); assert(!startsWith([0, 1, 2, 3, 4, 5], 5)); assert(!startsWith([0, 1, 2, 3, 4, 5], 1)); assert(startsWith([0, 1, 2, 3, 4, 5], 0)); assert(startsWith([0, 1, 2, 3, 4, 5], 5, 0, 1) == 2); assert(startsWith([0, 1, 2, 3, 4, 5], [0])); assert(startsWith([0, 1, 2, 3, 4, 5], [0, 1])); assert(startsWith([0, 1, 2, 3, 4, 5], [0, 1], 7) == 1); assert(!startsWith([0, 1, 2, 3, 4, 5], [0, 1, 7])); assert(startsWith([0, 1, 2, 3, 4, 5], [0, 1, 7], [0, 1, 2]) == 2); assert(!startsWith(filter!"true"([0, 1, 2, 3, 4, 5]), 1)); assert(startsWith(filter!"true"([0, 1, 2, 3, 4, 5]), 0)); assert(startsWith(filter!"true"([0, 1, 2, 3, 4, 5]), [0])); assert(startsWith(filter!"true"([0, 1, 2, 3, 4, 5]), [0, 1])); assert(startsWith(filter!"true"([0, 1, 2, 3, 4, 5]), [0, 1], 7) == 1); assert(!startsWith(filter!"true"([0, 1, 2, 3, 4, 5]), [0, 1, 7])); assert(startsWith(filter!"true"([0, 1, 2, 3, 4, 5]), [0, 1, 7], [0, 1, 2]) == 2); assert(startsWith([0, 1, 2, 3, 4, 5], filter!"true"([0, 1]))); assert(startsWith([0, 1, 2, 3, 4, 5], filter!"true"([0, 1]), 7) == 1); assert(!startsWith([0, 1, 2, 3, 4, 5], filter!"true"([0, 1, 7]))); assert(startsWith([0, 1, 2, 3, 4, 5], [0, 1, 7], filter!"true"([0, 1, 2])) == 2); } /** If $(D startsWith(r1, r2)), consume the corresponding elements off $(D r1) and return $(D true). Otherwise, leave $(D r1) unchanged and return $(D false). */ bool skipOver(alias pred = "a == b", R1, R2)(ref R1 r1, R2 r2) if (is(typeof(binaryFun!pred(r1.front, r2.front)))) { auto r = r1.save; while (!r2.empty && !r.empty && binaryFun!pred(r.front, r2.front)) { r.popFront(); r2.popFront(); } return r2.empty ? (r1 = r, true) : false; } unittest { //scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); auto s1 = "Hello world"; assert(!skipOver(s1, "Ha")); assert(s1 == "Hello world"); assert(skipOver(s1, "Hell") && s1 == "o world"); } /** Checks whether a range starts with an element, and if so, consume that element off $(D r) and return $(D true). Otherwise, leave $(D r) unchanged and return $(D false). */ bool skipOver(alias pred = "a == b", R, E)(ref R r, E e) if (is(typeof(binaryFun!pred(r.front, e)))) { return binaryFun!pred(r.front, e) ? (r.popFront(), true) : false; } unittest { auto s1 = "Hello world"; assert(!skipOver(s1, "Ha")); assert(s1 == "Hello world"); assert(skipOver(s1, "Hell") && s1 == "o world"); } /* (Not yet documented.) Consume all elements from $(D r) that are equal to one of the elements $(D es). */ void skipAll(alias pred = "a == b", R, Es...)(ref R r, Es es) //if (is(typeof(binaryFun!pred(r1.front, es[0])))) { loop: for (; !r.empty; r.popFront()) { foreach (i, E; Es) { if (binaryFun!pred(r.front, es[i])) { continue loop; } } break; } } unittest { //scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); auto s1 = "Hello world"; skipAll(s1, 'H', 'e'); assert(s1 == "llo world"); } /** The reciprocal of $(D startsWith). Example: ---- assert(endsWith("abc", "")); assert(!endsWith("abc", "b")); assert(endsWith("abc", "a", 'c') == 2); assert(endsWith("abc", "c", "a") == 1); assert(endsWith("abc", "c", "c") == 1); assert(endsWith("abc", "bc", "c") == 2); assert(endsWith("abc", "x", "c", "b") == 2); assert(endsWith("abc", "x", "aa", "bc") == 3); assert(endsWith("abc", "x", "aaa", "sab") == 0); assert(endsWith("abc", "x", "aaa", 'c', "sab") == 3); ---- */ uint endsWith(alias pred = "a == b", Range, Ranges...) (Range doesThisEnd, Ranges withOneOfThese) if (isInputRange!Range && Ranges.length > 1 && is(typeof(.endsWith!pred(doesThisEnd, withOneOfThese[0])) : bool) && is(typeof(.endsWith!pred(doesThisEnd, withOneOfThese[1 .. $])) : uint)) { alias doesThisEnd haystack; alias withOneOfThese needles; // Make one pass looking for empty ranges foreach (i, Unused; Ranges) { // Empty range matches everything static if (!is(typeof(binaryFun!pred(haystack.back, needles[i])) : bool)) { if (needles[i].empty) return i + 1; } } for (; !haystack.empty; haystack.popBack()) { foreach (i, Unused; Ranges) { static if (is(typeof(binaryFun!pred(haystack.back, needles[i])) : bool)) { // Single-element if (binaryFun!pred(haystack.back, needles[i])) { // found, but continue to account for one-element // range matches (consider endsWith("ab", "b", // 'b') should return 1, not 2). continue; } } else { if (binaryFun!pred(haystack.back, needles[i].back)) continue; } // This code executed on failure to match // Out with this guy, check for the others uint result = endsWith!pred(haystack, needles[0 .. i], needles[i + 1 .. $]); if (result > i) ++result; return result; } // If execution reaches this point, then the back matches for all // needles ranges. What we need to do now is to lop off the back of // all ranges involved and recurse. foreach (i, Unused; Ranges) { static if (is(typeof(binaryFun!pred(haystack.back, needles[i])) : bool)) { // Test has passed in the previous loop return i + 1; } else { needles[i].popBack(); if (needles[i].empty) return i + 1; } } } return 0; } /// Ditto bool endsWith(alias pred = "a == b", R1, R2) (R1 doesThisEnd, R2 withThis) if (isInputRange!R1 && isInputRange!R2 && is(typeof(binaryFun!pred(doesThisEnd.back, withThis.back)) : bool)) { alias doesThisEnd haystack; alias withThis needle; static if(is(typeof(pred) : string)) enum isDefaultPred = pred == "a == b"; else enum isDefaultPred = false; // Special case for two arrays static if (isArray!R1 && isArray!R2 && ((!isSomeString!R1 && !isSomeString!R2) || (isSomeString!R1 && isSomeString!R2 && is(Unqual!(typeof(haystack[0])) == Unqual!(typeof(needle[0]))) && isDefaultPred))) { if (haystack.length < needle.length) return false; immutable diff = haystack.length - needle.length; foreach (j; 0 .. needle.length) { if (!binaryFun!(pred)(needle[j], haystack[j + diff])) // not found return false; } // found! return true; } else { static if (hasLength!R1 && hasLength!R2) { if (haystack.length < needle.length) return false; } if (needle.empty) return true; for (; !haystack.empty; haystack.popBack()) { if (!binaryFun!pred(haystack.back, needle.back)) break; needle.popBack(); if (needle.empty) return true; } return false; } } /// Ditto bool endsWith(alias pred = "a == b", R, E) (R doesThisEnd, E withThis) if (isInputRange!R && is(typeof(binaryFun!pred(doesThisEnd.back, withThis)) : bool)) { return doesThisEnd.empty ? false : binaryFun!pred(doesThisEnd.back, withThis); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); //This is because we need to run some tests on ranges which _aren't_ arrays, //and as far as I can tell, all of the functions which would wrap an array //in a range (such as filter) don't return bidirectional ranges, so I'm //creating one here. auto static wrap(R)(R r) if (isBidirectionalRange!R) { struct Result { @property auto ref front() {return _range.front;} @property auto ref back() {return _range.back;} @property bool empty() {return _range.empty;} void popFront() {_range.popFront();} void popBack() {_range.popBack();} R _range; } return Result(r); } //foreach (S; TypeTuple!(char[], wchar[], dchar[], string, wstring, dstring)) foreach (S; TypeTuple!(char[], wstring)) { assert(!endsWith(to!S("abc"), 'a')); assert(endsWith(to!S("abc"), 'a', 'c') == 2); assert(!endsWith(to!S("abc"), 'x', 'n', 'b')); assert(endsWith(to!S("abc"), 'x', 'n', 'c') == 3); assert(endsWith(to!S("abc\uFF28"), 'a', '\uFF28', 'c') == 2); //foreach (T; TypeTuple!(char[], wchar[], dchar[], string, wstring, dstring)) foreach (T; TypeTuple!(dchar[], string)) { assert(endsWith(to!S("abc"), to!T(""))); assert(!endsWith(to!S("abc"), to!T("a"))); assert(!endsWith(to!S("abc"), to!T("b"))); assert(endsWith(to!S("abc"), to!T("bc"), 'c') == 2); assert(endsWith(to!S("abc"), to!T("a"), "c") == 2); assert(endsWith(to!S("abc"), to!T("c"), "a") == 1); assert(endsWith(to!S("abc"), to!T("c"), "c") == 1); assert(endsWith(to!S("abc"), to!T("x"), 'c', "b") == 2); assert(endsWith(to!S("abc"), 'x', to!T("aa"), "bc") == 3); assert(endsWith(to!S("abc"), to!T("x"), "aaa", "sab") == 0); assert(endsWith(to!S("abc"), to!T("x"), "aaa", "c", "sab") == 3); assert(endsWith(to!S("\uFF28el\uFF4co"), to!T("l\uFF4co"))); assert(endsWith(to!S("\uFF28el\uFF4co"), to!T("lo"), to!T("l\uFF4co")) == 2); } } assert(endsWith([0, 1, 2, 3, 4, 5], cast(int[])null)); assert(!endsWith([0, 1, 2, 3, 4, 5], 0)); assert(!endsWith([0, 1, 2, 3, 4, 5], 4)); assert(endsWith([0, 1, 2, 3, 4, 5], 5)); assert(endsWith([0, 1, 2, 3, 4, 5], 0, 4, 5) == 3); assert(endsWith([0, 1, 2, 3, 4, 5], [5])); assert(endsWith([0, 1, 2, 3, 4, 5], [4, 5])); assert(endsWith([0, 1, 2, 3, 4, 5], [4, 5], 7) == 1); assert(!endsWith([0, 1, 2, 3, 4, 5], [2, 4, 5])); assert(endsWith([0, 1, 2, 3, 4, 5], [2, 4, 5], [3, 4, 5]) == 2); assert(!endsWith(wrap([0, 1, 2, 3, 4, 5]), 4)); assert(endsWith(wrap([0, 1, 2, 3, 4, 5]), 5)); assert(endsWith(wrap([0, 1, 2, 3, 4, 5]), [5])); assert(endsWith(wrap([0, 1, 2, 3, 4, 5]), [4, 5])); assert(endsWith(wrap([0, 1, 2, 3, 4, 5]), [4, 5], 7) == 1); assert(!endsWith(wrap([0, 1, 2, 3, 4, 5]), [2, 4, 5])); assert(endsWith(wrap([0, 1, 2, 3, 4, 5]), [2, 4, 5], [3, 4, 5]) == 2); assert(endsWith([0, 1, 2, 3, 4, 5], wrap([4, 5]))); assert(endsWith([0, 1, 2, 3, 4, 5], wrap([4, 5]), 7) == 1); assert(!endsWith([0, 1, 2, 3, 4, 5], wrap([2, 4, 5]))); assert(endsWith([0, 1, 2, 3, 4, 5], [2, 4, 5], wrap([3, 4, 5])) == 2); } // findAdjacent /** Advances $(D r) until it finds the first two adjacent elements $(D a), $(D b) that satisfy $(D pred(a, b)). Performs $(BIGOH r.length) evaluations of $(D pred). See also $(WEB sgi.com/tech/stl/adjacent_find.html, STL's adjacent_find). Example: ---- int[] a = [ 11, 10, 10, 9, 8, 8, 7, 8, 9 ]; auto r = findAdjacent(a); assert(r == [ 10, 10, 9, 8, 8, 7, 8, 9 ]); p = findAdjacent!("a < b")(a); assert(p == [ 7, 8, 9 ]); ---- */ Range findAdjacent(alias pred = "a == b", Range)(Range r) if (isForwardRange!(Range)) { auto ahead = r; if (!ahead.empty) { for (ahead.popFront; !ahead.empty; r.popFront, ahead.popFront) { if (binaryFun!(pred)(r.front, ahead.front)) return r; } } return ahead; } unittest { //scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 11, 10, 10, 9, 8, 8, 7, 8, 9 ]; auto p = findAdjacent(a); assert(p == [10, 10, 9, 8, 8, 7, 8, 9 ]); p = findAdjacent!("a < b")(a); assert(p == [7, 8, 9]); // empty a = []; p = findAdjacent(a); assert(p.empty); // not found a = [ 1, 2, 3, 4, 5 ]; p = findAdjacent(a); assert(p.empty); p = findAdjacent!"a > b"(a); assert(p.empty); } // findAmong /** Advances $(D seq) by calling $(D seq.popFront) until either $(D find!(pred)(choices, seq.front)) is $(D true), or $(D seq) becomes empty. Performs $(BIGOH seq.length * choices.length) evaluations of $(D pred). See also $(WEB sgi.com/tech/stl/find_first_of.html, STL's find_first_of). Example: ---- int[] a = [ -1, 0, 1, 2, 3, 4, 5 ]; int[] b = [ 3, 1, 2 ]; assert(findAmong(a, b) == a[2 .. $]); ---- */ Range1 findAmong(alias pred = "a == b", Range1, Range2)( Range1 seq, Range2 choices) if (isInputRange!Range1 && isForwardRange!Range2) { for (; !seq.empty && find!pred(choices, seq.front).empty; seq.popFront) { } return seq; } unittest { //scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ -1, 0, 2, 1, 2, 3, 4, 5 ]; int[] b = [ 1, 2, 3 ]; assert(findAmong(a, b) == [2, 1, 2, 3, 4, 5 ]); assert(findAmong(b, [ 4, 6, 7 ][]).empty); assert(findAmong!("a==b")(a, b).length == a.length - 2); assert(findAmong!("a==b")(b, [ 4, 6, 7 ][]).empty); } // count /** The first version counts the number of elements $(D x) in $(D r) for which $(D pred(x, value)) is $(D true). $(D pred) defaults to equality. Performs $(BIGOH r.length) evaluations of $(D pred). The second version returns the number of times $(D needle) occurs in $(D haystack). Throws an exception if $(D needle.empty), as the _count of the empty range in any range would be infinite. Overlapped counts are not considered, for example $(D count("aaa", "aa")) is $(D 1), not $(D 2). The third version counts the elements for which $(D pred(x)) is $(D true). Performs $(BIGOH r.length) evaluations of $(D pred). Example: ---- // count elements in range int[] a = [ 1, 2, 4, 3, 2, 5, 3, 2, 4 ]; assert(count(a, 2) == 3); assert(count!("a > b")(a, 2) == 5); // count range in range assert(count("abcadfabf", "ab") == 2); assert(count("ababab", "abab") == 1); assert(count("ababab", "abx") == 0); // count predicate in range assert(count!("a > 1")(a) == 8); ---- */ size_t count(alias pred = "a == b", Range, E)(Range r, E value) if (isInputRange!Range && is(typeof(binaryFun!pred(r.front, value)) == bool)) { bool pred2(ElementType!(Range) a) { return binaryFun!pred(a, value); } return count!(pred2)(r); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 1, 2, 4, 3, 2, 5, 3, 2, 4 ]; assert(count(a, 2) == 3, text(count(a, 2))); assert(count!("a > b")(a, 2) == 5, text(count!("a > b")(a, 2))); // check strings assert(count("日本語") == 3); assert(count("日本語"w) == 3); assert(count("日本語"d) == 3); assert(count!("a == '日'")("日本語") == 1); assert(count!("a == '本'")("日本語"w) == 1); assert(count!("a == '語'")("日本語"d) == 1); } unittest { debug(std_algorithm) printf("algorithm.count.unittest\n"); string s = "This is a fofofof list"; string sub = "fof"; assert(count(s, sub) == 2); } /// Ditto size_t count(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle) if (isInputRange!R1 && isForwardRange!R2 && is(typeof(binaryFun!pred(haystack, needle)) == bool)) { enforce(!needle.empty, "Cannot count occurrences of an empty range"); size_t result; for (; findSkip!pred(haystack, needle); ++result) { } return result; } unittest { assert(count("abcadfabf", "ab") == 2); assert(count("ababab", "abab") == 1); assert(count("ababab", "abx") == 0); } /// Ditto size_t count(alias pred = "true", Range)(Range r) if (isInputRange!(Range)) { size_t result; for (; !r.empty; r.popFront()) { if (unaryFun!pred(r.front)) ++result; } return result; } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 1, 2, 4, 3, 2, 5, 3, 2, 4 ]; assert(count!("a == 3")(a) == 2); } // balancedParens /** Checks whether $(D r) has "balanced parentheses", i.e. all instances of $(D lPar) are closed by corresponding instances of $(D rPar). The parameter $(D maxNestingLevel) controls the nesting level allowed. The most common uses are the default or $(D 0). In the latter case, no nesting is allowed. Example: ---- auto s = "1 + (2 * (3 + 1 / 2)"; assert(!balancedParens(s, '(', ')')); s = "1 + (2 * (3 + 1) / 2)"; assert(balancedParens(s, '(', ')')); s = "1 + (2 * (3 + 1) / 2)"; assert(!balancedParens(s, '(', ')', 1)); s = "1 + (2 * 3 + 1) / (2 - 5)"; assert(balancedParens(s, '(', ')', 1)); ---- */ bool balancedParens(Range, E)(Range r, E lPar, E rPar, size_t maxNestingLevel = size_t.max) if (isInputRange!(Range) && is(typeof(r.front == lPar))) { size_t count; for (; !r.empty; r.popFront()) { if (r.front == lPar) { if (count > maxNestingLevel) return false; ++count; } else if (r.front == rPar) { if (!count) return false; --count; } } return count == 0; } unittest { auto s = "1 + (2 * (3 + 1 / 2)"; assert(!balancedParens(s, '(', ')')); s = "1 + (2 * (3 + 1) / 2)"; assert(balancedParens(s, '(', ')')); s = "1 + (2 * (3 + 1) / 2)"; assert(!balancedParens(s, '(', ')', 0)); s = "1 + (2 * 3 + 1) / (2 - 5)"; assert(balancedParens(s, '(', ')', 0)); } // equal /** Returns $(D true) if and only if the two ranges compare equal element for element, according to binary predicate $(D pred). The ranges may have different element types, as long as $(D pred(a, b)) evaluates to $(D bool) for $(D a) in $(D r1) and $(D b) in $(D r2). Performs $(BIGOH min(r1.length, r2.length)) evaluations of $(D pred). See also $(WEB sgi.com/tech/stl/_equal.html, STL's _equal). Example: ---- int[] a = [ 1, 2, 4, 3 ]; assert(!equal(a, a[1..$])); assert(equal(a, a)); // different types double[] b = [ 1., 2, 4, 3]; assert(!equal(a, b[1..$])); assert(equal(a, b)); // predicated: ensure that two vectors are approximately equal double[] c = [ 1.005, 2, 4, 3]; assert(equal!(approxEqual)(b, c)); ---- */ bool equal(alias pred = "a == b", Range1, Range2)(Range1 r1, Range2 r2) if (isInputRange!(Range1) && isInputRange!(Range2) && is(typeof(binaryFun!pred(r1.front, r2.front)))) { for (; !r1.empty; r1.popFront(), r2.popFront()) { if (r2.empty) return false; if (!binaryFun!(pred)(r1.front, r2.front)) return false; } return r2.empty; } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 1, 2, 4, 3]; assert(!equal(a, a[1..$])); assert(equal(a, a)); // test with different types double[] b = [ 1., 2, 4, 3]; assert(!equal(a, b[1..$])); assert(equal(a, b)); // predicated double[] c = [ 1.005, 2, 4, 3]; assert(equal!(approxEqual)(b, c)); // utf-8 strings assert(equal("æøå", "æøå")); } // cmp /********************************** Performs three-way lexicographical comparison on two input ranges according to predicate $(D pred). Iterating $(D r1) and $(D r2) in lockstep, $(D cmp) compares each element $(D e1) of $(D r1) with the corresponding element $(D e2) in $(D r2). If $(D binaryFun!pred(e1, e2)), $(D cmp) returns a negative value. If $(D binaryFun!pred(e2, e1)), $(D cmp) returns a positive value. If one of the ranges has been finished, $(D cmp) returns a negative value if $(D r1) has fewer elements than $(D r2), a positive value if $(D r1) has more elements than $(D r2), and $(D 0) if the ranges have the same number of elements. If the ranges are strings, $(D cmp) performs UTF decoding appropriately and compares the ranges one code point at a time. */ int cmp(alias pred = "a < b", R1, R2)(R1 r1, R2 r2) if (isInputRange!R1 && isInputRange!R2 && !(isSomeString!R1 && isSomeString!R2)) { for (;; r1.popFront(), r2.popFront()) { if (r1.empty) return -cast(int)!r2.empty; if (r2.empty) return !r1.empty; auto a = r1.front, b = r2.front; if (binaryFun!pred(a, b)) return -1; if (binaryFun!pred(b, a)) return 1; } } // Specialization for strings (for speed purposes) int cmp(alias pred = "a < b", R1, R2)(R1 r1, R2 r2) if (isSomeString!R1 && isSomeString!R2) { static if(is(typeof(pred) : string)) enum isLessThan = pred == "a < b"; else enum isLessThan = false; // For speed only static int threeWay(size_t a, size_t b) { static if (size_t.sizeof == int.sizeof && isLessThan) return a - b; else return binaryFun!pred(b, a) ? 1 : binaryFun!pred(a, b) ? -1 : 0; } // For speed only // @@@BUG@@@ overloading should be allowed for nested functions static int threeWayInt(int a, int b) { static if (isLessThan) return a - b; else return binaryFun!pred(b, a) ? 1 : binaryFun!pred(a, b) ? -1 : 0; } static if (typeof(r1[0]).sizeof == typeof(r2[0]).sizeof && isLessThan) { static if (typeof(r1[0]).sizeof == 1) { immutable len = min(r1.length, r2.length); immutable result = std.c.string.memcmp(r1.ptr, r2.ptr, len); if (result) return result; } else { auto p1 = r1.ptr, p2 = r2.ptr, pEnd = p1 + min(r1.length, r2.length); for (; p1 != pEnd; ++p1, ++p2) { if (*p1 != *p2) return threeWayInt(cast(int) *p1, cast(int) *p2); } } return threeWay(r1.length, r2.length); } else { for (size_t i1, i2;;) { if (i1 == r1.length) return threeWay(i2, r2.length); if (i2 == r2.length) return threeWay(r1.length, i1); immutable c1 = std.utf.decode(r1, i1), c2 = std.utf.decode(r2, i2); if (c1 != c2) return threeWayInt(cast(int) c1, cast(int) c2); } } } unittest { int result; debug(string) printf("string.cmp.unittest\n"); result = cmp("abc", "abc"); assert(result == 0); // result = cmp(null, null); // assert(result == 0); result = cmp("", ""); assert(result == 0); result = cmp("abc", "abcd"); assert(result < 0); result = cmp("abcd", "abc"); assert(result > 0); result = cmp("abc"d, "abd"); assert(result < 0); result = cmp("bbc", "abc"w); assert(result > 0); result = cmp("aaa", "aaaa"d); assert(result < 0); result = cmp("aaaa", "aaa"d); assert(result > 0); result = cmp("aaa", "aaa"d); assert(result == 0); result = cmp(cast(int[])[], cast(int[])[]); assert(result == 0); result = cmp([1, 2, 3], [1, 2, 3]); assert(result == 0); result = cmp([1, 3, 2], [1, 2, 3]); assert(result > 0); result = cmp([1, 2, 3], [1L, 2, 3, 4]); assert(result < 0); result = cmp([1L, 2, 3], [1, 2]); assert(result > 0); } // MinType template MinType(T...) { static assert(T.length >= 2); static if (T.length == 2) { static if (!is(typeof(T[0].min))) alias CommonType!(T[0 .. 2]) MinType; else static if (mostNegative!(T[1]) < mostNegative!(T[0])) alias T[1] MinType; else static if (mostNegative!(T[1]) > mostNegative!(T[0])) alias T[0] MinType; else static if (T[1].max < T[0].max) alias T[1] MinType; else alias T[0] MinType; } else { alias MinType!(MinType!(T[0 .. 2]), T[2 .. $]) MinType; } } // min /** Returns the minimum of the passed-in values. The type of the result is computed by using $(XREF traits, CommonType). */ MinType!(T1, T2, T) min(T1, T2, T...)(T1 a, T2 b, T xs) { static if (T.length == 0) { static if (isIntegral!(T1) && isIntegral!(T2) && (mostNegative!(T1) < 0) != (mostNegative!(T2) < 0)) static if (mostNegative!(T1) < 0) immutable chooseB = b < a && a > 0; else immutable chooseB = b < a || b < 0; else immutable chooseB = b < a; return cast(typeof(return)) (chooseB ? b : a); } else { return min(min(a, b), xs); } } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int a = 5; short b = 6; double c = 2; auto d = min(a, b); assert(is(typeof(d) == int)); assert(d == 5); auto e = min(a, b, c); assert(is(typeof(e) == double)); assert(e == 2); // mixed signedness test a = -10; uint f = 10; static assert(is(typeof(min(a, f)) == int)); assert(min(a, f) == -10); } // MaxType template MaxType(T...) { static assert(T.length >= 2); static if (T.length == 2) { static if (!is(typeof(T[0].min))) alias CommonType!(T[0 .. 2]) MaxType; else static if (T[1].max > T[0].max) alias T[1] MaxType; else alias T[0] MaxType; } else { alias MaxType!(MaxType!(T[0], T[1]), T[2 .. $]) MaxType; } } // max /** Returns the maximum of the passed-in values. The type of the result is computed by using $(XREF traits, CommonType). Example: ---- int a = 5; short b = 6; double c = 2; auto d = max(a, b); assert(is(typeof(d) == int)); assert(d == 6); auto e = min(a, b, c); assert(is(typeof(e) == double)); assert(e == 2); ---- */ MaxType!(T1, T2, T) max(T1, T2, T...)(T1 a, T2 b, T xs) { static if (T.length == 0) { static if (isIntegral!(T1) && isIntegral!(T2) && (mostNegative!(T1) < 0) != (mostNegative!(T2) < 0)) static if (mostNegative!(T1) < 0) immutable chooseB = b > a || a < 0; else immutable chooseB = b > a && b > 0; else immutable chooseB = b > a; return cast(typeof(return)) (chooseB ? b : a); } else { return max(max(a, b), xs); } } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int a = 5; short b = 6; double c = 2; auto d = max(a, b); assert(is(typeof(d) == int)); assert(d == 6); auto e = max(a, b, c); assert(is(typeof(e) == double)); assert(e == 6); // mixed sign a = -5; uint f = 5; static assert(is(typeof(max(a, f)) == uint)); assert(max(a, f) == 5); } /** Returns the minimum element of a range together with the number of occurrences. The function can actually be used for counting the maximum or any other ordering predicate (that's why $(D maxCount) is not provided). Example: ---- int[] a = [ 2, 3, 4, 1, 2, 4, 1, 1, 2 ]; // Minimum is 1 and occurs 3 times assert(minCount(a) == tuple(1, 3)); // Maximum is 4 and occurs 2 times assert(minCount!("a > b")(a) == tuple(4, 2)); ---- */ Tuple!(ElementType!(Range), size_t) minCount(alias pred = "a < b", Range)(Range range) { if (range.empty) return typeof(return)(); auto p = &(range.front()); size_t occurrences = 1; for (range.popFront; !range.empty; range.popFront) { if (binaryFun!(pred)(*p, range.front)) continue; if (binaryFun!(pred)(range.front, *p)) { // change the min p = &(range.front()); occurrences = 1; } else { ++occurrences; } } return tuple(*p, occurrences); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 2, 3, 4, 1, 2, 4, 1, 1, 2 ]; assert(minCount(a) == tuple(1, 3)); assert(minCount!("a > b")(a) == tuple(4, 2)); int[][] b = [ [4], [2, 4], [4], [4] ]; auto c = minCount!("a[0] < b[0]")(b); assert(c == tuple([2, 4], 1), text(c[0])); } // minPos /** Returns the position of the minimum element of forward range $(D range), i.e. a subrange of $(D range) starting at the position of its smallest element and with the same ending as $(D range). The function can actually be used for counting the maximum or any other ordering predicate (that's why $(D maxPos) is not provided). Example: ---- int[] a = [ 2, 3, 4, 1, 2, 4, 1, 1, 2 ]; // Minimum is 1 and first occurs in position 3 assert(minPos(a) == [ 1, 2, 4, 1, 1, 2 ]); // Maximum is 4 and first occurs in position 2 assert(minPos!("a > b")(a) == [ 4, 1, 2, 4, 1, 1, 2 ]); ---- */ Range minPos(alias pred = "a < b", Range)(Range range) { if (range.empty) return range; auto result = range; for (range.popFront; !range.empty; range.popFront) { if (binaryFun!(pred)(result.front, range.front) || !binaryFun!(pred)(range.front, result.front)) continue; // change the min result = range; } return result; } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 2, 3, 4, 1, 2, 4, 1, 1, 2 ]; // Minimum is 1 and first occurs in position 3 assert(minPos(a) == [ 1, 2, 4, 1, 1, 2 ]); // Maximum is 4 and first occurs in position 5 assert(minPos!("a > b")(a) == [ 4, 1, 2, 4, 1, 1, 2 ]); } // mismatch /** Sequentially compares elements in $(D r1) and $(D r2) in lockstep, and stops at the first mismatch (according to $(D pred), by default equality). Returns a tuple with the reduced ranges that start with the two mismatched values. Performs $(BIGOH min(r1.length, r2.length)) evaluations of $(D pred). See also $(WEB sgi.com/tech/stl/_mismatch.html, STL's _mismatch). Example: ---- int[] x = [ 1, 5, 2, 7, 4, 3 ]; double[] y = [ 1., 5, 2, 7.3, 4, 8 ]; auto m = mismatch(x, y); assert(m[0] == x[3 .. $]); assert(m[1] == y[3 .. $]); ---- */ Tuple!(Range1, Range2) mismatch(alias pred = "a == b", Range1, Range2)(Range1 r1, Range2 r2) if (isInputRange!(Range1) && isInputRange!(Range2)) { for (; !r1.empty && !r2.empty; r1.popFront(), r2.popFront()) { if (!binaryFun!(pred)(r1.front, r2.front)) break; } return tuple(r1, r2); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); // doc example int[] x = [ 1, 5, 2, 7, 4, 3 ]; double[] y = [ 1., 5, 2, 7.3, 4, 8 ]; auto m = mismatch(x, y); assert(m[0] == [ 7, 4, 3 ]); assert(m[1] == [ 7.3, 4, 8 ]); int[] a = [ 1, 2, 3 ]; int[] b = [ 1, 2, 4, 5 ]; auto mm = mismatch(a, b); assert(mm[0] == [3]); assert(mm[1] == [4, 5]); } // levenshteinDistance /** Encodes $(WEB realityinteractive.com/rgrzywinski/archives/000249.html, edit operations) necessary to transform one sequence into another. Given sequences $(D s) (source) and $(D t) (target), a sequence of $(D EditOp) encodes the steps that need to be taken to convert $(D s) into $(D t). For example, if $(D s = "cat") and $(D "cars"), the minimal sequence that transforms $(D s) into $(D t) is: skip two characters, replace 't' with 'r', and insert an 's'. Working with edit operations is useful in applications such as spell-checkers (to find the closest word to a given misspelled word), approximate searches, diff-style programs that compute the difference between files, efficient encoding of patches, DNA sequence analysis, and plagiarism detection. */ enum EditOp : char { /** Current items are equal; no editing is necessary. */ none = 'n', /** Substitute current item in target with current item in source. */ substitute = 's', /** Insert current item from the source into the target. */ insert = 'i', /** Remove current item from the target. */ remove = 'r' } struct Levenshtein(Range, alias equals, CostType = size_t) { void deletionIncrement(CostType n) { _deletionIncrement = n; InitMatrix(); } void insertionIncrement(CostType n) { _insertionIncrement = n; InitMatrix(); } CostType distance(Range s, Range t) { auto slen = walkLength(s), tlen = walkLength(t); AllocMatrix(slen + 1, tlen + 1); foreach (i; 1 .. rows) { auto sfront = s.front; s.popFront(); auto tt = t; foreach (j; 1 .. cols) { auto cSub = _matrix[i - 1][j - 1] + (equals(sfront, tt.front) ? 0 : _substitutionIncrement); tt.popFront(); auto cIns = _matrix[i][j - 1] + _insertionIncrement; auto cDel = _matrix[i - 1][j] + _deletionIncrement; switch (min_index(cSub, cIns, cDel)) { case 0: _matrix[i][j] = cSub; break; case 1: _matrix[i][j] = cIns; break; default: _matrix[i][j] = cDel; break; } } } return _matrix[slen][tlen]; } EditOp[] path(Range s, Range t) { distance(s, t); return path(); } EditOp[] path() { EditOp[] result; size_t i = rows - 1, j = cols - 1; // restore the path while (i || j) { auto cIns = j == 0 ? CostType.max : _matrix[i][j - 1]; auto cDel = i == 0 ? CostType.max : _matrix[i - 1][j]; auto cSub = i == 0 || j == 0 ? CostType.max : _matrix[i - 1][j - 1]; switch (min_index(cSub, cIns, cDel)) { case 0: result ~= _matrix[i - 1][j - 1] == _matrix[i][j] ? EditOp.none : EditOp.substitute; --i; --j; break; case 1: result ~= EditOp.insert; --j; break; default: result ~= EditOp.remove; --i; break; } } reverse(result); return result; } private: CostType _deletionIncrement = 1, _insertionIncrement = 1, _substitutionIncrement = 1; CostType[][] _matrix; size_t rows, cols; void AllocMatrix(size_t r, size_t c) { rows = r; cols = c; if (!_matrix || _matrix.length < r || _matrix[0].length < c) { delete _matrix; _matrix = new CostType[][](r, c); InitMatrix(); } } void InitMatrix() { foreach (i, row; _matrix) { row[0] = i * _deletionIncrement; } if (!_matrix) return; for (auto i = 0u; i != _matrix[0].length; ++i) { _matrix[0][i] = i * _insertionIncrement; } } static uint min_index(CostType i0, CostType i1, CostType i2) { if (i0 <= i1) { return i0 <= i2 ? 0 : 2; } else { return i1 <= i2 ? 1 : 2; } } } /** Returns the $(WEB wikipedia.org/wiki/Levenshtein_distance, Levenshtein distance) between $(D s) and $(D t). The Levenshtein distance computes the minimal amount of edit operations necessary to transform $(D s) into $(D t). Performs $(BIGOH s.length * t.length) evaluations of $(D equals) and occupies $(BIGOH s.length * t.length) storage. Example: ---- assert(levenshteinDistance("cat", "rat") == 1); assert(levenshteinDistance("parks", "spark") == 2); assert(levenshteinDistance("kitten", "sitting") == 3); // ignore case assert(levenshteinDistance!("std.uni.toUpper(a) == std.uni.toUpper(b)") ("parks", "SPARK") == 2); ---- */ size_t levenshteinDistance(alias equals = "a == b", Range1, Range2) (Range1 s, Range2 t) if (isForwardRange!(Range1) && isForwardRange!(Range2)) { Levenshtein!(Range1, binaryFun!(equals), size_t) lev; return lev.distance(s, t); } //Verify Examples. unittest { assert(levenshteinDistance("cat", "rat") == 1); assert(levenshteinDistance("parks", "spark") == 2); assert(levenshteinDistance("kitten", "sitting") == 3); assert(levenshteinDistance!("std.uni.toUpper(a) == std.uni.toUpper(b)") ("parks", "SPARK") == 2); } /** Returns the Levenshtein distance and the edit path between $(D s) and $(D t). Example: --- string a = "Saturday", b = "Sunday"; auto p = levenshteinDistanceAndPath(a, b); assert(p[0] == 3); assert(equal(p[1], "nrrnsnnn")); --- */ Tuple!(size_t, EditOp[]) levenshteinDistanceAndPath(alias equals = "a == b", Range1, Range2) (Range1 s, Range2 t) if (isForwardRange!(Range1) && isForwardRange!(Range2)) { Levenshtein!(Range1, binaryFun!(equals)) lev; auto d = lev.distance(s, t); return tuple(d, lev.path); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); assert(levenshteinDistance("a", "a") == 0); assert(levenshteinDistance("a", "b") == 1); assert(levenshteinDistance("aa", "ab") == 1); assert(levenshteinDistance("aa", "abc") == 2); assert(levenshteinDistance("Saturday", "Sunday") == 3); assert(levenshteinDistance("kitten", "sitting") == 3); //lev.deletionIncrement = 2; //lev.insertionIncrement = 100; string a = "Saturday", b = "Sunday"; auto p = levenshteinDistanceAndPath(a, b); assert(cast(string) p[1] == "nrrnsnnn"); } // copy /** Copies the content of $(D source) into $(D target) and returns the remaining (unfilled) part of $(D target). See also $(WEB sgi.com/tech/stl/_copy.html, STL's _copy). If a behavior similar to $(WEB sgi.com/tech/stl/copy_backward.html, STL's copy_backward) is needed, use $(D copy(retro(source), retro(target))). See also $(XREF range, retro). Example: ---- int[] a = [ 1, 5 ]; int[] b = [ 9, 8 ]; int[] c = new int[a.length + b.length + 10]; auto d = copy(b, copy(a, c)); assert(c[0 .. a.length + b.length] == a ~ b); assert(d.length == 10); ---- As long as the target range elements support assignment from source range elements, different types of ranges are accepted. Example: ---- float[] a = [ 1.0f, 5 ]; double[] b = new double[a.length]; auto d = copy(a, b); ---- To copy at most $(D n) elements from range $(D a) to range $(D b), you may want to use $(D copy(take(a, n), b)). To copy those elements from range $(D a) that satisfy predicate $(D pred) to range $(D b), you may want to use $(D copy(filter!(pred)(a), b)). Example: ---- int[] a = [ 1, 5, 8, 9, 10, 1, 2, 0 ]; auto b = new int[a.length]; auto c = copy(filter!("(a & 1) == 1")(a), b); assert(b[0 .. $ - c.length] == [ 1, 5, 9, 1 ]); ---- */ Range2 copy(Range1, Range2)(Range1 source, Range2 target) if (isInputRange!Range1 && isOutputRange!(Range2, ElementType!Range1)) { static if(isArray!Range1 && isArray!Range2 && is(Unqual!(typeof(source[0])) == Unqual!(typeof(target[0])))) { // Array specialization. This uses optimized memory copying routines // under the hood and is about 10-20x faster than the generic // implementation. enforce(target.length >= source.length, "Cannot copy a source array into a smaller target array."); target[0..source.length] = source; return target[source.length..$]; } else { // Generic implementation. for (; !source.empty; source.popFront()) { put(target, source.front); } return target; } } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); { int[] a = [ 1, 5 ]; int[] b = [ 9, 8 ]; int[] c = new int[a.length + b.length + 10]; auto d = copy(b, copy(a, c)); assert(c[0 .. a.length + b.length] == a ~ b); assert(d.length == 10); } { int[] a = [ 1, 5 ]; int[] b = [ 9, 8 ]; auto e = copy(filter!("a > 1")(a), b); assert(b[0] == 5 && e.length == 1); } } // swapRanges /** Swaps all elements of $(D r1) with successive elements in $(D r2). Returns a tuple containing the remainder portions of $(D r1) and $(D r2) that were not swapped (one of them will be empty). The ranges may be of different types but must have the same element type and support swapping. Example: ---- int[] a = [ 100, 101, 102, 103 ]; int[] b = [ 0, 1, 2, 3 ]; auto c = swapRanges(a[1 .. 3], b[2 .. 4]); assert(c[0].empty && c[1].empty); assert(a == [ 100, 2, 3, 103 ]); assert(b == [ 0, 1, 101, 102 ]); ---- */ Tuple!(Range1, Range2) swapRanges(Range1, Range2)(Range1 r1, Range2 r2) if (isInputRange!(Range1) && isInputRange!(Range2) && hasSwappableElements!(Range1) && hasSwappableElements!(Range2) && is(ElementType!(Range1) == ElementType!(Range2))) { for (; !r1.empty && !r2.empty; r1.popFront, r2.popFront) { swap(r1.front, r2.front); } return tuple(r1, r2); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 100, 101, 102, 103 ]; int[] b = [ 0, 1, 2, 3 ]; auto c = swapRanges(a[1 .. 3], b[2 .. 4]); assert(c[0].empty && c[1].empty); assert(a == [ 100, 2, 3, 103 ]); assert(b == [ 0, 1, 101, 102 ]); } // reverse /** Reverses $(D r) in-place. Performs $(D r.length) evaluations of $(D swap). See also $(WEB sgi.com/tech/stl/_reverse.html, STL's _reverse). Example: ---- int[] arr = [ 1, 2, 3 ]; reverse(arr); assert(arr == [ 3, 2, 1 ]); ---- */ void reverse(Range)(Range r) if (isBidirectionalRange!(Range) && hasSwappableElements!(Range)) { while (!r.empty) { swap(r.front, r.back); r.popFront; if (r.empty) break; r.popBack; } } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] range = null; reverse(range); range = [ 1 ]; reverse(range); assert(range == [1]); range = [1, 2]; reverse(range); assert(range == [2, 1]); range = [1, 2, 3]; reverse(range); assert(range == [3, 2, 1]); } // bringToFront /** The $(D bringToFront) function has considerable flexibility and usefulness. It can rotate elements in one buffer left or right, swap buffers of equal length, and even move elements across disjoint buffers of different types and different lengths. $(D bringToFront) takes two ranges $(D front) and $(D back), which may be of different types. Considering the concatenation of $(D front) and $(D back) one unified range, $(D bringToFront) rotates that unified range such that all elements in $(D back) are brought to the beginning of the unified range. The relative ordering of elements in $(D front) and $(D back), respectively, remains unchanged. The simplest use of $(D bringToFront) is for rotating elements in a buffer. For example: ---- auto arr = [4, 5, 6, 7, 1, 2, 3]; bringToFront(arr[0 .. 4], arr[4 .. $]); assert(arr == [ 1, 2, 3, 4, 5, 6, 7 ]); ---- The $(D front) range may actually "step over" the $(D back) range. This is very useful with forward ranges that cannot compute comfortably right-bounded subranges like $(D arr[0 .. 4]) above. In the example below, $(D r2) is a right subrange of $(D r1). ---- auto list = SList!(int)(4, 5, 6, 7, 1, 2, 3); auto r1 = list[]; auto r2 = list[]; popFrontN(r2, 4); assert(equal(r2, [ 1, 2, 3 ])); bringToFront(r1, r2); assert(equal(list[], [ 1, 2, 3, 4, 5, 6, 7 ])); ---- Elements can be swapped across ranges of different types: ---- auto list = SList!(int)(4, 5, 6, 7); auto vec = [ 1, 2, 3 ]; bringToFront(list[], vec); assert(equal(list[], [ 1, 2, 3, 4 ])); assert(equal(vec, [ 5, 6, 7 ])); ---- Performs $(BIGOH max(front.length, back.length)) evaluations of $(D swap). See also $(WEB sgi.com/tech/stl/_rotate.html, STL's rotate). Preconditions: Either $(D front) and $(D back) are disjoint, or $(D back) is reachable from $(D front) and $(D front) is not reachable from $(D back). Returns: The number of elements brought to the front, i.e., the length of $(D back). */ size_t bringToFront(Range1, Range2)(Range1 front, Range2 back) if (isInputRange!Range1 && isForwardRange!Range2) { enum bool sameHeadExists = is(typeof(front.sameHead(back))); size_t result; for (bool semidone; !front.empty && !back.empty; ) { static if (sameHeadExists) { if (front.sameHead(back)) break; // shortcut } // Swap elements until front and/or back ends. auto back0 = back.save; size_t nswaps; do { static if (sameHeadExists) { // Detect the stepping-over condition. if (front.sameHead(back0)) back0 = back.save; } swapFront(front, back); ++nswaps; front.popFront(); back.popFront(); } while (!front.empty && !back.empty); if (!semidone) result += nswaps; // Now deal with the remaining elements. if (back.empty) { if (front.empty) break; // Right side was shorter, which means that we've brought // all the back elements to the front. semidone = true; // Next pass: bringToFront(front, back0) to adjust the rest. back = back0; } else { assert(front.empty); // Left side was shorter. Let's step into the back. static if (is(Range1 == Take!Range2)) { front = take(back0, nswaps); } else { immutable subresult = bringToFront(take(back0, nswaps), back); if (!semidone) result += subresult; break; // done } } } return result; } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); // doc example { int[] arr = [4, 5, 6, 7, 1, 2, 3]; auto p = bringToFront(arr[0 .. 4], arr[4 .. $]); assert(p == arr.length - 4); assert(arr == [ 1, 2, 3, 4, 5, 6, 7 ], text(arr)); } { auto list = SList!(int)(4, 5, 6, 7, 1, 2, 3); auto r1 = list[]; auto r2 = list[]; popFrontN(r2, 4); assert(equal(r2, [ 1, 2, 3 ])); bringToFront(r1, r2); assert(equal(list[], [ 1, 2, 3, 4, 5, 6, 7 ])); } { auto list = SList!(int)(4, 5, 6, 7); auto vec = [ 1, 2, 3 ]; bringToFront(list[], vec); assert(equal(list[], [ 1, 2, 3, 4 ])); assert(equal(vec, [ 5, 6, 7 ])); } // a more elaborate test { auto rnd = Random(unpredictableSeed); int[] a = new int[uniform(100, 200, rnd)]; int[] b = new int[uniform(100, 200, rnd)]; foreach (ref e; a) e = uniform(-100, 100, rnd); foreach (ref e; b) e = uniform(-100, 100, rnd); int[] c = a ~ b; // writeln("a= ", a); // writeln("b= ", b); auto n = bringToFront(c[0 .. a.length], c[a.length .. $]); //writeln("c= ", c); assert(n == b.length); assert(c == b ~ a, text(c, "\n", a, "\n", b)); } // different types, moveFront, no sameHead { static struct R(T) { T[] data; size_t i; @property { R save() { return this; } bool empty() { return i >= data.length; } T front() { return data[i]; } T front(real e) { return data[i] = cast(T) e; } alias front moveFront; } void popFront() { ++i; } } auto a = R!int([1, 2, 3, 4, 5]); auto b = R!real([6, 7, 8, 9]); auto n = bringToFront(a, b); assert(n == 4); assert(a.data == [6, 7, 8, 9, 1]); assert(b.data == [2, 3, 4, 5]); } // front steps over back { int[] arr, r1, r2; // back is shorter arr = [4, 5, 6, 7, 1, 2, 3]; r1 = arr; r2 = arr[4 .. $]; bringToFront(r1, r2) == 3 || assert(0); assert(equal(arr, [1, 2, 3, 4, 5, 6, 7])); // front is shorter arr = [5, 6, 7, 1, 2, 3, 4]; r1 = arr; r2 = arr[3 .. $]; bringToFront(r1, r2) == 4 || assert(0); assert(equal(arr, [1, 2, 3, 4, 5, 6, 7])); } } // SwapStrategy /** Defines the swapping strategy for algorithms that need to swap elements in a range (such as partition and sort). The strategy concerns the swapping of elements that are not the core concern of the algorithm. For example, consider an algorithm that sorts $(D [ "abc", "b", "aBc" ]) according to $(D toUpper(a) < toUpper(b)). That algorithm might choose to swap the two equivalent strings $(D "abc") and $(D "aBc"). That does not affect the sorting since both $(D [ "abc", "aBc", "b" ]) and $(D [ "aBc", "abc", "b" ]) are valid outcomes. Some situations require that the algorithm must NOT ever change the relative ordering of equivalent elements (in the example above, only $(D [ "abc", "aBc", "b" ]) would be the correct result). Such algorithms are called $(B stable). If the ordering algorithm may swap equivalent elements discretionarily, the ordering is called $(B unstable). Yet another class of algorithms may choose an intermediate tradeoff by being stable only on a well-defined subrange of the range. There is no established terminology for such behavior; this library calls it $(B semistable). Generally, the $(D stable) ordering strategy may be more costly in time and/or space than the other two because it imposes additional constraints. Similarly, $(D semistable) may be costlier than $(D unstable). As (semi-)stability is not needed very often, the ordering algorithms in this module parameterized by $(D SwapStrategy) all choose $(D SwapStrategy.unstable) as the default. */ enum SwapStrategy { /** Allows freely swapping of elements as long as the output satisfies the algorithm's requirements. */ unstable, /** In algorithms partitioning ranges in two, preserve relative ordering of elements only to the left of the partition point. */ semistable, /** Preserve the relative ordering of elements to the largest extent allowed by the algorithm's requirements. */ stable, } /** Eliminates elements at given offsets from $(D range) and returns the shortened range. In the simplest call, one element is removed. ---- int[] a = [ 3, 5, 7, 8 ]; assert(remove(a, 1) == [ 3, 7, 8 ]); assert(a == [ 3, 7, 8, 8 ]); ---- In the case above the element at offset $(D 1) is removed and $(D remove) returns the range smaller by one element. The original array has remained of the same length because all functions in $(D std.algorithm) only change $(I content), not $(I topology). The value $(D 8) is repeated because $(XREF algorithm, move) was invoked to move elements around and on integers $(D move) simply copies the source to the destination. To replace $(D a) with the effect of the removal, simply assign $(D a = remove(a, 1)). The slice will be rebound to the shorter array and the operation completes with maximal efficiency. Multiple indices can be passed into $(D remove). In that case, elements at the respective indices are all removed. The indices must be passed in increasing order, otherwise an exception occurs. ---- int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; assert(remove(a, 1, 3, 5) == [ 0, 2, 4, 6, 7, 8, 9, 10 ]); ---- (Note how all indices refer to slots in the $(I original) array, not in the array as it is being progressively shortened.) Finally, any combination of integral offsets and tuples composed of two integral offsets can be passed in. ---- int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; assert(remove(a, 1, tuple(3, 5), 9) == [ 0, 2, 6, 7, 8, 10 ]); ---- In this case, the slots at positions 1, 3, 4, and 9 are removed from the array. The tuple passes in a range closed to the left and open to the right (consistent with built-in slices), e.g. $(D tuple(3, 5)) means indices $(D 3) and $(D 4) but not $(D 5). If the need is to remove some elements in the range but the order of the remaining elements does not have to be preserved, you may want to pass $(D SwapStrategy.unstable) to $(D remove). ---- int[] a = [ 0, 1, 2, 3 ]; assert(remove!(SwapStrategy.unstable)(a, 1) == [ 0, 3, 2 ]); ---- In the case above, the element at slot $(D 1) is removed, but replaced with the last element of the range. Taking advantage of the relaxation of the stability requirement, $(D remove) moved elements from the end of the array over the slots to be removed. This way there is less data movement to be done which improves the execution time of the function. The function $(D remove) works on any forward range. The moving strategy is (listed from fastest to slowest): $(UL $(LI If $(D s == SwapStrategy.unstable && isRandomAccessRange!Range && hasLength!Range), then elements are moved from the end of the range into the slots to be filled. In this case, the absolute minimum of moves is performed.) $(LI Otherwise, if $(D s == SwapStrategy.unstable && isBidirectionalRange!Range && hasLength!Range), then elements are still moved from the end of the range, but time is spent on advancing between slots by repeated calls to $(D range.popFront).) $(LI Otherwise, elements are moved incrementally towards the front of $(D range); a given element is never moved several times, but more elements are moved than in the previous cases.)) */ Range remove (SwapStrategy s = SwapStrategy.stable, Range, Offset...) (Range range, Offset offset) if (isBidirectionalRange!Range && hasLength!Range && s != SwapStrategy.stable && Offset.length >= 1) { enum bool tupleLeft = is(typeof(offset[0][0])) && is(typeof(offset[0][1])); enum bool tupleRight = is(typeof(offset[$ - 1][0])) && is(typeof(offset[$ - 1][1])); static if (!tupleLeft) { alias offset[0] lStart; auto lEnd = lStart + 1; } else { auto lStart = offset[0][0]; auto lEnd = offset[0][1]; } static if (!tupleRight) { alias offset[$ - 1] rStart; auto rEnd = rStart + 1; } else { auto rStart = offset[$ - 1][0]; auto rEnd = offset[$ - 1][1]; } // Begin. Test first to see if we need to remove the rightmost // element(s) in the range. In that case, life is simple - chop // and recurse. if (rEnd == range.length) { // must remove the last elements of the range range.popBackN(rEnd - rStart); static if (Offset.length > 1) { return .remove!(s, Range, Offset[0 .. $ - 1]) (range, offset[0 .. $ - 1]); } else { return range; } } // Ok, there are "live" elements at the end of the range auto t = range; auto lDelta = lEnd - lStart, rDelta = rEnd - rStart; auto rid = min(lDelta, rDelta); foreach (i; 0 .. rid) { move(range.back, t.front); range.popBack; t.popFront; } if (rEnd - rStart == lEnd - lStart) { // We got rid of both left and right static if (Offset.length > 2) { return .remove!(s, Range, Offset[1 .. $ - 1]) (range, offset[1 .. $ - 1]); } else { return range; } } else if (rEnd - rStart < lEnd - lStart) { // We got rid of the entire right subrange static if (Offset.length > 2) { return .remove!(s, Range) (range, tuple(lStart + rid, lEnd), offset[1 .. $ - 1]); } else { auto tmp = tuple(lStart + rid, lEnd); return .remove!(s, Range, typeof(tmp)) (range, tmp); } } else { // We got rid of the entire left subrange static if (Offset.length > 2) { return .remove!(s, Range) (range, offset[1 .. $ - 1], tuple(rStart, lEnd - rid)); } else { auto tmp = tuple(rStart, lEnd - rid); return .remove!(s, Range, typeof(tmp)) (range, tmp); } } } // Ditto Range remove (SwapStrategy s = SwapStrategy.stable, Range, Offset...) (Range range, Offset offset) if ((isForwardRange!Range && !isBidirectionalRange!Range || !hasLength!Range || s == SwapStrategy.stable) && Offset.length >= 1) { auto result = range; auto src = range, tgt = range; size_t pos; foreach (i; offset) { static if (is(typeof(i[0])) && is(typeof(i[1]))) { auto from = i[0], delta = i[1] - i[0]; } else { auto from = i; enum delta = 1; } assert(pos <= from); for (; pos < from; ++pos, src.popFront, tgt.popFront) { move(src.front, tgt.front); } // now skip source to the "to" position src.popFrontN(delta); pos += delta; foreach (j; 0 .. delta) result.popBack; } // leftover move moveAll(src, tgt); return result; } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; //writeln(remove!(SwapStrategy.stable)(a, 1)); a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; assert(remove!(SwapStrategy.stable)(a, 1) == [ 0, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]); a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; assert(remove!(SwapStrategy.unstable)(a, 0, 10) == [ 9, 1, 2, 3, 4, 5, 6, 7, 8 ]); a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; assert(remove!(SwapStrategy.unstable)(a, 0, tuple(9, 11)) == [ 8, 1, 2, 3, 4, 5, 6, 7 ]); a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; //writeln(remove!(SwapStrategy.stable)(a, 1, 5)); a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; assert(remove!(SwapStrategy.stable)(a, 1, 5) == [ 0, 2, 3, 4, 6, 7, 8, 9, 10 ]); a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; //writeln(remove!(SwapStrategy.stable)(a, 1, 3, 5)); a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; assert(remove!(SwapStrategy.stable)(a, 1, 3, 5) == [ 0, 2, 4, 6, 7, 8, 9, 10]); a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; //writeln(remove!(SwapStrategy.stable)(a, 1, tuple(3, 5))); a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; assert(remove!(SwapStrategy.stable)(a, 1, tuple(3, 5)) == [ 0, 2, 5, 6, 7, 8, 9, 10]); } /** Reduces the length of the bidirectional range $(D range) by only keeping elements that satisfy $(D pred). If $(D s = SwapStrategy.unstable), elements are moved from the right end of the range over the elements to eliminate. If $(D s = SwapStrategy.stable) (the default), elements are moved progressively to front such that their relative order is preserved. Returns the tail portion of the range that was moved. Example: ---- int[] a = [ 1, 2, 3, 2, 3, 4, 5, 2, 5, 6 ]; assert(a[0 .. remove!("a == 2")(a).length] == [ 1, 3, 3, 4, 5, 5, 6 ]); ---- */ Range remove(alias pred, SwapStrategy s = SwapStrategy.stable, Range) (Range range) if (isBidirectionalRange!Range) { auto result = range; static if (s != SwapStrategy.stable) { for (;!range.empty;) { if (!unaryFun!(pred)(range.front)) { range.popFront; continue; } move(range.back, range.front); range.popBack; result.popBack; } } else { auto tgt = range; for (; !range.empty; range.popFront) { if (unaryFun!(pred)(range.front)) { // yank this guy result.popBack; continue; } // keep this guy move(range.front, tgt.front); tgt.popFront; } } return result; } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 1, 2, 3, 2, 3, 4, 5, 2, 5, 6 ]; assert(remove!("a == 2", SwapStrategy.unstable)(a) == [ 1, 6, 3, 5, 3, 4, 5 ]); a = [ 1, 2, 3, 2, 3, 4, 5, 2, 5, 6 ]; //writeln(remove!("a != 2", SwapStrategy.stable)(a)); assert(remove!("a == 2", SwapStrategy.stable)(a) == [ 1, 3, 3, 4, 5, 5, 6 ]); } // eliminate /* * Reduces $(D r) by overwriting all elements $(D x) that satisfy $(D pred(x)). Returns the reduced range. Example: ---- int[] arr = [ 1, 2, 3, 4, 5 ]; // eliminate even elements auto r = eliminate!("(a & 1) == 0")(arr); assert(r == [ 1, 3, 5 ]); assert(arr == [ 1, 3, 5, 4, 5 ]); ---- */ // Range eliminate(alias pred, // SwapStrategy ss = SwapStrategy.unstable, // alias move = .move, // Range)(Range r) // { // alias Iterator!(Range) It; // static void assignIter(It a, It b) { move(*b, *a); } // return range(begin(r), partitionold!(not!(pred), ss, assignIter, Range)(r)); // } // unittest // { // int[] arr = [ 1, 2, 3, 4, 5 ]; // // eliminate even elements // auto r = eliminate!("(a & 1) == 0")(arr); // assert(find!("(a & 1) == 0")(r).empty); // } /* * Reduces $(D r) by overwriting all elements $(D x) that satisfy $(D pred(x, v)). Returns the reduced range. Example: ---- int[] arr = [ 1, 2, 3, 2, 4, 5, 2 ]; // keep elements different from 2 auto r = eliminate(arr, 2); assert(r == [ 1, 3, 4, 5 ]); assert(arr == [ 1, 3, 4, 5, 4, 5, 2 ]); ---- */ // Range eliminate(alias pred = "a == b", // SwapStrategy ss = SwapStrategy.semistable, // Range, Value)(Range r, Value v) // { // alias Iterator!(Range) It; // bool comp(typeof(*It) a) { return !binaryFun!(pred)(a, v); } // static void assignIterB(It a, It b) { *a = *b; } // return range(begin(r), // partitionold!(comp, // ss, assignIterB, Range)(r)); // } // unittest // { // int[] arr = [ 1, 2, 3, 2, 4, 5, 2 ]; // // keep elements different from 2 // auto r = eliminate(arr, 2); // assert(r == [ 1, 3, 4, 5 ]); // assert(arr == [ 1, 3, 4, 5, 4, 5, 2 ]); // } // partition /** Partitions a range in two using $(D pred) as a predicate. Specifically, reorders the range $(D r = [left, right$(RPAREN)) using $(D swap) such that all elements $(D i) for which $(D pred(i)) is $(D true) come before all elements $(D j) for which $(D pred(j)) returns $(D false). Performs $(BIGOH r.length) (if unstable or semistable) or $(BIGOH r.length * log(r.length)) (if stable) evaluations of $(D less) and $(D swap). The unstable version computes the minimum possible evaluations of $(D swap) (roughly half of those performed by the semistable version). See also STL's $(WEB sgi.com/tech/stl/_partition.html, _partition) and $(WEB sgi.com/tech/stl/stable_partition.html, stable_partition). Returns: The right part of $(D r) after partitioning. If $(D ss == SwapStrategy.stable), $(D partition) preserves the relative ordering of all elements $(D a), $(D b) in $(D r) for which $(D pred(a) == pred(b)). If $(D ss == SwapStrategy.semistable), $(D partition) preserves the relative ordering of all elements $(D a), $(D b) in the left part of $(D r) for which $(D pred(a) == pred(b)). Example: ---- auto Arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; auto arr = Arr.dup; static bool even(int a) { return (a & 1) == 0; } // Partition arr such that even numbers come first auto r = partition!(even)(arr); // Now arr is separated in evens and odds. // Numbers may have become shuffled due to instability assert(r == arr[5 .. $]); assert(count!(even)(arr[0 .. 5]) == 5); assert(find!(even)(r).empty); // Can also specify the predicate as a string. // Use 'a' as the predicate argument name arr[] = Arr[]; r = partition!(q{(a & 1) == 0})(arr); assert(r == arr[5 .. $]); // Now for a stable partition: arr[] = Arr[]; r = partition!(q{(a & 1) == 0}, SwapStrategy.stable)(arr); // Now arr is [2 4 6 8 10 1 3 5 7 9], and r points to 1 assert(arr == [2, 4, 6, 8, 10, 1, 3, 5, 7, 9] && r == arr[5 .. $]); // In case the predicate needs to hold its own state, use a delegate: arr[] = Arr[]; int x = 3; // Put stuff greater than 3 on the left bool fun(int a) { return a > x; } r = partition!(fun, SwapStrategy.semistable)(arr); // Now arr is [4 5 6 7 8 9 10 2 3 1] and r points to 2 assert(arr == [4, 5, 6, 7, 8, 9, 10, 2, 3, 1] && r == arr[7 .. $]); ---- */ Range partition(alias predicate, SwapStrategy ss = SwapStrategy.unstable, Range)(Range r) if ((ss == SwapStrategy.stable && isRandomAccessRange!(Range)) || (ss != SwapStrategy.stable && isForwardRange!(Range))) { alias unaryFun!(predicate) pred; if (r.empty) return r; static if (ss == SwapStrategy.stable) { if (r.length == 1) { if (pred(r.front)) r.popFront; return r; } const middle = r.length / 2; alias .partition!(pred, ss, Range) recurse; auto lower = recurse(r[0 .. middle]); auto upper = recurse(r[middle .. $]); bringToFront(lower, r[middle .. r.length - upper.length]); return r[r.length - lower.length - upper.length .. r.length]; } else static if (ss == SwapStrategy.semistable) { for (; !r.empty; r.popFront) { // skip the initial portion of "correct" elements if (pred(r.front)) continue; // hit the first "bad" element auto result = r; for (r.popFront; !r.empty; r.popFront) { if (!pred(r.front)) continue; swap(result.front, r.front); result.popFront; } return result; } return r; } else // ss == SwapStrategy.unstable { // Inspired from www.stepanovpapers.com/PAM3-partition_notes.pdf, // section "Bidirectional Partition Algorithm (Hoare)" auto result = r; for (;;) { for (;;) { if (r.empty) return result; if (!pred(r.front)) break; r.popFront; result.popFront; } // found the left bound assert(!r.empty); for (;;) { if (pred(r.back)) break; r.popBack; if (r.empty) return result; } // found the right bound, swap & make progress static if (is(typeof(swap(r.front, r.back)))) { swap(r.front, r.back); } else { auto t1 = moveFront(r), t2 = moveBack(r); r.front = t2; r.back = t1; } r.popFront; result.popFront; r.popBack; } } } unittest // partition { auto Arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; auto arr = Arr.dup; static bool even(int a) { return (a & 1) == 0; } // Partition a such that even numbers come first auto p1 = partition!(even)(arr); // Now arr is separated in evens and odds. assert(p1 == arr[5 .. $], text(p1)); assert(count!(even)(arr[0 .. $ - p1.length]) == p1.length); assert(find!(even)(p1).empty); // Notice that numbers have become shuffled due to instability arr[] = Arr[]; // Can also specify the predicate as a string. // Use 'a' as the predicate argument name p1 = partition!(q{(a & 1) == 0})(arr); assert(p1 == arr[5 .. $]); // Same result as above. Now for a stable partition: arr[] = Arr[]; p1 = partition!(q{(a & 1) == 0}, SwapStrategy.stable)(arr); // Now arr is [2 4 6 8 10 1 3 5 7 9], and p points to 1 assert(arr == [2, 4, 6, 8, 10, 1, 3, 5, 7, 9], text(arr)); assert(p1 == arr[5 .. $], text(p1)); // In case the predicate needs to hold its own state, use a delegate: arr[] = Arr[]; int x = 3; // Put stuff greater than 3 on the left bool fun(int a) { return a > x; } p1 = partition!(fun, SwapStrategy.semistable)(arr); // Now arr is [4 5 6 7 8 9 10 2 3 1] and p points to 2 assert(arr == [4, 5, 6, 7, 8, 9, 10, 2, 3, 1] && p1 == arr[7 .. $]); // test with random data auto a = rndstuff!(int)(); partition!(even)(a); assert(isPartitioned!(even)(a)); auto b = rndstuff!(string); partition!(`a.length < 5`)(b); assert(isPartitioned!(`a.length < 5`)(b)); } /** Returns $(D true) if $(D r) is partitioned according to predicate $(D pred). Example: ---- int[] r = [ 1, 3, 5, 7, 8, 2, 4, ]; assert(isPartitioned!("a & 1")(r)); ---- */ bool isPartitioned(alias pred, Range)(Range r) if (isForwardRange!(Range)) { for (; !r.empty; r.popFront) { if (unaryFun!(pred)(r.front)) continue; for (r.popFront; !r.empty; r.popFront) { if (unaryFun!(pred)(r.front)) return false; } break; } return true; } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] r = [ 1, 3, 5, 7, 8, 2, 4, ]; assert(isPartitioned!("a & 1")(r)); } // partition3 /** Rearranges elements in $(D r) in three adjacent ranges and returns them. The first and leftmost range only contains elements in $(D r) less than $(D pivot). The second and middle range only contains elements in $(D r) that are equal to $(D pivot). Finally, the third and rightmost range only contains elements in $(D r) that are greater than $(D pivot). The less-than test is defined by the binary function $(D less). Example: ---- auto a = [ 8, 3, 4, 1, 4, 7, 4 ]; auto pieces = partition3(a, 4); assert(a == [ 1, 3, 4, 4, 4, 7, 8 ]; assert(pieces[0] == [ 1, 3 ]); assert(pieces[1] == [ 4, 4, 4 ]); assert(pieces[2] == [ 7, 8 ]); ---- BUGS: stable $(D partition3) has not been implemented yet. */ auto partition3(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range, E) (Range r, E pivot) if (ss == SwapStrategy.unstable && isRandomAccessRange!Range && hasSwappableElements!Range && hasLength!Range && is(typeof(binaryFun!less(r.front, pivot)) == bool) && is(typeof(binaryFun!less(pivot, r.front)) == bool) && is(typeof(binaryFun!less(r.front, r.front)) == bool)) { // The algorithm is described in "Engineering a sort function" by // Jon Bentley et al, pp 1257. alias binaryFun!less lessFun; size_t i, j, k = r.length, l = k; bigloop: for (;;) { for (;; ++j) { if (j == k) break bigloop; assert(j < r.length); if (lessFun(r[j], pivot)) continue; if (lessFun(pivot, r[j])) break; swap(r[i++], r[j]); } assert(j < k); for (;;) { assert(k > 0); if (!lessFun(pivot, r[--k])) { if (lessFun(r[k], pivot)) break; swap(r[k], r[--l]); } if (j == k) break bigloop; } // Here we know r[j] > pivot && r[k] < pivot swap(r[j++], r[k]); } // Swap the equal ranges from the extremes into the middle auto strictlyLess = j - i, strictlyGreater = l - k; auto swapLen = min(i, strictlyLess); swapRanges(r[0 .. swapLen], r[j - swapLen .. j]); swapLen = min(r.length - l, strictlyGreater); swapRanges(r[k .. k + swapLen], r[r.length - swapLen .. r.length]); return tuple(r[0 .. strictlyLess], r[strictlyLess .. r.length - strictlyGreater], r[r.length - strictlyGreater .. r.length]); } unittest { auto a = [ 8, 3, 4, 1, 4, 7, 4 ]; auto pieces = partition3(a, 4); assert(a == [ 1, 3, 4, 4, 4, 8, 7 ]); assert(pieces[0] == [ 1, 3 ]); assert(pieces[1] == [ 4, 4, 4 ]); assert(pieces[2] == [ 8, 7 ]); a = null; pieces = partition3(a, 4); assert(a.empty); assert(pieces[0].empty); assert(pieces[1].empty); assert(pieces[2].empty); a.length = uniform(0, 100); foreach (ref e; a) { e = uniform(0, 50); } pieces = partition3(a, 25); assert(pieces[0].length + pieces[1].length + pieces[2].length == a.length); foreach (e; pieces[0]) { assert(e < 25); } foreach (e; pieces[1]) { assert(e == 25); } foreach (e; pieces[2]) { assert(e > 25); } } // topN /** Reorders the range $(D r) using $(D swap) such that $(D r[nth]) refers to the element that would fall there if the range were fully sorted. In addition, it also partitions $(D r) such that all elements $(D e1) from $(D r[0]) to $(D r[nth]) satisfy $(D !less(r[nth], e1)), and all elements $(D e2) from $(D r[nth]) to $(D r[r.length]) satisfy $(D !less(e2, r[nth])). Effectively, it finds the nth smallest (according to $(D less)) elements in $(D r). Performs $(BIGOH r.length) (if unstable) or $(BIGOH r.length * log(r.length)) (if stable) evaluations of $(D less) and $(D swap). See also $(WEB sgi.com/tech/stl/nth_element.html, STL's nth_element). Example: ---- int[] v = [ 25, 7, 9, 2, 0, 5, 21 ]; auto n = 4; topN!(less)(v, n); assert(v[n] == 9); // Equivalent form: topN!("a < b")(v, n); assert(v[n] == 9); ---- BUGS: Stable topN has not been implemented yet. */ void topN(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range)(Range r, size_t nth) if (isRandomAccessRange!(Range) && hasLength!Range) { static assert(ss == SwapStrategy.unstable, "Stable topN not yet implemented"); while (r.length > nth) { auto pivot = r.length / 2; swap(r[pivot], r.back); assert(!binaryFun!(less)(r.back, r.back)); bool pred(ElementType!(Range) a) { return binaryFun!(less)(a, r.back); } auto right = partition!(pred, ss)(r); assert(right.length >= 1); swap(right.front, r.back); pivot = r.length - right.length; if (pivot == nth) { return; } if (pivot < nth) { ++pivot; r = r[pivot .. $]; nth -= pivot; } else { assert(pivot < r.length); r = r[0 .. pivot]; } } } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); //scope(failure) writeln(stderr, "Failure testing algorithm"); //auto v = ([ 25, 7, 9, 2, 0, 5, 21 ]).dup; int[] v = [ 7, 6, 5, 4, 3, 2, 1, 0 ]; sizediff_t n = 3; topN!("a < b")(v, n); assert(reduce!max(v[0 .. n]) <= v[n]); assert(reduce!min(v[n + 1 .. $]) >= v[n]); // v = ([3, 4, 5, 6, 7, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5]).dup; n = 3; topN(v, n); assert(reduce!max(v[0 .. n]) <= v[n]); assert(reduce!min(v[n + 1 .. $]) >= v[n]); // v = ([3, 4, 5, 6, 7, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5]).dup; n = 1; topN(v, n); assert(reduce!max(v[0 .. n]) <= v[n]); assert(reduce!min(v[n + 1 .. $]) >= v[n]); // v = ([3, 4, 5, 6, 7, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5]).dup; n = v.length - 1; topN(v, n); assert(v[n] == 7); // v = ([3, 4, 5, 6, 7, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5]).dup; n = 0; topN(v, n); assert(v[n] == 1); double[][] v1 = [[-10, -5], [-10, -3], [-10, -5], [-10, -4], [-10, -5], [-9, -5], [-9, -3], [-9, -5],]; // double[][] v1 = [ [-10, -5], [-10, -4], [-9, -5], [-9, -5], // [-10, -5], [-10, -3], [-10, -5], [-9, -3],]; double[]*[] idx = [ &v1[0], &v1[1], &v1[2], &v1[3], &v1[4], &v1[5], &v1[6], &v1[7], ]; auto mid = v1.length / 2; topN!((a, b){ return (*a)[1] < (*b)[1]; })(idx, mid); foreach (e; idx[0 .. mid]) assert((*e)[1] <= (*idx[mid])[1]); foreach (e; idx[mid .. $]) assert((*e)[1] >= (*idx[mid])[1]); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = new int[uniform(1, 10000)]; foreach (ref e; a) e = uniform(-1000, 1000); auto k = uniform(0, a.length); topN(a, k); if (k > 0) { auto left = reduce!max(a[0 .. k]); assert(left <= a[k]); } if (k + 1 < a.length) { auto right = reduce!min(a[k + 1 .. $]); assert(right >= a[k]); } } /** Stores the smallest elements of the two ranges in the left-hand range. */ void topN(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range1, Range2)(Range1 r1, Range2 r2) if (isRandomAccessRange!(Range1) && hasLength!Range1 && isInputRange!Range2 && is(ElementType!Range1 == ElementType!Range2)) { static assert(ss == SwapStrategy.unstable, "Stable topN not yet implemented"); auto heap = BinaryHeap!Range1(r1); for (; !r2.empty; r2.popFront) { heap.conditionalInsert(r2.front); } } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 5, 7, 2, 6, 7 ]; int[] b = [ 2, 1, 5, 6, 7, 3, 0 ]; topN(a, b); sort(a); sort(b); assert(a == [0, 1, 2, 2, 3]); } // sort /** Sorts a random-access range according to predicate $(D less). Performs $(BIGOH r.length * log(r.length)) (if unstable) or $(BIGOH r.length * log(r.length) * log(r.length)) (if stable) evaluations of $(D less) and $(D swap). See also STL's $(WEB sgi.com/tech/stl/_sort.html, _sort) and $(WEB sgi.com/tech/stl/stable_sort.html, stable_sort). Example: ---- int[] array = [ 1, 2, 3, 4 ]; // sort in descending order sort!("a > b")(array); assert(array == [ 4, 3, 2, 1 ]); // sort in ascending order sort(array); assert(array == [ 1, 2, 3, 4 ]); // sort with a delegate bool myComp(int x, int y) { return x > y; } sort!(myComp)(array); assert(array == [ 4, 3, 2, 1 ]); // Showcase stable sorting string[] words = [ "aBc", "a", "abc", "b", "ABC", "c" ]; sort!("toUpper(a) < toUpper(b)", SwapStrategy.stable)(words); assert(words == [ "a", "aBc", "abc", "ABC", "b", "c" ]); ---- */ SortedRange!(Range, less) sort(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range)(Range r) { alias binaryFun!(less) lessFun; static if (is(typeof(lessFun(r.front, r.front)) == bool)) { sortImpl!(lessFun, ss)(r); static if(is(typeof(text(r)))) { enum maxLen = 8; assert(isSorted!lessFun(r), text("Failed to sort range of type ", Range.stringof, ". Actual result is: ", r[0 .. r.length > maxLen ? maxLen : r.length ], r.length > maxLen ? "..." : "")); } else assert(isSorted!lessFun(r), text("Unable to sort range of type ", Range.stringof, ": <unable to print elements>")); } else { static assert(false, "Invalid predicate passed to sort: "~less); } return assumeSorted!less(r); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); // sort using delegate int a[] = new int[100]; auto rnd = Random(unpredictableSeed); foreach (ref e; a) { e = uniform(-100, 100, rnd); } int i = 0; bool greater2(int a, int b) { return a + i > b + i; } bool delegate(int, int) greater = &greater2; sort!(greater)(a); assert(isSorted!(greater)(a)); // sort using string sort!("a < b")(a); assert(isSorted!("a < b")(a)); // sort using function; all elements equal foreach (ref e; a) { e = 5; } static bool less(int a, int b) { return a < b; } sort!(less)(a); assert(isSorted!(less)(a)); string[] words = [ "aBc", "a", "abc", "b", "ABC", "c" ]; bool lessi(string a, string b) { return toUpper(a) < toUpper(b); } sort!(lessi, SwapStrategy.stable)(words); assert(words == [ "a", "aBc", "abc", "ABC", "b", "c" ]); // sort using ternary predicate //sort!("b - a")(a); //assert(isSorted!(less)(a)); a = rndstuff!(int); sort(a); assert(isSorted(a)); auto b = rndstuff!(string); sort!("toLower(a) < toLower(b)")(b); assert(isSorted!("toUpper(a) < toUpper(b)")(b)); } private template validPredicates(E, less...) { static if (less.length == 0) enum validPredicates = true; else static if (less.length == 1 && is(typeof(less[0]) == SwapStrategy)) enum validPredicates = true; else enum validPredicates = is(typeof(binaryFun!(less[0])(E.init, E.init)) == bool) && validPredicates!(E, less[1 .. $]); } /** Sorts a range by multiple keys. The call $(D multiSort!("a.id < b.id", "a.date > b.date")(r)) sorts the range $(D r) by $(D id) ascending, and sorts elements that have the same $(D id) by $(D date) descending. Such a call is equivalent to $(D sort!"a.id != b.id ? a.id < b.id : a.date > b.date"(r)), but $(D multiSort) is faster because it does fewer comparisons (in addition to being more convenient). Example: ---- static struct Point { int x, y; } auto pts1 = [ Point(0, 0), Point(5, 5), Point(0, 1), Point(0, 2) ]; auto pts2 = [ Point(0, 0), Point(0, 1), Point(0, 2), Point(5, 5) ]; multiSort!("a.x < b.x", "a.y < b.y", SwapStrategy.unstable)(pts1); assert(pts1 == pts2); ---- */ template multiSort(less...) //if (less.length > 1) { void multiSort(Range)(Range r) if (validPredicates!(ElementType!Range, less)) { static if (is(typeof(less[$ - 1]) == SwapStrategy)) { enum ss = less[$ - 1]; alias less[0 .. $ - 1] funs; } else { alias SwapStrategy.unstable ss; alias less funs; } alias binaryFun!(funs[0]) lessFun; static if (funs.length > 1) { while (r.length > 1) { auto p = getPivot!lessFun(r); auto t = partition3!(less[0], ss)(r, r[p]); if (t[0].length <= t[2].length) { .multiSort!less(t[0]); .multiSort!(less[1 .. $])(t[1]); r = t[2]; } else { .multiSort!(less[1 .. $])(t[1]); .multiSort!less(t[2]); r = t[0]; } } } else { sort!(lessFun, ss)(r); } } } unittest { static struct Point { int x, y; } auto pts1 = [ Point(5, 6), Point(1, 0), Point(5, 7), Point(1, 1), Point(1, 2), Point(0, 1) ]; auto pts2 = [ Point(0, 1), Point(1, 0), Point(1, 1), Point(1, 2), Point(5, 6), Point(5, 7) ]; static assert(validPredicates!(Point, "a.x < b.x", "a.y < b.y")); multiSort!("a.x < b.x", "a.y < b.y", SwapStrategy.unstable)(pts1); assert(pts1 == pts2); auto pts3 = indexed(pts1, iota(pts1.length)); multiSort!("a.x < b.x", "a.y < b.y", SwapStrategy.unstable)(pts3); assert(equal(pts3, pts2)); } private size_t getPivot(alias less, Range)(Range r) { // This algorithm sorts the first, middle and last elements of r, // then returns the index of the middle element. In effect, it uses the // median-of-three heuristic. alias binaryFun!(less) pred; immutable len = r.length; immutable size_t mid = len / 2; immutable uint result = ((cast(uint) (pred(r[0], r[mid]))) << 2) | ((cast(uint) (pred(r[0], r[len - 1]))) << 1) | (cast(uint) (pred(r[mid], r[len - 1]))); switch(result) { case 0b001: swapAt(r, 0, len - 1); swapAt(r, 0, mid); break; case 0b110: swapAt(r, mid, len - 1); break; case 0b011: swapAt(r, 0, mid); break; case 0b100: swapAt(r, mid, len - 1); swapAt(r, 0, mid); break; case 0b000: swapAt(r, 0, len - 1); break; case 0b111: break; default: assert(0); } return mid; } private void optimisticInsertionSort(alias less, Range)(Range r) { alias binaryFun!(less) pred; if(r.length < 2) { return ; } immutable maxJ = r.length - 1; for(size_t i = r.length - 2; i != size_t.max; --i) { size_t j = i; auto temp = r[i]; for(; j < maxJ && pred(r[j + 1], temp); ++j) { r[j] = r[j + 1]; } r[j] = temp; } } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); auto rnd = Random(1); int a[] = new int[uniform(100, 200, rnd)]; foreach (ref e; a) { e = uniform(-100, 100, rnd); } optimisticInsertionSort!(binaryFun!("a < b"), int[])(a); assert(isSorted(a)); } // private void swapAt(R)(R r, size_t i1, size_t i2) { static if (is(typeof(&r[i1]))) { swap(r[i1], r[i2]); } else { if (i1 == i2) return; auto t1 = moveAt(r, i1); auto t2 = moveAt(r, i2); r[i2] = t1; r[i1] = t2; } } private void sortImpl(alias less, SwapStrategy ss, Range)(Range r) { alias ElementType!(Range) Elem; enum size_t optimisticInsertionSortGetsBetter = 25; static assert(optimisticInsertionSortGetsBetter >= 1); while (r.length > optimisticInsertionSortGetsBetter) { const pivotIdx = getPivot!(less)(r); auto pivot = r[pivotIdx]; // partition static if (ss == SwapStrategy.unstable) { alias binaryFun!(less) pred; // partition swapAt(r, pivotIdx, r.length - 1); size_t lessI = size_t.max, greaterI = r.length - 1; while(true) { while(pred(r[++lessI], pivot)) {} while(greaterI > 0 && pred(pivot, r[--greaterI])) {} if(lessI < greaterI) { swapAt(r, lessI, greaterI); } else { break; } } swapAt(r, r.length - 1, lessI); auto right = r[lessI + 1..r.length]; auto left = r[0..min(lessI, greaterI + 1)]; if (right.length > left.length) { swap(left, right); } .sortImpl!(less, ss, Range)(right); r = left; } else // handle semistable and stable the same { static assert(ss != SwapStrategy.semistable); bool pred(Elem a) { return less(a, pivot); } auto right = partition!(pred, ss)(r); if (r.length == right.length) { // bad, bad pivot. pivot <= everything // find the first occurrence of the pivot bool pred1(Elem a) { return !less(pivot, a); } //auto firstPivotPos = find!(pred1)(r).ptr; auto pivotSpan = find!(pred1)(r); assert(!pivotSpan.empty); assert(!less(pivotSpan.front, pivot) && !less(pivot, pivotSpan.front)); // find the last occurrence of the pivot bool pred2(Elem a) { return less(pivot, a); } //auto lastPivotPos = find!(pred2)(pivotsRight[1 .. $]).ptr; auto pivotRunLen = find!(pred2)(pivotSpan[1 .. $]).length; pivotSpan = pivotSpan[0 .. pivotRunLen + 1]; // now rotate firstPivotPos..lastPivotPos to the front bringToFront(r, pivotSpan); r = r[pivotSpan.length .. $]; } else { .sortImpl!(less, ss, Range)(r[0 .. r.length - right.length]); r = right; } } } // residual sort static if (optimisticInsertionSortGetsBetter > 1) { optimisticInsertionSort!(less, Range)(r); } } // schwartzSort /** Sorts a range using an algorithm akin to the $(WEB wikipedia.org/wiki/Schwartzian_transform, Schwartzian transform), also known as the decorate-sort-undecorate pattern in Python and Lisp. (Not to be confused with $(WEB youtube.com/watch?v=S25Zf8svHZQ, the other Schwartz).) This function is helpful when the sort comparison includes an expensive computation. The complexity is the same as that of the corresponding $(D sort), but $(D schwartzSort) evaluates $(D transform) only $(D r.length) times (less than half when compared to regular sorting). The usage can be best illustrated with an example. Example: ---- uint hashFun(string) { ... expensive computation ... } string[] array = ...; // Sort strings by hash, slow sort!("hashFun(a) < hashFun(b)")(array); // Sort strings by hash, fast (only computes arr.length hashes): schwartzSort!(hashFun, "a < b")(array); ---- The $(D schwartzSort) function might require less temporary data and be faster than the Perl idiom or the decorate-sort-undecorate idiom present in Python and Lisp. This is because sorting is done in-place and only minimal extra data (one array of transformed elements) is created. To check whether an array was sorted and benefit of the speedup of Schwartz sorting, a function $(D schwartzIsSorted) is not provided because the effect can be achieved by calling $(D isSorted!less(map!transform(r))). */ void schwartzSort(alias transform, alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range)(Range r) if (isRandomAccessRange!(Range) && hasLength!(Range)) { alias typeof(transform(r.front)) XformType; auto xform = new XformType[r.length]; foreach (i, e; r) { xform[i] = transform(e); } auto z = zip(xform, r); alias typeof(z.front()) ProxyType; bool myLess(ProxyType a, ProxyType b) { return binaryFun!less(a[0], b[0]); } sort!(myLess, ss)(z); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); static double entropy(double[] probs) { double result = 0; foreach (p; probs) { if (!p) continue; //enforce(p > 0 && p <= 1, "Wrong probability passed to entropy"); result -= p * log2(p); } return result; } auto lowEnt = ([ 1.0, 0, 0 ]).dup, midEnt = ([ 0.1, 0.1, 0.8 ]).dup, highEnt = ([ 0.31, 0.29, 0.4 ]).dup; double arr[][] = new double[][3]; arr[0] = midEnt; arr[1] = lowEnt; arr[2] = highEnt; schwartzSort!(entropy, q{a > b})(arr); assert(arr[0] == highEnt); assert(arr[1] == midEnt); assert(arr[2] == lowEnt); assert(isSorted!("a > b")(map!(entropy)(arr))); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); static double entropy(double[] probs) { double result = 0; foreach (p; probs) { if (!p) continue; //enforce(p > 0 && p <= 1, "Wrong probability passed to entropy"); result -= p * log2(p); } return result; } auto lowEnt = ([ 1.0, 0, 0 ]).dup, midEnt = ([ 0.1, 0.1, 0.8 ]).dup, highEnt = ([ 0.31, 0.29, 0.4 ]).dup; double arr[][] = new double[][3]; arr[0] = midEnt; arr[1] = lowEnt; arr[2] = highEnt; schwartzSort!(entropy, q{a < b})(arr); assert(arr[0] == lowEnt); assert(arr[1] == midEnt); assert(arr[2] == highEnt); assert(isSorted!("a < b")(map!(entropy)(arr))); } // partialSort /** Reorders the random-access range $(D r) such that the range $(D r[0 .. mid]) is the same as if the entire $(D r) were sorted, and leaves the range $(D r[mid .. r.length]) in no particular order. Performs $(BIGOH r.length * log(mid)) evaluations of $(D pred). The implementation simply calls $(D topN!(less, ss)(r, n)) and then $(D sort!(less, ss)(r[0 .. n])). Example: ---- int[] a = [ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 ]; partialSort(a, 5); assert(a[0 .. 5] == [ 0, 1, 2, 3, 4 ]); ---- */ void partialSort(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range)(Range r, size_t n) if (isRandomAccessRange!(Range) && hasLength!(Range) && hasSlicing!(Range)) { topN!(less, ss)(r, n); sort!(less, ss)(r[0 .. n]); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 ]; partialSort(a, 5); assert(a[0 .. 5] == [ 0, 1, 2, 3, 4 ]); } // completeSort /** Sorts the random-access range $(D chain(lhs, rhs)) according to predicate $(D less). The left-hand side of the range $(D lhs) is assumed to be already sorted; $(D rhs) is assumed to be unsorted. The exact strategy chosen depends on the relative sizes of $(D lhs) and $(D rhs). Performs $(BIGOH lhs.length + rhs.length * log(rhs.length)) (best case) to $(BIGOH (lhs.length + rhs.length) * log(lhs.length + rhs.length)) (worst-case) evaluations of $(D swap). Example: ---- int[] a = [ 1, 2, 3 ]; int[] b = [ 4, 0, 6, 5 ]; completeSort(assumeSorted(a), b); assert(a == [ 0, 1, 2 ]); assert(b == [ 3, 4, 5, 6 ]); ---- */ void completeSort(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range1, Range2)(SortedRange!(Range1, less) lhs, Range2 rhs) if (hasLength!(Range2) && hasSlicing!(Range2)) { // Probably this algorithm can be optimized by using in-place // merge auto lhsOriginal = lhs.release(); foreach (i; 0 .. rhs.length) { auto sortedSoFar = chain(lhsOriginal, rhs[0 .. i]); auto ub = assumeSorted!less(sortedSoFar).upperBound(rhs[i]); if (!ub.length) continue; bringToFront(ub.release(), rhs[i .. i + 1]); } } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 1, 2, 3 ]; int[] b = [ 4, 0, 6, 5 ]; // @@@BUG@@@ The call below should work // completeSort(assumeSorted(a), b); completeSort!("a < b", SwapStrategy.unstable, int[], int[])( assumeSorted(a), b); assert(a == [ 0, 1, 2 ]); assert(b == [ 3, 4, 5, 6 ]); } // isSorted /** Checks whether a forward range is sorted according to the comparison operation $(D less). Performs $(BIGOH r.length) evaluations of $(D less). Example: ---- int[] arr = [4, 3, 2, 1]; assert(!isSorted(arr)); sort(arr); assert(isSorted(arr)); sort!("a > b")(arr); assert(isSorted!("a > b")(arr)); ---- */ bool isSorted(alias less = "a < b", Range)(Range r) if (isForwardRange!(Range)) { // @@@BUG@@@ Should work with inlined predicate bool pred(ElementType!Range a, ElementType!Range b) { return binaryFun!less(b, a); } return findAdjacent!pred(r).empty; } // makeIndex /** Computes an index for $(D r) based on the comparison $(D less). The index is a sorted array of pointers or indices into the original range. This technique is similar to sorting, but it is more flexible because (1) it allows "sorting" of immutable collections, (2) allows binary search even if the original collection does not offer random access, (3) allows multiple indexes, each on a different predicate, and (4) may be faster when dealing with large objects. However, using an index may also be slower under certain circumstances due to the extra indirection, and is always larger than a sorting-based solution because it needs space for the index in addition to the original collection. The complexity is the same as $(D sort)'s. $(D makeIndex) overwrites its second argument with the result, but never reallocates it. If the second argument's length is less than that of the range indexed, an exception is thrown. The first overload of $(D makeIndex) writes to a range containing pointers, and the second writes to a range containing offsets. The first overload requires $(D Range) to be a forward range, and the latter requires it to be a random-access range. Example: ---- immutable(int[]) arr = [ 2, 3, 1, 5, 0 ]; // index using pointers auto index1 = new immutable(int)*[arr.length]; makeIndex!("a < b")(arr, index1); assert(isSorted!("*a < *b")(index1)); // index using offsets auto index2 = new size_t[arr.length]; makeIndex!("a < b")(arr, index2); assert(isSorted! ((size_t a, size_t b){ return arr[a] < arr[b];}) (index2)); ---- */ void makeIndex( alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range, RangeIndex) (Range r, RangeIndex index) if (isForwardRange!(Range) && isRandomAccessRange!(RangeIndex) && is(ElementType!(RangeIndex) : ElementType!(Range)*)) { // assume collection already ordered size_t i; for (; !r.empty; r.popFront, ++i) index[i] = &(r.front); enforce(index.length == i); // sort the index static bool indirectLess(ElementType!(RangeIndex) a, ElementType!(RangeIndex) b) { return binaryFun!(less)(*a, *b); } sort!(indirectLess, ss)(index); } /// Ditto void makeIndex( alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range, RangeIndex) (Range r, RangeIndex index) if (isRandomAccessRange!(Range) && !isInfinite!(Range) && isRandomAccessRange!(RangeIndex) && !isInfinite!(RangeIndex) && isIntegral!(ElementType!(RangeIndex))) { alias Unqual!(ElementType!RangeIndex) I; enforce(r.length == index.length, "r and index must be same length for makeIndex."); static if(I.sizeof < size_t.sizeof) { enforce(r.length <= I.max, "Cannot create an index with " ~ "element type " ~ I.stringof ~ " with length " ~ to!string(r.length) ~ "." ); } for(I i = 0; i < r.length; ++i) { index[cast(size_t) i] = i; } // sort the index bool indirectLess(ElementType!(RangeIndex) a, ElementType!(RangeIndex) b) { return binaryFun!(less)(r[cast(size_t) a], r[cast(size_t) b]); } sort!(indirectLess, ss)(index); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); immutable(int)[] arr = [ 2, 3, 1, 5, 0 ]; // index using pointers auto index1 = new immutable(int)*[arr.length]; alias typeof(arr) ImmRange; alias typeof(index1) ImmIndex; static assert(isForwardRange!(ImmRange)); static assert(isRandomAccessRange!(ImmIndex)); static assert(!isIntegral!(ElementType!(ImmIndex))); static assert(is(ElementType!(ImmIndex) : ElementType!(ImmRange)*)); makeIndex!("a < b")(arr, index1); assert(isSorted!("*a < *b")(index1)); // index using offsets auto index2 = new long[arr.length]; makeIndex(arr, index2); assert(isSorted! ((long a, long b){ return arr[cast(size_t) a] < arr[cast(size_t) b]; })(index2)); // index strings using offsets string[] arr1 = ["I", "have", "no", "chocolate"]; auto index3 = new byte[arr1.length]; makeIndex(arr1, index3); assert(isSorted! ((byte a, byte b){ return arr1[a] < arr1[b];}) (index3)); } /** Specifies whether the output of certain algorithm is desired in sorted format. */ enum SortOutput { no, /// Don't sort output yes, /// Sort output } void topNIndex( alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range, RangeIndex)(Range r, RangeIndex index, SortOutput sorted = SortOutput.no) if (isIntegral!(ElementType!(RangeIndex))) { if (index.empty) return; enforce(ElementType!(RangeIndex).max >= index.length, "Index type too small"); bool indirectLess(ElementType!(RangeIndex) a, ElementType!(RangeIndex) b) { return binaryFun!(less)(r[a], r[b]); } auto heap = BinaryHeap!(RangeIndex, indirectLess)(index, 0); foreach (i; 0 .. r.length) { heap.conditionalInsert(cast(ElementType!RangeIndex) i); } if (sorted == SortOutput.yes) { while (!heap.empty) heap.removeFront(); } } void topNIndex( alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range, RangeIndex)(Range r, RangeIndex index, SortOutput sorted = SortOutput.no) if (is(ElementType!(RangeIndex) == ElementType!(Range)*)) { if (index.empty) return; static bool indirectLess(const ElementType!(RangeIndex) a, const ElementType!(RangeIndex) b) { return binaryFun!less(*a, *b); } auto heap = BinaryHeap!(RangeIndex, indirectLess)(index, 0); foreach (i; 0 .. r.length) { heap.conditionalInsert(&r[i]); } if (sorted == SortOutput.yes) { while (!heap.empty) heap.removeFront(); } } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); { int[] a = [ 10, 8, 9, 2, 4, 6, 7, 1, 3, 5 ]; int*[] b = new int*[5]; topNIndex!("a > b")(a, b, SortOutput.yes); //foreach (e; b) writeln(*e); assert(b == [ &a[0], &a[2], &a[1], &a[6], &a[5]]); } { int[] a = [ 10, 8, 9, 2, 4, 6, 7, 1, 3, 5 ]; auto b = new ubyte[5]; topNIndex!("a > b")(a, b, SortOutput.yes); //foreach (e; b) writeln(e, ":", a[e]); assert(b == [ cast(ubyte) 0, cast(ubyte)2, cast(ubyte)1, cast(ubyte)6, cast(ubyte)5], text(b)); } } /+ // topNIndexImpl // @@@BUG1904 /*private*/ void topNIndexImpl( alias less, bool sortAfter, SwapStrategy ss, SRange, TRange)(SRange source, TRange target) { alias binaryFun!(less) lessFun; static assert(ss == SwapStrategy.unstable, "Stable indexing not yet implemented"); alias Iterator!(SRange) SIter; alias std.iterator.ElementType!(TRange) TElem; enum usingInt = isIntegral!(TElem); static if (usingInt) { enforce(source.length <= TElem.max, "Numeric overflow at risk in computing topNIndexImpl"); } // types and functions used within SIter index2iter(TElem a) { static if (!usingInt) return a; else return begin(source) + a; } bool indirectLess(TElem a, TElem b) { return lessFun(*index2iter(a), *index2iter(b)); } void indirectCopy(SIter from, ref TElem to) { static if (!usingInt) to = from; else to = cast(TElem)(from - begin(source)); } // copy beginning of collection into the target auto sb = begin(source), se = end(source), tb = begin(target), te = end(target); for (; sb != se; ++sb, ++tb) { if (tb == te) break; indirectCopy(sb, *tb); } // if the index's size is same as the source size, just quicksort it // otherwise, heap-insert stuff in it. if (sb == se) { // everything in source is now in target... just sort the thing static if (sortAfter) sort!(indirectLess, ss)(target); } else { // heap-insert te = tb; tb = begin(target); target = range(tb, te); makeHeap!(indirectLess)(target); // add stuff to heap for (; sb != se; ++sb) { if (!lessFun(*sb, *index2iter(*tb))) continue; // copy the source over the smallest indirectCopy(sb, *tb); heapify!(indirectLess)(target, tb); } static if (sortAfter) sortHeap!(indirectLess)(target); } } /** topNIndex */ void topNIndex( alias less, SwapStrategy ss = SwapStrategy.unstable, SRange, TRange)(SRange source, TRange target) { return .topNIndexImpl!(less, false, ss)(source, target); } /// Ditto void topNIndex( string less, SwapStrategy ss = SwapStrategy.unstable, SRange, TRange)(SRange source, TRange target) { return .topNIndexImpl!(binaryFun!(less), false, ss)(source, target); } // partialIndex /** Computes an index for $(D source) based on the comparison $(D less) and deposits the result in $(D target). It is acceptable that $(D target.length < source.length), in which case only the smallest $(D target.length) elements in $(D source) get indexed. The target provides a sorted "view" into $(D source). This technique is similar to sorting and partial sorting, but it is more flexible because (1) it allows "sorting" of immutable collections, (2) allows binary search even if the original collection does not offer random access, (3) allows multiple indexes, each on a different comparison criterion, (4) may be faster when dealing with large objects. However, using an index may also be slower under certain circumstances due to the extra indirection, and is always larger than a sorting-based solution because it needs space for the index in addition to the original collection. The complexity is $(BIGOH source.length * log(target.length)). Two types of indexes are accepted. They are selected by simply passing the appropriate $(D target) argument: $(OL $(LI Indexes of type $(D Iterator!(Source)), in which case the index will be sorted with the predicate $(D less(*a, *b));) $(LI Indexes of an integral type (e.g. $(D size_t)), in which case the index will be sorted with the predicate $(D less(source[a], source[b])).)) Example: ---- immutable arr = [ 2, 3, 1 ]; int* index[3]; partialIndex(arr, index); assert(*index[0] == 1 && *index[1] == 2 && *index[2] == 3); assert(isSorted!("*a < *b")(index)); ---- */ void partialIndex( alias less, SwapStrategy ss = SwapStrategy.unstable, SRange, TRange)(SRange source, TRange target) { return .topNIndexImpl!(less, true, ss)(source, target); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); immutable arr = [ 2, 3, 1 ]; auto index = new immutable(int)*[3]; partialIndex!(binaryFun!("a < b"))(arr, index); assert(*index[0] == 1 && *index[1] == 2 && *index[2] == 3); assert(isSorted!("*a < *b")(index)); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); static bool less(int a, int b) { return a < b; } { string[] x = ([ "c", "a", "b", "d" ]).dup; // test with integrals auto index1 = new size_t[x.length]; partialIndex!(q{a < b})(x, index1); assert(index1[0] == 1 && index1[1] == 2 && index1[2] == 0 && index1[3] == 3); // half-sized index1 = new size_t[x.length / 2]; partialIndex!(q{a < b})(x, index1); assert(index1[0] == 1 && index1[1] == 2); // and with iterators auto index = new string*[x.length]; partialIndex!(q{a < b})(x, index); assert(isSorted!(q{*a < *b})(index)); assert(*index[0] == "a" && *index[1] == "b" && *index[2] == "c" && *index[3] == "d"); } { immutable arr = [ 2, 3, 1 ]; auto index = new immutable(int)*[arr.length]; partialIndex!(less)(arr, index); assert(*index[0] == 1 && *index[1] == 2 && *index[2] == 3); assert(isSorted!(q{*a < *b})(index)); } // random data auto b = rndstuff!(string); auto index = new string*[b.length]; partialIndex!("std.uni.toUpper(a) < std.uni.toUpper(b)")(b, index); assert(isSorted!("std.uni.toUpper(*a) < std.uni.toUpper(*b)")(index)); // random data with indexes auto index1 = new size_t[b.length]; bool cmp(string x, string y) { return std.uni.toUpper(x) < std.uni.toUpper(y); } partialIndex!(cmp)(b, index1); bool check(size_t x, size_t y) { return std.uni.toUpper(b[x]) < std.uni.toUpper(b[y]); } assert(isSorted!(check)(index1)); } // Commented out for now, needs reimplementation // // schwartzMakeIndex // /** // Similar to $(D makeIndex) but using $(D schwartzSort) to sort the // index. // Example: // ---- // string[] arr = [ "ab", "c", "Ab", "C" ]; // auto index = schwartzMakeIndex!(toUpper, less, SwapStrategy.stable)(arr); // assert(*index[0] == "ab" && *index[1] == "Ab" // && *index[2] == "c" && *index[2] == "C"); // assert(isSorted!("toUpper(*a) < toUpper(*b)")(index)); // ---- // */ // Iterator!(Range)[] schwartzMakeIndex( // alias transform, // alias less, // SwapStrategy ss = SwapStrategy.unstable, // Range)(Range r) // { // alias Iterator!(Range) Iter; // auto result = new Iter[r.length]; // // assume collection already ordered // size_t i = 0; // foreach (it; begin(r) .. end(r)) // { // result[i++] = it; // } // // sort the index // alias typeof(transform(*result[0])) Transformed; // static bool indirectLess(Transformed a, Transformed b) // { // return less(a, b); // } // static Transformed indirectTransform(Iter a) // { // return transform(*a); // } // schwartzSort!(indirectTransform, less, ss)(result); // return result; // } // /// Ditto // Iterator!(Range)[] schwartzMakeIndex( // alias transform, // string less = q{a < b}, // SwapStrategy ss = SwapStrategy.unstable, // Range)(Range r) // { // return .schwartzMakeIndex!( // transform, binaryFun!(less), ss, Range)(r); // } // version (wyda) unittest // { // string[] arr = [ "D", "ab", "c", "Ab", "C" ]; // auto index = schwartzMakeIndex!(toUpper, "a < b", // SwapStrategy.stable)(arr); // assert(isSorted!(q{toUpper(*a) < toUpper(*b)})(index)); // assert(*index[0] == "ab" && *index[1] == "Ab" // && *index[2] == "c" && *index[3] == "C"); // // random data // auto b = rndstuff!(string); // auto index1 = schwartzMakeIndex!(toUpper)(b); // assert(isSorted!("toUpper(*a) < toUpper(*b)")(index1)); // } +/ // canFind /** Returns $(D true) if and only if $(D value) can be found in $(D range). Performs $(BIGOH r.length) evaluations of $(D pred). */ bool canFind(alias pred = "a == b", Range, V)(Range range, V value) if (is(typeof(find!pred(range, value)))) { return !find!pred(range, value).empty; } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); auto a = rndstuff!(int); if (a.length) { auto b = a[a.length / 2]; assert(canFind(a, b)); } } // canFind /** Returns $(D true) if and only if a value $(D v) satisfying the predicate $(D pred) can be found in the forward range $(D range). Performs $(BIGOH r.length) evaluations of $(D pred). */ bool canFind(alias pred, Range)(Range range) if (is(typeof(find!pred(range)))) { return !find!pred(range).empty; } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); auto a = [ 1, 2, 0, 4 ]; assert(canFind!"a == 2"(a)); } // Scheduled for deprecation. Use std.range.SortedRange.canFind. bool canFindSorted(alias pred = "a < b", Range, V)(Range range, V value) { pragma(msg, "std.algorithm.canFindSorted is scheduled for " ~ "deprecation. Use std.range.SortedRange.canFind instead."); return assumeSorted!pred(range).canFind!V(value); } // Scheduled for deprecation. Use std.range.SortedRange.lowerBound. Range lowerBound(alias pred = "a < b", Range, V)(Range range, V value) { pragma(msg, "std.algorithm.lowerBound is scheduled for " ~ "deprecation. Use std.range.SortedRange.lowerBound instead."); return assumeSorted!pred(range).lowerBound!V(value).release; } // Scheduled for deprecation. Use std.range.SortedRange.upperBound. Range upperBound(alias pred = "a < b", Range, V)(Range range, V value) { pragma(msg, "std.algorithm.upperBound is scheduled for " ~ "deprecation. Use std.range.SortedRange.upperBound instead."); return assumeSorted!pred(range).upperBound!V(value).release; } // Scheduled for deprecation. Use std.range.SortedRange.equalRange. Range equalRange(alias pred = "a < b", Range, V)(Range range, V value) { pragma(msg, "std.algorithm.equalRange is scheduled for " ~ "deprecation. Use std.range.SortedRange.equalRange instead."); return assumeSorted!pred(range).equalRange!V(value).release; } /** Copies the top $(D n) elements of the input range $(D source) into the random-access range $(D target), where $(D n = target.length). Elements of $(D source) are not touched. If $(D sorted) is $(D true), the target is sorted. Otherwise, the target respects the $(WEB en.wikipedia.org/wiki/Binary_heap, heap property). Example: ---- int[] a = [ 10, 16, 2, 3, 1, 5, 0 ]; int[] b = new int[3]; topNCopy(a, b, true); assert(b == [ 0, 1, 2 ]); ---- */ TRange topNCopy(alias less = "a < b", SRange, TRange) (SRange source, TRange target, SortOutput sorted = SortOutput.no) if (isInputRange!(SRange) && isRandomAccessRange!(TRange) && hasLength!(TRange) && hasSlicing!(TRange)) { if (target.empty) return target; auto heap = BinaryHeap!(TRange, less)(target, 0); foreach (e; source) heap.conditionalInsert(e); auto result = target[0 .. heap.length]; if (sorted == SortOutput.yes) { while (!heap.empty) heap.removeFront(); } return result; } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 10, 16, 2, 3, 1, 5, 0 ]; int[] b = new int[3]; topNCopy(a, b, SortOutput.yes); assert(b == [ 0, 1, 2 ]); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); auto r = Random(unpredictableSeed); sizediff_t[] a = new sizediff_t[uniform(1, 1000, r)]; foreach (i, ref e; a) e = i; randomShuffle(a, r); auto n = uniform(0, a.length, r); sizediff_t[] b = new sizediff_t[n]; topNCopy!(binaryFun!("a < b"))(a, b, SortOutput.yes); assert(isSorted!(binaryFun!("a < b"))(b)); } /** Lazily computes the union of two or more ranges $(D rs). The ranges are assumed to be sorted by $(D less). Elements in the output are not unique; the length of the output is the sum of the lengths of the inputs. (The $(D length) member is offered if all ranges also have length.) The element types of all ranges must have a common type. Example: ---- int[] a = [ 1, 2, 4, 5, 7, 9 ]; int[] b = [ 0, 1, 2, 4, 7, 8 ]; int[] c = [ 10 ]; assert(setUnion(a, b).length == a.length + b.length); assert(equal(setUnion(a, b), [0, 1, 1, 2, 2, 4, 4, 5, 7, 7, 8, 9][])); assert(equal(setUnion(a, c, b), [0, 1, 1, 2, 2, 4, 4, 5, 7, 7, 8, 9, 10][])); ---- */ struct SetUnion(alias less = "a < b", Rs...) if (allSatisfy!(isInputRange, Rs)) { private: Rs _r; alias binaryFun!(less) comp; uint _crt; void adjustPosition(uint candidate = 0)() { static if (candidate == Rs.length) { _crt = _crt.max; } else { if (_r[candidate].empty) { adjustPosition!(candidate + 1)(); return; } foreach (i, U; Rs[candidate + 1 .. $]) { enum j = candidate + i + 1; if (_r[j].empty) continue; if (comp(_r[j].front, _r[candidate].front)) { // a new candidate was found adjustPosition!(j)(); return; } } // Found a successful candidate _crt = candidate; } } public: alias CommonType!(staticMap!(.ElementType, Rs)) ElementType; this(Rs rs) { this._r = rs; adjustPosition(); } @property bool empty() { return _crt == _crt.max; } void popFront() { // Assumes _crt is correct assert(!empty); foreach (i, U; Rs) { if (i < _crt) continue; // found _crt assert(!_r[i].empty); _r[i].popFront; adjustPosition(); return; } assert(false); } @property ElementType front() { assert(!empty); // Assume _crt is correct foreach (i, U; Rs) { if (i < _crt) continue; assert(!_r[i].empty); return _r[i].front; } assert(false); } static if(allSatisfy!(isForwardRange, Rs)) { @property typeof(this) save() { auto ret = this; foreach(ti, elem; _r) { ret._r[ti] = elem.save; } return ret; } } static if (allSatisfy!(hasLength, Rs)) { @property size_t length() { size_t result; foreach (i, U; Rs) { result += _r[i].length; } return result; } } } /// Ditto SetUnion!(less, Rs) setUnion(alias less = "a < b", Rs...) (Rs rs) { return typeof(return)(rs); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 1, 2, 4, 5, 7, 9 ]; int[] b = [ 0, 1, 2, 4, 7, 8 ]; int[] c = [ 10 ]; //foreach (e; setUnion(a, b)) writeln(e); assert(setUnion(a, b).length == a.length + b.length); assert(equal(setUnion(a, b), [0, 1, 1, 2, 2, 4, 4, 5, 7, 7, 8, 9][])); assert(equal(setUnion(a, c, b), [0, 1, 1, 2, 2, 4, 4, 5, 7, 7, 8, 9, 10][])); static assert(isForwardRange!(typeof(setUnion(a, b)))); } /** Lazily computes the intersection of two or more input ranges $(D rs). The ranges are assumed to be sorted by $(D less). The element types of all ranges must have a common type. Example: ---- int[] a = [ 1, 2, 4, 5, 7, 9 ]; int[] b = [ 0, 1, 2, 4, 7, 8 ]; int[] c = [ 0, 1, 4, 5, 7, 8 ]; assert(equal(setIntersection(a, a), a)); assert(equal(setIntersection(a, b), [1, 2, 4, 7][])); assert(equal(setIntersection(a, b, c), [1, 4, 7][])); ---- */ struct SetIntersection(alias less = "a < b", Rs...) if (allSatisfy!(isInputRange, Rs)) { static assert(Rs.length == 2); private: Rs _input; alias binaryFun!(less) comp; alias CommonType!(staticMap!(.ElementType, Rs)) ElementType; void adjustPosition() { // Positions to the first two elements that are equal while (!empty) { if (comp(_input[0].front, _input[1].front)) { _input[0].popFront; } else if (comp(_input[1].front, _input[0].front)) { _input[1].popFront; } else { break; } } } public: this(Rs input) { this._input = input; // position to the first element adjustPosition; } @property bool empty() { foreach (i, U; Rs) { if (_input[i].empty) return true; } return false; } void popFront() { assert(!empty); assert(!comp(_input[0].front, _input[1].front) && !comp(_input[1].front, _input[0].front)); _input[0].popFront; _input[1].popFront; adjustPosition; } @property ElementType front() { assert(!empty); return _input[0].front; } static if(allSatisfy!(isForwardRange, Rs)) { @property typeof(this) save() { auto ret = this; foreach(ti, elem; _input) { ret._input[ti] = elem.save; } return ret; } } } /// Ditto SetIntersection!(less, Rs) setIntersection(alias less = "a < b", Rs...) (Rs ranges) if (allSatisfy!(isInputRange, Rs)) { return typeof(return)(ranges); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 1, 2, 4, 5, 7, 9 ]; int[] b = [ 0, 1, 2, 4, 7, 8 ]; int[] c = [ 0, 1, 4, 5, 7, 8 ]; //foreach (e; setIntersection(a, b, c)) writeln(e); assert(equal(setIntersection(a, b), [1, 2, 4, 7][])); assert(equal(setIntersection(a, a), a)); static assert(isForwardRange!(typeof(setIntersection(a, a)))); // assert(equal(setIntersection(a, b, b, a), [1, 2, 4, 7][])); // assert(equal(setIntersection(a, b, c), [1, 4, 7][])); // assert(equal(setIntersection(a, c, b), [1, 4, 7][])); // assert(equal(setIntersection(b, a, c), [1, 4, 7][])); // assert(equal(setIntersection(b, c, a), [1, 4, 7][])); // assert(equal(setIntersection(c, a, b), [1, 4, 7][])); // assert(equal(setIntersection(c, b, a), [1, 4, 7][])); } /** Lazily computes the difference of $(D r1) and $(D r2). The two ranges are assumed to be sorted by $(D less). The element types of the two ranges must have a common type. Example: ---- int[] a = [ 1, 2, 4, 5, 7, 9 ]; int[] b = [ 0, 1, 2, 4, 7, 8 ]; assert(equal(setDifference(a, b), [5, 9][])); ---- */ struct SetDifference(alias less = "a < b", R1, R2) if (isInputRange!(R1) && isInputRange!(R2)) { private: R1 r1; R2 r2; alias binaryFun!(less) comp; void adjustPosition() { while (!r1.empty) { if (r2.empty || comp(r1.front, r2.front)) break; if (comp(r2.front, r1.front)) { r2.popFront; } else { // both are equal r1.popFront; r2.popFront; } } } public: this(R1 r1, R2 r2) { this.r1 = r1; this.r2 = r2; // position to the first element adjustPosition; } void popFront() { r1.popFront; adjustPosition; } @property ElementType!(R1) front() { assert(!empty); return r1.front; } static if(isForwardRange!R1 && isForwardRange!R2) { @property typeof(this) save() { auto ret = this; ret.r1 = r1.save; ret.r2 = r2.save; return ret; } } bool empty() { return r1.empty; } } /// Ditto SetDifference!(less, R1, R2) setDifference(alias less = "a < b", R1, R2) (R1 r1, R2 r2) { return typeof(return)(r1, r2); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 1, 2, 4, 5, 7, 9 ]; int[] b = [ 0, 1, 2, 4, 7, 8 ]; //foreach (e; setDifference(a, b)) writeln(e); assert(equal(setDifference(a, b), [5, 9][])); static assert(isForwardRange!(typeof(setDifference(a, b)))); } /** Lazily computes the symmetric difference of $(D r1) and $(D r2), i.e. the elements that are present in exactly one of $(D r1) and $(D r2). The two ranges are assumed to be sorted by $(D less), and the output is also sorted by $(D less). The element types of the two ranges must have a common type. Example: ---- int[] a = [ 1, 2, 4, 5, 7, 9 ]; int[] b = [ 0, 1, 2, 4, 7, 8 ]; assert(equal(setSymmetricDifference(a, b), [0, 5, 8, 9][])); ---- */ struct SetSymmetricDifference(alias less = "a < b", R1, R2) if (isInputRange!(R1) && isInputRange!(R2)) { private: R1 r1; R2 r2; //bool usingR2; alias binaryFun!(less) comp; void adjustPosition() { while (!r1.empty && !r2.empty) { if (comp(r1.front, r2.front) || comp(r2.front, r1.front)) { break; } // equal, pop both r1.popFront; r2.popFront; } } public: this(R1 r1, R2 r2) { this.r1 = r1; this.r2 = r2; // position to the first element adjustPosition; } void popFront() { assert(!empty); if (r1.empty) r2.popFront; else if (r2.empty) r1.popFront; else { // neither is empty if (comp(r1.front, r2.front)) { r1.popFront; } else { assert(comp(r2.front, r1.front)); r2.popFront; } } adjustPosition; } @property ElementType!(R1) front() { assert(!empty); if (r2.empty || !r1.empty && comp(r1.front, r2.front)) { return r1.front; } assert(r1.empty || comp(r2.front, r1.front)); return r2.front; } static if(isForwardRange!R1 && isForwardRange!R2) { @property typeof(this) save() { auto ret = this; ret.r1 = r1.save; ret.r2 = r2.save; return ret; } } ref auto opSlice() { return this; } @property bool empty() { return r1.empty && r2.empty; } } /// Ditto SetSymmetricDifference!(less, R1, R2) setSymmetricDifference(alias less = "a < b", R1, R2) (R1 r1, R2 r2) { return typeof(return)(r1, r2); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); int[] a = [ 1, 2, 4, 5, 7, 9 ]; int[] b = [ 0, 1, 2, 4, 7, 8 ]; //foreach (e; setSymmetricDifference(a, b)) writeln(e); assert(equal(setSymmetricDifference(a, b), [0, 5, 8, 9][])); static assert(isForwardRange!(typeof(setSymmetricDifference(a, b)))); } // Internal random array generators version(unittest) { private enum size_t maxArraySize = 50; private enum size_t minArraySize = maxArraySize - 1; private string[] rndstuff(T : string)() { static Random rnd; static bool first = true; if (first) { rnd = Random(unpredictableSeed); first = false; } string[] result = new string[uniform(minArraySize, maxArraySize, rnd)]; string alpha = "abcdefghijABCDEFGHIJ"; foreach (ref s; result) { foreach (i; 0 .. uniform(0u, 20u, rnd)) { auto j = uniform(0, alpha.length - 1, rnd); s ~= alpha[j]; } } return result; } private int[] rndstuff(T : int)() { static Random rnd; static bool first = true; if (first) { rnd = Random(unpredictableSeed); first = false; } int[] result = new int[uniform(minArraySize, maxArraySize, rnd)]; foreach (ref i; result) { i = uniform(-100, 100, rnd); } return result; } private double[] rndstuff(T : double)() { double[] result; foreach (i; rndstuff!(int)()) { result ~= i / 50.; } return result; } } // NWayUnion /** Computes the union of multiple sets. The input sets are passed as a range of ranges and each is assumed to be sorted by $(D less). Computation is done lazily, one union element at a time. The complexity of one $(D popFront) operation is $(BIGOH log(ror.length)). However, the length of $(D ror) decreases as ranges in it are exhausted, so the complexity of a full pass through $(D NWayUnion) is dependent on the distribution of the lengths of ranges contained within $(D ror). If all ranges have the same length $(D n) (worst case scenario), the complexity of a full pass through $(D NWayUnion) is $(BIGOH n * ror.length * log(ror.length)), i.e., $(D log(ror.length)) times worse than just spanning all ranges in turn. The output comes sorted (unstably) by $(D less). Warning: Because $(D NWayUnion) does not allocate extra memory, it will leave $(D ror) modified. Namely, $(D NWayUnion) assumes ownership of $(D ror) and discretionarily swaps and advances elements of it. If you want $(D ror) to preserve its contents after the call, you may want to pass a duplicate to $(D NWayUnion) (and perhaps cache the duplicate in between calls). Example: ---- double[][] a = [ [ 1, 4, 7, 8 ], [ 1, 7 ], [ 1, 7, 8], [ 4 ], [ 7 ], ]; auto witness = [ 1, 1, 1, 4, 4, 7, 7, 7, 7, 8, 8 ]; assert(equal(nWayUnion(a), witness[])); ---- */ struct NWayUnion(alias less, RangeOfRanges) { private alias .ElementType!(.ElementType!RangeOfRanges) ElementType; private alias binaryFun!less comp; private RangeOfRanges _ror; static bool compFront(.ElementType!RangeOfRanges a, .ElementType!RangeOfRanges b) { // revert comparison order so we get the smallest elements first return comp(b.front, a.front); } BinaryHeap!(RangeOfRanges, compFront) _heap; this(RangeOfRanges ror) { // Preemptively get rid of all empty ranges in the input // No need for stability either _ror = remove!("a.empty", SwapStrategy.unstable)(ror); //Build the heap across the range _heap.acquire(_ror); } @property bool empty() { return _ror.empty; } @property ref ElementType front() { return _heap.front.front; } void popFront() { _heap.removeFront(); // let's look at the guy just popped _ror.back.popFront; if (_ror.back.empty) { _ror.popBack; // nothing else to do: the empty range is not in the // heap and not in _ror return; } // Put the popped range back in the heap _heap.conditionalInsert(_ror.back) || assert(false); } } /// Ditto NWayUnion!(less, RangeOfRanges) nWayUnion (alias less = "a < b", RangeOfRanges) (RangeOfRanges ror) { return typeof(return)(ror); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); double[][] a = [ [ 1, 4, 7, 8 ], [ 1, 7 ], [ 1, 7, 8], [ 4 ], [ 7 ], ]; auto witness = [ 1, 1, 1, 4, 4, 7, 7, 7, 7, 8, 8 ]; //foreach (e; nWayUnion(a)) writeln(e); assert(equal(nWayUnion(a), witness[])); } // largestPartialIntersection /** Given a range of sorted forward ranges $(D ror), copies to $(D tgt) the elements that are common to most ranges, along with their number of occurrences. All ranges in $(D ror) are assumed to be sorted by $(D less). Only the most frequent $(D tgt.length) elements are returned. Example: ---- // Figure which number can be found in most arrays of the set of // arrays below. double[][] a = [ [ 1, 4, 7, 8 ], [ 1, 7 ], [ 1, 7, 8], [ 4 ], [ 7 ], ]; auto b = new Tuple!(double, uint)[1]; largestPartialIntersection(a, b); // First member is the item, second is the occurrence count assert(b[0] == tuple(7.0, 4u)); ---- $(D 7.0) is the correct answer because it occurs in $(D 4) out of the $(D 5) inputs, more than any other number. The second member of the resulting tuple is indeed $(D 4) (recording the number of occurrences of $(D 7.0)). If more of the top-frequent numbers are needed, just create a larger $(D tgt) range. In the axample above, creating $(D b) with length $(D 2) yields $(D tuple(1.0, 3u)) in the second position. The function $(D largestPartialIntersection) is useful for e.g. searching an $(LUCKY inverted index) for the documents most likely to contain some terms of interest. The complexity of the search is $(BIGOH n * log(tgt.length)), where $(D n) is the sum of lengths of all input ranges. This approach is faster than keeping an associative array of the occurrences and then selecting its top items, and also requires less memory ($(D largestPartialIntersection) builds its result directly in $(D tgt) and requires no extra memory). Warning: Because $(D largestPartialIntersection) does not allocate extra memory, it will leave $(D ror) modified. Namely, $(D largestPartialIntersection) assumes ownership of $(D ror) and discretionarily swaps and advances elements of it. If you want $(D ror) to preserve its contents after the call, you may want to pass a duplicate to $(D largestPartialIntersection) (and perhaps cache the duplicate in between calls). */ void largestPartialIntersection (alias less = "a < b", RangeOfRanges, Range) (RangeOfRanges ror, Range tgt, SortOutput sorted = SortOutput.no) { struct UnitWeights { static int opIndex(ElementType!(ElementType!RangeOfRanges)) { return 1; } } return largestPartialIntersectionWeighted!less(ror, tgt, UnitWeights(), sorted); } // largestPartialIntersectionWeighted /** Similar to $(D largestPartialIntersection), but associates a weight with each distinct element in the intersection. Example: ---- // Figure which number can be found in most arrays of the set of // arrays below, with specific per-element weights double[][] a = [ [ 1, 4, 7, 8 ], [ 1, 7 ], [ 1, 7, 8], [ 4 ], [ 7 ], ]; auto b = new Tuple!(double, uint)[1]; double[double] weights = [ 1:1.2, 4:2.3, 7:1.1, 8:1.1 ]; largestPartialIntersectionWeighted(a, b, weights); // First member is the item, second is the occurrence count assert(b[0] == tuple(4.0, 2u)); ---- The correct answer in this case is $(D 4.0), which, although only appears two times, has a total weight $(D 4.6) (three times its weight $(D 2.3)). The value $(D 7) is weighted with $(D 1.1) and occurs four times for a total weight $(D 4.4). */ void largestPartialIntersectionWeighted (alias less = "a < b", RangeOfRanges, Range, WeightsAA) (RangeOfRanges ror, Range tgt, WeightsAA weights, SortOutput sorted = SortOutput.no) { if (tgt.empty) return; alias ElementType!Range InfoType; bool heapComp(InfoType a, InfoType b) { return weights[a[0]] * a[1] > weights[b[0]] * b[1]; } topNCopy!heapComp(group(nWayUnion!less(ror)), tgt, sorted); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); double[][] a = [ [ 1, 4, 7, 8 ], [ 1, 7 ], [ 1, 7, 8], [ 4 ], [ 7 ], ]; auto b = new Tuple!(double, uint)[2]; largestPartialIntersection(a, b, SortOutput.yes); //sort(b); //writeln(b); assert(b == [ tuple(7., 4u), tuple(1., 3u) ][], text(b)); assert(a[0].empty); } unittest { debug(std_algorithm) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); string[][] a = [ [ "1", "4", "7", "8" ], [ "1", "7" ], [ "1", "7", "8"], [ "4" ], [ "7" ], ]; auto b = new Tuple!(string, uint)[2]; largestPartialIntersection(a, b, SortOutput.yes); //writeln(b); assert(b == [ tuple("7", 4u), tuple("1", 3u) ][], text(b)); } unittest { //scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done."); // Figure which number can be found in most arrays of the set of // arrays below, with specific per-element weights double[][] a = [ [ 1, 4, 7, 8 ], [ 1, 7 ], [ 1, 7, 8], [ 4 ], [ 7 ], ]; auto b = new Tuple!(double, uint)[1]; double[double] weights = [ 1:1.2, 4:2.3, 7:1.1, 8:1.1 ]; largestPartialIntersectionWeighted(a, b, weights); // First member is the item, second is the occurrence count //writeln(b[0]); assert(b[0] == tuple(4.0, 2u)); }
D
# FIXED F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/source/F2837xD_PieCtrl.c F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_device.h F2837xD_PieCtrl.obj: C:/PROGRA~3/MATLAB/SUPPOR~1/R2018a/3P778C~1.INS/TIC200~1.INS/ti-cgt-c2000_16.9.2.LTS/include/assert.h F2837xD_PieCtrl.obj: C:/PROGRA~3/MATLAB/SUPPOR~1/R2018a/3P778C~1.INS/TIC200~1.INS/ti-cgt-c2000_16.9.2.LTS/include/linkage.h F2837xD_PieCtrl.obj: C:/PROGRA~3/MATLAB/SUPPOR~1/R2018a/3P778C~1.INS/TIC200~1.INS/ti-cgt-c2000_16.9.2.LTS/include/stdarg.h F2837xD_PieCtrl.obj: C:/PROGRA~3/MATLAB/SUPPOR~1/R2018a/3P778C~1.INS/TIC200~1.INS/ti-cgt-c2000_16.9.2.LTS/include/stdbool.h F2837xD_PieCtrl.obj: C:/PROGRA~3/MATLAB/SUPPOR~1/R2018a/3P778C~1.INS/TIC200~1.INS/ti-cgt-c2000_16.9.2.LTS/include/stddef.h F2837xD_PieCtrl.obj: C:/PROGRA~3/MATLAB/SUPPOR~1/R2018a/3P778C~1.INS/TIC200~1.INS/ti-cgt-c2000_16.9.2.LTS/include/stdint.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_adc.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_analogsubsys.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_cla.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_cmpss.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_cputimer.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_dac.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_dcsm.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_dma.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_ecap.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_emif.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_epwm.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_epwm_xbar.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_eqep.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_flash.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_gpio.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_i2c.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_input_xbar.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_ipc.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_mcbsp.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_memconfig.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_nmiintrupt.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_output_xbar.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_piectrl.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_pievect.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_sci.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_sdfm.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_spi.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_sysctrl.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_upp.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_xbar.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_xint.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_Examples.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_GlobalPrototypes.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_cputimervars.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_Cla_defines.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_EPwm_defines.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_Adc_defines.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_Emif_defines.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_Gpio_defines.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_I2c_defines.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_Ipc_defines.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_Pie_defines.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_Dma_defines.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_SysCtrl_defines.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_Upp_defines.h F2837xD_PieCtrl.obj: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_defaultisr.h C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/source/F2837xD_PieCtrl.c: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_device.h: C:/PROGRA~3/MATLAB/SUPPOR~1/R2018a/3P778C~1.INS/TIC200~1.INS/ti-cgt-c2000_16.9.2.LTS/include/assert.h: C:/PROGRA~3/MATLAB/SUPPOR~1/R2018a/3P778C~1.INS/TIC200~1.INS/ti-cgt-c2000_16.9.2.LTS/include/linkage.h: C:/PROGRA~3/MATLAB/SUPPOR~1/R2018a/3P778C~1.INS/TIC200~1.INS/ti-cgt-c2000_16.9.2.LTS/include/stdarg.h: C:/PROGRA~3/MATLAB/SUPPOR~1/R2018a/3P778C~1.INS/TIC200~1.INS/ti-cgt-c2000_16.9.2.LTS/include/stdbool.h: C:/PROGRA~3/MATLAB/SUPPOR~1/R2018a/3P778C~1.INS/TIC200~1.INS/ti-cgt-c2000_16.9.2.LTS/include/stddef.h: C:/PROGRA~3/MATLAB/SUPPOR~1/R2018a/3P778C~1.INS/TIC200~1.INS/ti-cgt-c2000_16.9.2.LTS/include/stdint.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_adc.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_analogsubsys.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_cla.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_cmpss.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_cputimer.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_dac.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_dcsm.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_dma.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_ecap.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_emif.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_epwm.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_epwm_xbar.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_eqep.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_flash.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_gpio.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_i2c.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_input_xbar.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_ipc.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_mcbsp.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_memconfig.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_nmiintrupt.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_output_xbar.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_piectrl.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_pievect.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_sci.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_sdfm.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_spi.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_sysctrl.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_upp.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_xbar.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_headers/include/F2837xD_xint.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_Examples.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_GlobalPrototypes.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_cputimervars.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_Cla_defines.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_EPwm_defines.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_Adc_defines.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_Emif_defines.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_Gpio_defines.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_I2c_defines.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_Ipc_defines.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_Pie_defines.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_Dma_defines.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_SysCtrl_defines.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_Upp_defines.h: C:/TI/controlSUITE/device_support/F2837xD/v190/F2837xD_common/include/F2837xD_defaultisr.h:
D
/Users/GMoran/Desktop/ClassicPlayer/DerivedData/ClassicPlayer/Build/Intermediates/ClassicPlayer.build/Debug-iphonesimulator/ClassicPlayer.build/Objects-normal/x86_64/PlaylistsMenuVC.o : /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/NowPlayingVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/AboutScreenVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/SettingsVC.swift /Users/GMoran/Desktop/ClassicPlayer/AboutVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/MusicMenuVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/MainMenuVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/AlbumsMenuVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/PlaylistsMenuVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/ArtistsMenuVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/SongListMenuVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/Array+Shuffle.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/AppDelegate.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/C2AClickWheel.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/ImageTableCell.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/SettingsTableCell.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/MenuTableCell.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/ViewController.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/SettingsScreenViewController.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/StatusBarViewController.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/AVFoundation.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/MediaPlayer.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreText.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/AudioToolbox.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/CoreMedia.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/AVFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreAudio.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/GMoran/Desktop/ClassicPlayer/DerivedData/ClassicPlayer/Build/Intermediates/ClassicPlayer.build/Debug-iphonesimulator/ClassicPlayer.build/Objects-normal/x86_64/PlaylistsMenuVC~partial.swiftmodule : /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/NowPlayingVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/AboutScreenVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/SettingsVC.swift /Users/GMoran/Desktop/ClassicPlayer/AboutVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/MusicMenuVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/MainMenuVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/AlbumsMenuVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/PlaylistsMenuVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/ArtistsMenuVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/SongListMenuVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/Array+Shuffle.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/AppDelegate.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/C2AClickWheel.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/ImageTableCell.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/SettingsTableCell.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/MenuTableCell.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/ViewController.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/SettingsScreenViewController.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/StatusBarViewController.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/AVFoundation.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/MediaPlayer.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreText.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/AudioToolbox.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/CoreMedia.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/AVFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreAudio.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/GMoran/Desktop/ClassicPlayer/DerivedData/ClassicPlayer/Build/Intermediates/ClassicPlayer.build/Debug-iphonesimulator/ClassicPlayer.build/Objects-normal/x86_64/PlaylistsMenuVC~partial.swiftdoc : /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/NowPlayingVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/AboutScreenVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/SettingsVC.swift /Users/GMoran/Desktop/ClassicPlayer/AboutVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/MusicMenuVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/MainMenuVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/AlbumsMenuVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/PlaylistsMenuVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/ArtistsMenuVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/SongListMenuVC.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/Array+Shuffle.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/AppDelegate.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/C2AClickWheel.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/ImageTableCell.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/SettingsTableCell.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/MenuTableCell.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/ViewController.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/SettingsScreenViewController.swift /Users/GMoran/Desktop/ClassicPlayer/ClassicPlayer/StatusBarViewController.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/AVFoundation.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/MediaPlayer.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreText.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/AudioToolbox.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/CoreMedia.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/AVFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreAudio.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
/** License: Boost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Authors: Alexandru Ermicioi **/ module aermicioi.aedi.container.container; import aermicioi.aedi.factory.factory; import aermicioi.aedi.storage.locator; import aermicioi.aedi.storage.storage; import aermicioi.aedi.storage.alias_aware; /** Interface for objects that instantiate and manage the lifetime of objects in it. **/ interface Container : Locator!(Object, string) { public { /** Sets up the internal state of container. Sets up the internal state of container (Ex, for singleton container it will spawn all objects that locator contains). **/ Container instantiate(); } } /** Buildable/configurable instantiatiator with factories, and aliasing. **/ interface ConfigurableContainer : Container, Storage!(Factory, string), AliasAware!(string) { }
D
module dlangui.platforms.windows.winapp; version (Windows) { import core.runtime; import win32.windows; import std.string; import std.utf; import std.stdio; import std.algorithm; import std.file; import dlangui.platforms.common.platform; import dlangui.platforms.windows.win32fonts; import dlangui.platforms.windows.win32drawbuf; import dlangui.widgets.styles; import dlangui.widgets.widget; import dlangui.graphics.drawbuf; import dlangui.graphics.images; import dlangui.graphics.fonts; import dlangui.core.logger; version (USE_OPENGL) { import dlangui.graphics.glsupport; } pragma(lib, "gdi32.lib"); pragma(lib, "user32.lib"); pragma(lib, "libpng15.lib"); /// this function should be defined in user application! extern (C) int UIAppMain(string[] args); immutable WIN_CLASS_NAME = "DLANGUI_APP"; __gshared HINSTANCE _hInstance; __gshared int _cmdShow; version (USE_OPENGL) { bool setupPixelFormat(HDC hDC) { PIXELFORMATDESCRIPTOR pfd = { PIXELFORMATDESCRIPTOR.sizeof, /* size */ 1, /* version */ PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER, /* support double-buffering */ PFD_TYPE_RGBA, /* color type */ 16, /* prefered color depth */ 0, 0, 0, 0, 0, 0, /* color bits (ignored) */ 0, /* no alpha buffer */ 0, /* alpha bits (ignored) */ 0, /* no accumulation buffer */ 0, 0, 0, 0, /* accum bits (ignored) */ 16, /* depth buffer */ 0, /* no stencil buffer */ 0, /* no auxiliary buffers */ 0, /* main layer PFD_MAIN_PLANE */ 0, /* reserved */ 0, 0, 0, /* no layer, visible, damage masks */ }; int pixelFormat; pixelFormat = ChoosePixelFormat(hDC, &pfd); if (pixelFormat == 0) { Log.e("ChoosePixelFormat failed."); return false; } if (SetPixelFormat(hDC, pixelFormat, &pfd) != TRUE) { Log.e("SetPixelFormat failed."); return false; } return true; } HPALETTE setupPalette(HDC hDC) { import core.stdc.stdlib; HPALETTE hPalette = NULL; int pixelFormat = GetPixelFormat(hDC); PIXELFORMATDESCRIPTOR pfd; LOGPALETTE* pPal; int paletteSize; DescribePixelFormat(hDC, pixelFormat, PIXELFORMATDESCRIPTOR.sizeof, &pfd); if (pfd.dwFlags & PFD_NEED_PALETTE) { paletteSize = 1 << pfd.cColorBits; } else { return null; } pPal = cast(LOGPALETTE*) malloc(LOGPALETTE.sizeof + paletteSize * PALETTEENTRY.sizeof); pPal.palVersion = 0x300; pPal.palNumEntries = cast(ushort)paletteSize; /* build a simple RGB color palette */ { int redMask = (1 << pfd.cRedBits) - 1; int greenMask = (1 << pfd.cGreenBits) - 1; int blueMask = (1 << pfd.cBlueBits) - 1; int i; for (i=0; i<paletteSize; ++i) { pPal.palPalEntry[i].peRed = cast(ubyte)( (((i >> pfd.cRedShift) & redMask) * 255) / redMask); pPal.palPalEntry[i].peGreen = cast(ubyte)( (((i >> pfd.cGreenShift) & greenMask) * 255) / greenMask); pPal.palPalEntry[i].peBlue = cast(ubyte)( (((i >> pfd.cBlueShift) & blueMask) * 255) / blueMask); pPal.palPalEntry[i].peFlags = 0; } } hPalette = CreatePalette(pPal); free(pPal); if (hPalette) { SelectPalette(hDC, hPalette, FALSE); RealizePalette(hDC); } return hPalette; } private __gshared bool DERELICT_GL3_RELOADED = false; } class Win32Window : Window { Win32Platform _platform; HWND _hwnd; version (USE_OPENGL) { HGLRC _hGLRC; // opengl context HPALETTE _hPalette; } string _caption; Win32ColorDrawBuf _drawbuf; bool useOpengl; this(Win32Platform platform, string windowCaption, Window parent) { _platform = platform; _caption = windowCaption; _hwnd = CreateWindow(toUTF16z(WIN_CLASS_NAME), // window class name toUTF16z(windowCaption), // window caption WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, // window style CW_USEDEFAULT, // initial x position CW_USEDEFAULT, // initial y position CW_USEDEFAULT, // initial x size CW_USEDEFAULT, // initial y size null, // parent window handle null, // window menu handle _hInstance, // program instance handle cast(void*)this); // creation parameters version (USE_OPENGL) { import derelict.opengl3.wgl; /* initialize OpenGL rendering */ HDC hDC = GetDC(_hwnd); if (!DERELICT_GL3_RELOADED || openglEnabled) { if (setupPixelFormat(hDC)) { _hPalette = setupPalette(hDC); _hGLRC = wglCreateContext(hDC); if (_hGLRC) { wglMakeCurrent(hDC, _hGLRC); if (!DERELICT_GL3_RELOADED) { // run this code only once DERELICT_GL3_RELOADED = true; try { import derelict.opengl3.gl3; DerelictGL3.reload(); // successful if (initShaders()) { setOpenglEnabled(); useOpengl = true; } else { Log.e("Failed to compile shaders"); } } catch (Exception e) { Log.e("Derelict exception", e); } } else { if (initShaders()) { setOpenglEnabled(); useOpengl = true; } else { Log.e("Failed to compile shaders"); } } } } else { Log.e("Pixelformat failed"); // disable GL DERELICT_GL3_RELOADED = true; } } } } version (USE_OPENGL) { private void paintUsingOpenGL() { // hack to stop infinite WM_PAINT loop PAINTSTRUCT ps; HDC hdc2 = BeginPaint(_hwnd, &ps); EndPaint(_hwnd, &ps); import derelict.opengl3.gl3; import derelict.opengl3.wgl; import dlangui.graphics.gldrawbuf; //Log.d("onPaint() start drawing opengl viewport: ", _dx, "x", _dy); //PAINTSTRUCT ps; //HDC hdc = BeginPaint(_hwnd, &ps); //scope(exit) EndPaint(_hwnd, &ps); HDC hdc = GetDC(_hwnd); wglMakeCurrent(hdc, _hGLRC); glDisable(GL_DEPTH_TEST); glViewport(0, 0, _dx, _dy); float a = 1.0f; float r = ((_backgroundColor >> 16) & 255) / 255.0f; float g = ((_backgroundColor >> 8) & 255) / 255.0f; float b = ((_backgroundColor >> 0) & 255) / 255.0f; glClearColor(r, g, b, a); glClear(GL_COLOR_BUFFER_BIT); GLDrawBuf buf = new GLDrawBuf(_dx, _dy, false); buf.beforeDrawing(); static if (false) { // for testing for render buf.fillRect(Rect(100, 100, 200, 200), 0x704020); buf.fillRect(Rect(40, 70, 100, 120), 0x000000); buf.fillRect(Rect(80, 80, 150, 150), 0x80008000); // green drawableCache.get("exit").drawTo(buf, Rect(300, 100, 364, 164)); drawableCache.get("btn_default_pressed").drawTo(buf, Rect(300, 200, 564, 264)); drawableCache.get("btn_default_normal").drawTo(buf, Rect(300, 0, 400, 50)); drawableCache.get("btn_default_selected").drawTo(buf, Rect(0, 0, 100, 50)); FontRef fnt = currentTheme.font; fnt.drawText(buf, 40, 40, "Some Text 1234567890 !@#$^*", 0x80FF0000); } else { onDraw(buf); } buf.afterDrawing(); SwapBuffers(hdc); wglMakeCurrent(hdc, null); } } ~this() { Log.d("Window destructor"); version (USE_OPENGL) { import derelict.opengl3.wgl; if (_hGLRC) { uninitShaders(); wglMakeCurrent (null, null) ; wglDeleteContext(_hGLRC); _hGLRC = null; } } if (_hwnd) DestroyWindow(_hwnd); _hwnd = null; } Win32ColorDrawBuf getDrawBuf() { //RECT rect; //GetClientRect(_hwnd, &rect); //int dx = rect.right - rect.left; //int dy = rect.bottom - rect.top; if (_drawbuf is null) _drawbuf = new Win32ColorDrawBuf(_dx, _dy); else _drawbuf.resize(_dx, _dy); return _drawbuf; } override void show() { ShowWindow(_hwnd, _cmdShow); UpdateWindow(_hwnd); } override @property string windowCaption() { return _caption; } override @property void windowCaption(string caption) { _caption = caption; SetWindowTextW(_hwnd, toUTF16z(_caption)); } void onCreate() { Log.d("Window onCreate"); _platform.onWindowCreated(_hwnd, this); } void onDestroy() { Log.d("Window onDestroy"); _platform.onWindowDestroyed(_hwnd, this); } private void paintUsingGDI() { PAINTSTRUCT ps; HDC hdc = BeginPaint(_hwnd, &ps); scope(exit) EndPaint(_hwnd, &ps); Win32ColorDrawBuf buf = getDrawBuf(); buf.fill(_backgroundColor); onDraw(buf); buf.drawTo(hdc, 0, 0); } void onPaint() { Log.d("onPaint()"); long paintStart = currentTimeMillis; version (USE_OPENGL) { if (useOpengl && _hGLRC) { paintUsingOpenGL(); } else { paintUsingGDI(); } } else { paintUsingGDI(); } long paintEnd = currentTimeMillis; Log.d("WM_PAINT handling took ", paintEnd - paintStart, " ms"); } protected ButtonDetails _lbutton; protected ButtonDetails _mbutton; protected ButtonDetails _rbutton; private bool _mouseTracking; private bool onMouse(uint message, uint flags, short x, short y) { //Log.d("Win32 Mouse Message ", message, " flags=", flags, " x=", x, " y=", y); MouseButton button = MouseButton.None; MouseAction action = MouseAction.ButtonDown; ButtonDetails * pbuttonDetails = null; short wheelDelta = 0; switch (message) { case WM_MOUSEMOVE: action = MouseAction.Move; break; case WM_LBUTTONDOWN: action = MouseAction.ButtonDown; button = MouseButton.Left; pbuttonDetails = &_lbutton; break; case WM_RBUTTONDOWN: action = MouseAction.ButtonDown; button = MouseButton.Right; pbuttonDetails = &_rbutton; break; case WM_MBUTTONDOWN: action = MouseAction.ButtonDown; button = MouseButton.Middle; pbuttonDetails = &_mbutton; break; case WM_LBUTTONUP: action = MouseAction.ButtonUp; button = MouseButton.Left; pbuttonDetails = &_lbutton; break; case WM_RBUTTONUP: action = MouseAction.ButtonUp; button = MouseButton.Right; pbuttonDetails = &_rbutton; break; case WM_MBUTTONUP: action = MouseAction.ButtonUp; button = MouseButton.Middle; pbuttonDetails = &_mbutton; break; case WM_MOUSELEAVE: Log.d("WM_MOUSELEAVE"); action = MouseAction.Leave; break; case WM_MOUSEWHEEL: { action = MouseAction.Wheel; wheelDelta = (cast(short)(flags >> 16)) / 120; POINT pt; pt.x = x; pt.y = y; ScreenToClient(_hwnd, &pt); x = cast(short)pt.x; y = cast(short)pt.y; } break; default: // unsupported event return false; } if (action == MouseAction.ButtonDown) { pbuttonDetails.down(x, y, cast(ushort)flags); } else if (action == MouseAction.ButtonUp) { pbuttonDetails.up(x, y, cast(ushort)flags); } if (((message == WM_MOUSELEAVE) || (x < 0 || y < 0 || x > _dx || y > _dy)) && _mouseTracking) { action = MouseAction.Leave; Log.d("WM_MOUSELEAVE - releasing capture"); _mouseTracking = false; ReleaseCapture(); } if (message != WM_MOUSELEAVE && !_mouseTracking) { if (x >=0 && y >= 0 && x < _dx && y < _dy) { Log.d("Setting capture"); _mouseTracking = true; SetCapture(_hwnd); } } MouseEvent event = new MouseEvent(action, button, cast(ushort)flags, x, y, wheelDelta); event.lbutton = _lbutton; event.rbutton = _rbutton; event.mbutton = _mbutton; bool res = dispatchMouseEvent(event); if (res) { Log.d("Calling update() after mouse event"); update(); } return res; } protected uint _keyFlags; protected void updateKeyFlags(KeyAction action, KeyFlag flag) { if (action == KeyAction.KeyDown) _keyFlags |= flag; else _keyFlags &= ~flag; } bool onKey(KeyAction action, uint keyCode, int repeatCount, dchar character = 0) { KeyEvent event; if (action == KeyAction.KeyDown || action == KeyAction.KeyUp) { switch(keyCode) { case KeyCode.SHIFT: updateKeyFlags(action, KeyFlag.Shift); break; case KeyCode.CONTROL: updateKeyFlags(action, KeyFlag.Control); break; case KeyCode.ALT: updateKeyFlags(action, KeyFlag.Alt); break; default: break; } event = new KeyEvent(action, keyCode, _keyFlags); } else if (action == KeyAction.Text && character != 0) { dchar[] text; text ~= character; event = new KeyEvent(action, 0, _keyFlags, cast(dstring)text); } bool res = false; if (event !is null) { res = dispatchKeyEvent(event); } if (res) { Log.d("Calling update() after key event"); update(); } return res; } /// request window redraw override void invalidate() { InvalidateRect(_hwnd, null, FALSE); UpdateWindow(_hwnd); } /// after drawing, call to schedule redraw if animation is active override void scheduleAnimation() { invalidate(); } } class Win32Platform : Platform { this() { } bool registerWndClass() { //MSG msg; WNDCLASS wndclass; wndclass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wndclass.lpfnWndProc = &WndProc; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = _hInstance; wndclass.hIcon = LoadIcon(null, IDI_APPLICATION); wndclass.hCursor = LoadCursor(null, IDC_ARROW); wndclass.hbrBackground = cast(HBRUSH)GetStockObject(WHITE_BRUSH); wndclass.lpszMenuName = null; wndclass.lpszClassName = toUTF16z(WIN_CLASS_NAME); if(!RegisterClass(&wndclass)) { return false; } return true; } override int enterMessageLoop() { MSG msg; while (GetMessage(&msg, null, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; } private Win32Window[ulong] _windowMap; /// add window to window map void onWindowCreated(HWND hwnd, Win32Window window) { _windowMap[cast(ulong)hwnd] = window; } /// remove window from window map, returns true if there are some more windows left in map bool onWindowDestroyed(HWND hwnd, Win32Window window) { Win32Window wnd = getWindow(hwnd); if (wnd) { _windowMap.remove(cast(ulong)hwnd); destroy(window); } return _windowMap.length > 0; } /// returns number of currently active windows @property int windowCount() { return cast(int)_windowMap.length; } /// returns window instance by HWND Win32Window getWindow(HWND hwnd) { if ((cast(ulong)hwnd) in _windowMap) return _windowMap[cast(ulong)hwnd]; return null; } override Window createWindow(string windowCaption, Window parent) { return new Win32Window(this, windowCaption, parent); } } extern(Windows) int DLANGUIWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int result; try { Runtime.initialize(); result = myWinMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow); //Runtime.terminate(); } catch (Throwable e) // catch any uncaught exceptions { MessageBox(null, toUTF16z(e.toString()), "Error", MB_OK | MB_ICONEXCLAMATION); result = 0; // failed } return result; } string[] splitCmdLine(string line) { string[] res; int start = 0; bool insideQuotes = false; for (int i = 0; i <= line.length; i++) { char ch = i < line.length ? line[i] : 0; if (ch == '\"') { if (insideQuotes) { if (i > start) res ~= line[start .. i]; start = i + 1; insideQuotes = false; } else { insideQuotes = true; start = i + 1; } } else if (!insideQuotes && (ch == ' ' || ch == '\t' || ch == 0)) { if (i > start) { res ~= line[start .. i]; } start = i + 1; } } return res; } private __gshared Win32Platform platform; int myWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int iCmdShow) { setFileLogger(std.stdio.File("ui.log", "w")); setLogLevel(LogLevel.Trace); Log.d("myWinMain()"); string basePath = exePath(); Log.i("Current executable: ", exePath()); string cmdline = fromStringz(lpCmdLine); Log.i("Command line: ", cmdline); string[] args = splitCmdLine(cmdline); Log.i("Command line params: ", args); _cmdShow = iCmdShow; _hInstance = hInstance; platform = new Win32Platform(); if (!platform.registerWndClass()) { MessageBoxA(null, "This program requires Windows NT!", "DLANGUI App".toStringz, MB_ICONERROR); return 0; } Platform.setInstance(platform); if (true) { /// testing freetype font manager import dlangui.graphics.ftfonts; import win32.shlobj; FreeTypeFontManager ftfontMan = new FreeTypeFontManager(); string fontsPath = "c:\\Windows\\Fonts\\"; static if (false) { // SHGetFolderPathW not found in shell32.lib WCHAR szPath[MAX_PATH]; const CSIDL_FLAG_NO_ALIAS = 0x1000; const CSIDL_FLAG_DONT_UNEXPAND = 0x2000; if(SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_FONTS|CSIDL_FLAG_NO_ALIAS|CSIDL_FLAG_DONT_UNEXPAND, NULL, 0, szPath.ptr))) { fontsPath = toUTF8(fromWStringz(szPath)); } } ftfontMan.registerFont(fontsPath ~ "arial.ttf", FontFamily.SansSerif, "Arial", false, FontWeight.Normal); ftfontMan.registerFont(fontsPath ~ "arialbd.ttf", FontFamily.SansSerif, "Arial", false, FontWeight.Bold); ftfontMan.registerFont(fontsPath ~ "arialbi.ttf", FontFamily.SansSerif, "Arial", true, FontWeight.Bold); ftfontMan.registerFont(fontsPath ~ "ariali.ttf", FontFamily.SansSerif, "Arial", true, FontWeight.Normal); ftfontMan.registerFont(fontsPath ~ "cour.ttf", FontFamily.MonoSpace, "Courier New", false, FontWeight.Normal); ftfontMan.registerFont(fontsPath ~ "courbd.ttf", FontFamily.MonoSpace, "Courier New", false, FontWeight.Bold); ftfontMan.registerFont(fontsPath ~ "courbi.ttf", FontFamily.MonoSpace, "Courier New", true, FontWeight.Bold); ftfontMan.registerFont(fontsPath ~ "couri.ttf", FontFamily.MonoSpace, "Courier New", true, FontWeight.Normal); ftfontMan.registerFont(fontsPath ~ "times.ttf", FontFamily.Serif, "Times New Roman", false, FontWeight.Normal); ftfontMan.registerFont(fontsPath ~ "timesbd.ttf", FontFamily.Serif, "Times New Roman", false, FontWeight.Bold); ftfontMan.registerFont(fontsPath ~ "timesbi.ttf", FontFamily.Serif, "Times New Roman", true, FontWeight.Bold); ftfontMan.registerFont(fontsPath ~ "timesi.ttf", FontFamily.Serif, "Times New Roman", true, FontWeight.Normal); FontManager.instance = ftfontMan; } // use Win32 font manager if (FontManager.instance is null) { //Win32FontManager fontMan = new Win32FontManager(); FontManager.instance = new Win32FontManager(); } currentTheme = createDefaultTheme(); version (USE_OPENGL) { import derelict.opengl3.gl3; DerelictGL3.load(); // just to check OpenGL context Log.i("Trying to setup OpenGL context"); Win32Window tmpWindow = new Win32Window(platform, "", null); destroy(tmpWindow); if (openglEnabled) Log.i("OpenGL support is enabled"); else Log.w("OpenGL support is disabled"); // process messages platform.enterMessageLoop(); } // Load versions 1.2+ and all supported ARB and EXT extensions. Log.i("Entering UIAppMain: ", args); int result = UIAppMain(args); Log.i("UIAppMain returned ", result); return result; } extern(Windows) LRESULT WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { HDC hdc; RECT rect; void * p = cast(void*)GetWindowLongPtr(hwnd, GWLP_USERDATA); Win32Window windowParam = p is null ? null : cast(Win32Window)(p); Win32Window window = platform.getWindow(hwnd); if (windowParam !is null && window !is null) assert(window is windowParam); if (window is null && windowParam !is null) { Log.e("Cannot find window in map by HWND"); } switch (message) { case WM_CREATE: { CREATESTRUCT * pcreateStruct = cast(CREATESTRUCT*)lParam; window = cast(Win32Window)pcreateStruct.lpCreateParams; void * ptr = cast(void*) window; SetWindowLongPtr(hwnd, GWLP_USERDATA, cast(LONG_PTR)ptr); window._hwnd = hwnd; window.onCreate(); } return 0; case WM_DESTROY: if (window !is null) window.onDestroy(); if (platform.windowCount == 0) PostQuitMessage(0); return 0; case WM_WINDOWPOSCHANGED: { if (window !is null) { WINDOWPOS * pos = cast(WINDOWPOS*)lParam; GetClientRect(hwnd, &rect); int dx = rect.right - rect.left; int dy = rect.bottom - rect.top; //window.onResize(pos.cx, pos.cy); window.onResize(dx, dy); InvalidateRect(hwnd, null, FALSE); } } return 0; case WM_ERASEBKGND: // processed return 1; case WM_PAINT: { if (window !is null) window.onPaint(); } return 0; // processed case WM_MOUSELEAVE: case WM_MOUSEMOVE: case WM_LBUTTONDOWN: case WM_MBUTTONDOWN: case WM_RBUTTONDOWN: case WM_LBUTTONUP: case WM_MBUTTONUP: case WM_RBUTTONUP: case WM_MOUSEWHEEL: if (window !is null) { if (window.onMouse(message, cast(uint)wParam, cast(short)(lParam & 0xFFFF), cast(short)((lParam >> 16) & 0xFFFF))) return 0; // processed } // not processed - default handling return DefWindowProc(hwnd, message, wParam, lParam); case WM_KEYDOWN: case WM_KEYUP: if (window !is null) { int repeatCount = lParam & 0xFFFF; if (window.onKey(message == WM_KEYDOWN ? KeyAction.KeyDown : KeyAction.KeyUp, wParam, repeatCount)) return 0; // processed return 0; } break; case WM_UNICHAR: if (window !is null) { int repeatCount = lParam & 0xFFFF; if (window.onKey(KeyAction.Text, wParam, repeatCount, wParam == UNICODE_NOCHAR ? 0 : wParam)) return 1; // processed return 1; } break; case WM_GETMINMAXINFO: case WM_NCCREATE: case WM_NCCALCSIZE: default: //Log.d("Unhandled message ", message); break; } return DefWindowProc(hwnd, message, wParam, lParam); } //=========================================== // end of version(Windows) //=========================================== }
D
# FIXED OSAL/osal_list.obj: C:/ti/simplelink_cc26x2_sdk_1_60_00_04_eng/source/ti/ble5stack/osal/src/common/osal_list.c OSAL/osal_list.obj: C:/ti/simplelink_cc26x2_sdk_1_60_00_04_eng/source/ti/ble5stack/osal/src/inc/osal_list.h OSAL/osal_list.obj: C:/ti/simplelink_cc26x2_sdk_1_60_00_04_eng/source/ti/ble5stack/osal/src/inc/comdef.h OSAL/osal_list.obj: C:/ti/simplelink_cc26x2_sdk_1_60_00_04_eng/source/ti/ble5stack/hal/src/target/_common/hal_types.h OSAL/osal_list.obj: C:/ti/simplelink_cc26x2_sdk_1_60_00_04_eng/source/ti/ble5stack/hal/src/target/_common/../_common/cc26xx/_hal_types.h OSAL/osal_list.obj: C:/ti/ccs730/ccsv7/tools/compiler/ti-cgt-arm_16.9.4.LTS/include/stdint.h OSAL/osal_list.obj: C:/ti/ccs730/ccsv7/tools/compiler/ti-cgt-arm_16.9.4.LTS/include/stdbool.h OSAL/osal_list.obj: C:/ti/simplelink_cc26x2_sdk_1_60_00_04_eng/source/ti/ble5stack/hal/src/inc/hal_defs.h C:/ti/simplelink_cc26x2_sdk_1_60_00_04_eng/source/ti/ble5stack/osal/src/common/osal_list.c: C:/ti/simplelink_cc26x2_sdk_1_60_00_04_eng/source/ti/ble5stack/osal/src/inc/osal_list.h: C:/ti/simplelink_cc26x2_sdk_1_60_00_04_eng/source/ti/ble5stack/osal/src/inc/comdef.h: C:/ti/simplelink_cc26x2_sdk_1_60_00_04_eng/source/ti/ble5stack/hal/src/target/_common/hal_types.h: C:/ti/simplelink_cc26x2_sdk_1_60_00_04_eng/source/ti/ble5stack/hal/src/target/_common/../_common/cc26xx/_hal_types.h: C:/ti/ccs730/ccsv7/tools/compiler/ti-cgt-arm_16.9.4.LTS/include/stdint.h: C:/ti/ccs730/ccsv7/tools/compiler/ti-cgt-arm_16.9.4.LTS/include/stdbool.h: C:/ti/simplelink_cc26x2_sdk_1_60_00_04_eng/source/ti/ble5stack/hal/src/inc/hal_defs.h:
D
module android.java.java.util.function_.BinaryOperator; public import android.java.java.util.function_.BinaryOperator_d_interface; import arsd.jni : ImportExportImpl; mixin ImportExportImpl!BinaryOperator; import import2 = android.java.java.lang.Class; import import0 = android.java.java.util.function_.BinaryOperator; import import3 = android.java.java.util.function_.BiFunction;
D
/******************************************************************************* Example turtle-based test suite for `TestedAppKind.Daemon`. Copyright: Copyright (c) 2015-2017 sociomantic labs GmbH. All rights reserved. *******************************************************************************/ module example.daemon.main; import ocean.transition; import turtle.runner.Runner; import turtle.TestCase; /******************************************************************************* Root application class which defines how tests will be run. Must inherit `TurtleRunner` to get all automation features. *******************************************************************************/ class MyTurtleRunnerTask : TurtleRunnerTask!(TestedAppKind.Daemon) { // can be used to log messages integrated with turtle verbose trace import turtle.runner.Logging; /*************************************************************************** This method can be overridden to specify additional files to copy into the test sandbox. Each element in returned array must be a struct with two fields - path relative to project root of file to copy and destination path relative to sandbox root. ***************************************************************************/ override public CopyFileEntry[] copyFiles ( ) { return [ CopyFileEntry("doc/etc/example.ini", "etc/example.ini") ]; } /*************************************************************************** This method must be overridden to define how the tested application process is to be started. ***************************************************************************/ override protected void configureTestedApplication ( out double delay, out istring[] args, out istring[istring] env ) { delay = 0.5; // wait time between starting the app and running tests args = null; // any CLI arguments env = null; // any environment variables } /*************************************************************************** The `prepare` method gets called after all filesystem preparations are finished. It can be used to start addition mock environment services that are expected by tested app or do additional manipulations with the sandbox. ***************************************************************************/ override public void prepare ( ) { log.info("Preparing environment and the sandbox"); } /*************************************************************************** This method gets called each time a test case requests that the state of the test suite environment be reset. Clean any custom state you may have in environment mocks / sandbox here. ***************************************************************************/ override public void reset ( ) { log.info("Resetting everything"); } } /******************************************************************************* If no custom CLI argument handling is needed, one can simply use base `TurtleRunner` class instantiated with your runner task type, calling its `main` method directly. Alternatively, one can also inherit from `TurtleRunner` and customize it too, but that is more advanced topic not covered in this example. *******************************************************************************/ int main ( istring[] args ) { auto name = "example"[]; auto test_package = "example.daemon"[]; auto sandbox_folder = "example-daemon"[]; auto runner = new TurtleRunner!(MyTurtleRunnerTask)(name, test_package, sandbox_folder); return runner.main(args); } /******************************************************************************* Example test case that will cause early termination upon failure because it is described as "fatal". Note that despite the fact that this test comes first in the module, it will actually be run last (as the class name suggests) because it has a lower priority value. *******************************************************************************/ class TestLast : TestCase { import ocean.core.Test; override public Description description ( ) { Description dscr; dscr.name = "Very important test"; dscr.fatal = true; dscr.priority = 0; return dscr; } override public void run ( ) { // test failure is indicated by throwing an exception // any exception class is allowed test(false, "This is expected to fail and terminate"); } } /******************************************************************************* Another example test case. This will be run first and won't cause the termination of the whole test suite on failure. Turtle will simply count such non-fatal test failures and print them in the end. *******************************************************************************/ class Test1 : TestCase { import ocean.core.Test; override public Description description ( ) { Description dscr; dscr.name = "Non-critical test"; dscr.fatal = false; dscr.priority = 1; return dscr; } override public void run ( ) { test(false, "This is expected to fail and continue"); } } /******************************************************************************* Example of multi-test that consists from multiple nested test cases that get created at runtime. This example is very artificial and only shows how this feature is processed by TurtleRunner. To see when this feature is applicable, check the documentation of `MultiTestCase` *******************************************************************************/ class Test2 : MultiTestCase { import ocean.text.convert.Format; import ocean.core.Test; static class NestedTest : TestCase { int num; this ( int num ) { this.num = num; } override public Description description ( ) { return Description(Format("Nested test #{}", this.num), false, false, 0); } override public void run ( ) { test!("==")(3, 4); } } override public Description description ( ) { Description dscr; dscr.name = "Example of test case consisting from many nested " ~ "ones (created at runtime)"; dscr.fatal = false; dscr.priority = 1; return dscr; } override TestCase[] getNestedCases ( ) { TestCase[] retval; for (int i = 1; i < 4; ++i) retval ~= new NestedTest(i); return retval; } } /******************************************************************************* Control unix socket usage example. Requires support from tested application to pass. *******************************************************************************/ class Test3 : TestCase { import ocean.core.Test; import turtle.env.ControlSocket : sendCommand; override public Description description ( ) { Description dscr; dscr.name = "Unix socket usage example"; dscr.fatal = false; dscr.priority = 1; return dscr; } override public void run ( ) { auto response = sendCommand(this, "ping", "42"); test!("==")(response, "pong 42"); } }
D
/*#D*/ // Copyright © 2012-2017, Jakob Bornecrantz. All rights reserved. // See copyright notice in src/volt/license.d (BOOST ver. 1.0). module main; import core.exception; import watt.path : getExecDir, dirSeparator, baseName, dirName; import watt.conv : toLower; import watt.io.std : error, output, writefln; import watt.io.file : exists, read, searchDir; import watt.text.string : splitLines; import watt.text.format : format; import volt.arg; import volt.errors; import volt.license; import volt.interfaces; import volt.driver; import volt.util.path; import volt.util.perf : Perf, perf; /*! * The entry point for the compiler. * * Parses args and hands them of to the driver. */ int main(string[] strArgs) { Settings settings; perf.perfInit(); scope (exit) { perf.close(); string name, file; if (settings !is null) { name = settings.outputFile; file = settings.perfOutput; } if (name is null) { name = "N/A"; } if (file !is null) { perf.print(file, name); } // Flush all output on close. error.flush(); output.flush(); } auto cmd = strArgs[0]; strArgs = strArgs[1 .. $]; settings = new Settings(cmd, getExecDir()); setDefault(settings); auto ver = new VersionSet(); auto target = new TargetInfo(); // Get a list of arguments. Arg[] args; string[] files; try { if (!handleArgs(getConfigLines(), /*#ref*/args, ver, settings)) { return 0; } if (!handleArgs(strArgs, /*#ref*/args, ver, settings)) { return 0; } filterArgs(args, /*#ref*/files, ver, settings); if (!checkArgs(files, settings)) { return 0; } } catch (Exception e) { writefln(e.msg); return 0; } settings.processConfigs(); settings.replaceMacros(); foreach (ref f; files) { f = settings.replaceEscapes(f); } auto vc = new VoltDriver(settings, ver, target, files); int ret = vc.compile(); vc.close(); return ret; } bool checkArgs(string[] files, Settings settings) { if (files.length == 0) { writefln("%s: no input files", settings.execCmd); return false; } return true; } struct ArgLooper { private: size_t mI; string[] mArgs; public: void set(string[] args) { this.mArgs = args; this.mI = 0; } string next() { if (mI >= mArgs.length) { throw new Exception("missing argument"); } return mArgs[mI++]; } string nextOrNull() { if (mI >= mArgs.length) { return null; } return mArgs[mI++]; } } bool handleArgs(string[] strArgs, ref Arg[] args, VersionSet ver, Settings settings) { ArgLooper looper; looper.set(strArgs); Arg.Conditional cond; int condPlatform; int condArch; void applyCond(Arg arg) { if (cond == Arg.Conditional.None) { return; } arg.condPlatform = condPlatform; arg.condArch = condArch; arg.cond = cond; condPlatform = 0; condArch = 0; cond = Arg.Conditional.None; } void setCondP(Platform platform) { cond |= Arg.Conditional.Platform; condPlatform |= 1 << platform; } void setCondA(Arch arch) { cond |= Arg.Conditional.Arch; condArch |= 1 << arch; } void libraryName(string name) { auto arg = new Arg(name, Arg.Kind.LibraryName); applyCond(arg); args ~= arg; } void libraryPath(string path) { auto arg = new Arg(path, Arg.Kind.LibraryPath); applyCond(arg); args ~= arg; } Arg makeArgFile(string file) { auto arg = new Arg(file, Arg.Kind.File); applyCond(arg); args ~= arg; return arg; } Arg makeArgNext(Arg.Kind kind) { auto n = looper.next(); auto arg = new Arg(n, kind); applyCond(arg); args ~= arg; return arg; } Arg makeArg(Arg.Kind kind) { auto arg = new Arg(kind); applyCond(arg); args ~= arg; return arg; } for (string arg = looper.nextOrNull(); arg !is null; arg = looper.nextOrNull()) { // Handle @file.txt arguments. if (arg.length > 0 && arg[0] == '@') { string[] lines; if (!getLinesFromFile(arg[1 .. $], /*#ref*/lines)) { writefln("can not find file \"%s\"", arg[1 .. $]); return false; } if (!handleArgs(lines, /*#ref*/args, ver, settings)) return false; continue; } switch (arg) with (Arg.Kind) { // Special cased. case "--help", "-h": return printUsage(); case "-license", "--license": return printLicense(); case "--arch": settings.arch = parseArch(looper.next()); continue; case "--platform": settings.platform = parsePlatform(looper.next(), /*#out*/settings.cRuntime); continue; case "--no-stdlib": settings.noStdLib = true; continue; // Regular args. case "-D": makeArgNext(Identifier); continue; case "-o": makeArgNext(Output); continue; case "-I": case "-lib-I", "--lib-I": makeArgNext(IncludePath); continue; case "-src-I", "--src-I": makeArgNext(SrcPath); continue; case "--import-as-src": makeArgNext(ImportAsSrc); continue; case "-L": libraryPath(looper.next()); continue; case "-l": libraryName(looper.next()); continue; case "-F": makeArgNext(FrameworkPath); continue; case "-framework", "--framework": makeArgNext(FrameworkName); continue; case "--dep": makeArgNext(Dep); continue; case "-jo": makeArgNext(JSONOutput); continue; case "-cc", "--cc": makeArgNext(CCompiler); continue; case "-Xcc", "--Xcc": makeArgNext(CCompilerArg); continue; case "-ld", "--ld": makeArgNext(LD); continue; case "-Xld", "--Xld": makeArgNext(LDArg); continue; case "-link", "--link": makeArgNext(Link); continue; case "-Xlink", "--Xlink": makeArgNext(LinkArg); continue; case "-clang", "--clang": makeArgNext(Clang); continue; case "-Xclang", "--Xclang": makeArgNext(ClangArg); continue; case "-linker", "--linker": makeArgNext(Linker); continue; case "-Xlinker", "--Xlinker": makeArgNext(LinkerArg); continue; case "-llvm-ar", "--llvm-ar": makeArgNext(LLVMAr); continue; case "-Xllvm-ar", "--Xllvm-ar": makeArgNext(LLVMArArg); continue; case "--internal-d": // Ignore. TODO: Remove. continue; case "--internal-dbg": makeArg(InternalDebug); continue; case "--internal-perf": makeArg(InternalPerf); continue; case "--internal-diff": makeArg(InternalDiff); continue; case "--perf-output": makeArgNext(PerfOutput); continue; case "-w": makeArg(Warnings); continue; case "-d", "-debug", "--debug": makeArg(Debug); continue; case "-release", "--release": makeArg(Release); continue; case "-c": makeArg(NoLink); continue; case "-E": makeArg(PreprocessOnly); continue; case "-J": makeArgNext(StringImportPath); continue; case "-emit-llvm", "--emit-llvm": makeArg(EmitLLVM); continue; case "--emit-bitcode": //warningEmitBitcode(); makeArg(EmitBitcode); continue; case "--no-backend", "-S": makeArg(CompileOnly); continue; case "--missing": makeArg(MissingDeps); continue; case "--no-catch": makeArg(InternalNoCatch); continue; case "--simple-trace": makeArg(DebugSimpleTrace); continue; case "--if-stdlib": cond |= Arg.Conditional.Std; continue; case "--if-linux": setCondP(Platform.Linux); continue; case "--if-osx": setCondP(Platform.OSX); continue; case "--if-msvc": setCondP(Platform.MSVC); continue; case "--if-mingw": setCondP(Platform.MinGW); continue; case "--if-metal": setCondP(Platform.Metal); continue; case "--if-x86": setCondA(Arch.X86); continue; case "--if-x86_64": setCondA(Arch.X86_64); continue; // Handle combined arguments. default: if (arg.length > 2) { switch (arg[0 .. 2]) { case "-l": libraryName(arg[2 .. $]); continue; case "-L": libraryPath(arg[2 .. $]); continue; default: break; } } break; } if (arg.length > 1 && arg[0] == '-') { error.writefln("Unknown argument: '%s'", arg); return false; } makeArgFile(arg); } return true; } string[] getConfigLines() { string[] lines; string file = format("%s%svolt.conf", getExecDir(), dirSeparator); getLinesFromFile(file, /*#ref*/lines); return lines; } bool getLinesFromFile(string file, ref string[] lines) { if (!exists(file)) { return false; } auto src = cast(string) read(file); foreach (line; splitLines(src)) { if (line.length > 0 && line[0] != '#') { lines ~= line; } } return true; } void setDefault(Settings settings) { // Only MinGW is supported. version (Windows) { settings.platform = Platform.MinGW; settings.cRuntime = CRuntime.MinGW; } else version (linux) { // D2 settings.platform = Platform.Linux; settings.cRuntime = CRuntime.Glibc; } else version (Linux) { // Volt settings.platform = Platform.Linux; settings.cRuntime = CRuntime.Glibc; } else version (OSX) { settings.platform = Platform.OSX; settings.cRuntime = CRuntime.Darwin; } else { static assert(false); } version (X86) { settings.arch = Arch.X86; } else version (X86_64) { settings.arch = Arch.X86_64; } else { static assert(false); } } bool printUsage() { writefln("usage: volt [options] [source files]"); writefln("\t-h,--help Print this message and quit."); writefln("\t--license Print license information and quit."); writefln("\t-o outputname Set output to outputname."); writefln("\t-I path Add a include path."); writefln("\t-L path Add a library path."); writefln("\t-l path Add a library."); writefln("\t-J path Define a path for string import to look for files."); writefln("\t-D ident Define a new version flag"); writefln("\t-w Enable warnings."); writefln("\t--debug Compile in debug mode."); writefln("\t--release Compile in release mode."); writefln("\t-c Compile only, do not link."); writefln("\t-E Only perform conditional removal (implies -S)."); version (OSX) { writefln("\t-F path Add a framework path."); writefln("\t--framework name Add a framework."); } writefln("\t--dep depfile Dependency file (in make format)."); writefln("\t--simple-trace Print the name of functions to stdout as they're run."); writefln("\t-jo Write documentation to specified JSON file."); writefln(""); writefln("\t--arch Select processer architecture: 'x86', 'x86_64', 'le32'"); writefln("\t--platform Select platform: 'mingw','linux','osx','msvc','metal'"); writefln(""); writefln("\t--cc compiler C compiler to use for linking."); writefln("\t--Xcc arg Add an argument when invoking the cc linker."); writefln("\t--ld linker LD compatible program to use for linking."); writefln("\t--Xld arg Add an argument when invoking the linker."); writefln("\t--link msvc MSVC link program to use for linking."); writefln("\t--Xlink arg Add an argument when invoking MSVC link."); writefln("\t--emit-bitcode Emit LLVM bitcode (implies -c)."); writefln("\t-S,--no-backend Stop compilation before the backend."); writefln("\t--no-catch For compiler debugging purposes."); writefln("\t--import-as-src Search usual paths for a given import (eg 'std.stdio')"); writefln("\t and behave as if that module was being compiled."); writefln(""); writefln("\t--no-stdlib Don't include any stdlib (from config or arguments)"); writefln(""); writefln("\t--if-stdlib Only apply the following argument if using stdlib."); writefln("\t--if-'platform' Only apply the following argument if platform is this."); writefln("\t--if-'arch' Only apply the following argument if arch is this."); writefln("\t (The if args are cumulative so that multiple"); writefln("\t arch & platforms or togther, like so:"); writefln("\t ('arch' || 'arch') && 'platform' && 'stdlib')"); writefln(""); writefln("\t--perf-output Enables compiler profiling and sets output file"); writefln(""); writefln("\t--internal-d Enables internal D friendlier rules."); writefln("\t--internal-dbg Enables internal debug printing."); writefln("\t--internal-perf Enables internal performance timings."); writefln("\t--internal-diff Enables internal debug diff printing."); return false; } bool printLicense() { foreach (license; licenseArray) { writefln(license); } return false; }
D
/Users/kubat/Documents/Tutorials/AdvancedNotes/Build/Intermediates/AdvancedNotes.build/Debug-iphonesimulator/AdvancedNotes.build/Objects-normal/x86_64/SummaryViewController.o : /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Paragraph+CoreDataProperties.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/Constants.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Picture+CoreDataProperties.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Summary/DetailNavController.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/Services/EditService.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Summary/View/ReminderCellView.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Master/ViewController/MasterViewController.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/Base/NSDate+ISO8601.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/Base/ANEntity.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Reminder+CoreDataProperties.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/Base/FrameTextView.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Paragraph/ParagraphViewController.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/DescendantID+CoreDataProperties.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Summary/View/PictureCellView.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/AppDelegate+DummyDataImport.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/DescendantID.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/Services/CoreDataService.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Master/View/Cell/MainTableViewCell.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Paragraph.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Tag+CoreDataProperties.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Note.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Reminder.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/Services/CoreDataStack.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/AppDelegate.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Tag.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Summary/View/SummaryCellView.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Note+CoreDataProperties.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Picture.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/Base/NSManagedObject+Utils.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Reminder/RemindersViewController.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Summary/ViewController/SummaryViewController.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Summary/View/ParagraphCellView.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/AdvancedNotes-Bridging-Header.h /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreData.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Users/kubat/Documents/Tutorials/AdvancedNotes/Build/Intermediates/AdvancedNotes.build/Debug-iphonesimulator/AdvancedNotes.build/Objects-normal/x86_64/SummaryViewController~partial.swiftmodule : /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Paragraph+CoreDataProperties.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/Constants.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Picture+CoreDataProperties.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Summary/DetailNavController.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/Services/EditService.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Summary/View/ReminderCellView.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Master/ViewController/MasterViewController.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/Base/NSDate+ISO8601.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/Base/ANEntity.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Reminder+CoreDataProperties.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/Base/FrameTextView.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Paragraph/ParagraphViewController.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/DescendantID+CoreDataProperties.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Summary/View/PictureCellView.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/AppDelegate+DummyDataImport.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/DescendantID.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/Services/CoreDataService.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Master/View/Cell/MainTableViewCell.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Paragraph.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Tag+CoreDataProperties.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Note.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Reminder.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/Services/CoreDataStack.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/AppDelegate.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Tag.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Summary/View/SummaryCellView.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Note+CoreDataProperties.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Picture.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/Base/NSManagedObject+Utils.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Reminder/RemindersViewController.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Summary/ViewController/SummaryViewController.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Summary/View/ParagraphCellView.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/AdvancedNotes-Bridging-Header.h /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreData.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Users/kubat/Documents/Tutorials/AdvancedNotes/Build/Intermediates/AdvancedNotes.build/Debug-iphonesimulator/AdvancedNotes.build/Objects-normal/x86_64/SummaryViewController~partial.swiftdoc : /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Paragraph+CoreDataProperties.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/Constants.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Picture+CoreDataProperties.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Summary/DetailNavController.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/Services/EditService.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Summary/View/ReminderCellView.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Master/ViewController/MasterViewController.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/Base/NSDate+ISO8601.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/Base/ANEntity.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Reminder+CoreDataProperties.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/Base/FrameTextView.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Paragraph/ParagraphViewController.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/DescendantID+CoreDataProperties.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Summary/View/PictureCellView.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/AppDelegate+DummyDataImport.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/DescendantID.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/Services/CoreDataService.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Master/View/Cell/MainTableViewCell.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Paragraph.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Tag+CoreDataProperties.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Note.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Reminder.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/Services/CoreDataStack.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/AppDelegate.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Tag.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Summary/View/SummaryCellView.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Note+CoreDataProperties.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/ManagedObjects/Picture.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/Base/NSManagedObject+Utils.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Reminder/RemindersViewController.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Summary/ViewController/SummaryViewController.swift /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/App/Summary/View/ParagraphCellView.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Users/kubat/Documents/Tutorials/AdvancedNotes/AdvancedNotes/AdvancedNotes-Bridging-Header.h /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreData.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule
D
<?xml version="1.0" encoding="ASCII" standalone="no"?> <di:SashWindowsMngr xmlns:di="http://www.eclipse.org/papyrus/0.7.0/sashdi" xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmi:version="2.0"> <pageList> <availablePage> <emfPageIdentifier href="VAR_23_banking-7677718841.notation#_copSALmGEeKQQp7P9cQvNQ"/> </availablePage> </pageList> <sashModel currentSelection="//@sashModel/@windows.0/@children.0"> <windows> <children xsi:type="di:TabFolder"> <children> <emfPageIdentifier href="VAR_23_banking-7677718841.notation#_copSALmGEeKQQp7P9cQvNQ"/> </children> </children> </windows> </sashModel> </di:SashWindowsMngr>
D
/** * Partially implemented D lexer. I have no plans to continue working on this. * * Example: * ---- auto source = Source(import("filename.d")); Token token; do { token = lex(source); write(token.raw); } while(token.type != Type.EOF); * ---- * LICENSE: Boost 1.0 * AUTHOR: Simen Endsjø <simendsjo@gmail.com> * */ module simendsjo.dc.lexer; // Here be dragons! import std.exception; import std.stdio; import core.vararg; import std.range, std.conv, std.ascii, std.string; import std.file; import std.traits; import std.algorithm; import std.array; enum Type : ushort { _typeNotSet, // represents an internal lexer error invalid, identifier, // basic types void_, bool_, char_, wchar_, dchar_, auto_, int8, uint8, int16, uint16, int32, uint32, int64, uint64, float32, float64, float80, enum_, struct_, union_, interface_, class_, alias_, function_, delegate_, mixin_, override_, private_, protected_, package_, public_, extern_, static_, final_, const_, immutable_, abstract_, in_, out_, inout_, ref_, lazy_, debug_, version_, deprecated_, module_, import_, if_, else_, do_, while_, for_, switch_, case_, default_, break_, continue_, with_, synchronized_, return_, goto_, throw_, try_, catch_, finally_, foreach_, foreach_reverse_, scope_, body_, invariant_, unittest_, macro_, at, pure_, nothrow_, shared_, gshared, // special tokens FILE, LINE, EOF, TIME, TIMESTAMP, DATE, VENDOR, VERSION, xor, xorAssign, pow, powAssign, shiftLeft, shiftRight, // brackets lparen, rparen, lbracket, rbracket, lcurly, rcurly, // literals boolv, int8v, uint8v, int16v, uint16v, int32v, uint32v, int64v, uint64v, float32v, float64v, float80v, char8v, char16v, char32v, stringv, wstringv, dstringv, div, divAssign, and, andAssign, and2, or, orAssign, or2, minus, minusAssign, decrement, plus, plusAssign, increment, dot, range, dot3, question, comma, colon, dollar, star, percent, hash, semicolon, tilde, // comments lineComment, blockComment, codeComment, ddocLineComment, ddocBlockComment, ddocCodeComment, assign, equals, goesTo, greater, greaterEquals, less, lessEquals, exclaim, // ! space, // ' ' tab, // \t lineFeed, // \n carriageReturn, // \r } shared(Type[string]) stringToken; shared(Type[string]) keywords; shared(string[Type]) tokenString; shared static this() { scope(exit) { stringToken = cast(shared(Type[string]))stringToken.rehash; keywords = cast(shared(Type[string]))keywords.rehash; tokenString = cast(shared(string[Type]))tokenString.rehash; } void add(string tok, Type type, bool isKeyword = false) { tokenString[type] = tok; stringToken[tok] = type; if(isKeyword) keywords[tok] = type; } add(" ", Type.space); /+ add("//", Type.lineComment); add("/*", Type.blockStartComment); add("*/", Type.blockEndComment); add("/+", Type.codeStartComment); add("+/", Type.codeEndComment); add("///", Type.ddocLineComment); add("/**", Type.ddocBlockStartComment); add("*/", Type.ddocBlockEndComment); add("/++", Type.ddocCodeStartComment); add("+/", Type.ddocCodeEndComment); +/ add(";", Type.semicolon); add("\r", Type.carriageReturn); add("\n", Type.lineFeed); add("@", Type.at); add("^", Type.xor); add("^^", Type.pow); add("^^=", Type.powAssign); add("module", Type.module_, true); add("int", Type.int32, true); add("if", Type.if_, true); add("void", Type.void_, true); add("bool", Type.bool_, true); add("char", Type.char_, true); add("wchar", Type.wchar_, true); add("dchar", Type.dchar_, true); add("auto", Type.auto_, true); add("byte", Type.int8, true); add("ubyte", Type.uint8, true); add("short", Type.int16, true); add("ushort", Type.uint16, true); add("int", Type.int32, true); add("uint", Type.uint32, true); add("long", Type.int64, true); add("ulong", Type.uint64, true); add("float", Type.float32, true); add("double", Type.float64, true); add("real", Type.float80, true); add("enum", Type.enum_, true); add("struct", Type.struct_, true); add("union", Type.union_, true); add("interface", Type.interface_, true); add("class", Type.class_, true); add("alias", Type.alias_, true); add("function", Type.function_, true); add("delegate", Type.delegate_, true); add("mixin", Type.mixin_, true); add("override", Type.override_, true); add("private", Type.private_, true); add("protected", Type.protected_, true); add("package", Type.package_, true); add("public", Type.public_, true); add("extern", Type.extern_, true); add("static", Type.static_, true); add("final", Type.final_, true); add("abstract", Type.abstract_, true); add("in", Type.in_, true); add("out", Type.out_, true); add("ref", Type.ref_, true); add("inout", Type.inout_, true); add("lazy", Type.lazy_, true); add("debug", Type.debug_, true); add("version", Type.version_, true); add("deprecated", Type.deprecated_, true); add("module", Type.module_, true); add("import", Type.import_, true); add("if", Type.if_, true); add("else", Type.else_, true); add("do", Type.do_, true); add("while", Type.while_, true); add("for", Type.for_, true); add("switch", Type.switch_, true); add("case", Type.case_, true); add("default", Type.default_, true); add("break", Type.break_, true); add("continue_", Type.continue_, true); add("with", Type.with_, true); add("synchronized", Type.synchronized_, true); add("return", Type.return_, true); add("goto", Type.goto_, true); add("throw", Type.throw_, true); add("try", Type.try_, true); add("catch", Type.catch_, true); add("finally", Type.finally_, true); add("foreach", Type.foreach_, true); add("foreach_reverse", Type.foreach_reverse_, true); add("scope", Type.scope_, true); add("body", Type.body_, true); add("invariant", Type.invariant_, true); add("macro", Type.macro_, true); add("pure", Type.pure_, true); add("nothrow", Type.nothrow_, true); add("const", Type.const_, true); add("immutable", Type.immutable_, true); add("shared", Type.shared_, true); add("__gshared", Type.gshared, true); add("__FILE__", Type.FILE, true); add("__LINE__", Type.LINE, true); add("__DATE__", Type.DATE, true); add("__TIME__", Type.TIME, true); add("__TIMESTAMP__", Type.TIMESTAMP, true); add("__VENDOR__", Type.VENDOR, true); add("__VERSION__", Type.VERSION, true); add("__EOF__", Type.EOF, true); add("unittest", Type.unittest_, true); } struct Location { private: size_t line = -1; size_t column = -1; invariant() { assert(line > 0); assert(column > 0); } } struct LocationRange { Location start; Location end; invariant() { assert(end.line >= start.line); // Can only point forward assert(end.line == start.line && end.column >= start.column); } } bool fitsIn(U, T)(T value) { return cast(U)value == value; } Type smallestTypeOf(T)(T value) { if(fitsIn!(bool)(value)) return Type.boolv; else if(fitsIn!(byte)(value)) return Type.int8v; else if(fitsIn!(ubyte)(value)) return Type.uint8v; else if(fitsIn!(short)(value)) return Type.int16v; else if(fitsIn!(ushort)(value)) return Type.uint16v; else if(fitsIn!(int)(value)) return Type.int32v; else if(fitsIn!(uint)(value)) return Type.uint32v; else if(fitsIn!(long)(value)) return Type.int64v; else if(fitsIn!(ulong)(value)) return Type.uint64v; else if(fitsIn!(float)(value)) return Type.float32v; else if(fitsIn!(double)(value)) return Type.float64v; else if(fitsIn!(real)(value)) return Type.float80v; assert(0); } template dtypeOf(Type type) { static if(type == Type.boolv) alias bool dtypeOf; else static if(type == Type.int8v) alias byte dtypeOf; else static if(type == Type.uint8v) alias ubyte dtypeOf; else static if(type == Type.int16v) alias short dtypeOf; else static if(type == Type.uint16v) alias ushort dtypeOf; else static if(type == Type.int32v) alias int dtypeOf; else static if(type == Type.uint32v) alias uint dtypeOf; else static if(type == Type.int64v) alias long dtypeOf; else static if(type == Type.uint64v) alias ulong dtypeOf; else static if(type == Type.float32v) alias float dtypeOf; else static if(type == Type.float64v) alias double dtypeOf; else static if(type == Type.char8v) alias char dtypeOf; else static if(type == Type.char16v) alias wchar dtypeOf; else static if(type == Type.char32v) alias dchar dtypeOf; else static if(type == Type.stringv) alias string dtypeOf; else static if(type == Type.wstringv) alias wstring dtypeOf; else static if(type == Type.dstringv) alias dstring dtypeOf; else static assert(0, text("Literal type '", to!string(type), "' has no matching D type")); } bool isFloatingPointLiteral(Type type) { return type == Type.float32v || type == Type.float64v || type == Type.float80v; } bool isFloatingPointType(Type type) { return type == Type.float32 || type == Type.float64 || type == Type.float80; } bool isSignedIntegerType(Type type) { return type == Type.int8 || type == Type.int16 || type == Type.int32 || type == Type.int64; } bool isUnsignedIntegerType(Type type) { return type == Type.uint8 || type == Type.uint16 || type == Type.uint32 || type == Type.uint64; } bool isIntegralType(Type type) { return type.isSignedIntegerType() || type.isUnsignedIntegerType(); } bool isSignedIntegerLiteral(Type type) { return type == Type.int8v || type == Type.int16v || type == Type.int32v || type == Type.int64v; } bool isUnsignedIntegerLiteral(Type type) { return type == Type.uint8v || type == Type.uint16v || type == Type.uint32v || type == Type.uint64v; } bool isIntegerLiteral(Type type) { return type.isSignedIntegerLiteral() || type.isUnsignedIntegerLiteral(); } bool isCharType(Type type) { return type == Type.char_ || type == Type.wchar_ || type == Type.dchar_; } bool isCharLiteral(Type type) { return type == Type.char8v || type == Type.char16v || type == Type.char32v; } bool isDBuiltinType(Type type) { return type == Type.bool_ || type.isIntegralType() || type.isFloatingPointType() || type.isIntegralType(); } bool isWhitespace(Type type) { return type == Type.space || type == Type.tab; } template tokenTypeOf(T) { static if(is(T == bool)) enum tokenTypeOf = Type.boolv; else static if(is(T == byte)) enum tokenTypeOf = Type.int8v; else static if(is(T == ubyte)) enum tokenTypeOf = Type.uint8v; else static if(is(T == short)) enum tokenTypeOf = Type.int16v; else static if(is(T == ushort)) enum tokenTypeOf = Type.uint16v; else static if(is(T == int)) enum tokenTypeOf = Type.int32v; else static if(is(T == uint)) enum tokenTypeOf = Type.uint32v; else static if(is(T == long)) enum tokenTypeOf = Type.int64v; else static if(is(T == ulong)) enum tokenTypeOf = Type.uint64v; else static if(is(T == float)) enum tokenTypeOf = Type.float32v; else static if(is(T == double)) enum tokenTypeOf = Type.float64v; else static if(is(T == real)) enum tokenTypeOf = Type.float80v; else static assert(0, "no corresponding token type"); } // Creates property for Token literal values embedding an assert // to make sure we only use the correct literal type template VPropertyString(Type type) { enum vstr = to!string(type); alias dtypeOf!type dtype; enum dtypestr = dtype.stringof; // getter enum VPropertyString = // getter dtypestr~` `~vstr~`() nothrow pure const @safe {` `assert(type == Type.`~vstr~`);` `return _`~vstr~`;}` // setter `void `~vstr~`(`~dtypestr~` value) nothrow pure @safe {` `assert(type == Type.`~vstr~`);` `_`~vstr~` = value; }`; } mixin template VProperty(Type type) { enum vstr = to!string(type); alias dtypeOf!type dtype; enum dtypestr = dtype.stringof; @property { mixin(VPropertyString!(type)); } } struct Token { Type type; LocationRange location; /// The raw unproccessed text as found in the source file for this location range string raw; /// A D reserved keyword bool isKeyword; // values (literal) union { bool _boolv; byte _int8v; ubyte _uint8v; short _int16v; ushort _uint16v; int _int32v; uint _uint32v; long _int64v; ulong _uint64v; float _float32v; double _float64v; char _char8v; wchar _char16v; dchar _char32v; string _stringv; wstring _wstringv; dstring _dstringv; } mixin VProperty!(Type.boolv); mixin VProperty!(Type.int8v); mixin VProperty!(Type.uint8v); mixin VProperty!(Type.int16v); mixin VProperty!(Type.uint16v); mixin VProperty!(Type.int32v); mixin VProperty!(Type.uint32v); mixin VProperty!(Type.int64v); mixin VProperty!(Type.uint64v); mixin VProperty!(Type.float32v); mixin VProperty!(Type.float64v); mixin VProperty!(Type.char8v); mixin VProperty!(Type.char16v); mixin VProperty!(Type.char32v); mixin VProperty!(Type.stringv); mixin VProperty!(Type.wstringv); mixin VProperty!(Type.dstringv); void setValue(Type type, T = dtypeOf!type)(T value) nothrow pure @safe { this.type = type; // This is a hack as we cannot have to! in a pure function even if it's only evaluated at compile time enum vstr = stringOf!type; mixin(vstr~` = cast(typeof(`~vstr~`))value;`); mixin(`assert(`~vstr~` == value);`); } void setValue(T)(T value) nothrow pure @safe { setValue!(tokenTypeOf!T)(value); } } // DMD bug 6169 - pull 652 // This is a hack as we cannot have to! in a pure function even if it's only evaluated at compile time template stringOf(alias value) { enum stringOf = to!string(value); } enum IssueType { debug_, trace, info, hint, warning, error, fatal, } struct Issue { IssueType type; LocationRange location; string message; string file; size_t line; this(IssueType type, LocationRange location, string message, string file = __FILE__, size_t line = __LINE__) pure nothrow @safe { this.type = type; this.location = location; this.message = message; this.file = file; this.line = line; } } enum SourceContext { code, ddoc } struct Source { private: string source; string rest; Location location; size_t pos; Issue[] issues; SourceContext context = SourceContext.code; public: this(string source) pure nothrow @safe { this(source, Location(1, 1)); } this(string source, Location location) pure nothrow @safe { this(source, location, 0); } this(string source, Location location, size_t pos) const pure @safe { this.source = source; this.location = location; this.pos = 0; this.rest = source[pos .. $]; } bool matches(string txt) const pure nothrow @safe { for(size_t i; i < txt.length; i++) if(peekN(i) != txt[i]) return false; return true; } bool matchesAny(Args ...)(Args txts) const pure nothrow @safe { foreach(txt; txts) if(matches(txt)) return true; return false; } @property bool isEOF() const pure nothrow @safe { return empty || matchesAny("\0", "\x1A"); // FIXME: is this correct? what if it's in a string or comment? } @property bool isNewline() const nothrow pure @safe { return matches("\r\n") || matches("\n"); } @property bool isEOL() const nothrow pure @safe { return isEOF || isNewline; } void consumeAny(Args ...)(Args txts) pure @safe in { assert(matchesAny(txts)); } body { foreach(txt; txts) { if(consumeIfMatch(txt)) return; } assert(0, "no texts exist to consume"); } void consume(string txt) pure @safe in { assert(matches(txt)); } body { for(int i; i < txt.length; i++) { assert(front == txt[i]); popFront(); } } bool consumeIfMatch(string txt) pure @safe { if(matches(txt)) { consume(txt); return true; } return false; } bool consumeIfMatchAny(Args ...)(Args txts) { foreach(txt; txts) { if(consumeIfMatch(txt)) return true; } return false; } string sliceFrom(Source marked) const pure nothrow @safe in { assert(source == marked.source, "cannot select from Source - not the same source"); assert(pos >= marked.pos); assert(pos <= source.length); } body { return source[marked.pos .. pos]; } dchar peek() const pure nothrow @safe { return peekN(1); } dchar peek2() const pure nothrow @safe { return peekN(2); } dchar peekN(size_t n) const pure nothrow @safe in { assert(n >= 0); } body { if(pos+n >= source.length) return '\0'; else return source[pos+n]; // TODO: decode?! } // cannot be const as don't take a copy of issues Source mark() pure @safe { auto result = Source(source, location); result.pos = pos; result.rest = rest; result.issues = issues; return result; } void popFront() pure @safe in { assert(!rest.empty, "cannot popFront on empty source"); } body { switch(rest.front) { case '\n': location.line++; goto case; // reset column on nix/bsd case '\r': location.column = 1; break; default: location.column++; break; } rest.popFront(); ++pos; } @property dchar front() const pure @safe { if(pos >= source.length) return '\0'; return rest.front; } /** * Returns true if the entire source text has been iterated. This does not * check for any EOF markers in the codeComment * */ @property bool empty() const pure nothrow @safe { // empty(T)(T[]) might throw, so we'll roll our own to use nothrow return rest.length == 0; } void error(string message, string file = __FILE__, size_t line = __LINE__) pure nothrow @safe { error(this.location, message, file, line); } void error(Location location, string message, string file = __FILE__, size_t line = __LINE__) pure nothrow @safe { error(LocationRange(this.location, location), message, file, line); } void error(LocationRange location, string message, string file = __FILE__, size_t line = __LINE__) pure nothrow @safe { issues ~= Issue(IssueType.error, location, message, file, line); } const pure nothrow @safe invariant() { assert(pos >= 0, "position cannot be negative"); assert(pos <= source.length, "internal position exceeds source length"); } } dtypeOf!(type) convToNumber(Type type)(string num) { return to!(dtypeOf!(type))(num); } void lexHexLiteral(ref Source source, ref Token token, int num=0) @trusted in { assert(num >= 0, "cannot lex a negative amount of hex literals"); assert(num%2 == 0, "hex literals comes in pairs"); } body { auto start = source.mark(); Location location = token.location.start = token.location.end = source.location; ulong value; int numParsed; // number of parsed characters bool success; while(true) { assert(!source.isEOF, "source empty while lexing hex literal"); location.column++; if(source.front == '_') { if(numParsed == 0) { source.error(location, "Hex literals cannot start with underscore."); token.type = Type.invalid; break; } else if(numParsed%2 != 0) { source.error(location, format("An underscore can only be used between groups of two hex characters.")); token.type = Type.invalid; break; } else if(source.peek() == '\0') { source.error(location, "A hex literal cannot end in an underscore."); token.type = Type.invalid; break; } else if(numParsed%2 != 0 && !isHexDigit(source.front)) { source.error(location, format("Expected hex character, got '%s'.", source.front)); token.type = Type.invalid; break; } else { source.popFront(); continue; } assert(0, "_ is front, but no condition is met!"); } else if(!source.front.isHexDigit()) { source.error(location, format("Expected hex character, got '%s'.", source.front)); token.type = Type.invalid; break; } // Add hex value - Stolen from the dmd frontend assert(source.front.isHexDigit()); auto ch = source.front; if(isDigit(ch)) ch -= '0'; else if(isLower(ch)) ch -= ('a' - 10); else ch -= ('A' - 10); assert(cast(ubyte)ch >= 0 && cast(ubyte)ch <= 16); value = (value*16) + cast(ubyte)ch; ++numParsed; source.popFront(); // Are we done or cannot proceed? bool finished = (numParsed >= num && num > 0) || (!source.isEOF && numParsed%2 == 0 && num == 0 && !source.front.isHexDigit()); if(finished) { //TODO: peek to see if the next character is hex or _ - illegal! success = true; break; } else if(source.isEOF) { if(numParsed%2 != 0) { token.type = Type.invalid; source.error(location, "Expected hex character, got EOF."); } success = true; break; } } // Set value on token bool validData = numParsed > 0 && numParsed%2 == 0; if(success && validData) { if(numParsed <= 2) token.setValue!(Type.uint8v)(value); else if(numParsed <= 4) token.setValue!(Type.uint16v)(value); else if(numParsed <= 8) token.setValue!(Type.uint32v)(value); else if(numParsed <= 16) token.setValue!(Type.uint64v)(value); else assert(0, text("numParsed == ", numParsed)); } // Enough hex digits according to type? bool tooFew = num > 0 && numParsed < num; if(tooFew) { switch(num) { case 0: break; case 2: source.error(text(`\x hex escape needs 2 hex characters, got `, numParsed, ".")); token.type = Type.invalid; break; case 4: source.error(text(`\u hex escape needs 4 hex characters, got `, numParsed, ".")); token.type = Type.invalid; break; case 8: source.error(text(`\U hex escape needs 8 hex characters, got `, numParsed, ".")); token.type = Type.invalid; break; default: assert(0, text("num = ", num)); } } } void lexHexEscape(ref Source source, ref Token token) in { assert(source.matchesAny("x", "u", "U")); } body { int ndigits; switch(source.front) { case 'x': ndigits = 2; goto Lhex; case 'u': ndigits = 4; goto Lhex; case 'U': ndigits = 8; goto Lhex; Lhex: assert(ndigits > 0 && ndigits%2 == 0); source.popFront(); source.lexHexLiteral(token, ndigits); break; default: assert(0, "Invalid hex escape start"); } } void lexEscape(ref Source source, ref Token token) in { assert(source.front == '\\'); } out { assert(token.type == Type.char8v || token.type == Type.invalid); } body { char ch = '!'; source.popFront(); // \ switch(source.front) { // FIXME: What about octal digits? // FIXME: What about named character entities? // FIXME: What about 0x1A and EOF? case 'x': case 'u': case 'U': source.lexHexEscape(token); // lexHexEscape sets the type as integer, so we need to change the type token.type = Type.char8v; assert(cast(char)token.int8v == token.char8v); break; case '\'': ch = '\''; goto LsetValue; case '"': ch = '\"'; goto LsetValue; case '?': ch = '\?'; goto LsetValue; case '\\': ch = '\\'; goto LsetValue; case 'a': ch = '\a'; goto LsetValue; case 'b': ch = '\b'; goto LsetValue; case 'f': ch = '\f'; goto LsetValue; case 'n': ch = '\n'; goto LsetValue; case 'r': ch = '\r'; goto LsetValue; case 't': ch = '\t'; goto LsetValue; case 'v': ch = '\v'; goto LsetValue; case '0': ch = '\0'; goto LsetValue; LsetValue: assert(ch != '!', "escape char not set"); token.setValue!(Type.char8v)(ch); source.popFront(); // ch break; default: assert(ch == '!', "escape char set"); source.error(text("Cannot lex character escape: invalid char escape '", source.front, "'")); token.type = Type.invalid; source.popFront(); break; } } void lexChar(ref Source source, ref Token token) in { assert(source.front == '\'', text("expected ' to start char literal, got '", source.front, "'")); } out { assert(token.type == Type.invalid || token.type == Type.char8v); } body { source.popFront(); // ' switch(source.front) { case '\\': source.lexEscape(token); break; // lexEscape should have popped case '\n': token.location.end.line++; goto case; // nix and bsd resets column too case '\r': token.location.end.column = 1; goto LPop; case '\0': goto LPop; case '\'': source.error("No character or unterminated '."); goto LPop; default: token.location.end.column++; goto LPop; LPop: source.popFront(); break; } if(source.front != '\'') { source.error(text("Expected ' to end character literal, got '", source.front, "'.")); // TODO: read to next ' or EOF? } else { token.type = Type.char8v; source.popFront(); // ' } } void lexNumber(ref Source source, ref Token token) in { assert(!source.isEOF); switch(source.front) { case '-': case '+': case '0': .. case '9': break; default: // text() is impure assert(0, "current character: '" ~ to!char(source.front) ~ "' is not a number"); } } body { auto start = source.mark(); bool neg = source.consumeIfMatch("-"); if(source.consumeIfMatchAny("0b", "0B")) { source.lexBinaryLiteral(token); } else if(source.consumeIfMatchAny("0x", "0X")) { source.lexHexLiteral(token); } else { auto consumeDigits = () { while(source.front.isDigit()) source.popFront(); }; if(source.front == '0' && source.peek() >= '0' && source.peek() <= '7') { source.error("Octal literals not supported. Use octal!()"); token.type = Type.invalid; consumeDigits(); } else { if(source.front == '.' && source.peek().isDigit() /* not UFCS */) // floating point { source.popFront(); // '.' consumeDigits(); } else // integer { consumeDigits(); } auto value = to!int(source.sliceFrom(start)); token.setValue(value); } } // Get correct type // Convert number // Set location // Update source location } bool isValidBinaryLiteral(dchar ch) { return ch == '0' || ch == '1' || ch == '_'; } void lexBinaryLiteral(ref Source source, ref Token token) in { assert(source.front.isValidBinaryLiteral()); } body { auto app = appender!(char[])(); for(; source.front.isValidBinaryLiteral(); source.popFront()) { if(source.front != '_') app.put(source.front); } auto value = to!int(app.data, 2); // FIXME: Choose smallest type token.setValue(value); } void lexWysiwygString(ref Source source, ref Token token) in { assert(source.front == 'r' || source.front == '`'); } out { // lexString should set the type as it checks for postfix assert(token.type == Type._typeNotSet || token.type == Type.invalid); } body { // find character to end literal if(source.front == 'r') { source.popFront(); if(source.front != '"') { source.error(text(`Expected '"' following 'r' wysiwyg string, got '`, source.front, "'")); token.type = Type.invalid; return; } assert(source.front == '"'); } auto end = source.front; assert(end == '"' || end == '`'); source.popFront(); // skip start character auto data = appender!(char[])(); while(source.front != end) { if(source.isEOF) { break; } else if(source.front == end) { break; } else if(source.front == '\\' && source.peek() == end) { source.popFront(); // \ assert(source.front == end); } data.put(source.front); source.popFront(); } if(source.front == end) { token.stringv = data.data.idup; source.popFront(); // skip end } else if(source.isEOF) { source.error(text("Cannot lex wysiwyg string: Expected '", end, "', got EOF.")); token.type = Type.invalid; } } void lexHexString(ref Source source, ref Token token) { assert(source.front == 'x'); source.popFront(); assert(source.front == '"'); assert(0, "not implemented"); } /* * q"IDENT * somestring * IDENT" * -> * "somestring * " // ending newline included * */ void lexIdentifierDelimitedString(ref Source source, ref Token token) in { assert(source.front.isValidIdentifierStart()); } body { // find ident auto identStart = source.mark(); source.popFront(); string ident; while(true) { if(source.isEOF) { source.error("Cannot lex delimited string:" " Expected valid identifier character, but got EOF"); token.type = Type.invalid; return; } else if(source.isNewline) { ident = source.sliceFrom(identStart); break; } else if(!source.front.isValidIdentifier()) { source.error(text("Cannot lex delimited string:" " Expected valid identifier character, but got '", source.front)); token.type = Type.invalid; return; } source.popFront(); } assert(ident && ident.length, "delimited ident not found"); assert(!source.isEOF); assert(source.isNewline, "should stop at newline or return early when error is found"); source.popFront(); // the beginning newline shouldn't be a part of the string auto start = source.mark(); // read string until ending ident is found auto identEnd = ident ~ "\""; auto nixEnd = "\n" ~ identEnd; // nix newline auto winEnd = "\r\n" ~ identEnd; // windows newline while(!(source.isEOF || source.front == '"' || source.matchesAny(winEnd, nixEnd))) source.popFront(); if(source.isEOF || source.front == '"') { source.error(text("Cannot lex delimited string: Didn't find ending \\n", ident, "\"")); token.type = Type.invalid; } else { assert(source.isNewline); source.consumeAny("\r\n", "\n"); // ending newline is part of the string token.stringv = source.sliceFrom(start); source.consume(identEnd); } } /** * Returns: true if ch is any of [, (, < or { */ bool isOpeningDelimiter(in dchar ch) pure nothrow @safe { switch(ch) { case '[': case '(': case '<': case '{': return true; default: return false; } assert(0); } /** * Returns: true if ch is any of ], ), > or } */ bool isClosingDelimiter(in dchar ch) pure nothrow @safe { switch(ch) { case ']': case ')': case '>': case '}': return true; default: return false; } assert(0); } /** * Returns: The matching opening or closing delimiter for the symbol. Ie. ch=='(' returns ')' */ dchar getMatchingDelimiter(in dchar ch) pure nothrow @safe in { assert(ch.isOpeningDelimiter() || ch.isClosingDelimiter()); } out(result) { assert(result.isOpeningDelimiter() || result.isClosingDelimiter()); } body { switch(ch) { case '[': return ']'; case '(': return ')'; case '<': return '>'; case '{': return '}'; case ']': return '['; case ')': return '('; case '>': return '<'; case '}': return '{'; default: assert(0, "not a delimiter with matching"); } assert(0); } void lexNestedDelimitedString(ref Source source, ref Token token) in { assert(source.front.isOpeningDelimiter()); } out { // lexString should set the type assert(token.type == Type._typeNotSet || token.type == Type.invalid); } body { dchar open = source.front; dchar close = open.getMatchingDelimiter(); assert(close.isClosingDelimiter()); source.popFront(); // opening delimiter auto start = source.mark(); int depth = 1; do { if(source.front == '"') { source.error(text("Unmatched '", start, "'")); token.type = Type.invalid; return; } else if(source.front == open) ++depth; else if(source.front == close) --depth; if(depth > 0) source.popFront(); // don't pop ending delimiter as we don't want it in token.stringv assert(depth >= 0); } while(depth > 0); assert(source.front == close); if(source.peek() == '"') { auto data = source.sliceFrom(start); token.stringv = data; source.popFront(); // closing delimiter source.popFront(); // " } else { source.error(text(`Cannot lex delimited string:` `Expected " following closing delimiter, but got '`, source.front, "'")); token.type = Type.invalid; } } void lexDelimitedString(ref Source source, ref Token token) in { assert(source.matches(`q"`)); } out { // lexString should set the type assert(token.type == Type._typeNotSet || token.type == Type.invalid); } body { source.consume(`q"`); if(source.front.isOpeningDelimiter()) // nested delimiter { source.lexNestedDelimitedString(token); } else if(source.front.isValidIdentifierStart()) // identifier delimiter { source.lexIdentifierDelimitedString(token); } else // some single char delimiter { auto delim = source.front; source.popFront(); // delimiter is not part of the string auto start = source.mark(); while(!(source.isEOF || source.front == delim)) source.popFront(); if(source.isEOF) { source.error(text("Cannot lex delimited string: Didnt find ending '", delim, "'\"")); token.type = Type.invalid; } else { assert(source.front == delim); token.stringv = source.sliceFrom(start); source.popFront(); // delimiter is not part of the string assert(source.front == '"'); source.popFront(); } } } void lexTokenString(ref Source source, ref Token token) in { assert(source.matches(`q{`)); } out { // lexString should set the type assert(token.type == Type._typeNotSet || token.type == Type.invalid); } body { source.consume("q{"); auto start = source.mark(); int depth = 1; do { if(source.isEOF) { source.error("Cannot lex token string: Expected token or }, got EOF"); token.type = Type.invalid; return; } else if(source.front == '{') { ++depth; } else if(source.front == '}') { --depth; } if(depth > 0) source.popFront(); // don't pop } as we don't want to include it in our token.stringv assert(depth >= 0); } while(depth > 0); assert(source.front == '}'); token.stringv = source.sliceFrom(start); source.popFront(); // token strings must be lexical valid, so let's lex the result and check for errors auto strSource = Source(token.stringv); while(lex(strSource).type != Type.EOF) {} // FIXME: Bug or spec? assert(strSource.empty, "EOF found in token string instead of at the end - is this really a bug? Or allowed according to spec?"); auto errors = strSource.issues.filter!((a) => a.type == IssueType.error)().array(); if(errors.length) // move errors over copy errors { errors.map!((e) => source.issues ~= e)(); token.type = Type.invalid; } } void lexDoubleQuotedString(ref Source source, ref Token token) in { assert(source.front == '"', text("Expected \" to start double quoted string, got '", source.front, "'")); } out { // if we successfully parse a string, // lexString should take care of setting the correct type assert(token.type == Type._typeNotSet || token.type == Type.invalid); } body { // TODO: implement copy on write for the data in case it doesn't contain any escape literals? // The appender is very slow.. auto data = appender!(char[])(); source.popFront(); // " while(!(source.isEOF || source.front == '"')) { if(source.front == '\\') { Token esc; source.lexEscape(esc); if(esc.type == Type.invalid) return; // FIXME: Try to recover? We don't know where or what failed. Could inspect issues.. assert(esc.type == Type.char8v); data.put(esc.char8v); } else { data.put(source.front); source.popFront(); } } if(source.isEOF) { source.error(`Cannot lex double quoted string: Expected character or '"', got EOF`); token.type = Type.invalid; } else { assert(source.front == '"'); source.popFront(); // " token.stringv = data.data.idup; } } void lexString(ref Source source, ref Token token) in { assert(source.matchesAny(`"`, "q", "`", "x", "r")); } out { assert(token.type == Type.invalid || token.type == Type.stringv || token.type == Type.wstringv || token.type == Type.dstringv); } body { // check for optional string postfix bool checkForPostfix = true; switch(source.front) { case '"': source.lexDoubleQuotedString(token); break; case 'q': switch(source.peek()) { case '"': source.lexDelimitedString(token); break; case '{': source.lexTokenString(token); break; default: source.error(text("Cannot lex delimited string: Expected \", ` or {, got '", source.peek(), "'.")); token.type = Type.invalid; break; } checkForPostfix = false; break; case 'x': if(source.peek() == '"') { source.lexHexString(token); } else { source.error(text(`Cannot lex hex string: Expected ", got '`, source.peek(), "'.")); token.type = Type.invalid; } break; case 'r': if(source.peek() == '"') // regular wysiwyg string { goto case; } else { source.error(text(`Cannot lex wysiwyg string: Expected ", got '`, source.peek(), "'.")); token.type = Type.invalid; break; } assert(0); case '`': source.lexWysiwygString(token); break; default: assert(0, text("Cannot lex string. Unknown string start character '", source.front, "'")); } assert(token.type == Type.invalid || token.type == Type._typeNotSet, "the sub-lexstring functions should not set the type"); if(token.type == Type.invalid) return; // optional string postfix if(!source.isEOF && checkForPostfix) { switch(source.front) { case 'w': source.popFront(); token.type = Type.wstringv; break; case 'd': source.popFront(); token.type = Type.dstringv; break; case 'c': source.popFront(); goto default; default: token.type = Type.stringv; break; } } else token.type = Type.stringv; } bool isValidIdentifierStart(dchar ch) { switch(ch) { case '_': case 'a': .. case 'z': case 'A': .. case 'Z': return true; default: return false; } assert(0, "invalid identifier start"); } bool isValidIdentifier(dchar ch) { switch(ch) { case '_': case 'a': .. case 'z': case 'A': .. case 'Z': case '0': .. case '9': return true; default: return false; } assert(0, "invalid identifier"); } bool isValidIdentifier(string ident) { if(!ident[0].isValidIdentifierStart()) return false; if(ident.length > 1) { foreach(ch; ident[1..$]) { if(!ch.isValidIdentifier()) return false; } } return true; } void lexIdentifier(ref Source source, ref Token token) in { assert(source.front.isValidIdentifierStart()); } body { auto start = source.mark(); while(source.peek().isValidIdentifier()) source.popFront(); source.popFront(); auto ident = source.sliceFrom(start); with(token) { stringv = ident; type = keywords.get(ident, Type.identifier); if(type != Type.identifier) isKeyword = true; } } void lexRegularComment(ref Source source, ref Token token) in { if(source.matchesAny("/++", "/**")) // could be ddoc assert(source.matchesAny("/++/", "/**/")); // nope - fooled! else assert(source.matchesAny("/+", "/*", "//")); } body { source.consumeAny("//", "/*", "/+"); auto start = source.mark(); if(token.type == Type.lineComment) { while(!source.isEOL) source.popFront(); token.stringv = source.sliceFrom(start); } else if(token.type == Type.blockComment) { while(!(source.isEOF || source.matches("*/"))) source.popFront(); token.stringv = source.sliceFrom(start); if(!source.consumeIfMatch("*/")) source.error(`Expected "*/", got EOF.`); } else if(token.type == Type.codeComment) { auto level = 1; while(!source.isEOF && level > 0) { if(source.matches("+/")) { --level; level > 0 && source.consume("+/"); } else if(source.consumeIfMatch("/+")) ++level; else source.popFront(); assert(level >= 0); } if(level == 0) { token.stringv = source.sliceFrom(start); source.consume("+/"); } else source.error(`Expected "+/", got EOF.`); } else assert(0); } void lexDdocComment(ref Source source, ref Token token) in { assert(!source.matchesAny("/++/", "/**/")); assert(source.matchesAny("/++", "/**", "///")); } body { // FIXME: gobble up everything for now to focus on other parts source.consumeAny("///", "/**", "/++"); auto start = source.mark(); if(token.type == Type.lineComment) { while(!source.isEOL) source.popFront(); token.stringv = source.sliceFrom(start); } else if(token.type == Type.blockComment) { while(!(source.isEOF || source.matches("*/"))) source.popFront(); token.stringv = source.sliceFrom(start); if(!source.consumeIfMatch("*/")) source.error(`Expected "*/", got EOF.`); } else if(token.type == Type.codeComment) { auto level = 1; while(!source.isEOF && level > 0) { if(source.matches("+/")) { --level; level > 0 && source.consume("+/"); } else if(source.consumeIfMatch("/+")) ++level; else source.popFront(); assert(level >= 0); } if(level == 0) { token.stringv = source.sliceFrom(start); source.consume("+/"); } else source.error(`Expected "+/", got EOF.`); } else assert(0); } void lexComment(ref Source source, ref Token token) in { assert(source.matchesAny("//", "/*", "/+")); } body { switch(source.peek()) { case '/': token.type = Type.lineComment; if(source.matches("///")) source.lexDdocComment(token); else if(source.matches("//")) source.lexRegularComment(token); else assert(0); break; case '*': token.type = Type.blockComment; if(source.matches("/**/")) source.lexRegularComment(token); else if(source.matches("/**")) source.lexDdocComment(token); else if(source.matches("/*")) source.lexRegularComment(token); else assert(0); break; case '+': token.type = Type.codeComment; if(source.matches("/++/")) source.lexRegularComment(token); else if(source.matches("/++")) source.lexDdocComment(token); else if(source.matches("/+")) source.lexRegularComment(token); else assert(0); break; default: assert(0, "invalid token identifier"); } } bool isEOF(dchar ch) { return ch == 0 || ch == 0x1A; } Token lex(ref Source source) { auto start = source.mark(); Token token; assert(token.type == Type._typeNotSet); token.location.start = token.location.end = source.location; scope(exit) { assert(token.type != Type._typeNotSet, text("Token type not set! Token: ", token)); assert(token.raw == "", text("Token raw value already set! Token: ", token)); token.location.end = source.location; token.raw = source.sliceFrom(start); } void single(Type type) { assert(token.type == Type._typeNotSet, "token.type set twice"); assert(!source.isEOF, "cannot check for single token on an empty source"); token.type = type; source.popFront(); } bool singleIf(string match, Type type) { assert(token.type == Type._typeNotSet, "token.type set twice"); assert(!source.isEOF, "cannot check for single token on an empty source"); if(source.consumeIfMatch(match)) { token.type = type; return true; } return false; } switch(source.front) { case 0: case 0x1A: token.type = Type.EOF; break; case ' ': single(Type.space); break; case '\t': single(Type.tab); break; case '\r': single(Type.carriageReturn); break; case '\n': single(Type.lineFeed); break; case '\'': source.lexChar(token); break; case '\\': source.lexEscape(token); break; case '0': .. case '9': source.lexNumber(token); break; case 'q': case 'r': case 'x': if(source.peek().isValidIdentifier()) goto Lidentifier; goto case; // it's a string case '`': case '"': source.lexString(token); break; case 'A': .. case 'Z': case 'a': .. case 'p': /*skip q and r*/ case 's': .. case 'w': /*skip x*/ case 'y': case 'z': case '_': assert(!source.matchesAny("x", "q", "r"), "string type, not an identifier"); Lidentifier: assert(source.front.isValidIdentifierStart()); source.lexIdentifier(token); break; case '/': if(source.matchesAny("//", "/*", "/+")) { source.lexComment(token); assert(source.context == SourceContext.code, text("Entire comment not lexed!: ", token)); } else { bool match = singleIf("/=", Type.divAssign) || singleIf( "/", Type.div); assert(match); } break; case '.': bool match = singleIf("...", Type.dot3) || singleIf( "..", Type.range) || singleIf( ".", Type.dot); assert(match); break; case '&': bool match = singleIf("&&", Type.and2) || singleIf("&=", Type.andAssign) || singleIf( "&", Type.and); assert(match); break; case '|': bool match = singleIf("||", Type.or2) || singleIf("|=", Type.orAssign) || singleIf( "|", Type.or); assert(match); break; case '-': if(source.peek().isDigit()) source.lexNumber(token); else { bool match = singleIf("-=", Type.minusAssign) || singleIf("--", Type.decrement) || singleIf( "-", Type.minus); assert(match); } break; case '+': bool match = singleIf("+=", Type.plusAssign) || singleIf("++", Type.increment) || singleIf( "+", Type.plus); assert(match); break; case '<': bool match = singleIf("<=", Type.lessEquals) || singleIf("<<", Type.shiftLeft) || singleIf( "<", Type.less); assert(match); break; case '>': bool match = singleIf(">=", Type.greaterEquals) || singleIf(">>", Type.shiftRight) || singleIf( ">", Type.greater); assert(match); break; case '=': bool match = singleIf("==", Type.equals) || singleIf("=>", Type.goesTo) || singleIf( "=", Type.assign); assert(match); break; case '^': bool match = singleIf("^^=", Type.powAssign) || singleIf( "^^", Type.pow) || singleIf( "^=", Type.xorAssign) || singleIf( "^", Type.xor); break; case '(': single(Type.lparen); break; case ')': single(Type.rparen); break; case '[': single(Type.lbracket); break; case ']': single(Type.rbracket); break; case '{': single(Type.lcurly); break; case '}': single(Type.rcurly); break; case '!': single(Type.exclaim); break; case '~': single(Type.tilde); break; case '?': single(Type.question); break; case ',': single(Type.comma); break; case ';': single(Type.semicolon); break; case ':': single(Type.colon); break; case '$': single(Type.dollar); break; case '@': single(Type.at); break; case '*': single(Type.star); break; case '%': single(Type.percent); break; case '#': single(Type.hash); break; default: assert(0, text("invalid character '", source.front, "'")); } return token; } // Some writer functions to better see what fails during testing version(unittest) { string[] _testName; int _testIndent = -1; @property string indent() { return rightJustify("", _testIndent*2); } @property string currentTest() { return _testName[_testIndent]; } @property void currentTest(string text) { if(_testName.length <= _testIndent) _testName ~= text; else _testName[_testIndent] = text; } void testBegin(string text) { ++_testIndent; currentTest = text; debug(Unittest) writeln("\n", indent, "*** TEST: ", currentTest, " ***"); } void testEnd() { debug(Unittest) writeln(indent, "*** DONE TEST: ", currentTest, " ***"); --_testIndent; } void testHeader(string text) { debug(Unittest) writeln("\n", indent, ">>> ", text, ":"); } void twriteln(Args ...)(Args args) { debug(Unittest) writeln(args); } } // Specialized functions to make testing and locating errors a bit simpler // linux doesn't give me line numbers in stacktraces, so use the file/line workaround version(unittest) { Source source; Token token; void lexIt(string code, string file = __FILE__, size_t line = __LINE__) { twriteln(indent, "@", file, ":", line, ": `", code, "`"); source = Source(code); token = lex(source); } void assume(string condition)(string file = __FILE__, size_t line = __LINE__) { mixin(`bool success = `~condition~`;`); if(!success) { // Cannot writeln(source) because of phobos bug http://d.puremagic.com/issues/show_bug.cgi?id=7476 writeln(indent, "FAIL: `", condition, "`\n", indent, " TOKEN: ", token, "\n", indent, " SOURCE: ", source.location, " ", source.issues, " ", source.source); assume(success, file, line); } } void assume()(bool success, string file = __FILE__, size_t line = __LINE__) { if(!success) writeln(indent, "ASSERT@", file, ":", line); assert(success); } void assumeType(string code, Type type, string file = __FILE__, size_t line = __LINE__) { lexIt(code, file, line); assumeType(type, file, line); } void assumeType(Type type, string file = __FILE__, size_t line = __LINE__) { auto success = token.type == type; if(!success) twriteln(indent(), "!!! Expected ", type, " got ", token.type); assume(token.type == type, file, line); } void assumeIssueMessage(IssueType type, string msg, string file = __FILE__, size_t line = __LINE__) { if(source.issues.length == 0) { twriteln(indent, "!!! Expected `", msg, "`, but found no issues!"); assume(false, file, line); } auto issue = source.issues[0]; if(issue.type != type) { twriteln(indent, "!!! Expected ", type, ":`", msg, "`, but found ", issue); assume(false, file, line); } if(issue.message != msg) twriteln(indent, "!!! Expected `", msg, "`, but got `", issue.message, "`: ", issue); assume(issue.message == msg, file, line); } void assumeError(string code, string msg, string file = __FILE__, size_t line = __LINE__) { lexIt(code, file, line); assumeIssueMessage(IssueType.error, msg, file, line); } } unittest { testBegin("TYPES"); testHeader("EOF"); assumeType("", Type.EOF); assumeType("\0", Type.EOF); assumeType("\x1A", Type.EOF); testHeader("Brackets"); assumeType("(", Type.lparen); assumeType(")", Type.rparen); assumeType("[", Type.lbracket); assumeType("]", Type.rbracket); assumeType("{", Type.lcurly); assumeType("}", Type.rcurly); testHeader("Equal"); assumeType("=", Type.assign); assumeType("==", Type.equals); testHeader("Whitespace"); assumeType(" ", Type.space); assumeType("\t", Type.tab); assumeType("\r", Type.carriageReturn); assumeType("\n", Type.lineFeed); testHeader("Misc"); assumeType(";", Type.semicolon); assumeType(":", Type.colon); assumeType(".", Type.dot); assumeType("..", Type.range); assumeType("...", Type.dot3); testHeader("Plus"); assumeType("+", Type.plus); assumeType("+=", Type.plusAssign); assumeType("++", Type.increment); testHeader("Minus"); assumeType("-", Type.minus); assumeType("-=", Type.minusAssign); assumeType("--", Type.decrement); testHeader("Equals"); assumeType("=", Type.assign); assumeType("=>", Type.goesTo); assumeType("==", Type.equals); testHeader("Greater"); assumeType(">", Type.greater); assumeType(">=", Type.greaterEquals); testHeader("Less"); assumeType("<", Type.less); assumeType("<=", Type.lessEquals); testHeader("Hat"); assumeType("^", Type.xor); assumeType("^^", Type.pow); assumeType("^^=", Type.powAssign); testHeader("Identifier"); assumeType("a", Type.identifier); assumeType("_a", Type.identifier); assumeType("a_", Type.identifier); assumeType("qa", Type.identifier); assumeType("xa", Type.identifier); assumeType("ra", Type.identifier); testHeader("Keywords"); assumeType("void", Type.void_); assumeType("bool", Type.bool_); assumeType("char", Type.char_); assumeType("wchar", Type.wchar_); assumeType("dchar", Type.dchar_); assumeType("auto", Type.auto_); assumeType("byte", Type.int8); assumeType("ubyte", Type.uint8); assumeType("short", Type.int16); assumeType("ushort", Type.uint16); assumeType("int", Type.int32); assumeType("uint", Type.uint32); assumeType("long", Type.int64); assumeType("ulong", Type.uint64); assumeType("float", Type.float32); assumeType("double", Type.float64); assumeType("real", Type.float80); assumeType("enum", Type.enum_); assumeType("struct", Type.struct_); assumeType("union", Type.union_); assumeType("interface", Type.interface_); assumeType("class", Type.class_); assumeType("alias", Type.alias_); assumeType("function", Type.function_); assumeType("delegate", Type.delegate_); assumeType("mixin", Type.mixin_); assumeType("override", Type.override_); assumeType("private", Type.private_); assumeType("protected", Type.protected_); assumeType("package", Type.package_); assumeType("public", Type.public_); assumeType("extern", Type.extern_); assumeType("static", Type.static_); assumeType("final", Type.final_); assumeType("const", Type.const_); assumeType("immutable", Type.immutable_); assumeType("abstract", Type.abstract_); assumeType("in", Type.in_); assumeType("out", Type.out_); assumeType("ref", Type.ref_); assumeType("inout", Type.inout_); assumeType("lazy", Type.lazy_); assumeType("debug", Type.debug_); assumeType("version", Type.version_); assumeType("deprecated", Type.deprecated_); assumeType("module", Type.module_); assumeType("import", Type.import_); assumeType("if", Type.if_); assumeType("else", Type.else_); assumeType("do", Type.do_); assumeType("while", Type.while_); assumeType("for", Type.for_); assumeType("switch", Type.switch_); assumeType("case", Type.case_); assumeType("default", Type.default_); assumeType("break", Type.break_); assumeType("continue_", Type.continue_); assumeType("with", Type.with_); assumeType("synchronized", Type.synchronized_); assumeType("return", Type.return_); assumeType("goto", Type.goto_); assumeType("throw", Type.throw_); assumeType("try", Type.try_); assumeType("catch", Type.catch_); assumeType("finally", Type.finally_); assumeType("foreach", Type.foreach_); assumeType("foreach_reverse", Type.foreach_reverse_); assumeType("scope", Type.scope_); // scope(exit), failure / success is it's own types to not use keywords!! // TODO: add scope(otherstuff) here assumeType("body", Type.body_); assumeType("invariant", Type.invariant_); assumeType("macro", Type.macro_); assumeType("pure", Type.pure_); assumeType("nothrow", Type.nothrow_); assumeType("shared", Type.shared_); assumeType("__gshared", Type.gshared); assumeType("@", Type.at); assumeType("^^", Type.pow); assumeType("^^=", Type.powAssign); assumeType("unittest", Type.unittest_); testHeader("Div"); assumeType("/", Type.div); assumeType("/=", Type.divAssign); assumeType("__FILE__", Type.FILE); assumeType("__LINE__", Type.LINE); assumeType("__TIME__", Type.TIME); assumeType("__TIMESTAMP__", Type.TIMESTAMP); assumeType("__DATE__", Type.DATE); assumeType("__VENDOR__", Type.VENDOR); assumeType("__VERSION__", Type.VERSION); testEnd(); } unittest { testBegin("CHAR ESCAPE"); lexIt(`'\''`); writeln(token.char8v); assumeType(`'\''`, Type.char8v); assume!q{token.char8v == '\''}(); assumeType(`'\"'`, Type.char8v); assume!q{token.char8v == '\"'}(); assumeType(`'\?'`, Type.char8v); assume!q{token.char8v == '\?'}(); assumeType(`'\\'`, Type.char8v); assume!q{token.char8v == '\\'}(); assumeType(`'\a'`, Type.char8v); assume!q{token.char8v == '\a'}(); assumeType(`'\b'`, Type.char8v); assume!q{token.char8v == '\b'}(); assumeType(`'\f'`, Type.char8v); assume!q{token.char8v == '\f'}(); assumeType(`'\n'`, Type.char8v); assume!q{token.char8v == '\n'}(); assumeType(`'\r'`, Type.char8v); assume!q{token.char8v == '\r'}(); assumeType(`'\t'`, Type.char8v); assume!q{token.char8v == '\t'}(); assumeType(`'\v'`, Type.char8v); assume!q{token.char8v == '\v'}(); assumeType(`'\0'`, Type.char8v); assume!q{token.char8v == '\0'}(); assumeType(`'\x00'`, Type.char8v); assume!q{token.char8v == '\x00'}(); assumeType(`'\x1A'`, Type.char8v); assume!q{token.char8v == '\x1A'}(); testEnd(); } unittest { testBegin("COMMENT"); // eof valid end assumeType("//", Type.lineComment); assume!q{source.issues.length == 0}(); assume!q{source.context == SourceContext.code}(); assume!q{token.raw == `//`}(); assume!q{token.stringv == ``}(); assumeType("//\n", Type.lineComment); assume!q{source.issues.length == 0}(); assume!q{source.context == SourceContext.code}(); assume!q{token.raw == `//`}(); assume!q{token.stringv == ``}(); assumeType("//a", Type.lineComment); assume!q{source.issues.length == 0}(); assume!q{source.context == SourceContext.code}(); assume!q{token.raw == `//a`}(); assume!q{token.stringv == `a`}(); assumeType("//a\n", Type.lineComment); assume!q{source.issues.length == 0}(); assume!q{source.context == SourceContext.code}(); assume!q{token.raw == `//a`}(); assume!q{token.stringv == `a`}(); assumeType("//comment here", Type.lineComment); assume!q{source.context == SourceContext.code}(); assume!q{token.raw == `//comment here`}(); assume!q{token.stringv == `comment here`}(); assumeType("//+", Type.lineComment); assume!q{source.issues.length == 0}(); assume!q{source.context == SourceContext.code}(); assume!q{token.raw == `//+`}(); assume!q{token.stringv == `+`}(); assumeType("//*", Type.lineComment); assume!q{source.issues.length == 0}(); assume!q{source.context == SourceContext.code}(); assume!q{token.raw == `//*`}(); assume!q{token.stringv == `*`}(); // Should be error as */ is missing assumeError("/*", `Expected "*/", got EOF.`); assumeType("/*", Type.blockComment); assume!q{source.context == SourceContext.code}(); assume!q{token.raw == "/*"}(); assume!q{token.stringv == ``}(); // Should be error as +/ is missing assumeError("/+", `Expected "+/", got EOF.`); assumeType("/+", Type.codeComment); assume!q{source.context == SourceContext.code}(); assume!q{token.raw == "/+"}(); assume!q{token.stringv == ``}(); assumeType("/*a*/", Type.blockComment); assume!q{source.issues.length == 0}(); assume!q{source.context == SourceContext.code}(); assume!q{token.raw == `/*a*/`}(); assume!q{token.stringv == "a"}(); assumeType("/**/", Type.blockComment); assume!q{source.issues.length == 0}(); assume!q{source.context == SourceContext.code}(); assume!q{token.raw == `/**/`}(); assume!q{token.stringv == ""}(); assumeType("/*some comment*/", Type.blockComment); assume!q{source.issues.length == 0}(); assume!q{source.context == SourceContext.code}(); assume!q{token.raw == `/*some comment*/`}(); assume!q{token.stringv == `some comment`}(); assumeType("/++/", Type.codeComment); assume!q{source.issues.length == 0}(); assume!q{source.context == SourceContext.code}(); assume!q{token.raw == `/++/`}(); assume!q{token.stringv == ``}(); assumeType("/+/++/+/", Type.codeComment); assume!q{source.issues.length == 0}(); assume!q{source.context == SourceContext.code}(); assume!q{token.raw == `/+/++/+/`}(); assume!q{token.stringv == `/++/`}(); testEnd(); } unittest { /+ testBegin("HEX ESCAPE"); testHeader("CORRECT"); assumeType(`\xFFFF`, Type.uint16v); assume!q{token.uint16v == 0xFF_FF}(); assumeType(`\xFF_FF`, Type.uint16v); assume!q{token.uint16v == 0xFF_FF}(); assumeType(`\xFFFFFFFF`, Type.uint16v); assume!q{token.uint16v == 0xFF_FF}(); assumeType(`\xFF_FF_FF_FF`, Type.uint16v); assume!q{token.uint16v == 0xFF_FF}(); assumeType(`\uFFFFFFFF`, Type.uint32v); assume!q{token.uint32v == 0xFF_FF_FF_FF}(); assumeType(`\uFF_FF_FF_FF`, Type.uint32v); assume!q{token.uint32v == 0xFF_FF_FF_FF}(); assumeType(`\uFFFFFFFFFFFFFFFF`, Type.uint32v); assume!q{token.uint32v == 0xFF_FF_FF_FF}(); assumeType(`\uFF_FF_FF_FF_FF_FF_FF_FF`, Type.uint32v); assume!q{token.uint32v == 0xFF_FF_FF_FF}(); assumeType(`\UFFFFFFFFFFFFFFFF`, Type.uint64v); assume!q{token.uint64v == 0xFF_FF_FF_FF_FF_FF_FF_FF}(); assumeType(`\UFF_FF_FF_FF_FF_FF_FF_FF`, Type.uint64v); assume!q{token.uint64v == 0xFF_FF_FF_FF_FF_FF_FF_FF}(); testHeader("CHOOSES SMALLEST TYPE"); twriteln("!!! TODO: Add these tests"); testHeader("ERRORS"); assumeType(`\xFF`, Type.invalid); assumeError(`\xFF`, "\\x hex escape needs 4 hex characters, got 2."); assume!q{token.type == Type.invalid}(); assumeError(`\xJ`, "Expected hex character, got 'J'."); assume!q{token.type == Type.invalid}(); assumeError(`\xFF_FJ`, "Expected hex character, got 'J'."); assume!q{token.type == Type.invalid}(); assumeError(`\xJF_FF`, "Expected hex character, got 'J'."); assume!q{token.type == Type.invalid}(); assumeError(`\uFF_FF_FF`, "\\u hex escape needs 8 hex characters, got 6."); assume!q{token.type == Type.invalid}(); assumeError(`\UFF_FF_FF_FF_FF_FF_FF`, "\\U hex escape needs 16 hex characters, got 14."); assume!q{token.type == Type.invalid}(); testEnd(); +/ } unittest { testBegin("DDOC"); twriteln("!!! TODO: ADD TESTS"); version(none) { assumeType("///", Type.lineComment); assume!q{source.context == SourceContext.ddoc}(); assumeType("/**", Type.blockComment); assume!q{source.context == SourceContext.ddoc}(); assumeType("/++", Type.codeComment); assume!q{source.context == SourceContext.ddoc}(); } testEnd(); } unittest { // Same rules as hex escape, so we wont do much testing here testBegin("HEX LITERAL"); assumeType("0xFF", Type.uint8v); testEnd(); } unittest { testBegin("INTEGER"); assumeType(to!string(byte.min), Type.int32v); assume!q{token.int8v == byte.min}(); assumeType(to!string(short.min), Type.int32v); assume!q{token.int16v == short.min}(); assumeType(to!string(int.min), Type.int32v); assume!q{token.int32v == int.min}(); /* assumeType(to!string(long.min), Type.int64v); assume!q{token.int64v == long.min}(); assumeType(to!string(byte.max), Type.int32v); assume!q{token.int8v == byte.max}(); assumeType(to!string(short.max), Type.int32v); assume!q{token.int16v == short.max}(); assumeType(to!string(int.max), Type.int32v); assume!q{token.int32v == int.max}(); assumeType(to!string(long.max), Type.int64v); assume!q{token.int64v == long.max}(); assumeType(`0`, Type.int32v); assume!q{token.boolv == false}(); assumeType(`1`, Type.int32v); assume!q{token.uint8v == true}(); assumeType(`2`, Type.int32v); assume!q{token.int8v == 2}(); assumeType(`-1`, Type.int32v); assume!q{token.int8v == -1}(); assumeType(to!string(byte.max+1), Type.int32v); assume!q{token.uint8v == byte.max+1}(); // signed.min - 1 == larger signed assumeType(to!string(byte.min-1), Type.int32v); assume!q{token.int16v == byte.min-1}(); // unsigned.max + 1 == larger signed assumeType(to!string(ubyte.max+1), Type.int32v); assume!q{token.int16v == ubyte.max+1}(); */ testEnd(); } unittest { // FIXME: should use smallest type testBegin("BINARY LITERAL"); assumeType("0b00", Type.int32v); assume!q{token.int32v == 0b00}(); assumeType("0b10", Type.int32v); assume!q{token.int32v == 0b10}(); assumeType("0b01", Type.int32v); assume!q{token.int32v == 0b01}(); assumeType("0b1_1", Type.int32v); assume!q{token.int32v == 0b11}(); testEnd(); } unittest { testBegin("FLOAT"); testEnd(); } unittest { testBegin("STRING"); assumeType(`"'"`, Type.stringv); assume!q{token.stringv == "'"}(); assumeType(`""`, Type.stringv); assume!q{token.raw == `""`}(); assume!q{token.stringv == ""}(); assumeType(`""c`, Type.stringv); assume!q{token.raw == `""c`}(); assume!q{token.stringv == ""c}(); assumeType(`""w`, Type.wstringv); assume!q{token.raw == `""w`}(); assume!q{token.stringv == ""c}(); // stored as utf-8 internally assumeType(`""d`, Type.dstringv); assume!q{token.raw == `""d`}(); assume!q{token.stringv == ""c}(); // stored as utf-8 internally assumeType(`"\x1A"`, Type.stringv); assume!q{token.stringv == "\x1A"}(); assumeType(`"\""`, Type.stringv); assume!q{token.stringv == `"`}(); assumeType(`" \""`, Type.stringv); assume!q{token.stringv == ` "`}(); assumeType(`" \" "`, Type.stringv); assume!q{token.stringv == ` " `}(); assumeType(`"'"`, Type.stringv); assume!q{token.stringv == "'"}(); assumeType(`" \" '"`, Type.stringv); assume!q{token.raw == `" \" '"`}(); assume!q{token.stringv == ` " '`}(); testEnd(); } unittest { testBegin("TOKEN STRING"); assumeType(`q{}`, Type.stringv); assume!q{token.raw == `q{}`}(); assume!q{token.stringv == ``}(); testEnd(); } unittest { testBegin("DELIMITED STRING"); // single symbol delimited string assumeType(`q"/foo/"`, Type.stringv); assume!q{token.stringv == q"/foo/"}(); // nested delimited string assumeType(`q"[f[o[o]]]"`, Type.stringv); assume!q{token.stringv == q"[f[o[o]]]"}(); // ident delimited string assumeType( `q"EOF somestring EOF"`, Type.stringv); assume!q{token.stringv == q"EOF somestring EOF"}(); testEnd(); } unittest { testBegin("WYSIWYG"); assumeType("``", Type.stringv); assumeType("``c", Type.stringv); assumeType("``w", Type.wstringv); assumeType("``d", Type.dstringv); assumeType("`''`", Type.stringv); //assumeType("`'\\''`", Type.stringv); lexIt("`\\`"); lexIt("`\\`"); lexIt("`'\\''`"); writeln(token.stringv); testEnd(); } /+ void main() { import std.datetime; auto source = Source(import("lexer.d")); Token token; write("1: "); // line 1 auto sw = StopWatch(AutoStart.yes); do { token = lex(source); version(none) { write(token.raw); if(token.type == Type.lineFeed) write(token.location.end.line, ": "); } } while(token.type != Type.EOF); writeln("Time (msecs): ", sw.peek().msecs); writeln("Issues:"); foreach(issue; source.issues) writeln(issue); } +/
D
/home/hustccc/OS_Tutorial_Summer_of_Code/zcore_test/target/debug/deps/zcore_test-b6cffd4c34aa76e0.rmeta: src/lib.rs /home/hustccc/OS_Tutorial_Summer_of_Code/zcore_test/target/debug/deps/libzcore_test-b6cffd4c34aa76e0.rlib: src/lib.rs /home/hustccc/OS_Tutorial_Summer_of_Code/zcore_test/target/debug/deps/zcore_test-b6cffd4c34aa76e0.d: src/lib.rs src/lib.rs:
D
/Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Intermediates.noindex/RamonEvandro.build/Debug-iphonesimulator/ComprasUSA.build/Objects-normal/x86_64/BuyTabBarViewController.o : /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/Validate.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/AppDelegate.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Intermediates.noindex/RamonEvandro.build/Debug-iphonesimulator/ComprasUSA.build/DerivedSources/CoreDataGenerated/BuyList/BuyList+CoreDataModel.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/ProductTableViewCell.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/Ext+UIApplication.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/Ext+UIViewController.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/BaseViewController.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/TotalViewController.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/BuyTabBarViewController.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/SettingsViewController.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/CreateProductViewController.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/BuyListViewController.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Intermediates.noindex/RamonEvandro.build/Debug-iphonesimulator/ComprasUSA.build/DerivedSources/CoreDataGenerated/BuyList/State+CoreDataProperties.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Intermediates.noindex/RamonEvandro.build/Debug-iphonesimulator/ComprasUSA.build/DerivedSources/CoreDataGenerated/BuyList/Product+CoreDataProperties.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Intermediates.noindex/RamonEvandro.build/Debug-iphonesimulator/ComprasUSA.build/DerivedSources/CoreDataGenerated/BuyList/State+CoreDataClass.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Intermediates.noindex/RamonEvandro.build/Debug-iphonesimulator/ComprasUSA.build/DerivedSources/CoreDataGenerated/BuyList/Product+CoreDataClass.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Products/Debug-iphonesimulator/EmptyDataSet-Swift/EmptyDataSet_Swift.framework/Modules/EmptyDataSet_Swift.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreData.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Products/Debug-iphonesimulator/EmptyDataSet-Swift/EmptyDataSet_Swift.framework/Headers/EmptyDataSet-Swift-umbrella.h /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Products/Debug-iphonesimulator/EmptyDataSet-Swift/EmptyDataSet_Swift.framework/Headers/EmptyDataSet_Swift-Swift.h /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Products/Debug-iphonesimulator/EmptyDataSet-Swift/EmptyDataSet_Swift.framework/Modules/module.modulemap /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Intermediates.noindex/RamonEvandro.build/Debug-iphonesimulator/ComprasUSA.build/Objects-normal/x86_64/BuyTabBarViewController~partial.swiftmodule : /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/Validate.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/AppDelegate.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Intermediates.noindex/RamonEvandro.build/Debug-iphonesimulator/ComprasUSA.build/DerivedSources/CoreDataGenerated/BuyList/BuyList+CoreDataModel.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/ProductTableViewCell.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/Ext+UIApplication.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/Ext+UIViewController.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/BaseViewController.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/TotalViewController.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/BuyTabBarViewController.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/SettingsViewController.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/CreateProductViewController.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/BuyListViewController.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Intermediates.noindex/RamonEvandro.build/Debug-iphonesimulator/ComprasUSA.build/DerivedSources/CoreDataGenerated/BuyList/State+CoreDataProperties.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Intermediates.noindex/RamonEvandro.build/Debug-iphonesimulator/ComprasUSA.build/DerivedSources/CoreDataGenerated/BuyList/Product+CoreDataProperties.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Intermediates.noindex/RamonEvandro.build/Debug-iphonesimulator/ComprasUSA.build/DerivedSources/CoreDataGenerated/BuyList/State+CoreDataClass.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Intermediates.noindex/RamonEvandro.build/Debug-iphonesimulator/ComprasUSA.build/DerivedSources/CoreDataGenerated/BuyList/Product+CoreDataClass.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Products/Debug-iphonesimulator/EmptyDataSet-Swift/EmptyDataSet_Swift.framework/Modules/EmptyDataSet_Swift.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreData.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Products/Debug-iphonesimulator/EmptyDataSet-Swift/EmptyDataSet_Swift.framework/Headers/EmptyDataSet-Swift-umbrella.h /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Products/Debug-iphonesimulator/EmptyDataSet-Swift/EmptyDataSet_Swift.framework/Headers/EmptyDataSet_Swift-Swift.h /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Products/Debug-iphonesimulator/EmptyDataSet-Swift/EmptyDataSet_Swift.framework/Modules/module.modulemap /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Intermediates.noindex/RamonEvandro.build/Debug-iphonesimulator/ComprasUSA.build/Objects-normal/x86_64/BuyTabBarViewController~partial.swiftdoc : /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/Validate.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/AppDelegate.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Intermediates.noindex/RamonEvandro.build/Debug-iphonesimulator/ComprasUSA.build/DerivedSources/CoreDataGenerated/BuyList/BuyList+CoreDataModel.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/ProductTableViewCell.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/Ext+UIApplication.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/Ext+UIViewController.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/BaseViewController.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/TotalViewController.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/BuyTabBarViewController.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/SettingsViewController.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/CreateProductViewController.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/BuyList/BuyListViewController.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Intermediates.noindex/RamonEvandro.build/Debug-iphonesimulator/ComprasUSA.build/DerivedSources/CoreDataGenerated/BuyList/State+CoreDataProperties.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Intermediates.noindex/RamonEvandro.build/Debug-iphonesimulator/ComprasUSA.build/DerivedSources/CoreDataGenerated/BuyList/Product+CoreDataProperties.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Intermediates.noindex/RamonEvandro.build/Debug-iphonesimulator/ComprasUSA.build/DerivedSources/CoreDataGenerated/BuyList/State+CoreDataClass.swift /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Intermediates.noindex/RamonEvandro.build/Debug-iphonesimulator/ComprasUSA.build/DerivedSources/CoreDataGenerated/BuyList/Product+CoreDataClass.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Products/Debug-iphonesimulator/EmptyDataSet-Swift/EmptyDataSet_Swift.framework/Modules/EmptyDataSet_Swift.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreData.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Products/Debug-iphonesimulator/EmptyDataSet-Swift/EmptyDataSet_Swift.framework/Headers/EmptyDataSet-Swift-umbrella.h /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Products/Debug-iphonesimulator/EmptyDataSet-Swift/EmptyDataSet_Swift.framework/Headers/EmptyDataSet_Swift-Swift.h /Users/ramonhonorio/workspace/ios/fiap/BuyList/DerivedData/RamonEvandro/Build/Products/Debug-iphonesimulator/EmptyDataSet-Swift/EmptyDataSet_Swift.framework/Modules/module.modulemap
D
module windows.qualityofservice; public import system; public import windows.nativewifi; public import windows.systemservices; public import windows.winsock; extern(Windows): struct FLOWSPEC { uint TokenRate; uint TokenBucketSize; uint PeakBandwidth; uint Latency; uint DelayVariation; uint ServiceType; uint MaxSduSize; uint MinimumPolicedSize; } struct QOS_OBJECT_HDR { uint ObjectType; uint ObjectLength; } struct QOS_SD_MODE { QOS_OBJECT_HDR ObjectHdr; uint ShapeDiscardMode; } struct QOS_SHAPING_RATE { QOS_OBJECT_HDR ObjectHdr; uint ShapingRate; } struct RsvpObjHdr { ushort obj_length; ubyte obj_class; ubyte obj_ctype; } struct Session_IPv4 { in_addr sess_destaddr; ubyte sess_protid; ubyte sess_flags; ushort sess_destport; } struct RSVP_SESSION { RsvpObjHdr sess_header; _sess_u_e__Union sess_u; } struct Rsvp_Hop_IPv4 { in_addr hop_ipaddr; uint hop_LIH; } struct RSVP_HOP { RsvpObjHdr hop_header; _hop_u_e__Union hop_u; } struct RESV_STYLE { RsvpObjHdr style_header; uint style_word; } struct Filter_Spec_IPv4 { in_addr filt_ipaddr; ushort filt_unused; ushort filt_port; } struct Filter_Spec_IPv4GPI { in_addr filt_ipaddr; uint filt_gpi; } struct FILTER_SPEC { RsvpObjHdr filt_header; _filt_u_e__Union filt_u; } struct Scope_list_ipv4 { in_addr scopl_ipaddr; } struct RSVP_SCOPE { RsvpObjHdr scopl_header; _scope_u_e__Union scope_u; } struct Error_Spec_IPv4 { in_addr errs_errnode; ubyte errs_flags; ubyte errs_code; ushort errs_value; } struct ERROR_SPEC { RsvpObjHdr errs_header; _errs_u_e__Union errs_u; } struct POLICY_DATA { RsvpObjHdr PolicyObjHdr; ushort usPeOffset; ushort usReserved; } struct POLICY_ELEMENT { ushort usPeLength; ushort usPeType; ubyte ucPeData; } enum int_serv_wkp { IS_WKP_HOP_CNT = 4, IS_WKP_PATH_BW = 6, IS_WKP_MIN_LATENCY = 8, IS_WKP_COMPOSED_MTU = 10, IS_WKP_TB_TSPEC = 127, IS_WKP_Q_TSPEC = 128, } struct IntServMainHdr { ubyte ismh_version; ubyte ismh_unused; ushort ismh_len32b; } struct IntServServiceHdr { ubyte issh_service; ubyte issh_flags; ushort issh_len32b; } struct IntServParmHdr { ubyte isph_parm_num; ubyte isph_flags; ushort isph_len32b; } struct GenTspecParms { float TB_Tspec_r; float TB_Tspec_b; float TB_Tspec_p; uint TB_Tspec_m; uint TB_Tspec_M; } struct GenTspec { IntServServiceHdr gen_Tspec_serv_hdr; IntServParmHdr gen_Tspec_parm_hdr; GenTspecParms gen_Tspec_parms; } struct QualTspecParms { uint TB_Tspec_M; } struct QualTspec { IntServServiceHdr qual_Tspec_serv_hdr; IntServParmHdr qual_Tspec_parm_hdr; QualTspecParms qual_Tspec_parms; } struct QualAppFlowSpec { IntServServiceHdr Q_spec_serv_hdr; IntServParmHdr Q_spec_parm_hdr; QualTspecParms Q_spec_parms; } struct IntServTspecBody { IntServMainHdr st_mh; _tspec_u_e__Union tspec_u; } struct SENDER_TSPEC { RsvpObjHdr stspec_header; IntServTspecBody stspec_body; } struct CtrlLoadFlowspec { IntServServiceHdr CL_spec_serv_hdr; IntServParmHdr CL_spec_parm_hdr; GenTspecParms CL_spec_parms; } struct GuarRspec { float Guar_R; uint Guar_S; } struct GuarFlowSpec { IntServServiceHdr Guar_serv_hdr; IntServParmHdr Guar_Tspec_hdr; GenTspecParms Guar_Tspec_parms; IntServParmHdr Guar_Rspec_hdr; GuarRspec Guar_Rspec; } struct IntServFlowSpec { IntServMainHdr spec_mh; _spec_u_e__Union spec_u; } struct IS_FLOWSPEC { RsvpObjHdr flow_header; IntServFlowSpec flow_body; } struct flow_desc { _u1_e__Union u1; _u2_e__Union u2; } struct Gads_parms_t { IntServServiceHdr Gads_serv_hdr; IntServParmHdr Gads_Ctot_hdr; uint Gads_Ctot; IntServParmHdr Gads_Dtot_hdr; uint Gads_Dtot; IntServParmHdr Gads_Csum_hdr; uint Gads_Csum; IntServParmHdr Gads_Dsum_hdr; uint Gads_Dsum; } struct GenAdspecParams { IntServServiceHdr gen_parm_hdr; IntServParmHdr gen_parm_hopcnt_hdr; uint gen_parm_hopcnt; IntServParmHdr gen_parm_pathbw_hdr; float gen_parm_path_bw; IntServParmHdr gen_parm_minlat_hdr; uint gen_parm_min_latency; IntServParmHdr gen_parm_compmtu_hdr; uint gen_parm_composed_MTU; } struct IS_ADSPEC_BODY { IntServMainHdr adspec_mh; GenAdspecParams adspec_genparms; } struct ADSPEC { RsvpObjHdr adspec_header; IS_ADSPEC_BODY adspec_body; } struct ID_ERROR_OBJECT { ushort usIdErrLength; ubyte ucAType; ubyte ucSubType; ushort usReserved; ushort usIdErrorValue; ubyte ucIdErrData; } struct LPM_HANDLE__ { int unused; } struct RHANDLE__ { int unused; } struct RSVP_MSG_OBJS { int RsvpMsgType; RSVP_SESSION* pRsvpSession; RSVP_HOP* pRsvpFromHop; RSVP_HOP* pRsvpToHop; RESV_STYLE* pResvStyle; RSVP_SCOPE* pRsvpScope; int FlowDescCount; flow_desc* pFlowDescs; int PdObjectCount; POLICY_DATA** ppPdObjects; ERROR_SPEC* pErrorSpec; ADSPEC* pAdspec; } alias PALLOCMEM = extern(Windows) void* function(uint Size); alias PFREEMEM = extern(Windows) void function(void* pv); struct policy_decision { uint lpvResult; ushort wPolicyErrCode; ushort wPolicyErrValue; } alias CBADMITRESULT = extern(Windows) uint* function(LPM_HANDLE__* LpmHandle, RHANDLE__* RequestHandle, uint ulPcmActionFlags, int LpmError, int PolicyDecisionsCount, policy_decision* pPolicyDecisions); alias CBGETRSVPOBJECTS = extern(Windows) uint* function(LPM_HANDLE__* LpmHandle, RHANDLE__* RequestHandle, int LpmError, int RsvpObjectsCount, RsvpObjHdr** ppRsvpObjects); struct LPM_INIT_INFO { uint PcmVersionNumber; uint ResultTimeLimit; int ConfiguredLpmCount; PALLOCMEM AllocMemory; PFREEMEM FreeMemory; CBADMITRESULT PcmAdmitResultCallback; CBGETRSVPOBJECTS GetRsvpObjectsCallback; } struct lpmiptable { uint ulIfIndex; uint MediaType; in_addr IfIpAddr; in_addr IfNetMask; } enum QOS_TRAFFIC_TYPE { QOSTrafficTypeBestEffort = 0, QOSTrafficTypeBackground = 1, QOSTrafficTypeExcellentEffort = 2, QOSTrafficTypeAudioVideo = 3, QOSTrafficTypeVoice = 4, QOSTrafficTypeControl = 5, } enum QOS_SET_FLOW { QOSSetTrafficType = 0, QOSSetOutgoingRate = 1, QOSSetOutgoingDSCPValue = 2, } struct QOS_PACKET_PRIORITY { uint ConformantDSCPValue; uint NonConformantDSCPValue; uint ConformantL2Value; uint NonConformantL2Value; } struct QOS_FLOW_FUNDAMENTALS { BOOL BottleneckBandwidthSet; ulong BottleneckBandwidth; BOOL AvailableBandwidthSet; ulong AvailableBandwidth; BOOL RTTSet; uint RTT; } enum QOS_FLOWRATE_REASON { QOSFlowRateNotApplicable = 0, QOSFlowRateContentChange = 1, QOSFlowRateCongestion = 2, QOSFlowRateHigherContentEncoding = 3, QOSFlowRateUserCaused = 4, } enum QOS_SHAPING { QOSShapeOnly = 0, QOSShapeAndMark = 1, QOSUseNonConformantMarkings = 2, } struct QOS_FLOWRATE_OUTGOING { ulong Bandwidth; QOS_SHAPING ShapingBehavior; QOS_FLOWRATE_REASON Reason; } enum QOS_QUERY_FLOW { QOSQueryFlowFundamentals = 0, QOSQueryPacketPriority = 1, QOSQueryOutgoingRate = 2, } enum QOS_NOTIFY_FLOW { QOSNotifyCongested = 0, QOSNotifyUncongested = 1, QOSNotifyAvailable = 2, } struct QOS_VERSION { ushort MajorVersion; ushort MinorVersion; } struct QOS_FRIENDLY_NAME { QOS_OBJECT_HDR ObjectHdr; ushort FriendlyName; } struct QOS_TRAFFIC_CLASS { QOS_OBJECT_HDR ObjectHdr; uint TrafficClass; } struct QOS_DS_CLASS { QOS_OBJECT_HDR ObjectHdr; uint DSField; } struct QOS_DIFFSERV { QOS_OBJECT_HDR ObjectHdr; uint DSFieldCount; ubyte DiffservRule; } struct QOS_DIFFSERV_RULE { ubyte InboundDSField; ubyte ConformingOutboundDSField; ubyte NonConformingOutboundDSField; ubyte ConformingUserPriority; ubyte NonConformingUserPriority; } struct QOS_TCP_TRAFFIC { QOS_OBJECT_HDR ObjectHdr; } alias TCI_NOTIFY_HANDLER = extern(Windows) void function(HANDLE ClRegCtx, HANDLE ClIfcCtx, uint Event, HANDLE SubCode, uint BufSize, char* Buffer); alias TCI_ADD_FLOW_COMPLETE_HANDLER = extern(Windows) void function(HANDLE ClFlowCtx, uint Status); alias TCI_MOD_FLOW_COMPLETE_HANDLER = extern(Windows) void function(HANDLE ClFlowCtx, uint Status); alias TCI_DEL_FLOW_COMPLETE_HANDLER = extern(Windows) void function(HANDLE ClFlowCtx, uint Status); struct TCI_CLIENT_FUNC_LIST { TCI_NOTIFY_HANDLER ClNotifyHandler; TCI_ADD_FLOW_COMPLETE_HANDLER ClAddFlowCompleteHandler; TCI_MOD_FLOW_COMPLETE_HANDLER ClModifyFlowCompleteHandler; TCI_DEL_FLOW_COMPLETE_HANDLER ClDeleteFlowCompleteHandler; } struct ADDRESS_LIST_DESCRIPTOR { uint MediaType; NETWORK_ADDRESS_LIST AddressList; } struct TC_IFC_DESCRIPTOR { uint Length; const(wchar)* pInterfaceName; const(wchar)* pInterfaceID; ADDRESS_LIST_DESCRIPTOR AddressListDesc; } struct TC_SUPPORTED_INFO_BUFFER { ushort InstanceIDLength; ushort InstanceID; ulong InterfaceLuid; ADDRESS_LIST_DESCRIPTOR AddrListDesc; } struct TC_GEN_FILTER { ushort AddressType; uint PatternSize; void* Pattern; void* Mask; } struct TC_GEN_FLOW { FLOWSPEC SendingFlowspec; FLOWSPEC ReceivingFlowspec; uint TcObjectsLength; QOS_OBJECT_HDR TcObjects; } struct IP_PATTERN { uint Reserved1; uint Reserved2; uint SrcAddr; uint DstAddr; _S_un_e__Union S_un; ubyte ProtocolId; ubyte Reserved3; } struct IPX_PATTERN { _Src_e__Struct Src; _Src_e__Struct Dest; } struct ENUMERATION_BUFFER { uint Length; uint OwnerProcessId; ushort FlowNameLength; ushort FlowName; TC_GEN_FLOW* pFlow; uint NumberOfFilters; TC_GEN_FILTER GenericFilter; } @DllImport("qwave.dll") BOOL QOSCreateHandle(QOS_VERSION* Version, int* QOSHandle); @DllImport("qwave.dll") BOOL QOSCloseHandle(HANDLE QOSHandle); @DllImport("qwave.dll") BOOL QOSStartTrackingClient(HANDLE QOSHandle, SOCKADDR* DestAddr, uint Flags); @DllImport("qwave.dll") BOOL QOSStopTrackingClient(HANDLE QOSHandle, SOCKADDR* DestAddr, uint Flags); @DllImport("qwave.dll") BOOL QOSEnumerateFlows(HANDLE QOSHandle, uint* Size, char* Buffer); @DllImport("qwave.dll") BOOL QOSAddSocketToFlow(HANDLE QOSHandle, uint Socket, SOCKADDR* DestAddr, QOS_TRAFFIC_TYPE TrafficType, uint Flags, uint* FlowId); @DllImport("qwave.dll") BOOL QOSRemoveSocketFromFlow(HANDLE QOSHandle, uint Socket, uint FlowId, uint Flags); @DllImport("qwave.dll") BOOL QOSSetFlow(HANDLE QOSHandle, uint FlowId, QOS_SET_FLOW Operation, uint Size, char* Buffer, uint Flags, OVERLAPPED* Overlapped); @DllImport("qwave.dll") BOOL QOSQueryFlow(HANDLE QOSHandle, uint FlowId, QOS_QUERY_FLOW Operation, uint* Size, char* Buffer, uint Flags, OVERLAPPED* Overlapped); @DllImport("qwave.dll") BOOL QOSNotifyFlow(HANDLE QOSHandle, uint FlowId, QOS_NOTIFY_FLOW Operation, uint* Size, char* Buffer, uint Flags, OVERLAPPED* Overlapped); @DllImport("qwave.dll") BOOL QOSCancel(HANDLE QOSHandle, OVERLAPPED* Overlapped); @DllImport("TRAFFIC.dll") uint TcRegisterClient(uint TciVersion, HANDLE ClRegCtx, TCI_CLIENT_FUNC_LIST* ClientHandlerList, int* pClientHandle); @DllImport("TRAFFIC.dll") uint TcEnumerateInterfaces(HANDLE ClientHandle, uint* pBufferSize, TC_IFC_DESCRIPTOR* InterfaceBuffer); @DllImport("TRAFFIC.dll") uint TcOpenInterfaceA(const(char)* pInterfaceName, HANDLE ClientHandle, HANDLE ClIfcCtx, int* pIfcHandle); @DllImport("TRAFFIC.dll") uint TcOpenInterfaceW(const(wchar)* pInterfaceName, HANDLE ClientHandle, HANDLE ClIfcCtx, int* pIfcHandle); @DllImport("TRAFFIC.dll") uint TcCloseInterface(HANDLE IfcHandle); @DllImport("TRAFFIC.dll") uint TcQueryInterface(HANDLE IfcHandle, Guid* pGuidParam, ubyte NotifyChange, uint* pBufferSize, char* Buffer); @DllImport("TRAFFIC.dll") uint TcSetInterface(HANDLE IfcHandle, Guid* pGuidParam, uint BufferSize, char* Buffer); @DllImport("TRAFFIC.dll") uint TcQueryFlowA(const(char)* pFlowName, Guid* pGuidParam, uint* pBufferSize, char* Buffer); @DllImport("TRAFFIC.dll") uint TcQueryFlowW(const(wchar)* pFlowName, Guid* pGuidParam, uint* pBufferSize, char* Buffer); @DllImport("TRAFFIC.dll") uint TcSetFlowA(const(char)* pFlowName, Guid* pGuidParam, uint BufferSize, char* Buffer); @DllImport("TRAFFIC.dll") uint TcSetFlowW(const(wchar)* pFlowName, Guid* pGuidParam, uint BufferSize, char* Buffer); @DllImport("TRAFFIC.dll") uint TcAddFlow(HANDLE IfcHandle, HANDLE ClFlowCtx, uint Flags, TC_GEN_FLOW* pGenericFlow, int* pFlowHandle); @DllImport("TRAFFIC.dll") uint TcGetFlowNameA(HANDLE FlowHandle, uint StrSize, const(char)* pFlowName); @DllImport("TRAFFIC.dll") uint TcGetFlowNameW(HANDLE FlowHandle, uint StrSize, const(wchar)* pFlowName); @DllImport("TRAFFIC.dll") uint TcModifyFlow(HANDLE FlowHandle, TC_GEN_FLOW* pGenericFlow); @DllImport("TRAFFIC.dll") uint TcAddFilter(HANDLE FlowHandle, TC_GEN_FILTER* pGenericFilter, int* pFilterHandle); @DllImport("TRAFFIC.dll") uint TcDeregisterClient(HANDLE ClientHandle); @DllImport("TRAFFIC.dll") uint TcDeleteFlow(HANDLE FlowHandle); @DllImport("TRAFFIC.dll") uint TcDeleteFilter(HANDLE FilterHandle); @DllImport("TRAFFIC.dll") uint TcEnumerateFlows(HANDLE IfcHandle, int* pEnumHandle, uint* pFlowCount, uint* pBufSize, ENUMERATION_BUFFER* Buffer); struct QOS { FLOWSPEC SendingFlowspec; FLOWSPEC ReceivingFlowspec; WSABUF ProviderSpecific; }
D
//----------------------------------------------------------------------------- // wxD - Utils.d // (C) 2005 bero <berobero@users.sourceforge.net> // based on // wx.NET - Utils.cs // /// Common Utils wrapper classes. // // Written by Alexander Olk (xenomorph2@onlinehome.de) // (C) 2003 Alexander Olk // Licensed under the wxWidgets license, see LICENSE.txt for details. // // $Id: Utils.d,v 1.10 2007/01/28 23:06:37 afb Exp $ //----------------------------------------------------------------------------- module wx.Utils; public import wx.common; public import wx.Window; //! \cond EXTERN static extern (C) IntPtr wxGlobal_GetHomeDir(); static extern (C) IntPtr wxGlobal_GetCwd(); static extern (C) void wxSleep_func(int num); static extern (C) void wxMilliSleep_func(uint num); static extern (C) void wxMicroSleep_func(uint num); static extern (C) void wxYield_func(); static extern (C) void wxBeginBusyCursor_func(); static extern (C) void wxEndBusyCursor_func(); static extern (C) void wxMutexGuiEnter_func(); static extern (C) void wxMutexGuiLeave_func(); //! \endcond public static string GetHomeDir() { return cast(string) new wxString(wxGlobal_GetHomeDir(), true); } public static string GetCwd() { return cast(string) new wxString(wxGlobal_GetCwd(), true); } //--------------------------------------------------------------------- public static void wxSleep(int num) { wxSleep_func(num); } public static void wxMilliSleep(int num) { wxMilliSleep_func(num); } public static void wxMicroSleep(int num) { wxMicroSleep_func(num); } //--------------------------------------------------------------------- public static void wxYield() { wxYield_func(); } //--------------------------------------------------------------------- public static void BeginBusyCursor() { wxBeginBusyCursor_func(); } public static void EndBusyCursor() { wxEndBusyCursor_func(); } //--------------------------------------------------------------------- public static void MutexGuiEnter() { wxMutexGuiEnter_func(); } public static void MutexGuiLeave() { wxMutexGuiLeave_func(); } //--------------------------------------------------------------------- alias BusyCursor wxBusyCursor; public class BusyCursor : IDisposable { private bool disposed = false; public this() { BeginBusyCursor(); } ~this() { Dispose(); } public void Dispose() { if (!disposed) { disposed = true; EndBusyCursor(); } } } //--------------------------------------------------------------------- //! \cond EXTERN static extern (C) IntPtr wxWindowDisabler_ctor(IntPtr winToSkip); static extern (C) void wxWindowDisabler_dtor(IntPtr self); //! \endcond alias WindowDisabler wxWindowDisabler; public scope class WindowDisabler : wxObject { //--------------------------------------------------------------------- public this(IntPtr wxobj) { super(wxobj); } private this(IntPtr wxobj, bool memOwn) { super(wxobj); this.memOwn = memOwn; } public this() { this(cast(Window)null); } public this(Window winToSkip) { this(wxWindowDisabler_ctor(wxObject.SafePtr(winToSkip)), true); } //--------------------------------------------------------------------- override protected void dtor() { wxWindowDisabler_dtor(wxobj); } } //--------------------------------------------------------------------- //! \cond EXTERN static extern (C) IntPtr wxBusyInfo_ctor(string message, IntPtr parent); static extern (C) void wxBusyInfo_dtor(IntPtr self); //! \endcond alias BusyInfo wxBusyInfo; public scope class BusyInfo : wxObject { //--------------------------------------------------------------------- public this(IntPtr wxobj) { super(wxobj); } public this(string message) { this(message, null); } public this(string message, Window parent) { this(wxBusyInfo_ctor(message, wxObject.SafePtr(parent)), true); } private this(IntPtr wxobj, bool memOwn) { super(wxobj); this.memOwn = memOwn; } //--------------------------------------------------------------------- override protected void dtor() { wxBusyInfo_dtor(wxobj); } } //---------------------------------------------------------------------
D
module contains_usage_scoped_import_members; import contains_declaration_scoped_import_members : struct_; void main(string[] args){ struct_ var; <ref>struct_member(var); }
D
module android.java.java.security.KeyStoreException; public import android.java.java.security.KeyStoreException_d_interface; import arsd.jni : ImportExportImpl; mixin ImportExportImpl!KeyStoreException; import import4 = android.java.java.lang.Class; import import3 = android.java.java.lang.StackTraceElement;
D
/Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/Core.build/Exports.swift.o : /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/RFC1123.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/String+Polymorphic.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Sequence.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Collection+Safe.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Cache.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Extendable.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/EmptyInitializable.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/DataFile.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/String+CaseInsensitiveCompare.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Semaphore.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/String.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Dispatch.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Lock.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Portal.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/FileProtocol.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/StaticDataBuffer.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/DispatchTime+Utilities.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Bits.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Exports.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Result.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Int+Hex.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Array.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/WorkingDirectory.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/libc.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/Debugging.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/Bits.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/CHTTP.build/module.modulemap /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/CSQLite.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/Core.build/Exports~partial.swiftmodule : /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/RFC1123.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/String+Polymorphic.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Sequence.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Collection+Safe.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Cache.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Extendable.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/EmptyInitializable.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/DataFile.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/String+CaseInsensitiveCompare.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Semaphore.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/String.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Dispatch.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Lock.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Portal.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/FileProtocol.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/StaticDataBuffer.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/DispatchTime+Utilities.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Bits.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Exports.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Result.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Int+Hex.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Array.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/WorkingDirectory.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/libc.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/Debugging.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/Bits.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/CHTTP.build/module.modulemap /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/CSQLite.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/Core.build/Exports~partial.swiftdoc : /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/RFC1123.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/String+Polymorphic.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Sequence.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Collection+Safe.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Cache.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Extendable.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/EmptyInitializable.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/DataFile.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/String+CaseInsensitiveCompare.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Semaphore.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/String.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Dispatch.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Lock.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Portal.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/FileProtocol.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/StaticDataBuffer.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/DispatchTime+Utilities.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Bits.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Exports.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Result.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Int+Hex.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/Array.swift /Users/chenzuncheng/Desktop/vaporTest/.build/checkouts/core.git-9210800844849382486/Sources/Core/WorkingDirectory.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/libc.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/Debugging.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/Bits.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/CHTTP.build/module.modulemap /Users/chenzuncheng/Desktop/vaporTest/.build/x86_64-apple-macosx10.10/debug/CSQLite.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
D
/Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/SQL.build/SQLRawBuilder.swift.o : /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLBind.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLJoinMethod.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLTable.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLCreateTable.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDropTable.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLAlterTable.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLSerializable.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDataType.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLUpdate.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDelete.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLLiteral.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLBoolLiteral.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDefaultLiteral.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLTableConstraintAlgorithm.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLColumnConstraintAlgorithm.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLJoin.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLExpression.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLSelectExpression.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLCollation.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLForeignKeyAction.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLConnection.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDirection.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLFunction.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLColumnDefinition.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLCreateTableBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDropTableBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLAlterTableBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLPredicateBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLUpdateBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDeleteBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLColumnBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLPredicateGroupBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLSelectBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLInsertBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLRawBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLCreateIndexBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLQueryBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLQueryEncoder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLQueryFetcher.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLIndexModifier.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLIdentifier.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLTableIdentifier.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLColumnIdentifier.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLError.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLBinaryOperator.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/Exports.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLSelect.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDistinct.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLFunctionArgument.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLTableConstraint.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLColumnConstraint.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLInsert.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLCreateIndex.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDropIndex.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLGroupBy.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLOrderBy.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLForeignKey.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLPrimaryKey.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLQuery.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/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/NIO.swiftmodule /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/Async.swiftmodule /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/Service.swiftmodule /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/Core.swiftmodule /Users/nice/HelloWord/.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/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/NIOConcurrencyHelpers.swiftmodule /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/Bits.swiftmodule /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/NIOFoundationCompat.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/DatabaseKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/nice/HelloWord/.build/checkouts/swift-nio.git-5005363973595484456/Sources/CNIOAtomics/include/cpp_magic.h /Users/nice/HelloWord/.build/checkouts/swift-nio.git-5005363973595484456/Sources/CNIODarwin/include/c_nio_darwin.h /Users/nice/HelloWord/.build/checkouts/swift-nio.git-5005363973595484456/Sources/CNIOAtomics/include/c-atomics.h /Users/nice/HelloWord/.build/checkouts/swift-nio.git-5005363973595484456/Sources/CNIOLinux/include/c_nio_linux.h /Users/nice/HelloWord/.build/checkouts/swift-nio-zlib-support.git--6556802241718767980/module.modulemap /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/CNIOSHA1.build/module.modulemap /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/CNIOOpenSSL.build/module.modulemap /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/CCryptoOpenSSL.build/module.modulemap /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/CNIOZlib.build/module.modulemap /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/CNIODarwin.build/module.modulemap /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/CNIOHTTPParser.build/module.modulemap /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/CNIOAtomics.build/module.modulemap /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/CNIOLinux.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/SQL.build/SQLRawBuilder~partial.swiftmodule : /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLBind.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLJoinMethod.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLTable.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLCreateTable.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDropTable.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLAlterTable.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLSerializable.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDataType.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLUpdate.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDelete.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLLiteral.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLBoolLiteral.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDefaultLiteral.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLTableConstraintAlgorithm.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLColumnConstraintAlgorithm.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLJoin.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLExpression.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLSelectExpression.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLCollation.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLForeignKeyAction.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLConnection.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDirection.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLFunction.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLColumnDefinition.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLCreateTableBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDropTableBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLAlterTableBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLPredicateBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLUpdateBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDeleteBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLColumnBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLPredicateGroupBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLSelectBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLInsertBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLRawBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLCreateIndexBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLQueryBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLQueryEncoder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLQueryFetcher.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLIndexModifier.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLIdentifier.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLTableIdentifier.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLColumnIdentifier.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLError.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLBinaryOperator.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/Exports.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLSelect.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDistinct.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLFunctionArgument.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLTableConstraint.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLColumnConstraint.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLInsert.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLCreateIndex.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDropIndex.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLGroupBy.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLOrderBy.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLForeignKey.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLPrimaryKey.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLQuery.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/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/NIO.swiftmodule /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/Async.swiftmodule /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/Service.swiftmodule /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/Core.swiftmodule /Users/nice/HelloWord/.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/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/NIOConcurrencyHelpers.swiftmodule /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/Bits.swiftmodule /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/NIOFoundationCompat.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/DatabaseKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/nice/HelloWord/.build/checkouts/swift-nio.git-5005363973595484456/Sources/CNIOAtomics/include/cpp_magic.h /Users/nice/HelloWord/.build/checkouts/swift-nio.git-5005363973595484456/Sources/CNIODarwin/include/c_nio_darwin.h /Users/nice/HelloWord/.build/checkouts/swift-nio.git-5005363973595484456/Sources/CNIOAtomics/include/c-atomics.h /Users/nice/HelloWord/.build/checkouts/swift-nio.git-5005363973595484456/Sources/CNIOLinux/include/c_nio_linux.h /Users/nice/HelloWord/.build/checkouts/swift-nio-zlib-support.git--6556802241718767980/module.modulemap /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/CNIOSHA1.build/module.modulemap /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/CNIOOpenSSL.build/module.modulemap /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/CCryptoOpenSSL.build/module.modulemap /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/CNIOZlib.build/module.modulemap /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/CNIODarwin.build/module.modulemap /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/CNIOHTTPParser.build/module.modulemap /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/CNIOAtomics.build/module.modulemap /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/CNIOLinux.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/SQL.build/SQLRawBuilder~partial.swiftdoc : /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLBind.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLJoinMethod.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLTable.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLCreateTable.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDropTable.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLAlterTable.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLSerializable.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDataType.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLUpdate.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDelete.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLLiteral.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLBoolLiteral.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDefaultLiteral.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLTableConstraintAlgorithm.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLColumnConstraintAlgorithm.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLJoin.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLExpression.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLSelectExpression.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLCollation.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLForeignKeyAction.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLConnection.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDirection.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLFunction.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLColumnDefinition.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLCreateTableBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDropTableBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLAlterTableBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLPredicateBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLUpdateBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDeleteBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLColumnBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLPredicateGroupBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLSelectBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLInsertBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLRawBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLCreateIndexBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLQueryBuilder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLQueryEncoder.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLQueryFetcher.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLIndexModifier.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLIdentifier.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLTableIdentifier.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLColumnIdentifier.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLError.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLBinaryOperator.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/Exports.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLSelect.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDistinct.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLFunctionArgument.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLTableConstraint.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLColumnConstraint.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLInsert.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLCreateIndex.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLDropIndex.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLGroupBy.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLOrderBy.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLForeignKey.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLPrimaryKey.swift /Users/nice/HelloWord/.build/checkouts/sql.git-3312412671859601518/Sources/SQL/SQLQuery.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/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/NIO.swiftmodule /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/Async.swiftmodule /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/Service.swiftmodule /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/Core.swiftmodule /Users/nice/HelloWord/.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/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/NIOConcurrencyHelpers.swiftmodule /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/Bits.swiftmodule /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/NIOFoundationCompat.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/DatabaseKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/nice/HelloWord/.build/checkouts/swift-nio.git-5005363973595484456/Sources/CNIOAtomics/include/cpp_magic.h /Users/nice/HelloWord/.build/checkouts/swift-nio.git-5005363973595484456/Sources/CNIODarwin/include/c_nio_darwin.h /Users/nice/HelloWord/.build/checkouts/swift-nio.git-5005363973595484456/Sources/CNIOAtomics/include/c-atomics.h /Users/nice/HelloWord/.build/checkouts/swift-nio.git-5005363973595484456/Sources/CNIOLinux/include/c_nio_linux.h /Users/nice/HelloWord/.build/checkouts/swift-nio-zlib-support.git--6556802241718767980/module.modulemap /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/CNIOSHA1.build/module.modulemap /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/CNIOOpenSSL.build/module.modulemap /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/CCryptoOpenSSL.build/module.modulemap /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/CNIOZlib.build/module.modulemap /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/CNIODarwin.build/module.modulemap /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/CNIOHTTPParser.build/module.modulemap /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/CNIOAtomics.build/module.modulemap /Users/nice/HelloWord/.build/x86_64-apple-macosx10.10/debug/CNIOLinux.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
D
/* * Hello Object DLL Self-Registering Server * Heavily modified from: */ /* * SELFREG.CPP * Server Self-Registrtation Utility, Chapter 5 * * Copyright (c)1993-1995 Microsoft Corporation, All Rights Reserved * * Kraig Brockschmidt, Microsoft * Internet : kraigb@microsoft.com * Compuserve: >INTERNET:kraigb@microsoft.com */ import std.c.stdio; import std.c.stdlib; import std.c.string; import std.string; import std.c.windows.windows; import std.c.windows.com; import chello; //This class factory object creates Hello objects. class CHelloClassFactory : ComObject, IClassFactory { public: this() { MessageBoxA(null,"CHelloClassFactory()",null,MB_OK); } ~this() { MessageBoxA(null,"~CHelloClassFactory()",null,MB_OK); } extern (Windows): // IUnknown members HRESULT QueryInterface(const(IID)* riid, LPVOID *ppv) { MessageBoxA(null,"CHelloClassFactory.QueryInterface()",null,MB_OK); if (IID_IUnknown == *riid) { MessageBoxA(null,"IUnknown",null,MB_OK); *ppv = cast(void*)cast(IUnknown)this; } else if (IID_IClassFactory == *riid) { MessageBoxA(null,"IClassFactory",null,MB_OK); *ppv = cast(void*)cast(IClassFactory)this; } else { *ppv = null; return E_NOINTERFACE; } AddRef(); return NOERROR; } // IClassFactory members HRESULT CreateInstance(IUnknown pUnkOuter, IID* riid, LPVOID * ppvObj) { CHello pObj; HRESULT hr; MessageBoxA(null,"CHelloClassFactory.CreateInstance()",null,MB_OK); *ppvObj = null; hr = E_OUTOFMEMORY; //Verify that a controlling unknown asks for IUnknown if (null !is pUnkOuter && memcmp(&IID_IUnknown, riid, IID.sizeof)) return CLASS_E_NOAGGREGATION; //Create the object passing function to notify on destruction. pObj = new CHello(pUnkOuter, &ObjectDestroyed); if (!pObj) return hr; if (pObj.Init()) { hr = pObj.QueryInterface(riid, ppvObj); } //Kill the object if initial creation or Init failed. if (FAILED(hr)) delete pObj; else g_cObj++; return hr; } HRESULT LockServer(BOOL fLock) { MessageBoxA(null,"CHelloClassFactory.LockServer()",null,MB_OK); if (fLock) g_cLock++; else g_cLock--; return NOERROR; } }; //Count number of objects and number of locks. ULONG g_cObj=0; ULONG g_cLock=0; HINSTANCE g_hInst; extern (C) { void *_atopsp; void gc_init(); void gc_term(); void _minit(); void _moduleCtor(); void _moduleUnitTests(); } extern (Windows): BOOL DllMain(HINSTANCE hInstance, ULONG ulReason, LPVOID pvReserved) { //_atopsp = (void*)&hInstance; switch (ulReason) { case DLL_PROCESS_ATTACH: gc_init(); _minit(); _moduleCtor(); // _moduleUnitTests(); MessageBoxA(null,"ATTACH",null,MB_OK); break; case DLL_PROCESS_DETACH: MessageBoxA(null,"DETACH",null,MB_OK); gc_term(); break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: // Multiple threads not supported yet MessageBoxA(null,"THREAD",null,MB_OK); return false; } g_hInst=hInstance; return true; } /* * DllGetClassObject * * Purpose: * Provides an IClassFactory for a given CLSID that this DLL is * registered to support. This DLL is placed under the CLSID * in the registration database as the InProcServer. * * Parameters: * clsID REFCLSID that identifies the class factory * desired. Since this parameter is passed this * DLL can handle any number of objects simply * by returning different class factories here * for different CLSIDs. * * riid REFIID specifying the interface the caller wants * on the class object, usually IID_ClassFactory. * * ppv LPVOID * in which to return the interface * pointer. * * Return Value: * HRESULT NOERROR on success, otherwise an error code. */ HRESULT DllGetClassObject(CLSID* rclsid, IID* riid, LPVOID * ppv) { HRESULT hr; CHelloClassFactory pObj; MessageBoxA(null, "DllGetClassObject()", null, MB_OK); //printf("DllGetClassObject()\n"); if (CLSID_Hello != *rclsid) return E_FAIL; pObj = new CHelloClassFactory(); if (!pObj) return E_OUTOFMEMORY; hr = pObj.QueryInterface(riid, ppv); if (FAILED(hr)) delete pObj; return hr; } /* * Answers if the DLL can be freed, that is, if there are no * references to anything this DLL provides. * * Return Value: * BOOL true if nothing is using us, false otherwise. */ HRESULT DllCanUnloadNow() { SCODE sc; MessageBoxA(null, "DllCanUnloadNow()", null, MB_OK); // Any locks or objects? sc = (0 == g_cObj && 0 == g_cLock) ? S_OK : S_FALSE; return sc; } /* * Instructs the server to create its own registry entries * * Return Value: * HRESULT NOERROR if registration successful, error * otherwise. */ HRESULT DllRegisterServer() { char szID[128]; char szCLSID[128]; char szModule[512]; MessageBoxA(null,"DllRegisterServer()",null,MB_OK); //Create some base key strings. StringFromGUID2(&CLSID_Hello, cast(LPOLESTR)szID, 128); unicode2ansi(szID.ptr); strcpy(szCLSID.ptr, "CLSID\\"); strcat(szCLSID.ptr, szID.ptr); //Create ProgID keys SetKeyAndValue("Hello1.0", null, "Hello Object"); SetKeyAndValue("Hello1.0", "CLSID", szID.ptr); //Create VersionIndependentProgID keys SetKeyAndValue("Hello", null, "Hello Object"); SetKeyAndValue("Hello", "CurVer", "Hello1.0"); SetKeyAndValue("Hello", "CLSID", szID.ptr); //Create entries under CLSID SetKeyAndValue(szCLSID.ptr, null, "Hello Object"); SetKeyAndValue(szCLSID.ptr, "ProgID", "Hello1.0"); SetKeyAndValue(szCLSID.ptr, "VersionIndependentProgID", "Hello"); SetKeyAndValue(szCLSID.ptr, "NotInsertable", null); GetModuleFileNameA(g_hInst, szModule.ptr, szModule.length); SetKeyAndValue(szCLSID.ptr, "InprocServer32", szModule.ptr); return NOERROR; } /* * Purpose: * Instructs the server to remove its own registry entries * * Return Value: * HRESULT NOERROR if registration successful, error * otherwise. */ HRESULT DllUnregisterServer() { char szID[128]; char szCLSID[128]; char szTemp[256]; MessageBoxA(null,"DllUnregisterServer()",null,MB_OK); //Create some base key strings. StringFromGUID2(&CLSID_Hello, cast(LPOLESTR)szID, 128); unicode2ansi(szID.ptr); strcpy(szCLSID.ptr, "CLSID\\"); strcat(szCLSID.ptr, szID.ptr); RegDeleteKeyA(HKEY_CLASSES_ROOT, "Hello\\CurVer"); RegDeleteKeyA(HKEY_CLASSES_ROOT, "Hello\\CLSID"); RegDeleteKeyA(HKEY_CLASSES_ROOT, "Hello"); RegDeleteKeyA(HKEY_CLASSES_ROOT, "Hello1.0\\CLSID"); RegDeleteKeyA(HKEY_CLASSES_ROOT, "Hello1.0"); strcpy(szTemp.ptr, szCLSID.ptr); strcat(szTemp.ptr, "\\"); strcat(szTemp.ptr, "ProgID"); RegDeleteKeyA(HKEY_CLASSES_ROOT, szTemp.ptr); strcpy(szTemp.ptr, szCLSID.ptr); strcat(szTemp.ptr, "\\"); strcat(szTemp.ptr, "VersionIndependentProgID"); RegDeleteKeyA(HKEY_CLASSES_ROOT, szTemp.ptr); strcpy(szTemp.ptr, szCLSID.ptr); strcat(szTemp.ptr, "\\"); strcat(szTemp.ptr, "NotInsertable"); RegDeleteKeyA(HKEY_CLASSES_ROOT, szTemp.ptr); strcpy(szTemp.ptr, szCLSID.ptr); strcat(szTemp.ptr, "\\"); strcat(szTemp.ptr, "InprocServer32"); RegDeleteKeyA(HKEY_CLASSES_ROOT, szTemp.ptr); RegDeleteKeyA(HKEY_CLASSES_ROOT, szCLSID.ptr); return NOERROR; } /* * SetKeyAndValue * * Purpose: * Private helper function for DllRegisterServer that creates * a key, sets a value, and closes that key. * * Parameters: * pszKey LPTSTR to the name of the key * pszSubkey LPTSTR ro the name of a subkey * pszValue LPTSTR to the value to store * * Return Value: * BOOL true if successful, false otherwise. */ BOOL SetKeyAndValue(LPCSTR pszKey, LPCSTR pszSubkey, LPCSTR pszValue) { HKEY hKey; char szKey[256]; BOOL result; strcpy(szKey.ptr, pszKey); if (pszSubkey) { strcat(szKey.ptr, "\\"); strcat(szKey.ptr, pszSubkey); } result = true; if (ERROR_SUCCESS != RegCreateKeyExA(HKEY_CLASSES_ROOT , szKey.ptr, 0, null, REG_OPTION_NON_VOLATILE , KEY_ALL_ACCESS, null, &hKey, null)) result = false; else { if (null!=pszValue) { if (RegSetValueExA(hKey, null, 0, REG_SZ, cast(BYTE *)pszValue , (strlen(pszValue)+1)*char.sizeof) != ERROR_SUCCESS) result = false; } if (RegCloseKey(hKey) != ERROR_SUCCESS) result = false; } if (!result) MessageBoxA(null,"SetKeyAndValue() failed",null,MB_OK); return result; } /* * ObjectDestroyed * * Purpose: * Function for the Hello object to call when it gets destroyed. * Since we're in a DLL we only track the number of objects here, * letting DllCanUnloadNow take care of the rest. */ extern (D) void ObjectDestroyed() { MessageBoxA(null,"ObjectDestroyed()",null,MB_OK); g_cObj--; } void unicode2ansi(char *s) { wchar *w; for (w = cast(wchar *)s; *w; w++) *s++ = *w; *s = 0; } extern (C) int printf(char *format, ...) { return 0; }
D
// //------------------------------------------------------------------------------ // Copyright 2012-2019 Coverify Systems Technology // Copyright 2007-2014 Mentor Graphics Corporation // Copyright 2010-2014 Synopsys, Inc. // Copyright 2007-2018 Cadence Design Systems, Inc. // Copyright 2011 AMD // Copyright 2014-2018 NVIDIA Corporation // All Rights Reserved Worldwide // // Licensed under the Apache License, Version 2.0 (the // "License"); you may not use this file except in // compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in // writing, software distributed under the License is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See // the License for the specific language governing // permissions and limitations under the License. //------------------------------------------------------------------------------ module uvm.base.uvm_pool; import uvm.base.uvm_object: uvm_object; import uvm.base.uvm_printer: uvm_printer; import uvm.base.uvm_object_defines; import uvm.base.uvm_once; import uvm.meta.meta; import uvm.meta.misc; import esdl.rand.misc: _esdl__Norand; import std.conv: to; // Title -- NODOCS -- Pool Classes // This section defines the <uvm_pool #(KEY, VAL)> class and derivative. //------------------------------------------------------------------------------ // // CLASS -- NODOCS -- uvm_pool #(KEY,VAL) // //------------------------------------------------------------------------------ // Implements a class-based dynamic associative array. Allows sparse arrays to // be allocated on demand, and passed and stored by reference. //------------------------------------------------------------------------------ // @uvm-ieee 1800.2-2017 auto 11.2.1 class uvm_pool(KEY=int, VAL=uvm_void): uvm_object, _esdl__Norand { alias uvm_pool!(KEY,VAL) this_type; protected VAL[KEY] _pool; mixin uvm_object_essentials; // Allow no aliasing, since aliasing leaks out the original assoc // array thus putting concurrency in peril // For this aliasing VAL[KEY] dup_pool() { synchronized (this) { static if (__traits(compiles, _pool.dup)) { return _pool.dup; } else { assert (false, "Cannot copy: " ~ typeof(_pool).stringof); // return null; } } } // alias dup_pool this; // Function -- NODOCS -- new // // Creates a new pool with the given ~name~. // @uvm-ieee 1800.2-2017 auto 11.2.2.1 this(string name="") { synchronized (this) { super(name); } } int opApply(int delegate(ref KEY, ref VAL) dg) { synchronized (this) { int result = 0; auto keys = _pool.keys; for (size_t i = 0; i != keys.length; ++i) { result = dg(keys[i], _pool[keys[i]]); if (result) { break; } } return result; } } int opApply(int delegate(ref VAL) dg) { synchronized (this) { int result = 0; auto keys = _pool.keys; for (size_t i = 0; i != keys.length; ++i) { result = dg(_pool[keys[i]]); if (result) { break; } } return result; } } // We delibrately do not return a pointer from opBinaryRight since // that pointer can in that case escape the concurrency guards bool opBinaryRight(string OP)(KEY key) if (OP == "in") { synchronized (this) { if (key in _pool) { return true; } else { return false; } } } void opIndexAssign(VAL val, KEY key) { synchronized (this) { _pool[key] = val; } } VAL opIndex(KEY key) { synchronized (this) { return _pool[key]; } } // Function -- NODOCS -- get_global_pool // // Returns the singleton global pool for the item type, VAL. // // This allows items to be shared amongst components throughout the // verification environment. static class uvm_once: uvm_once_base { @uvm_immutable_sync this_type _m_global_pool; this() { synchronized (this) { _m_global_pool = new this_type("pool"); } } } mixin (uvm_once_sync_string); // private __gshared this_type[uvm_object] _m_global_pool; static this_type get_global_pool() { // import uvm.base.uvm_coreservice; // synchronized (typeid(this_type)) { // uvm_coreservice_t cs = uvm_coreservice_t.get(); // uvm_root top = cs.get_root(); // if (top !in _m_global_pool || _m_global_pool[top] is null) { // _m_global_pool[top] = new this_type("pool"); // } // return _m_global_pool[top]; // } return m_global_pool; } // Function -- NODOCS -- get_global // // Returns the specified item instance from the global item pool. // @uvm-ieee 1800.2-2017 auto 11.2.2.3 static VAL get_global(KEY key) { return m_global_pool.get(key); } // Function -- NODOCS -- get // // Returns the item with the given ~key~. // // If no item exists by that key, a new item is created with that key // and returned. // @uvm-ieee 1800.2-2017 auto 11.2.2.4 VAL get(KEY key) { synchronized (this) { VAL* vptr = key in _pool; if (vptr is null) { VAL default_value; _pool[key] = default_value; return default_value; } else { return *vptr; } } } // Function -- NODOCS -- add // // Adds the given (~key~, ~item~) pair to the pool. If an item already // exists at the given ~key~ it is overwritten with the new ~item~. // @uvm-ieee 1800.2-2017 auto 11.2.2.5 void add(KEY key, VAL item) { synchronized (this) { _pool[key] = item; } } // Function -- NODOCS -- num // // Returns the number of uniquely keyed items stored in the pool. // @uvm-ieee 1800.2-2017 auto 11.2.2.6 size_t num() { synchronized (this) { return _pool.length; } } alias length = num; // Function -- NODOCS -- delete // // Removes the item with the given ~key~ from the pool. // @uvm-ieee 1800.2-2017 auto 11.2.2.7 void remove(KEY key) { import uvm.base.uvm_globals; synchronized (this) { if (!exists(key)) { uvm_report_warning("POOLDEL", "delete: pool key doesn't exist. " ~ "Ignoring delete request"); return; } _pool.remove(key); } } void remove() { synchronized (this) { _pool.clear(); } } void clear() { synchronized (this) { _pool.clear(); } } // Function -- NODOCS -- exists // // Returns 1 if a item with the given ~key~ exists in the pool, // 0 otherwise. // @uvm-ieee 1800.2-2017 auto 11.2.2.8 bool exists(KEY key) { synchronized (this) { if (key in _pool) return true; else return false; } } // We are not defining the iterative operators for pool. Instead we // expose the protected member pool using "this" alias. private size_t _index; private KEY[] _keys; // Function -- NODOCS -- first // // Returns the key of the first item stored in the pool. // // If the pool is empty, then ~key~ is unchanged and 0 is returned. // // If the pool is not empty, then ~key~ is key of the first item // and 1 is returned. // @uvm-ieee 1800.2-2017 auto 11.2.2.9 int first(ref KEY key) { import std.algorithm; synchronized (this) { this._keys = _pool.keys; static if (__traits(compiles, KEY.init < KEY.init)) { sort(_keys); } if (_keys.length == 0) { return 0; } else { _index = 0; key = _keys[_index]; return 1; } } } // Function -- NODOCS -- last // // Returns the key of the last item stored in the pool. // // If the pool is empty, then 0 is returned and ~key~ is unchanged. // // If the pool is not empty, then ~key~ is set to the last key in // the pool and 1 is returned. // @uvm-ieee 1800.2-2017 auto 11.2.2.10 int last(ref KEY key) { import std.algorithm; synchronized (this) { this._keys = _pool.keys; static if (__traits(compiles, KEY.init < KEY.init)) { sort(_keys); } if (_keys.length == 0) { return 0; } else { _index = _keys.length - 1; key = _keys[_index]; return 1; } } } // Function -- NODOCS -- next // // Returns the key of the next item in the pool. // // If the input ~key~ is the last key in the pool, then ~key~ is // left unchanged and 0 is returned. // // If a next key is found, then ~key~ is updated with that key // and 1 is returned. // @uvm-ieee 1800.2-2017 auto 11.2.2.11 int next(ref KEY key) { synchronized (this) { if (_keys.length == 0 || _keys.length - 1 <= _index) { return 0; } else { ++_index; key = _keys[_index]; return 1; } } } // Function -- NODOCS -- prev // // Returns the key of the previous item in the pool. // // If the input ~key~ is the first key in the pool, then ~key~ is // left unchanged and 0 is returned. // // If a previous key is found, then ~key~ is updated with that key // and 1 is returned. // @uvm-ieee 1800.2-2017 auto 11.2.2.12 int prev(ref KEY key) { synchronized (this) { if (_keys.length == 0 || _index == 0) { return 0; } else { --_index; key = _keys[_index]; return 1; } } } override void do_copy(uvm_object rhs) { if (rhs is null) { return; } auto p = cast (this_type) rhs; if (p is null) { return; } super.do_copy(rhs); synchronized (this) { _pool = p.dup_pool; } } override void do_print(uvm_printer printer) { synchronized (this) { size_t cnt; printer.print_array_header("pool", _pool.length, "aa_object_string"); foreach (key, val; _pool) { string item = "[-key" ~ cnt.to!string() ~ "--]"; string v = val.to!string; printer.print_generic(item,"",-1,v,'['); ++cnt; } printer.print_array_footer(); } } }; //------------------------------------------------------------------------------ // // CLASS -- NODOCS -- uvm_object_string_pool #(VAL) // //------------------------------------------------------------------------------ // This provides a specialization of the generic <uvm_pool #(KEY,VAL)> class for // an associative array of <uvm_object>-based objects indexed by string. // Specializations of this class include the ~uvm_event_pool~ (a // uvm_object_string_pool storing <uvm_event>s) and // ~uvm_barrier_pool~ (a uvm_obejct_string_pool storing <uvm_barrier>s). //------------------------------------------------------------------------------ class uvm_object_string_pool(VAL=uvm_object): uvm_pool!(string,VAL) { alias this_type = uvm_object_string_pool!(VAL); mixin uvm_object_essentials; // Function -- NODOCS -- new // // Creates a new pool with the given ~name~. this(string name = "") { synchronized (this) { super(name); } } // Function -- NODOCS -- get_global_pool // // Returns the singleton global pool for the item type, VAL. // // This allows items to be shared amongst components throughout the // verification environment. // private __gshared this_type[uvm_object] _m_global_pool; static class uvm_once: uvm_once_base { @uvm_immutable_sync this_type _m_global_pool; this() { synchronized (this) { _m_global_pool = new this_type("pool"); } } } mixin (uvm_once_sync_string); static this_type get_global_pool() { // import uvm.base.uvm_coreservice; // synchronized (typeid(this_type)) { // uvm_coreservice_t cs = uvm_coreservice_t.get(); // uvm_root top = cs.get_root(); // if (top !in _m_global_pool || _m_global_pool[top] is null) { // _m_global_pool[top] = new this_type("global_pool"); // } // return _m_global_pool[top]; // } return m_global_pool; } // Function -- NODOCS -- get_global // // Returns the specified item instance from the global item pool. static VAL get_global(string key) { return m_global_pool.get(key); } // Function -- NODOCS -- get // // Returns the object item at the given string ~key~. // // If no item exists by the given ~key~, a new item is created for that key // and returned. override VAL get(string key) { synchronized (this) { VAL* vptr = key in _pool; if (vptr is null) { auto val = new VAL(key); _pool[key] = val; return val; } else { return *vptr; } } } // Function -- NODOCS -- remove // // Removes the item with the given string ~key~ from the pool. override void remove(string key) { import uvm.base.uvm_globals; import std.string: format; synchronized (this) { if (!exists(key)) { uvm_report_warning("POOLDEL", format("delete: key '%s' doesn't exist", key)); return; } _pool.remove(key); } } // Function- do_print override void do_print(uvm_printer printer) { synchronized (this) { printer.print_array_header("pool", _pool.length, "aa_object_string"); foreach (key,val; _pool) { printer.print_object("[" ~ key ~ "]", val, '['); } printer.print_array_footer(); } } } // Moved to uvm_aliases // import uvm.base.uvm_barrier; // import uvm.base.uvm_event; // alias uvm_object_string_pool!(uvm_barrier) uvm_barrier_pool; // alias uvm_object_string_pool!(uvm_event!(uvm_object)) uvm_event_pool; // alias uvm_queue_string_pool = uvm_object_string_pool!(uvm_queue!string); // alias uvm_string_object_resource_pool = // uvm_pool!(string, uvm_resource!(uvm_object));;
D
# FIXED ICallBLE/icall_lite_translation.obj: C:/ti/simplelink_cc2640r2_sdk_1_40_00_45/source/ti/ble5stack/icall/src/icall_lite_translation.c ICallBLE/icall_lite_translation.obj: C:/ti/simplelink_cc2640r2_sdk_1_40_00_45/source/ti/ble5stack/osal/src/inc/osal.h ICallBLE/icall_lite_translation.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_16.9.6.LTS/include/limits.h ICallBLE/icall_lite_translation.obj: C:/ti/simplelink_cc2640r2_sdk_1_40_00_45/source/ti/ble5stack/osal/src/inc/comdef.h ICallBLE/icall_lite_translation.obj: C:/ti/simplelink_cc2640r2_sdk_1_40_00_45/source/ti/ble5stack/hal/src/target/_common/hal_types.h ICallBLE/icall_lite_translation.obj: C:/ti/simplelink_cc2640r2_sdk_1_40_00_45/source/ti/ble5stack/hal/src/target/_common/../_common/cc26xx/_hal_types.h ICallBLE/icall_lite_translation.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_16.9.6.LTS/include/stdint.h ICallBLE/icall_lite_translation.obj: C:/ti/simplelink_cc2640r2_sdk_1_40_00_45/source/ti/ble5stack/hal/src/inc/hal_defs.h ICallBLE/icall_lite_translation.obj: C:/ti/simplelink_cc2640r2_sdk_1_40_00_45/source/ti/ble5stack/osal/src/inc/osal_memory.h ICallBLE/icall_lite_translation.obj: C:/ti/simplelink_cc2640r2_sdk_1_40_00_45/source/ti/ble5stack/osal/src/inc/osal_timers.h ICallBLE/icall_lite_translation.obj: C:/ti/simplelink_cc2640r2_sdk_1_40_00_45/source/ti/ble5stack/icall/src/inc/icall.h ICallBLE/icall_lite_translation.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_16.9.6.LTS/include/stdbool.h ICallBLE/icall_lite_translation.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_16.9.6.LTS/include/stdlib.h ICallBLE/icall_lite_translation.obj: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_16.9.6.LTS/include/linkage.h ICallBLE/icall_lite_translation.obj: C:/ti/simplelink_cc2640r2_sdk_1_40_00_45/source/ti/ble5stack/hal/src/inc/hal_assert.h ICallBLE/icall_lite_translation.obj: C:/ti/simplelink_cc2640r2_sdk_1_40_00_45/source/ti/ble5stack/hal/src/target/_common/hal_types.h ICallBLE/icall_lite_translation.obj: C:/ti/simplelink_cc2640r2_sdk_1_40_00_45/source/ti/ble5stack/icall/src/inc/icall_lite_translation.h C:/ti/simplelink_cc2640r2_sdk_1_40_00_45/source/ti/ble5stack/icall/src/icall_lite_translation.c: C:/ti/simplelink_cc2640r2_sdk_1_40_00_45/source/ti/ble5stack/osal/src/inc/osal.h: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_16.9.6.LTS/include/limits.h: C:/ti/simplelink_cc2640r2_sdk_1_40_00_45/source/ti/ble5stack/osal/src/inc/comdef.h: C:/ti/simplelink_cc2640r2_sdk_1_40_00_45/source/ti/ble5stack/hal/src/target/_common/hal_types.h: C:/ti/simplelink_cc2640r2_sdk_1_40_00_45/source/ti/ble5stack/hal/src/target/_common/../_common/cc26xx/_hal_types.h: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_16.9.6.LTS/include/stdint.h: C:/ti/simplelink_cc2640r2_sdk_1_40_00_45/source/ti/ble5stack/hal/src/inc/hal_defs.h: C:/ti/simplelink_cc2640r2_sdk_1_40_00_45/source/ti/ble5stack/osal/src/inc/osal_memory.h: C:/ti/simplelink_cc2640r2_sdk_1_40_00_45/source/ti/ble5stack/osal/src/inc/osal_timers.h: C:/ti/simplelink_cc2640r2_sdk_1_40_00_45/source/ti/ble5stack/icall/src/inc/icall.h: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_16.9.6.LTS/include/stdbool.h: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_16.9.6.LTS/include/stdlib.h: C:/ti/ccsv8/tools/compiler/ti-cgt-arm_16.9.6.LTS/include/linkage.h: C:/ti/simplelink_cc2640r2_sdk_1_40_00_45/source/ti/ble5stack/hal/src/inc/hal_assert.h: C:/ti/simplelink_cc2640r2_sdk_1_40_00_45/source/ti/ble5stack/hal/src/target/_common/hal_types.h: C:/ti/simplelink_cc2640r2_sdk_1_40_00_45/source/ti/ble5stack/icall/src/inc/icall_lite_translation.h:
D
module UnrealScript.UnrealEd.FaceFXStudioSkelComponent; import ScriptClasses; import UnrealScript.Helpers; import UnrealScript.Engine.SkeletalMeshComponent; extern(C++) interface FaceFXStudioSkelComponent : SkeletalMeshComponent { public extern(D): private static __gshared ScriptClass mStaticClass; @property final static ScriptClass StaticClass() { mixin(MGSCC("Class UnrealEd.FaceFXStudioSkelComponent")); } private static __gshared FaceFXStudioSkelComponent mDefaultProperties; @property final static FaceFXStudioSkelComponent DefaultProperties() { mixin(MGDPC("FaceFXStudioSkelComponent", "FaceFXStudioSkelComponent UnrealEd.Default__FaceFXStudioSkelComponent")); } }
D
PLONG PLAT ED95 KD LOMAGAGE HIMAGAGE SLAT SLONG RESULTNO DP DM WT ROCKTYPE 264.399994 75 15.6000004 0 2 65 -8.80000019 126.699997 1206 10.3999996 18 0.370506191 extrusives, intrusives 317 63 14 16 23 56 -32.5 151 1840 20 20 0.474967739 extrusives, basalts 305 73 17 29 23 56 -42 147 1821 25 29 0.414576134 extrusives, basalts 275.5 71.0999985 3.5 45.5 33 36 -31.7000008 150.199997 1891 4.80000019 4.80000019 0.986572482 extrusives
D
/Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/SQL.build/SQLUpdate.swift.o : /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLBind.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLJoinMethod.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLTable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLCreateTable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDropTable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLAlterTable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLSerializable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDataType.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLUpdate.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDelete.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLLiteral.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLBoolLiteral.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDefaultLiteral.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLTableConstraintAlgorithm.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLColumnConstraintAlgorithm.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLJoin.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLExpression.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLSelectExpression.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLCollation.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLForeignKeyAction.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLConnection.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDirection.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLFunction.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLColumnDefinition.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLCreateTableBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDropTableBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLAlterTableBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLPredicateBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLUpdateBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDeleteBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLColumnBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLPredicateGroupBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLSelectBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLInsertBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLRawBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLCreateIndexBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLQueryBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLQueryEncoder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLQueryFetcher.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLIndexModifier.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLIdentifier.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLTableIdentifier.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLColumnIdentifier.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLError.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLBinaryOperator.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/Exports.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLSelect.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDistinct.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLFunctionArgument.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLTableConstraint.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLColumnConstraint.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLInsert.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLCreateIndex.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDropIndex.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLGroupBy.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLOrderBy.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLForeignKey.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLPrimaryKey.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLQuery.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Service.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Core.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/COperatingSystem.swiftmodule /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 /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/DatabaseKit.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOHTTP1.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/SQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/PostgreSQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/FluentPostgreSQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/FluentSQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIO.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/HTTP.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOTLS.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Async.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Command.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Service.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Console.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Core.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/SQLite.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/FluentSQLite.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOPriorityQueue.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Logging.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Debugging.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Routing.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/SQLBenchmark.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/FluentBenchmark.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/COperatingSystem.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Random.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/URLEncodedForm.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Authentication.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Validation.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Crypto.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/App.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Vapor.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Redis.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Bits.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/WebSocket.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOWebSocket.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/DatabaseKit.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/TemplateKit.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Fluent.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Multipart.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/swift-nio-zlib-support/module.modulemap /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/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/SQL.build/SQLUpdate~partial.swiftmodule : /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLBind.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLJoinMethod.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLTable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLCreateTable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDropTable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLAlterTable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLSerializable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDataType.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLUpdate.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDelete.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLLiteral.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLBoolLiteral.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDefaultLiteral.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLTableConstraintAlgorithm.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLColumnConstraintAlgorithm.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLJoin.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLExpression.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLSelectExpression.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLCollation.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLForeignKeyAction.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLConnection.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDirection.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLFunction.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLColumnDefinition.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLCreateTableBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDropTableBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLAlterTableBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLPredicateBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLUpdateBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDeleteBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLColumnBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLPredicateGroupBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLSelectBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLInsertBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLRawBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLCreateIndexBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLQueryBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLQueryEncoder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLQueryFetcher.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLIndexModifier.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLIdentifier.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLTableIdentifier.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLColumnIdentifier.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLError.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLBinaryOperator.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/Exports.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLSelect.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDistinct.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLFunctionArgument.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLTableConstraint.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLColumnConstraint.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLInsert.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLCreateIndex.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDropIndex.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLGroupBy.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLOrderBy.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLForeignKey.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLPrimaryKey.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLQuery.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Service.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Core.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/COperatingSystem.swiftmodule /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 /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/DatabaseKit.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOHTTP1.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/SQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/PostgreSQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/FluentPostgreSQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/FluentSQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIO.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/HTTP.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOTLS.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Async.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Command.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Service.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Console.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Core.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/SQLite.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/FluentSQLite.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOPriorityQueue.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Logging.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Debugging.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Routing.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/SQLBenchmark.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/FluentBenchmark.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/COperatingSystem.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Random.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/URLEncodedForm.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Authentication.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Validation.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Crypto.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/App.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Vapor.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Redis.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Bits.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/WebSocket.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOWebSocket.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/DatabaseKit.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/TemplateKit.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Fluent.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Multipart.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/swift-nio-zlib-support/module.modulemap /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/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/SQL.build/SQLUpdate~partial.swiftdoc : /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLBind.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLJoinMethod.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLTable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLCreateTable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDropTable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLAlterTable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLSerializable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDataType.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLUpdate.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDelete.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLLiteral.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLBoolLiteral.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDefaultLiteral.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLTableConstraintAlgorithm.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLColumnConstraintAlgorithm.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLJoin.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLExpression.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLSelectExpression.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLCollation.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLForeignKeyAction.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLConnection.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDirection.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLFunction.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLColumnDefinition.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLCreateTableBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDropTableBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLAlterTableBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLPredicateBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLUpdateBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDeleteBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLColumnBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLPredicateGroupBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLSelectBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLInsertBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLRawBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLCreateIndexBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLQueryBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLQueryEncoder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLQueryFetcher.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLIndexModifier.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLIdentifier.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLTableIdentifier.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLColumnIdentifier.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLError.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLBinaryOperator.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/Exports.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLSelect.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDistinct.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLFunctionArgument.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLTableConstraint.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLColumnConstraint.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLInsert.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLCreateIndex.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDropIndex.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLGroupBy.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLOrderBy.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLForeignKey.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLPrimaryKey.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLQuery.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Service.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Core.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/COperatingSystem.swiftmodule /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 /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/DatabaseKit.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOHTTP1.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/SQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/PostgreSQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/FluentPostgreSQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/FluentSQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIO.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/HTTP.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOTLS.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Async.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Command.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Service.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Console.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Core.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/SQLite.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/FluentSQLite.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOPriorityQueue.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Logging.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Debugging.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Routing.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/SQLBenchmark.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/FluentBenchmark.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/COperatingSystem.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Random.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/URLEncodedForm.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Authentication.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Validation.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Crypto.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/App.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Vapor.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Redis.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Bits.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/WebSocket.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOWebSocket.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/DatabaseKit.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/TemplateKit.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Fluent.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Multipart.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/swift-nio-zlib-support/module.modulemap /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/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/SQL.build/SQLUpdate~partial.swiftsourceinfo : /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLBind.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLJoinMethod.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLTable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLCreateTable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDropTable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLAlterTable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLSerializable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDataType.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLUpdate.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDelete.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLLiteral.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLBoolLiteral.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDefaultLiteral.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLTableConstraintAlgorithm.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLColumnConstraintAlgorithm.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLJoin.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLExpression.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLSelectExpression.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLCollation.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLForeignKeyAction.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLConnection.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDirection.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLFunction.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLColumnDefinition.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLCreateTableBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDropTableBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLAlterTableBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLPredicateBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLUpdateBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDeleteBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLColumnBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLPredicateGroupBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLSelectBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLInsertBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLRawBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLCreateIndexBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLQueryBuilder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLQueryEncoder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLQueryFetcher.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLIndexModifier.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLIdentifier.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLTableIdentifier.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLColumnIdentifier.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLError.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLBinaryOperator.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/Exports.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLSelect.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDistinct.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLFunctionArgument.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLTableConstraint.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLColumnConstraint.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLInsert.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLCreateIndex.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLDropIndex.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLGroupBy.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLOrderBy.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLForeignKey.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLPrimaryKey.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/sql/Sources/SQL/SQLQuery.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Service.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Core.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/COperatingSystem.swiftmodule /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 /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/DatabaseKit.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOHTTP1.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/SQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/PostgreSQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/FluentPostgreSQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/FluentSQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIO.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/HTTP.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOTLS.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Async.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Command.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Service.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Console.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Core.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/SQLite.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/FluentSQLite.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOPriorityQueue.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Logging.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Debugging.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Routing.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/SQLBenchmark.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/FluentBenchmark.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/COperatingSystem.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Random.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/URLEncodedForm.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Authentication.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Validation.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Crypto.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/App.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Vapor.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Redis.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Bits.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/WebSocket.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/NIOWebSocket.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/DatabaseKit.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/TemplateKit.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Fluent.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/Multipart.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppUsers/.build/checkouts/swift-nio-zlib-support/module.modulemap /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
module evael.network.packet; import evael.lib.containers : Array; struct Packet { public Array!ubyte data; @nogc public this(in size_t capacity) { this.data = Array!ubyte(capacity); this.data.length = capacity; } @nogc public ~this() { this.data.dispose(); } }
D
/Users/zaidtayyab/Desktop/Template/Build/Template/Build/Intermediates/Pods.build/Debug-iphonesimulator/Kingfisher.build/Objects-normal/x86_64/Indicator.o : /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/String+MD5.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/Resource.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/Image.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/ImageCache.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/ImageTransition.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/KingfisherOptionsInfo.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/ImageDownloader.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/KingfisherManager.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/ImagePrefetcher.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/UIButton+Kingfisher.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/ImageView+Kingfisher.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/Kingfisher.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/RequestModifier.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/ThreadHelper.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/Filter.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/CacheSerializer.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/ImageProcessor.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/Indicator.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/AnimatedImageView.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/Box.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/Kingfisher/Kingfisher-umbrella.h /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/Kingfisher.h /Users/zaidtayyab/Desktop/Template/Build/Template/Build/Intermediates/Pods.build/Debug-iphonesimulator/Kingfisher.build/unextended-module.modulemap /Users/zaidtayyab/Desktop/Template/Build/Template/Build/Intermediates/Pods.build/Debug-iphonesimulator/Kingfisher.build/Objects-normal/x86_64/Indicator~partial.swiftmodule : /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/String+MD5.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/Resource.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/Image.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/ImageCache.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/ImageTransition.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/KingfisherOptionsInfo.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/ImageDownloader.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/KingfisherManager.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/ImagePrefetcher.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/UIButton+Kingfisher.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/ImageView+Kingfisher.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/Kingfisher.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/RequestModifier.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/ThreadHelper.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/Filter.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/CacheSerializer.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/ImageProcessor.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/Indicator.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/AnimatedImageView.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/Box.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/Kingfisher/Kingfisher-umbrella.h /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/Kingfisher.h /Users/zaidtayyab/Desktop/Template/Build/Template/Build/Intermediates/Pods.build/Debug-iphonesimulator/Kingfisher.build/unextended-module.modulemap /Users/zaidtayyab/Desktop/Template/Build/Template/Build/Intermediates/Pods.build/Debug-iphonesimulator/Kingfisher.build/Objects-normal/x86_64/Indicator~partial.swiftdoc : /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/String+MD5.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/Resource.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/Image.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/ImageCache.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/ImageTransition.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/KingfisherOptionsInfo.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/ImageDownloader.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/KingfisherManager.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/ImagePrefetcher.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/UIButton+Kingfisher.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/ImageView+Kingfisher.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/Kingfisher.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/RequestModifier.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/ThreadHelper.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/Filter.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/CacheSerializer.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/ImageProcessor.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/Indicator.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/AnimatedImageView.swift /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/Box.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/Kingfisher/Kingfisher-umbrella.h /Users/zaidtayyab/Desktop/Template/Pods/Kingfisher/Sources/Kingfisher.h /Users/zaidtayyab/Desktop/Template/Build/Template/Build/Intermediates/Pods.build/Debug-iphonesimulator/Kingfisher.build/unextended-module.modulemap
D
module org.serviio.upnp.protocol.soap.SOAPParameter; import java.lang.String; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /// FIXME: //@Retention(RetentionPolicy.RUNTIME) //@Target({java.lang.annotation.ElementType.PARAMETER}) public /*@*/interface SOAPParameter { /*public abstract*/ String value(); } /* Location: D:\Program Files\Serviio\lib\serviio.jar * Qualified Name: org.serviio.upnp.protocol.soap.SOAPParameter * JD-Core Version: 0.6.2 */
D
/home/jean/Documents/EDS_project_Alarm_Part/Software/target/rls/debug/build/proc-macro2-b8072f251f87f12e/build_script_build-b8072f251f87f12e: /home/jean/.cargo/registry/src/github.com-1ecc6299db9ec823/proc-macro2-0.4.30/build.rs /home/jean/Documents/EDS_project_Alarm_Part/Software/target/rls/debug/build/proc-macro2-b8072f251f87f12e/build_script_build-b8072f251f87f12e.d: /home/jean/.cargo/registry/src/github.com-1ecc6299db9ec823/proc-macro2-0.4.30/build.rs /home/jean/.cargo/registry/src/github.com-1ecc6299db9ec823/proc-macro2-0.4.30/build.rs:
D
/Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/DerivedData/NetflixRoulette/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/AlamofireImage.build/Objects-normal/x86_64/ImageFilter.o : /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/Image.swift /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/UIImage+AlamofireImage.swift /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/UIButton+AlamofireImage.swift /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/Request+AlamofireImage.swift /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/UIImageView+AlamofireImage.swift /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/ImageCache.swift /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/ImageDownloader.swift /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/ImageFilter.swift /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/AFIError.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/DerivedData/NetflixRoulette/Build/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/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/Target\ Support\ Files/AlamofireImage/AlamofireImage-umbrella.h /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/Target\ Support\ Files/Alamofire/Alamofire-umbrella.h /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/DerivedData/NetflixRoulette/Build/Products/Debug-iphonesimulator/Alamofire/Alamofire.framework/Headers/Alamofire-Swift.h /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/DerivedData/NetflixRoulette/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/AlamofireImage.build/unextended-module.modulemap /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/DerivedData/NetflixRoulette/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/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/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/DerivedData/NetflixRoulette/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/AlamofireImage.build/Objects-normal/x86_64/ImageFilter~partial.swiftmodule : /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/Image.swift /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/UIImage+AlamofireImage.swift /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/UIButton+AlamofireImage.swift /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/Request+AlamofireImage.swift /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/UIImageView+AlamofireImage.swift /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/ImageCache.swift /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/ImageDownloader.swift /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/ImageFilter.swift /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/AFIError.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/DerivedData/NetflixRoulette/Build/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/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/Target\ Support\ Files/AlamofireImage/AlamofireImage-umbrella.h /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/Target\ Support\ Files/Alamofire/Alamofire-umbrella.h /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/DerivedData/NetflixRoulette/Build/Products/Debug-iphonesimulator/Alamofire/Alamofire.framework/Headers/Alamofire-Swift.h /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/DerivedData/NetflixRoulette/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/AlamofireImage.build/unextended-module.modulemap /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/DerivedData/NetflixRoulette/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/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/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/DerivedData/NetflixRoulette/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/AlamofireImage.build/Objects-normal/x86_64/ImageFilter~partial.swiftdoc : /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/Image.swift /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/UIImage+AlamofireImage.swift /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/UIButton+AlamofireImage.swift /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/Request+AlamofireImage.swift /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/UIImageView+AlamofireImage.swift /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/ImageCache.swift /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/ImageDownloader.swift /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/ImageFilter.swift /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/AlamofireImage/Source/AFIError.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/DerivedData/NetflixRoulette/Build/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/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/Target\ Support\ Files/AlamofireImage/AlamofireImage-umbrella.h /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/Pods/Target\ Support\ Files/Alamofire/Alamofire-umbrella.h /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/DerivedData/NetflixRoulette/Build/Products/Debug-iphonesimulator/Alamofire/Alamofire.framework/Headers/Alamofire-Swift.h /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/DerivedData/NetflixRoulette/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/AlamofireImage.build/unextended-module.modulemap /Users/ramzy/Desktop/swift/Netflix_Roulette_Repo_V1_Final/netflix-roulette/DerivedData/NetflixRoulette/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/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
/Users/phungdu/Documents/code/vapor/TILApp/Build/Intermediates/TILApp.build/Debug/HTTP.build/Objects-normal/x86_64/HTTPServer.o : /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Utilities/RFC1123.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Message/URL+HTTP.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Utilities/HTTPHeaders+Basic.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Message/Forwarded.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Message/MediaTypePreference.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Body/HTTPBodyStorage.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Message/HTTPMessage.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Body/HTTPBodyRepresentable.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Message/HTTPHeaderName.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Responder/HTTPScheme.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Message/HTTPResponse.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Cookies/HTTPCookieValue.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Body/HTTPChunkedStream.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Responder/HTTPClientProtocolUpgrader.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Responder/HTTPServerResponder.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Codable/HTTPMessageCoder.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Utilities/HTTPHeaders+Bearer.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Responder/HTTPServer.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Utilities/HTTPError.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Cookies/HTTPCookies.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Message/HTTPHeaders.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Utilities/String+IsIPAddress.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Exports.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Responder/HTTPClient.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Message/HTTPRequest.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Body/HTTPBody.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/NIOHTTP1.framework/Modules/NIOHTTP1.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/NIOOpenSSL.framework/Modules/NIOOpenSSL.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/NIO.framework/Modules/NIO.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/NIOTLS.framework/Modules/NIOTLS.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/Async.framework/Modules/Async.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/Core.framework/Modules/Core.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/Debugging.framework/Modules/Debugging.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/COperatingSystem.framework/Modules/COperatingSystem.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/NIOConcurrencyHelpers.framework/Modules/NIOConcurrencyHelpers.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/Bits.framework/Modules/Bits.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/NIOFoundationCompat.framework/Modules/NIOFoundationCompat.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /usr/local/Cellar/libressl/2.8.3/include/openssl/asn1.h /usr/local/Cellar/libressl/2.8.3/include/openssl/tls1.h /usr/local/Cellar/libressl/2.8.3/include/openssl/dtls1.h /usr/local/Cellar/libressl/2.8.3/include/openssl/pkcs12.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ssl2.h /usr/local/Cellar/libressl/2.8.3/include/openssl/pem2.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ssl23.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ssl3.h /usr/local/Cellar/libressl/2.8.3/include/openssl/x509v3.h /usr/local/Cellar/libressl/2.8.3/include/openssl/md5.h /usr/local/Cellar/libressl/2.8.3/include/openssl/pkcs7.h /usr/local/Cellar/libressl/2.8.3/include/openssl/x509.h /usr/local/Cellar/libressl/2.8.3/include/openssl/sha.h /usr/local/Cellar/libressl/2.8.3/include/openssl/dsa.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ecdsa.h /usr/local/Cellar/libressl/2.8.3/include/openssl/rsa.h /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOZlib.framework/Headers/CNIOZlib.h /usr/local/Cellar/libressl/2.8.3/include/openssl/obj_mac.h /usr/local/Cellar/libressl/2.8.3/include/openssl/hmac.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ec.h /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOAtomics.framework/Headers/cpp_magic.h /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOLinux.framework/Headers/ifaddrs-android.h /usr/local/Cellar/libressl/2.8.3/include/openssl/rand.h /usr/local/Cellar/libressl/2.8.3/include/openssl/conf.h /usr/local/Cellar/libressl/2.8.3/include/openssl/opensslconf.h /usr/local/Cellar/libressl/2.8.3/include/openssl/dh.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ecdh.h /usr/local/Cellar/libressl/2.8.3/include/openssl/lhash.h /usr/local/Cellar/libressl/2.8.3/include/openssl/stack.h /usr/local/Cellar/libressl/2.8.3/include/openssl/safestack.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ssl.h /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/swift-nio-ssl.git-364103626492085369/Sources/CNIOOpenSSL/include/c_nio_openssl.h /usr/local/Cellar/libressl/2.8.3/include/openssl/pem.h /usr/local/Cellar/libressl/2.8.3/include/openssl/bn.h /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIODarwin.framework/Headers/CNIODarwin.h /usr/local/Cellar/libressl/2.8.3/include/openssl/bio.h /usr/local/Cellar/libressl/2.8.3/include/openssl/crypto.h /usr/local/Cellar/libressl/2.8.3/include/openssl/srtp.h /usr/local/Cellar/libressl/2.8.3/include/openssl/evp.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ossl_typ.h /usr/local/Cellar/libressl/2.8.3/include/openssl/buffer.h /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOHTTPParser.framework/Headers/CNIOHTTPParser.h /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOHTTPParser.framework/Headers/c_nio_http_parser.h /usr/local/Cellar/libressl/2.8.3/include/openssl/err.h /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOAtomics.framework/Headers/CNIOAtomics.h /usr/local/Cellar/libressl/2.8.3/include/openssl/opensslfeatures.h /usr/local/Cellar/libressl/2.8.3/include/openssl/objects.h /usr/local/Cellar/libressl/2.8.3/include/openssl/opensslv.h /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOLinux.framework/Headers/CNIOLinux.h /usr/local/Cellar/libressl/2.8.3/include/openssl/x509_vfy.h /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/swift-nio-ssl-support.git-5405304412507994221/module.modulemap /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/swift-nio-zlib-support.git--5226887469817572071/module.modulemap /Users/phungdu/Documents/code/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIOOpenSSL/module.modulemap /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOZlib.framework/Modules/module.modulemap /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIODarwin.framework/Modules/module.modulemap /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOHTTPParser.framework/Modules/module.modulemap /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOAtomics.framework/Modules/module.modulemap /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOLinux.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes /Users/phungdu/Documents/code/vapor/TILApp/Build/Intermediates/TILApp.build/Debug/HTTP.build/Objects-normal/x86_64/HTTPServer~partial.swiftmodule : /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Utilities/RFC1123.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Message/URL+HTTP.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Utilities/HTTPHeaders+Basic.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Message/Forwarded.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Message/MediaTypePreference.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Body/HTTPBodyStorage.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Message/HTTPMessage.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Body/HTTPBodyRepresentable.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Message/HTTPHeaderName.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Responder/HTTPScheme.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Message/HTTPResponse.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Cookies/HTTPCookieValue.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Body/HTTPChunkedStream.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Responder/HTTPClientProtocolUpgrader.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Responder/HTTPServerResponder.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Codable/HTTPMessageCoder.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Utilities/HTTPHeaders+Bearer.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Responder/HTTPServer.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Utilities/HTTPError.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Cookies/HTTPCookies.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Message/HTTPHeaders.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Utilities/String+IsIPAddress.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Exports.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Responder/HTTPClient.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Message/HTTPRequest.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Body/HTTPBody.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/NIOHTTP1.framework/Modules/NIOHTTP1.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/NIOOpenSSL.framework/Modules/NIOOpenSSL.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/NIO.framework/Modules/NIO.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/NIOTLS.framework/Modules/NIOTLS.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/Async.framework/Modules/Async.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/Core.framework/Modules/Core.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/Debugging.framework/Modules/Debugging.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/COperatingSystem.framework/Modules/COperatingSystem.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/NIOConcurrencyHelpers.framework/Modules/NIOConcurrencyHelpers.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/Bits.framework/Modules/Bits.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/NIOFoundationCompat.framework/Modules/NIOFoundationCompat.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /usr/local/Cellar/libressl/2.8.3/include/openssl/asn1.h /usr/local/Cellar/libressl/2.8.3/include/openssl/tls1.h /usr/local/Cellar/libressl/2.8.3/include/openssl/dtls1.h /usr/local/Cellar/libressl/2.8.3/include/openssl/pkcs12.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ssl2.h /usr/local/Cellar/libressl/2.8.3/include/openssl/pem2.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ssl23.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ssl3.h /usr/local/Cellar/libressl/2.8.3/include/openssl/x509v3.h /usr/local/Cellar/libressl/2.8.3/include/openssl/md5.h /usr/local/Cellar/libressl/2.8.3/include/openssl/pkcs7.h /usr/local/Cellar/libressl/2.8.3/include/openssl/x509.h /usr/local/Cellar/libressl/2.8.3/include/openssl/sha.h /usr/local/Cellar/libressl/2.8.3/include/openssl/dsa.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ecdsa.h /usr/local/Cellar/libressl/2.8.3/include/openssl/rsa.h /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOZlib.framework/Headers/CNIOZlib.h /usr/local/Cellar/libressl/2.8.3/include/openssl/obj_mac.h /usr/local/Cellar/libressl/2.8.3/include/openssl/hmac.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ec.h /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOAtomics.framework/Headers/cpp_magic.h /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOLinux.framework/Headers/ifaddrs-android.h /usr/local/Cellar/libressl/2.8.3/include/openssl/rand.h /usr/local/Cellar/libressl/2.8.3/include/openssl/conf.h /usr/local/Cellar/libressl/2.8.3/include/openssl/opensslconf.h /usr/local/Cellar/libressl/2.8.3/include/openssl/dh.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ecdh.h /usr/local/Cellar/libressl/2.8.3/include/openssl/lhash.h /usr/local/Cellar/libressl/2.8.3/include/openssl/stack.h /usr/local/Cellar/libressl/2.8.3/include/openssl/safestack.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ssl.h /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/swift-nio-ssl.git-364103626492085369/Sources/CNIOOpenSSL/include/c_nio_openssl.h /usr/local/Cellar/libressl/2.8.3/include/openssl/pem.h /usr/local/Cellar/libressl/2.8.3/include/openssl/bn.h /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIODarwin.framework/Headers/CNIODarwin.h /usr/local/Cellar/libressl/2.8.3/include/openssl/bio.h /usr/local/Cellar/libressl/2.8.3/include/openssl/crypto.h /usr/local/Cellar/libressl/2.8.3/include/openssl/srtp.h /usr/local/Cellar/libressl/2.8.3/include/openssl/evp.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ossl_typ.h /usr/local/Cellar/libressl/2.8.3/include/openssl/buffer.h /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOHTTPParser.framework/Headers/CNIOHTTPParser.h /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOHTTPParser.framework/Headers/c_nio_http_parser.h /usr/local/Cellar/libressl/2.8.3/include/openssl/err.h /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOAtomics.framework/Headers/CNIOAtomics.h /usr/local/Cellar/libressl/2.8.3/include/openssl/opensslfeatures.h /usr/local/Cellar/libressl/2.8.3/include/openssl/objects.h /usr/local/Cellar/libressl/2.8.3/include/openssl/opensslv.h /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOLinux.framework/Headers/CNIOLinux.h /usr/local/Cellar/libressl/2.8.3/include/openssl/x509_vfy.h /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/swift-nio-ssl-support.git-5405304412507994221/module.modulemap /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/swift-nio-zlib-support.git--5226887469817572071/module.modulemap /Users/phungdu/Documents/code/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIOOpenSSL/module.modulemap /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOZlib.framework/Modules/module.modulemap /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIODarwin.framework/Modules/module.modulemap /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOHTTPParser.framework/Modules/module.modulemap /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOAtomics.framework/Modules/module.modulemap /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOLinux.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes /Users/phungdu/Documents/code/vapor/TILApp/Build/Intermediates/TILApp.build/Debug/HTTP.build/Objects-normal/x86_64/HTTPServer~partial.swiftdoc : /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Utilities/RFC1123.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Message/URL+HTTP.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Utilities/HTTPHeaders+Basic.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Message/Forwarded.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Message/MediaTypePreference.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Body/HTTPBodyStorage.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Message/HTTPMessage.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Body/HTTPBodyRepresentable.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Message/HTTPHeaderName.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Responder/HTTPScheme.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Message/HTTPResponse.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Cookies/HTTPCookieValue.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Body/HTTPChunkedStream.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Responder/HTTPClientProtocolUpgrader.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Responder/HTTPServerResponder.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Codable/HTTPMessageCoder.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Utilities/HTTPHeaders+Bearer.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Responder/HTTPServer.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Utilities/HTTPError.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Cookies/HTTPCookies.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Message/HTTPHeaders.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Utilities/String+IsIPAddress.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Exports.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Responder/HTTPClient.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Message/HTTPRequest.swift /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/http.git-6906648727968998715/Sources/HTTP/Body/HTTPBody.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/NIOHTTP1.framework/Modules/NIOHTTP1.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/NIOOpenSSL.framework/Modules/NIOOpenSSL.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/NIO.framework/Modules/NIO.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/NIOTLS.framework/Modules/NIOTLS.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/Async.framework/Modules/Async.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/Core.framework/Modules/Core.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/Debugging.framework/Modules/Debugging.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/COperatingSystem.framework/Modules/COperatingSystem.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/NIOConcurrencyHelpers.framework/Modules/NIOConcurrencyHelpers.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/Bits.framework/Modules/Bits.swiftmodule/x86_64.swiftmodule /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/NIOFoundationCompat.framework/Modules/NIOFoundationCompat.swiftmodule/x86_64.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /usr/local/Cellar/libressl/2.8.3/include/openssl/asn1.h /usr/local/Cellar/libressl/2.8.3/include/openssl/tls1.h /usr/local/Cellar/libressl/2.8.3/include/openssl/dtls1.h /usr/local/Cellar/libressl/2.8.3/include/openssl/pkcs12.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ssl2.h /usr/local/Cellar/libressl/2.8.3/include/openssl/pem2.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ssl23.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ssl3.h /usr/local/Cellar/libressl/2.8.3/include/openssl/x509v3.h /usr/local/Cellar/libressl/2.8.3/include/openssl/md5.h /usr/local/Cellar/libressl/2.8.3/include/openssl/pkcs7.h /usr/local/Cellar/libressl/2.8.3/include/openssl/x509.h /usr/local/Cellar/libressl/2.8.3/include/openssl/sha.h /usr/local/Cellar/libressl/2.8.3/include/openssl/dsa.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ecdsa.h /usr/local/Cellar/libressl/2.8.3/include/openssl/rsa.h /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOZlib.framework/Headers/CNIOZlib.h /usr/local/Cellar/libressl/2.8.3/include/openssl/obj_mac.h /usr/local/Cellar/libressl/2.8.3/include/openssl/hmac.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ec.h /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOAtomics.framework/Headers/cpp_magic.h /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOLinux.framework/Headers/ifaddrs-android.h /usr/local/Cellar/libressl/2.8.3/include/openssl/rand.h /usr/local/Cellar/libressl/2.8.3/include/openssl/conf.h /usr/local/Cellar/libressl/2.8.3/include/openssl/opensslconf.h /usr/local/Cellar/libressl/2.8.3/include/openssl/dh.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ecdh.h /usr/local/Cellar/libressl/2.8.3/include/openssl/lhash.h /usr/local/Cellar/libressl/2.8.3/include/openssl/stack.h /usr/local/Cellar/libressl/2.8.3/include/openssl/safestack.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ssl.h /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/swift-nio-ssl.git-364103626492085369/Sources/CNIOOpenSSL/include/c_nio_openssl.h /usr/local/Cellar/libressl/2.8.3/include/openssl/pem.h /usr/local/Cellar/libressl/2.8.3/include/openssl/bn.h /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIODarwin.framework/Headers/CNIODarwin.h /usr/local/Cellar/libressl/2.8.3/include/openssl/bio.h /usr/local/Cellar/libressl/2.8.3/include/openssl/crypto.h /usr/local/Cellar/libressl/2.8.3/include/openssl/srtp.h /usr/local/Cellar/libressl/2.8.3/include/openssl/evp.h /usr/local/Cellar/libressl/2.8.3/include/openssl/ossl_typ.h /usr/local/Cellar/libressl/2.8.3/include/openssl/buffer.h /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOHTTPParser.framework/Headers/CNIOHTTPParser.h /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOHTTPParser.framework/Headers/c_nio_http_parser.h /usr/local/Cellar/libressl/2.8.3/include/openssl/err.h /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOAtomics.framework/Headers/CNIOAtomics.h /usr/local/Cellar/libressl/2.8.3/include/openssl/opensslfeatures.h /usr/local/Cellar/libressl/2.8.3/include/openssl/objects.h /usr/local/Cellar/libressl/2.8.3/include/openssl/opensslv.h /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOLinux.framework/Headers/CNIOLinux.h /usr/local/Cellar/libressl/2.8.3/include/openssl/x509_vfy.h /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/swift-nio-ssl-support.git-5405304412507994221/module.modulemap /Users/phungdu/Documents/code/vapor/TILApp/.build/checkouts/swift-nio-zlib-support.git--5226887469817572071/module.modulemap /Users/phungdu/Documents/code/vapor/TILApp/TILApp.xcodeproj/GeneratedModuleMap/CNIOOpenSSL/module.modulemap /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOZlib.framework/Modules/module.modulemap /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIODarwin.framework/Modules/module.modulemap /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOHTTPParser.framework/Modules/module.modulemap /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOAtomics.framework/Modules/module.modulemap /Users/phungdu/Documents/code/vapor/TILApp/Build/Products/Debug/CNIOLinux.framework/Modules/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
D
/* * 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 pango.c.matrix; import pango.c.types; import glib; import gobject; extern(C): /** * PangoMatrix: * @xx: 1st component of the transformation matrix * @xy: 2nd component of the transformation matrix * @yx: 3rd component of the transformation matrix * @yy: 4th component of the transformation matrix * @x0: x translation * @y0: y translation * * A structure specifying a transformation between user-space * coordinates and device coordinates. The transformation * is given by * * <programlisting> * x_device = x_user * matrix->xx + y_user * matrix->xy + matrix->x0; * y_device = x_user * matrix->yx + y_user * matrix->yy + matrix->y0; * </programlisting> * * Since: 1.6 **/ struct PangoMatrix { double xx=1; double xy=0; double yx=0; double yy=1; double x0=0; double y0=0; } pure GType pango_matrix_get_type (); PangoMatrix *pango_matrix_copy (const(PangoMatrix) *matrix); void pango_matrix_free (PangoMatrix *matrix); void pango_matrix_translate (PangoMatrix *matrix, double tx, double ty); void pango_matrix_scale (PangoMatrix *matrix, double scale_x, double scale_y); void pango_matrix_rotate (PangoMatrix *matrix, double degrees); void pango_matrix_concat (PangoMatrix *matrix, const(PangoMatrix) *new_matrix); void pango_matrix_transform_point (const(PangoMatrix) *matrix, double *x, double *y); void pango_matrix_transform_distance (const(PangoMatrix) *matrix, double *dx, double *dy); void pango_matrix_transform_rectangle (const(PangoMatrix) *matrix, PangoRectangle *rect); void pango_matrix_transform_pixel_rectangle (const(PangoMatrix) *matrix, PangoRectangle *rect); pure double pango_matrix_get_font_scale_factor (const(PangoMatrix) *matrix);
D
/* * Copyright (c) 2004-2008 Derelict Developers * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the names 'Derelict', 'DerelictGL', nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ module derelict.opengl.extension.ext.multi_draw_arrays; private { import derelict.opengl.gltypes; import derelict.opengl.gl; import derelict.opengl.extension.loader; import derelict.util.wrapper; } private bool enabled = false; struct EXTMultiDrawArrays { static bool load(char[] extString) { if(extString.findStr("GL_EXT_multi_draw_arrays") == -1) return false; if(!glBindExtFunc(cast(void**)&glMultiDrawArraysEXT, "glMultiDrawArraysEXT")) return false; if(!glBindExtFunc(cast(void**)&glMultiDrawElementsEXT, "glMultiDrawElementsEXT")) return false; enabled = true; return true; } static bool isEnabled() { return enabled; } } version(DerelictGL_NoExtensionLoaders) { } else { static this() { DerelictGL.registerExtensionLoader(&EXTMultiDrawArrays.load); } } extern(System): typedef void function(GLenum, GLint*, GLsizei*, GLsizei) pfglMultiDrawArraysEXT; typedef void function(GLenum, GLsizei*, GLenum, GLvoid*, GLsizei) pfglMultiDrawElementsEXT; pfglMultiDrawArraysEXT glMultiDrawArraysEXT; pfglMultiDrawElementsEXT glMultiDrawElementsEXT;
D
INSTANCE Mod_1548_PIR_Samuel_DI (Npc_Default) { // ------ NSC ------ name = "Samuel"; guild = GIL_out; id = 1548; voice = 14; flags = FALSE; npctype = NPCTYPE_MAIN; // ------ Attribute ------ B_SetAttributesToChapter (self, 1); // ------ Kampf-Taktik ------ fight_tactic = FAI_HUMAN_STRONG; // ------ Equippte Waffen ------ EquipItem (self, ItMw_1H_Mace_L_03); // ------ Inventory ------ // Händler // ------ visuals ------ B_SetNpcVisual (self, MALE, "Hum_Head_FatBAld", Face_B_Saturas, BodyTex_B, ITAR_PIR_L_Addon); Mdl_SetModelFatness (self, 1); Mdl_ApplyOverlayMds (self, "Humans_Relaxed.mds"); // ------ NSC-relevante Talente vergeben ------ B_GiveNpcTalents (self); // ------ Kampf-Talente ------ B_SetFightSkills (self,30); // ------ TA anmelden ------ daily_routine = Rtn_Start_1548; }; FUNC VOID Rtn_Start_1548 () { TA_Potion_Alchemy (06,00,08,00,"WP_DI_MAGIERAUM_INSIDE"); TA_Stand_Drinking (08,00,10,00,"WP_DI_ENTRANCE_MAGIERKELLER"); TA_Potion_Alchemy (10,00,12,00,"WP_DI_MAGIERAUM_INSIDE"); TA_Stand_Drinking (12,00,14,00,"WP_DI_ENTRANCE_MAGIERKELLER"); TA_Potion_Alchemy (14,00,16,00,"WP_DI_MAGIERAUM_INSIDE"); TA_Stand_Drinking (16,00,18,00,"WP_DI_ENTRANCE_MAGIERKELLER"); TA_Potion_Alchemy (18,00,20,00,"WP_DI_MAGIERAUM_INSIDE"); TA_Stand_Drinking (20,00,22,00,"WP_DI_ENTRANCE_MAGIERKELLER"); TA_Potion_Alchemy (22,00,06,00,"WP_DI_MAGIERAUM_INSIDE"); };
D
// Written in the D programming language. /** * Templates with which to extract information about types and symbols at * compile time. * * Macros: * WIKI = Phobos/StdTraits * * Copyright: Copyright Digital Mars 2005 - 2009. * License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>. * Authors: $(WEB digitalmars.com, Walter Bright), * Tomasz Stachowiak ($(D isExpressionTuple)), * $(WEB erdani.org, Andrei Alexandrescu), * Shin Fujishiro * Source: $(PHOBOSSRC std/_traits.d) */ /* Copyright Digital Mars 2005 - 2009. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ module std.traits; import std.typetuple; import std.typecons; import core.vararg; /////////////////////////////////////////////////////////////////////////////// // Functions /////////////////////////////////////////////////////////////////////////////// // Petit demangler // (this or similar thing will eventually go to std.demangle if necessary // ctfe stuffs are available) private { struct Demangle(T) { T value; // extracted information string rest; } /* Demangles mstr as the storage class part of Argument. */ Demangle!uint demangleParameterStorageClass(string mstr) { uint pstc = 0; // parameter storage class // Argument --> Argument2 | M Argument2 if (mstr.length > 0 && mstr[0] == 'M') { pstc |= ParameterStorageClass.scope_; mstr = mstr[1 .. $]; } // Argument2 --> Type | J Type | K Type | L Type ParameterStorageClass stc2; switch (mstr.length ? mstr[0] : char.init) { case 'J': stc2 = ParameterStorageClass.out_; break; case 'K': stc2 = ParameterStorageClass.ref_; break; case 'L': stc2 = ParameterStorageClass.lazy_; break; default : break; } if (stc2 != ParameterStorageClass.init) { pstc |= stc2; mstr = mstr[1 .. $]; } return Demangle!uint(pstc, mstr); } /* Demangles mstr as FuncAttrs. */ Demangle!uint demangleFunctionAttributes(string mstr) { enum LOOKUP_ATTRIBUTE = [ 'a': FunctionAttribute.pure_, 'b': FunctionAttribute.nothrow_, 'c': FunctionAttribute.ref_, 'd': FunctionAttribute.property, 'e': FunctionAttribute.trusted, 'f': FunctionAttribute.safe ]; uint atts = 0; // FuncAttrs --> FuncAttr | FuncAttr FuncAttrs // FuncAttr --> empty | Na | Nb | Nc | Nd | Ne | Nf while (mstr.length >= 2 && mstr[0] == 'N') { if (FunctionAttribute att = LOOKUP_ATTRIBUTE[ mstr[1] ]) { atts |= att; mstr = mstr[2 .. $]; } else assert(0); } return Demangle!uint(atts, mstr); } } /*** * Get the type of the return value from a function, * a pointer to function, a delegate, a struct * with an opCall, a pointer to a struct with an opCall, * or a class with an opCall. * Example: * --- * import std.traits; * int foo(); * ReturnType!(foo) x; // x is declared as int * --- */ template ReturnType(func...) if (func.length == 1 && isCallable!(func)) { static if (is(FunctionTypeOf!(func) R == return)) alias R ReturnType; else static assert(0, "argument has no return type"); } unittest { struct G { int opCall (int i) { return 1;} } alias ReturnType!(G) ShouldBeInt; static assert(is(ShouldBeInt == int)); G g; static assert(is(ReturnType!(g) == int)); G* p; alias ReturnType!(p) pg; static assert(is(pg == int)); class C { int opCall (int i) { return 1;} } static assert(is(ReturnType!(C) == int)); C c; static assert(is(ReturnType!(c) == int)); class Test { int prop() @property { return 0; } } alias ReturnType!(Test.prop) R_Test_prop; static assert(is(R_Test_prop == int)); alias ReturnType!((int a) { return a; }) R_dglit; static assert(is(R_dglit == int)); } /*** Get, as a tuple, the types of the parameters to a function, a pointer to function, a delegate, a struct with an $(D opCall), a pointer to a struct with an $(D opCall), or a class with an $(D opCall). Example: --- import std.traits; int foo(int, long); void bar(ParameterTypeTuple!(foo)); // declares void bar(int, long); void abc(ParameterTypeTuple!(foo)[1]); // declares void abc(long); --- */ template ParameterTypeTuple(func...) if (func.length == 1 && isCallable!(func)) { static if (is(FunctionTypeOf!(func) P == function)) alias P ParameterTypeTuple; else static assert(0, "argument has no parameters"); } unittest { int foo(int i, bool b) { return 0; } static assert (is(ParameterTypeTuple!(foo) == TypeTuple!(int, bool))); static assert (is(ParameterTypeTuple!(typeof(&foo)) == TypeTuple!(int, bool))); struct S { real opCall(real r, int i) { return 0.0; } } S s; static assert (is(ParameterTypeTuple!(S) == TypeTuple!(real, int))); static assert (is(ParameterTypeTuple!(S*) == TypeTuple!(real, int))); static assert (is(ParameterTypeTuple!(s) == TypeTuple!(real, int))); class Test { int prop() @property { return 0; } } alias ParameterTypeTuple!(Test.prop) P_Test_prop; static assert(P_Test_prop.length == 0); alias ParameterTypeTuple!((int a){}) P_dglit; static assert(P_dglit.length == 1); static assert(is(P_dglit[0] == int)); } /** Returns a tuple consisting of the storage classes of the parameters of a function $(D func). Example: -------------------- alias ParameterStorageClass STC; // shorten the enum name void func(ref int ctx, out real result, real param) { } alias ParameterStorageClassTuple!(func) pstc; static assert(pstc.length == 3); // three parameters static assert(pstc[0] == STC.ref_); static assert(pstc[1] == STC.out_); static assert(pstc[2] == STC.none); -------------------- */ enum ParameterStorageClass : uint { /** * These flags can be bitwise OR-ed together to represent complex storage * class. */ none = 0, /// ditto scope_ = 0b000_1, /// ditto out_ = 0b001_0, /// ditto ref_ = 0b010_0, /// ditto lazy_ = 0b100_0, /// ditto } /// ditto template ParameterStorageClassTuple(func...) if (func.length == 1 && isCallable!(func)) { alias ParameterStorageClassTupleImpl!(Unqual!(FunctionTypeOf!(func))).Result ParameterStorageClassTuple; } private template ParameterStorageClassTupleImpl(Func) { /* * TypeFuncion: * CallConvention FuncAttrs Arguments ArgClose Type */ alias ParameterTypeTuple!(Func) Params; // chop off CallConvention and FuncAttrs enum margs = demangleFunctionAttributes(mangledName!(Func)[1 .. $]).rest; // demangle Arguments and store parameter storage classes in a tuple template demangleNextParameter(string margs, size_t i = 0) { static if (i < Params.length) { enum demang = demangleParameterStorageClass(margs); enum skip = mangledName!(Params[i]).length; // for bypassing Type enum rest = demang.rest; alias TypeTuple!( demang.value + 0, // workaround: "not evaluatable at ..." demangleNextParameter!(rest[skip .. $], i + 1).Result ) Result; } else // went thru all the parameters { alias TypeTuple!() Result; } } alias demangleNextParameter!(margs).Result Result; } unittest { alias ParameterStorageClass STC; void noparam() {} static assert(ParameterStorageClassTuple!(noparam).length == 0); void test(scope int, ref int, out int, lazy int, int) { } alias ParameterStorageClassTuple!(test) test_pstc; static assert(test_pstc.length == 5); static assert(test_pstc[0] == STC.scope_); static assert(test_pstc[1] == STC.ref_); static assert(test_pstc[2] == STC.out_); static assert(test_pstc[3] == STC.lazy_); static assert(test_pstc[4] == STC.none); interface Test { void test_const(int) const; void test_sharedconst(int) shared const; } Test testi; alias ParameterStorageClassTuple!(Test.test_const) test_const_pstc; static assert(test_const_pstc.length == 1); static assert(test_const_pstc[0] == STC.none); alias ParameterStorageClassTuple!(testi.test_sharedconst) test_sharedconst_pstc; static assert(test_sharedconst_pstc.length == 1); static assert(test_sharedconst_pstc[0] == STC.none); alias ParameterStorageClassTuple!((ref int a) {}) dglit_pstc; static assert(dglit_pstc.length == 1); static assert(dglit_pstc[0] == STC.ref_); } /** Returns the attributes attached to a function $(D func). Example: -------------------- alias FunctionAttribute FA; // shorten the enum name real func(real x) pure nothrow @safe { return x; } static assert(functionAttributes!(func) & FA.pure_); static assert(functionAttributes!(func) & FA.safe); static assert(!(functionAttributes!(func) & FA.trusted)); // not @trusted -------------------- */ enum FunctionAttribute : uint { /** * These flags can be bitwise OR-ed together to represent complex attribute. */ none = 0, /// ditto pure_ = 0b00000001, /// ditto nothrow_ = 0b00000010, /// ditto ref_ = 0b00000100, /// ditto property = 0b00001000, /// ditto trusted = 0b00010000, /// ditto safe = 0b00100000, /// ditto } /// ditto template functionAttributes(func...) if (func.length == 1 && isCallable!(func)) { enum uint functionAttributes = demangleFunctionAttributes( mangledName!(Unqual!(FunctionTypeOf!(func)))[1 .. $] ).value; } unittest { alias FunctionAttribute FA; interface Set { int pureF() pure; int nothrowF() nothrow; ref int refF(); int propertyF() @property; int trustedF() @trusted; int safeF() @safe; } static assert(functionAttributes!(Set.pureF) == FA.pure_); static assert(functionAttributes!(Set.nothrowF) == FA.nothrow_); static assert(functionAttributes!(Set.refF) == FA.ref_); static assert(functionAttributes!(Set.propertyF) == FA.property); static assert(functionAttributes!(Set.trustedF) == FA.trusted); static assert(functionAttributes!(Set.safeF) == FA.safe); static assert(!(functionAttributes!(Set.safeF) & FA.trusted)); int pure_nothrow() pure nothrow { return 0; } static assert(functionAttributes!(pure_nothrow) == (FA.pure_ | FA.nothrow_)); static ref int static_ref_property() @property { return *(new int); } static assert(functionAttributes!(static_ref_property) == (FA.ref_ | FA.property)); ref int ref_property() @property { return *(new int); } static assert(functionAttributes!(ref_property) == (FA.ref_ | FA.property)); void safe_nothrow() @safe nothrow { } static assert(functionAttributes!(safe_nothrow) == (FA.safe | FA.nothrow_)); interface Test2 { int pure_const() pure const; int pure_sharedconst() pure shared const; } static assert(functionAttributes!(Test2.pure_const) == FA.pure_); static assert(functionAttributes!(Test2.pure_sharedconst) == FA.pure_); static assert(functionAttributes!((int a) {}) == (FA.safe | FA.pure_ | FA.nothrow_)); } private @safe void dummySafeFunc(alias func)() { alias ParameterTypeTuple!func Params; static if (Params.length) { Params args; func(args); } else { func(); } } /** Checks the func that is @safe or @trusted Example: -------------------- @system int add(int a, int b) {return a+b;} @safe int sub(int a, int b) {return a-b;} @trusted int mul(int a, int b) {return a*b;} bool a = isSafe!(add); assert(a == false); bool b = isSafe!(sub); assert(b == true); bool c = isSafe!(mul); assert(c == true); -------------------- */ template isSafe(alias func) { static if (is(typeof(func) == function)) { enum isSafe = (functionAttributes!(func) == FunctionAttribute.safe || functionAttributes!(func) == FunctionAttribute.trusted); } else { enum isSafe = is(typeof({dummySafeFunc!func();}())); } } @safe unittest { interface Set { int systemF() @system; int trustedF() @trusted; int safeF() @safe; } static assert(isSafe!((int a){})); static assert(isSafe!(Set.safeF)); static assert(isSafe!(Set.trustedF)); static assert(!isSafe!(Set.systemF)); } /** Checks the all functions are @safe or @trusted Example: -------------------- @system int add(int a, int b) {return a+b;} @safe int sub(int a, int b) {return a-b;} @trusted int mul(int a, int b) {return a*b;} bool a = areAllSafe!(add, sub); assert(a == false); bool b = areAllSafe!(sub, mul); assert(b == true); -------------------- */ template areAllSafe(funcs...) if (funcs.length > 0) { static if (funcs.length == 1) { enum areAllSafe = isSafe!(funcs[0]); } else static if (isSafe!(funcs[0])) { enum areAllSafe = areAllSafe!(funcs[1..$]); } else { enum areAllSafe = false; } } @safe unittest { interface Set { int systemF() @system; int trustedF() @trusted; int safeF() @safe; } static assert(areAllSafe!((int a){}, Set.safeF)); static assert(!areAllSafe!(Set.trustedF, Set.systemF)); } /** Checks the func that is @system Example: -------------------- @system int add(int a, int b) {return a+b;} @safe int sub(int a, int b) {return a-b;} @trusted int mul(int a, int b) {return a*b;} bool a = isUnsafe!(add); assert(a == true); bool b = isUnsafe!(sub); assert(b == false); bool c = isUnsafe!(mul); assert(c == false); -------------------- */ template isUnsafe(alias func) { enum isUnsafe = !isSafe!func; } @safe unittest { interface Set { int systemF() @system; int trustedF() @trusted; int safeF() @safe; } static assert(!isUnsafe!((int a){})); static assert(!isUnsafe!(Set.safeF)); static assert(!isUnsafe!(Set.trustedF)); static assert(isUnsafe!(Set.systemF)); } /** Returns the calling convention of function as a string. Example: -------------------- string a = functionLinkage!(writeln!(string, int)); assert(a == "D"); // extern(D) auto fp = &printf; string b = functionLinkage!(fp); assert(b == "C"); // extern(C) -------------------- */ template functionLinkage(func...) if (func.length == 1 && isCallable!(func)) { enum string functionLinkage = LOOKUP_LINKAGE[ mangledName!(Unqual!(FunctionTypeOf!(func)))[0] ]; } private enum LOOKUP_LINKAGE = [ 'F': "D", 'U': "C", 'W': "Windows", 'V': "Pascal", 'R': "C++" ]; unittest { extern(D) void Dfunc() {} extern(C) void Cfunc() {} static assert(functionLinkage!(Dfunc) == "D"); static assert(functionLinkage!(Cfunc) == "C"); interface Test { void const_func() const; void sharedconst_func() shared const; } static assert(functionLinkage!(Test.const_func) == "D"); static assert(functionLinkage!(Test.sharedconst_func) == "D"); static assert(functionLinkage!((int a){}) == "D"); } /** Determines what kind of variadic parameters function has. Example: -------------------- void func() {} static assert(variadicFunctionStyle!(func) == Variadic.no); extern(C) int printf(in char*, ...); static assert(variadicFunctionStyle!(printf) == Variadic.c); -------------------- */ enum Variadic { no, /// Function is not variadic. c, /// Function is a _C-style variadic function. /// Function is a _D-style variadic function, which uses d, /// __argptr and __arguments. typesafe, /// Function is a typesafe variadic function. } /// ditto template variadicFunctionStyle(func...) if (func.length == 1 && isCallable!(func)) { enum Variadic variadicFunctionStyle = determineVariadicity!( Unqual!(FunctionTypeOf!(func)) )(); } private Variadic determineVariadicity(Func)() { // TypeFuncion --> CallConvention FuncAttrs Arguments ArgClose Type immutable callconv = functionLinkage!(Func); immutable mfunc = mangledName!(Func); immutable mtype = mangledName!(ReturnType!(Func)); debug assert(mfunc[$ - mtype.length .. $] == mtype, mfunc ~ "|" ~ mtype); immutable argclose = mfunc[$ - mtype.length - 1]; final switch (argclose) { case 'X': return Variadic.typesafe; case 'Y': return (callconv == "C") ? Variadic.c : Variadic.d; case 'Z': return Variadic.no; } } unittest { extern(D) void novar() {}; extern(C) void cstyle(int, ...) {}; extern(D) void dstyle(...) {}; extern(D) void typesafe(int[]...) {}; static assert(variadicFunctionStyle!(novar) == Variadic.no); static assert(variadicFunctionStyle!(cstyle) == Variadic.c); static assert(variadicFunctionStyle!(dstyle) == Variadic.d); static assert(variadicFunctionStyle!(typesafe) == Variadic.typesafe); static assert(variadicFunctionStyle!((int[] a...) {}) == Variadic.typesafe); } /** Get the function type from a callable object $(D func). Using builtin $(D typeof) on a property function yields the types of the property value, not of the property function itself. Still, $(D FunctionTypeOf) is able to obtain function types of properties. -------------------- class C { int value() @property; } static assert(is( typeof(C.value) == int )); static assert(is( FunctionTypeOf!(C.value) == function )); -------------------- Note: Do not confuse function types with function pointer types; function types are usually used for compile-time reflection purposes. */ template FunctionTypeOf(func...) if (func.length == 1 && isCallable!(func)) { static if (is(typeof(& func[0]) Fsym : Fsym*) && is(Fsym == function) || is(typeof(& func[0]) Fsym == delegate)) { alias Fsym FunctionTypeOf; // HIT: (nested) function symbol } else static if (is(typeof(& func[0].opCall) Fobj == delegate)) { alias Fobj FunctionTypeOf; // HIT: callable object } else static if (is(typeof(& func[0].opCall) Ftyp : Ftyp*) && is(Ftyp == function)) { alias Ftyp FunctionTypeOf; // HIT: callable type } else static if (is(func[0] T) || is(typeof(func[0]) T)) { static if (is(T == function)) alias T FunctionTypeOf; // HIT: function else static if (is(T Fptr : Fptr*) && is(Fptr == function)) alias Fptr FunctionTypeOf; // HIT: function pointer else static if (is(T Fdlg == delegate)) alias Fdlg FunctionTypeOf; // HIT: delegate else static assert(0); } else static assert(0); } unittest { int test(int a) { return 0; } int propGet() @property { return 0; } int propSet(int a) @property { return 0; } int function(int) test_fp; int delegate(int) test_dg; static assert(is( typeof(test) == FunctionTypeOf!(typeof(test)) )); static assert(is( typeof(test) == FunctionTypeOf!(test) )); static assert(is( typeof(test) == FunctionTypeOf!(test_fp) )); static assert(is( typeof(test) == FunctionTypeOf!(test_dg) )); alias int GetterType() @property; alias int SetterType(int) @property; static assert(is( FunctionTypeOf!(propGet) == GetterType )); static assert(is( FunctionTypeOf!(propSet) == SetterType )); interface Prop { int prop() @property; } Prop prop; static assert(is( FunctionTypeOf!(Prop.prop) == GetterType )); static assert(is( FunctionTypeOf!(prop.prop) == GetterType )); class Callable { int opCall(int) { return 0; } } auto call = new Callable; static assert(is( FunctionTypeOf!(call) == typeof(test) )); struct StaticCallable { static int opCall(int) { return 0; } } StaticCallable stcall_val; StaticCallable* stcall_ptr; static assert(is( FunctionTypeOf!(stcall_val) == typeof(test) )); static assert(is( FunctionTypeOf!(stcall_ptr) == typeof(test) )); interface Overloads { void test(string); real test(real); int test(); int test() @property; } alias TypeTuple!(__traits(getVirtualFunctions, Overloads, "test")) ov; alias FunctionTypeOf!(ov[0]) F_ov0; alias FunctionTypeOf!(ov[1]) F_ov1; alias FunctionTypeOf!(ov[2]) F_ov2; alias FunctionTypeOf!(ov[3]) F_ov3; static assert(is(F_ov0* == void function(string))); static assert(is(F_ov1* == real function(real))); static assert(is(F_ov2* == int function())); static assert(is(F_ov3* == int function() @property)); alias FunctionTypeOf!((int a){ return a; }) F_dglit; static assert(is(F_dglit* : int function(int))); } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::// // Aggregate Types //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::// /*** * Get the types of the fields of a struct or class. * This consists of the fields that take up memory space, * excluding the hidden fields like the virtual function * table pointer. */ template FieldTypeTuple(S) { static if (is(S == struct) || is(S == class) || is(S == union)) alias typeof(S.tupleof) FieldTypeTuple; else alias TypeTuple!(S) FieldTypeTuple; //static assert(0, "argument is not struct or class"); } // // FieldOffsetsTuple // private template FieldOffsetsTupleImpl(size_t n, T...) // { // static if (T.length == 0) // { // alias TypeTuple!() Result; // } // else // { // //private alias FieldTypeTuple!(T[0]) Types; // private enum size_t myOffset = // ((n + T[0].alignof - 1) / T[0].alignof) * T[0].alignof; // static if (is(T[0] == struct)) // { // alias FieldTypeTuple!(T[0]) MyRep; // alias FieldOffsetsTupleImpl!(myOffset, MyRep, T[1 .. $]).Result // Result; // } // else // { // private enum size_t mySize = T[0].sizeof; // alias TypeTuple!(myOffset) Head; // static if (is(T == union)) // { // alias FieldOffsetsTupleImpl!(myOffset, T[1 .. $]).Result // Tail; // } // else // { // alias FieldOffsetsTupleImpl!(myOffset + mySize, // T[1 .. $]).Result // Tail; // } // alias TypeTuple!(Head, Tail) Result; // } // } // } // template FieldOffsetsTuple(T...) // { // alias FieldOffsetsTupleImpl!(0, T).Result FieldOffsetsTuple; // } // unittest // { // alias FieldOffsetsTuple!(int) T1; // assert(T1.length == 1 && T1[0] == 0); // // // struct S2 { char a; int b; char c; double d; char e, f; } // alias FieldOffsetsTuple!(S2) T2; // //pragma(msg, T2); // static assert(T2.length == 6 // && T2[0] == 0 && T2[1] == 4 && T2[2] == 8 && T2[3] == 16 // && T2[4] == 24&& T2[5] == 25); // // // class C { int a, b, c, d; } // struct S3 { char a; C b; char c; } // alias FieldOffsetsTuple!(S3) T3; // //pragma(msg, T2); // static assert(T3.length == 3 // && T3[0] == 0 && T3[1] == 4 && T3[2] == 8); // // // struct S4 { char a; union { int b; char c; } int d; } // alias FieldOffsetsTuple!(S4) T4; // //pragma(msg, FieldTypeTuple!(S4)); // static assert(T4.length == 4 // && T4[0] == 0 && T4[1] == 4 && T4[2] == 8); // } // /*** // Get the offsets of the fields of a struct or class. // */ // template FieldOffsetsTuple(S) // { // static if (is(S == struct) || is(S == class)) // alias typeof(S.tupleof) FieldTypeTuple; // else // static assert(0, "argument is not struct or class"); // } /*** Get the primitive types of the fields of a struct or class, in topological order. Example: ---- struct S1 { int a; float b; } struct S2 { char[] a; union { S1 b; S1 * c; } } alias RepresentationTypeTuple!(S2) R; assert(R.length == 4 && is(R[0] == char[]) && is(R[1] == int) && is(R[2] == float) && is(R[3] == S1*)); ---- */ template RepresentationTypeTuple(T) { static if (is(T == struct) || is(T == union) || is(T == class)) { alias RepresentationTypeTupleImpl!(FieldTypeTuple!T) RepresentationTypeTuple; } else static if (is(T U == typedef)) { alias RepresentationTypeTuple!U RepresentationTypeTuple; } else { alias RepresentationTypeTupleImpl!T RepresentationTypeTuple; } } private template RepresentationTypeTupleImpl(T...) { static if (T.length == 0) { alias TypeTuple!() RepresentationTypeTupleImpl; } else { static if (is(T[0] == struct) || is(T[0] == union)) // @@@BUG@@@ this should work // alias .RepresentationTypes!(T[0].tupleof) // RepresentationTypes; alias .RepresentationTypeTupleImpl!(FieldTypeTuple!(T[0]), T[1 .. $]) RepresentationTypeTupleImpl; else static if (is(T[0] U == typedef)) { alias .RepresentationTypeTupleImpl!(FieldTypeTuple!(U), T[1 .. $]) RepresentationTypeTupleImpl; } else { alias TypeTuple!(T[0], RepresentationTypeTupleImpl!(T[1 .. $])) RepresentationTypeTupleImpl; } } } unittest { alias RepresentationTypeTuple!(int) S1; static assert(is(S1 == TypeTuple!(int))); struct S2 { int a; } static assert(is(RepresentationTypeTuple!(S2) == TypeTuple!(int))); struct S3 { int a; char b; } static assert(is(RepresentationTypeTuple!(S3) == TypeTuple!(int, char))); struct S4 { S1 a; int b; S3 c; } static assert(is(RepresentationTypeTuple!(S4) == TypeTuple!(int, int, int, char))); struct S11 { int a; float b; } struct S21 { char[] a; union { S11 b; S11 * c; } } alias RepresentationTypeTuple!(S21) R; assert(R.length == 4 && is(R[0] == char[]) && is(R[1] == int) && is(R[2] == float) && is(R[3] == S11*)); class C { int a; float b; } alias RepresentationTypeTuple!C R1; static assert(R1.length == 2 && is(R1[0] == int) && is(R1[1] == float)); } /* RepresentationOffsets */ // private template Repeat(size_t n, T...) // { // static if (n == 0) alias TypeTuple!() Repeat; // else alias TypeTuple!(T, Repeat!(n - 1, T)) Repeat; // } // template RepresentationOffsetsImpl(size_t n, T...) // { // static if (T.length == 0) // { // alias TypeTuple!() Result; // } // else // { // private enum size_t myOffset = // ((n + T[0].alignof - 1) / T[0].alignof) * T[0].alignof; // static if (!is(T[0] == union)) // { // alias Repeat!(n, FieldTypeTuple!(T[0])).Result // Head; // } // static if (is(T[0] == struct)) // { // alias .RepresentationOffsetsImpl!(n, FieldTypeTuple!(T[0])).Result // Head; // } // else // { // alias TypeTuple!(myOffset) Head; // } // alias TypeTuple!(Head, // RepresentationOffsetsImpl!( // myOffset + T[0].sizeof, T[1 .. $]).Result) // Result; // } // } // template RepresentationOffsets(T) // { // alias RepresentationOffsetsImpl!(0, T).Result // RepresentationOffsets; // } // unittest // { // struct S1 { char c; int i; } // alias RepresentationOffsets!(S1) Offsets; // static assert(Offsets[0] == 0); // //pragma(msg, Offsets[1]); // static assert(Offsets[1] == 4); // } // hasRawAliasing private template hasRawPointerImpl(T...) { static if (T.length == 0) { enum result = false; } else { static if (is(T[0] foo : U*, U) && !isFunctionPointer!(T[0])) enum hasRawAliasing = !is(U == immutable); else static if (is(T[0] foo : U[], U) && !isStaticArray!(T[0])) enum hasRawAliasing = !is(U == immutable); else static if (isAssociativeArray!(T[0])) enum hasRawAliasing = !is(T[0] == immutable); else enum hasRawAliasing = false; enum result = hasRawAliasing || hasRawPointerImpl!(T[1 .. $]).result; } } private template HasRawLocalPointerImpl(T...) { static if (T.length == 0) { enum result = false; } else { static if (is(T[0] foo : U*, U) && !isFunctionPointer!(T[0])) enum hasRawLocalAliasing = !is(U == immutable) && !is(U == shared); else static if (is(T[0] foo : U[], U) && !isStaticArray!(T[0])) enum hasRawLocalAliasing = !is(U == immutable) && !is(U == shared); else static if (isAssociativeArray!(T[0])) enum hasRawLocalAliasing = !is(T[0] == immutable) && !is(T[0] == shared); else enum hasRawLocalAliasing = false; enum result = hasRawLocalAliasing || HasRawLocalPointerImpl!(T[1 .. $]).result; } } /* Statically evaluates to $(D true) if and only if $(D T)'s representation contains at least one field of pointer or array type. Members of class types are not considered raw pointers. Pointers to immutable objects are not considered raw aliasing. Example: --- // simple types static assert(!hasRawAliasing!(int)); static assert(hasRawAliasing!(char*)); // references aren't raw pointers static assert(!hasRawAliasing!(Object)); // built-in arrays do contain raw pointers static assert(hasRawAliasing!(int[])); // aggregate of simple types struct S1 { int a; double b; } static assert(!hasRawAliasing!(S1)); // indirect aggregation struct S2 { S1 a; double b; } static assert(!hasRawAliasing!(S2)); // struct with a pointer member struct S3 { int a; double * b; } static assert(hasRawAliasing!(S3)); // struct with an indirect pointer member struct S4 { S3 a; double b; } static assert(hasRawAliasing!(S4)); ---- */ private template hasRawAliasing(T...) { enum hasRawAliasing = hasRawPointerImpl!(RepresentationTypeTuple!T).result; } unittest { // simple types static assert(!hasRawAliasing!(int)); static assert(hasRawAliasing!(char*)); // references aren't raw pointers static assert(!hasRawAliasing!(Object)); static assert(!hasRawAliasing!(int)); struct S1 { int z; } static assert(!hasRawAliasing!(S1)); struct S2 { int* z; } static assert(hasRawAliasing!(S2)); struct S3 { int a; int* z; int c; } static assert(hasRawAliasing!(S3)); struct S4 { int a; int z; int c; } static assert(!hasRawAliasing!(S4)); struct S5 { int a; Object z; int c; } static assert(!hasRawAliasing!(S5)); union S6 { int a; int b; } static assert(!hasRawAliasing!(S6)); union S7 { int a; int * b; } static assert(hasRawAliasing!(S7)); //typedef int* S8; //static assert(hasRawAliasing!(S8)); enum S9 { a }; static assert(!hasRawAliasing!(S9)); // indirect members struct S10 { S7 a; int b; } static assert(hasRawAliasing!(S10)); struct S11 { S6 a; int b; } static assert(!hasRawAliasing!(S11)); static assert(hasRawAliasing!(int[string])); static assert(!hasRawAliasing!(immutable(int[string]))); } /* Statically evaluates to $(D true) if and only if $(D T)'s representation contains at least one non-shared field of pointer or array type. Members of class types are not considered raw pointers. Pointers to immutable objects are not considered raw aliasing. Example: --- // simple types static assert(!hasRawLocalAliasing!(int)); static assert(hasRawLocalAliasing!(char*)); static assert(!hasRawLocalAliasing!(shared char*)); // references aren't raw pointers static assert(!hasRawLocalAliasing!(Object)); // built-in arrays do contain raw pointers static assert(hasRawLocalAliasing!(int[])); static assert(!hasRawLocalAliasing!(shared int[])); // aggregate of simple types struct S1 { int a; double b; } static assert(!hasRawLocalAliasing!(S1)); // indirect aggregation struct S2 { S1 a; double b; } static assert(!hasRawLocalAliasing!(S2)); // struct with a pointer member struct S3 { int a; double * b; } static assert(hasRawLocalAliasing!(S3)); struct S4 { int a; shared double * b; } static assert(hasRawLocalAliasing!(S4)); // struct with an indirect pointer member struct S5 { S3 a; double b; } static assert(hasRawLocalAliasing!(S5)); struct S6 { S4 a; double b; } static assert(!hasRawLocalAliasing!(S6)); ---- */ private template hasRawUnsharedAliasing(T...) { enum hasRawUnsharedAliasing = HasRawLocalPointerImpl!(RepresentationTypeTuple!(T)).result; } unittest { // simple types static assert(!hasRawUnsharedAliasing!(int)); static assert(hasRawUnsharedAliasing!(char*)); static assert(!hasRawUnsharedAliasing!(shared char*)); // references aren't raw pointers static assert(!hasRawUnsharedAliasing!(Object)); static assert(!hasRawUnsharedAliasing!(int)); struct S1 { int z; } static assert(!hasRawUnsharedAliasing!(S1)); struct S2 { int* z; } static assert(hasRawUnsharedAliasing!(S2)); struct S3 { shared int* z; } static assert(!hasRawUnsharedAliasing!(S3)); struct S4 { int a; int* z; int c; } static assert(hasRawUnsharedAliasing!(S4)); struct S5 { int a; shared int* z; int c; } static assert(!hasRawUnsharedAliasing!(S5)); struct S6 { int a; int z; int c; } static assert(!hasRawUnsharedAliasing!(S6)); struct S7 { int a; Object z; int c; } static assert(!hasRawUnsharedAliasing!(S7)); union S8 { int a; int b; } static assert(!hasRawUnsharedAliasing!(S8)); union S9 { int a; int * b; } static assert(hasRawUnsharedAliasing!(S9)); union S10 { int a; shared int * b; } static assert(!hasRawUnsharedAliasing!(S10)); //typedef int* S11; //static assert(hasRawUnsharedAliasing!(S11)); //typedef shared int* S12; //static assert(hasRawUnsharedAliasing!(S12)); enum S13 { a }; static assert(!hasRawUnsharedAliasing!(S13)); // indirect members struct S14 { S9 a; int b; } static assert(hasRawUnsharedAliasing!(S14)); struct S15 { S10 a; int b; } static assert(!hasRawUnsharedAliasing!(S15)); struct S16 { S6 a; int b; } static assert(!hasRawUnsharedAliasing!(S16)); static assert(hasRawUnsharedAliasing!(int[string])); static assert(!hasRawUnsharedAliasing!(shared(int[string]))); static assert(!hasRawUnsharedAliasing!(immutable(int[string]))); } /* Statically evaluates to $(D true) if and only if $(D T)'s representation includes at least one non-immutable object reference. */ private template hasObjects(T...) { static if (T.length == 0) { enum hasObjects = false; } else static if (is(T[0] U == typedef)) { enum hasObjects = hasObjects!(U, T[1 .. $]); } else static if (is(T[0] == struct)) { enum hasObjects = hasObjects!( RepresentationTypeTuple!(T[0]), T[1 .. $]); } else { enum hasObjects = ((is(T[0] == class) || is(T[0] == interface)) && !is(T[0] == immutable)) || hasObjects!(T[1 .. $]); } } /* Statically evaluates to $(D true) if and only if $(D T)'s representation includes at least one non-immutable non-shared object reference. */ private template hasUnsharedObjects(T...) { static if (T.length == 0) { enum hasUnsharedObjects = false; } else static if (is(T[0] U == typedef)) { enum hasUnsharedObjects = hasUnsharedObjects!(U, T[1 .. $]); } else static if (is(T[0] == struct)) { enum hasUnsharedObjects = hasUnsharedObjects!( RepresentationTypeTuple!(T[0]), T[1 .. $]); } else { enum hasUnsharedObjects = ((is(T[0] == class) || is(T[0] == interface)) && !is(T[0] == immutable) && !is(T[0] == shared)) || hasUnsharedObjects!(T[1 .. $]); } } /** Returns $(D true) if and only if $(D T)'s representation includes at least one of the following: $(OL $(LI a raw pointer $(D U*) and $(D U) is not immutable;) $(LI an array $(D U[]) and $(D U) is not immutable;) $(LI a reference to a class or interface type $(D C) and $(D C) is not immutable.) $(LI an associative array that is not immutable.) $(LI a delegate.)) */ template hasAliasing(T...) { enum hasAliasing = hasRawAliasing!(T) || hasObjects!(T) || anySatisfy!(isDelegate, T); } // Specialization to special-case std.typecons.Rebindable. template hasAliasing(R : Rebindable!R) { enum hasAliasing = hasAliasing!R; } unittest { struct S1 { int a; Object b; } static assert(hasAliasing!(S1)); struct S2 { string a; } static assert(!hasAliasing!(S2)); struct S3 { int a; immutable Object b; } static assert(!hasAliasing!(S3)); struct X { float[3] vals; } static assert(!hasAliasing!X); static assert(hasAliasing!(uint[uint])); static assert(!hasAliasing!(immutable(uint[uint]))); static assert(hasAliasing!(void delegate())); static assert(!hasAliasing!(void function())); interface I; static assert(hasAliasing!I); static assert(hasAliasing!(Rebindable!(const Object))); static assert(!hasAliasing!(Rebindable!(immutable Object))); static assert(hasAliasing!(Rebindable!(shared Object))); static assert(hasAliasing!(Rebindable!(Object))); } /** Returns $(D true) if and only if $(D T)'s representation includes at least one of the following: $(OL $(LI a raw pointer $(D U*);) $(LI an array $(D U[]);) $(LI a reference to a class type $(D C).) $(LI an associative array.) $(LI a delegate.)) */ template hasIndirections(T) { enum hasIndirections = hasIndirectionsImpl!(RepresentationTypeTuple!T); } template hasIndirectionsImpl(T...) { static if (!T.length) { enum hasIndirectionsImpl = false; } else static if(isFunctionPointer!(T[0])) { enum hasIndirectionsImpl = hasIndirectionsImpl!(T[1 .. $]); } else static if(isStaticArray!(T[0])) { enum hasIndirectionsImpl = hasIndirectionsImpl!(T[1 .. $]) || hasIndirectionsImpl!(RepresentationTypeTuple!(typeof(T[0].init[0]))); } else { enum hasIndirectionsImpl = isPointer!(T[0]) || isDynamicArray!(T[0]) || is (T[0] : const(Object)) || isAssociativeArray!(T[0]) || isDelegate!(T[0]) || is(T[0] == interface) || hasIndirectionsImpl!(T[1 .. $]); } } unittest { struct S1 { int a; Object b; } static assert(hasIndirections!(S1)); struct S2 { string a; } static assert(hasIndirections!(S2)); struct S3 { int a; immutable Object b; } static assert(hasIndirections!(S3)); static assert(hasIndirections!(int[string])); static assert(hasIndirections!(void delegate())); interface I; static assert(hasIndirections!I); static assert(!hasIndirections!(void function())); static assert(hasIndirections!(void*[1])); static assert(!hasIndirections!(byte[1])); } // These are for backwards compatibility, are intentionally lacking ddoc, // and should eventually be deprecated. alias hasUnsharedAliasing hasLocalAliasing; alias hasRawUnsharedAliasing hasRawLocalAliasing; alias hasUnsharedObjects hasLocalObjects; /** Returns $(D true) if and only if $(D T)'s representation includes at least one of the following: $(OL $(LI a raw pointer $(D U*) and $(D U) is not immutable or shared;) $(LI an array $(D U[]) and $(D U) is not immutable or shared;) $(LI a reference to a class type $(D C) and $(D C) is not immutable or shared.) $(LI an associative array that is not immutable or shared.) $(LI a delegate that is not shared.)) */ template hasUnsharedAliasing(T...) { enum hasUnsharedAliasing = hasRawUnsharedAliasing!(T) || anySatisfy!(unsharedDelegate, T) || hasUnsharedObjects!(T); } // Specialization to special-case std.typecons.Rebindable. template hasUnsharedAliasing(R : Rebindable!R) { enum hasUnsharedAliasing = hasUnsharedAliasing!R; } private template unsharedDelegate(T) { enum bool unsharedDelegate = isDelegate!T && !is(T == shared); } unittest { struct S1 { int a; Object b; } static assert(hasUnsharedAliasing!(S1)); struct S2 { string a; } static assert(!hasUnsharedAliasing!(S2)); struct S3 { int a; immutable Object b; } static assert(!hasUnsharedAliasing!(S3)); struct S4 { int a; shared Object b; } static assert(!hasUnsharedAliasing!(S4)); struct S5 { char[] a; } static assert(hasUnsharedAliasing!(S5)); struct S6 { shared char[] b; } static assert(!hasUnsharedAliasing!(S6)); struct S7 { float[3] vals; } static assert(!hasUnsharedAliasing!(S7)); static assert(hasUnsharedAliasing!(uint[uint])); static assert(hasUnsharedAliasing!(void delegate())); static assert(!hasUnsharedAliasing!(shared(void delegate()))); static assert(!hasUnsharedAliasing!(void function())); interface I {} static assert(hasUnsharedAliasing!I); static assert(hasUnsharedAliasing!(Rebindable!(const Object))); static assert(!hasUnsharedAliasing!(Rebindable!(immutable Object))); static assert(!hasUnsharedAliasing!(Rebindable!(shared Object))); static assert(hasUnsharedAliasing!(Rebindable!(Object))); } /** True if $(D S) or any type embedded directly in the representation of $(D S) defines an elaborate copy constructor. Elaborate copy constructors are introduced by defining $(D this(this)) for a $(D struct). (Non-struct types never have elaborate copy constructors.) */ template hasElaborateCopyConstructor(S) { static if(!is(S == struct)) { enum bool hasElaborateCopyConstructor = false; } else { enum hasElaborateCopyConstructor = is(typeof({ S s; return &s.__postblit; })) || anySatisfy!(.hasElaborateCopyConstructor, typeof(S.tupleof)); } } unittest { static assert(!hasElaborateCopyConstructor!int); struct S { this(this) {} } static assert(hasElaborateCopyConstructor!S); struct S2 { uint num; } struct S3 { uint num; S s; } static assert(!hasElaborateCopyConstructor!S2); static assert(hasElaborateCopyConstructor!S3); } /** True if $(D S) or any type directly embedded in the representation of $(D S) defines an elaborate assignmentq. Elaborate assignments are introduced by defining $(D opAssign(typeof(this))) or $(D opAssign(ref typeof(this))) for a $(D struct). (Non-struct types never have elaborate assignments.) */ template hasElaborateAssign(S) { static if(!is(S == struct)) { enum bool hasElaborateAssign = false; } else { enum hasElaborateAssign = is(typeof(S.init.opAssign(S.init))) || is(typeof(S.init.opAssign({ return S.init; }()))) || anySatisfy!(.hasElaborateAssign, typeof(S.tupleof)); } } unittest { static assert(!hasElaborateAssign!int); struct S { void opAssign(S) {} } static assert(hasElaborateAssign!S); struct S1 { void opAssign(ref S1) {} } static assert(hasElaborateAssign!S1); struct S2 { void opAssign(S1) {} } static assert(!hasElaborateAssign!S2); struct S3 { S s; } static assert(hasElaborateAssign!S3); struct S4 { void opAssign(U)(auto ref U u) if (!__traits(isRef, u)) {} } static assert(hasElaborateAssign!S4); } /** True if $(D S) or any type directly embedded in the representation of $(D S) defines an elaborate destructor. Elaborate destructors are introduced by defining $(D ~this()) for a $(D struct). (Non-struct types never have elaborate destructors, even though classes may define $(D ~this()).) */ template hasElaborateDestructor(S) { static if(!is(S == struct)) { enum bool hasElaborateDestructor = false; } else { enum hasElaborateDestructor = is(typeof({S s; return &s.__dtor;})) || anySatisfy!(.hasElaborateDestructor, typeof(S.tupleof)); } } unittest { static assert(!hasElaborateDestructor!int); static struct S1 { } static assert(!hasElaborateDestructor!S1); static struct S2 { ~this() {} } static assert(hasElaborateDestructor!S2); static struct S3 { S2 field; } static assert(hasElaborateDestructor!S3); } /** Yields $(D true) if and only if $(D T) is an aggregate that defines a symbol called $(D name). */ template hasMember(T, string name) { static if (is(T == struct) || is(T == class) || is(T == union) || is(T == interface)) { enum bool hasMember = staticIndexOf!(name, __traits(allMembers, T)) != -1; } else { enum bool hasMember = false; } } unittest { //pragma(msg, __traits(allMembers, void delegate())); static assert(!hasMember!(int, "blah")); struct S1 { int blah; } static assert(hasMember!(S1, "blah")); struct S2 { int blah(); } static assert(hasMember!(S2, "blah")); struct C1 { int blah; } static assert(hasMember!(C1, "blah")); struct C2 { int blah(); } static assert(hasMember!(C2, "blah")); // 6973 import std.range; static assert(isOutputRange!(OutputRange!int, int)); } /** Retrieves the members of an enumerated type $(D enum E). Params: E = An enumerated type. $(D E) may have duplicated values. Returns: Static tuple composed of the members of the enumerated type $(D E). The members are arranged in the same order as declared in $(D E). Note: Returned values are strictly typed with $(D E). Thus, the following code does not work without the explicit cast: -------------------- enum E : int { a, b, c } int[] abc = cast(int[]) [ EnumMembers!E ]; -------------------- Cast is not necessary if the type of the variable is inferred. See the example below. Examples: Creating an array of enumerated values: -------------------- enum Sqrts : real { one = 1, two = 1.41421, three = 1.73205, } auto sqrts = [ EnumMembers!Sqrts ]; assert(sqrts == [ Sqrts.one, Sqrts.two, Sqrts.three ]); -------------------- A generic function $(D rank(v)) in the following example uses this template for finding a member $(D e) in an enumerated type $(D E). -------------------- // Returns i if e is the i-th enumerator of E. size_t rank(E)(E e) if (is(E == enum)) { foreach (i, member; EnumMembers!E) { if (e == member) return i; } assert(0, "Not an enum member"); } enum Mode { read = 1, write = 2, map = 4, } assert(rank(Mode.read ) == 0); assert(rank(Mode.write) == 1); assert(rank(Mode.map ) == 2); -------------------- */ template EnumMembers(E) if (is(E == enum)) { alias EnumSpecificMembers!(E, __traits(allMembers, E)) EnumMembers; } private template EnumSpecificMembers(Enum, names...) { static if (names.length > 0) { alias TypeTuple!( WithIdentifier!(names[0]) .Symbolize!(__traits(getMember, Enum, names[0])), EnumSpecificMembers!(Enum, names[1 .. $]) ) EnumSpecificMembers; } else { alias TypeTuple!() EnumSpecificMembers; } } unittest { enum A { a } static assert([ EnumMembers!A ] == [ A.a ]); enum B { a, b, c, d, e } static assert([ EnumMembers!B ] == [ B.a, B.b, B.c, B.d, B.e ]); } unittest // typed enums { enum A : string { a = "alpha", b = "beta" } static assert([ EnumMembers!A ] == [ A.a, A.b ]); static struct S { int value; int opCmp(S rhs) const nothrow { return value - rhs.value; } } enum B : S { a = S(1), b = S(2), c = S(3) } static assert([ EnumMembers!B ] == [ B.a, B.b, B.c ]); } unittest // duplicated values { enum A { a = 0, b = 0, c = 1, d = 1, e } static assert([ EnumMembers!A ] == [ A.a, A.b, A.c, A.d, A.e ]); } // Supply the specified identifier to an constant value. private template WithIdentifier(string ident) { static if (ident == "Symbolize") { template Symbolize(alias value) { enum Symbolize = value; } } else { mixin("template Symbolize(alias "~ ident ~")" ~"{" ~"alias "~ ident ~" Symbolize;" ~"}"); } } unittest { enum E { member, a = 0, b = 0 } static assert(__traits(identifier, EnumMembers!E[0]) == "member"); static assert(__traits(identifier, EnumMembers!E[1]) == "a"); static assert(__traits(identifier, EnumMembers!E[2]) == "b"); } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::// // Classes and Interfaces //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::// /*** * Get a $(D_PARAM TypeTuple) of the base class and base interfaces of * this class or interface. $(D_PARAM BaseTypeTuple!(Object)) returns * the empty type tuple. * * Example: * --- * import std.traits, std.typetuple, std.stdio; * interface I { } * class A { } * class B : A, I { } * * void main() * { * alias BaseTypeTuple!(B) TL; * writeln(typeid(TL)); // prints: (A,I) * } * --- */ template BaseTypeTuple(A) { static if (is(A P == super)) alias P BaseTypeTuple; else static assert(0, "argument is not a class or interface"); } unittest { interface I1 { } interface I2 { } interface I12 : I1, I2 { } static assert(is(BaseTypeTuple!I12 == TypeTuple!(I1, I2))); interface I3 : I1 { } interface I123 : I1, I2, I3 { } static assert(is(BaseTypeTuple!I123 == TypeTuple!(I1, I2, I3))); } unittest { interface I1 { } interface I2 { } class A { } class C : A, I1, I2 { } alias BaseTypeTuple!(C) TL; assert(TL.length == 3); assert(is (TL[0] == A)); assert(is (TL[1] == I1)); assert(is (TL[2] == I2)); assert(BaseTypeTuple!(Object).length == 0); } /** * Get a $(D_PARAM TypeTuple) of $(I all) base classes of this class, * in decreasing order. Interfaces are not included. $(D_PARAM * BaseClassesTuple!(Object)) yields the empty type tuple. * * Example: * --- * import std.traits, std.typetuple, std.stdio; * interface I { } * class A { } * class B : A, I { } * class C : B { } * * void main() * { * alias BaseClassesTuple!(C) TL; * writeln(typeid(TL)); // prints: (B,A,Object) * } * --- */ template BaseClassesTuple(T) { static if (is(T == Object)) { alias TypeTuple!() BaseClassesTuple; } static if (is(BaseTypeTuple!(T)[0] == Object)) { alias TypeTuple!(Object) BaseClassesTuple; } else { alias TypeTuple!(BaseTypeTuple!(T)[0], BaseClassesTuple!(BaseTypeTuple!(T)[0])) BaseClassesTuple; } } /** * Get a $(D_PARAM TypeTuple) of $(I all) interfaces directly or * indirectly inherited by this class or interface. Interfaces do not * repeat if multiply implemented. $(D_PARAM InterfacesTuple!(Object)) * yields the empty type tuple. * * Example: * --- * import std.traits, std.typetuple, std.stdio; * interface I1 { } * interface I2 { } * class A : I1, I2 { } * class B : A, I1 { } * class C : B { } * * void main() * { * alias InterfacesTuple!(C) TL; * writeln(typeid(TL)); // prints: (I1, I2) * } * --- */ template InterfacesTuple(T) { static if (is(T S == super) && S.length) alias NoDuplicates!(InterfacesTuple_Flatten!(S)) InterfacesTuple; else alias TypeTuple!() InterfacesTuple; } // internal private template InterfacesTuple_Flatten(H, T...) { static if (T.length) { alias TypeTuple!( InterfacesTuple_Flatten!(H), InterfacesTuple_Flatten!(T)) InterfacesTuple_Flatten; } else { static if (is(H == interface)) alias TypeTuple!(H, InterfacesTuple!(H)) InterfacesTuple_Flatten; else alias InterfacesTuple!(H) InterfacesTuple_Flatten; } } unittest { struct Test1_WorkaroundForBug2986 { // doc example interface I1 {} interface I2 {} class A : I1, I2 { } class B : A, I1 { } class C : B { } alias InterfacesTuple!(C) TL; static assert(is(TL[0] == I1) && is(TL[1] == I2)); } struct Test2_WorkaroundForBug2986 { interface Iaa {} interface Iab {} interface Iba {} interface Ibb {} interface Ia : Iaa, Iab {} interface Ib : Iba, Ibb {} interface I : Ia, Ib {} interface J {} class B : J {} class C : B, Ia, Ib {} static assert(is(InterfacesTuple!(I) == TypeTuple!(Ia, Iaa, Iab, Ib, Iba, Ibb))); static assert(is(InterfacesTuple!(C) == TypeTuple!(J, Ia, Iaa, Iab, Ib, Iba, Ibb))); } } /** * Get a $(D_PARAM TypeTuple) of $(I all) base classes of $(D_PARAM * T), in decreasing order, followed by $(D_PARAM T)'s * interfaces. $(D_PARAM TransitiveBaseTypeTuple!(Object)) yields the * empty type tuple. * * Example: * --- * import std.traits, std.typetuple, std.stdio; * interface I { } * class A { } * class B : A, I { } * class C : B { } * * void main() * { * alias TransitiveBaseTypeTuple!(C) TL; * writeln(typeid(TL)); // prints: (B,A,Object,I) * } * --- */ template TransitiveBaseTypeTuple(T) { static if (is(T == Object)) alias TypeTuple!() TransitiveBaseTypeTuple; else alias TypeTuple!(BaseClassesTuple!(T), InterfacesTuple!(T)) TransitiveBaseTypeTuple; } unittest { interface J1 {} interface J2 {} class B1 {} class B2 : B1, J1, J2 {} class B3 : B2, J1 {} alias TransitiveBaseTypeTuple!(B3) TL; assert(TL.length == 5); assert(is (TL[0] == B2)); assert(is (TL[1] == B1)); assert(is (TL[2] == Object)); assert(is (TL[3] == J1)); assert(is (TL[4] == J2)); assert(TransitiveBaseTypeTuple!(Object).length == 0); } /** Returns a tuple of non-static functions with the name $(D name) declared in the class or interface $(D C). Covariant duplicates are shrunk into the most derived one. Example: -------------------- interface I { I foo(); } class B { real foo(real v) { return v; } } class C : B, I { override C foo() { return this; } // covariant overriding of I.foo() } alias MemberFunctionsTuple!(C, "foo") foos; static assert(foos.length == 2); static assert(__traits(isSame, foos[0], C.foo)); static assert(__traits(isSame, foos[1], B.foo)); -------------------- */ template MemberFunctionsTuple(C, string name) if (is(C == class) || is(C == interface)) { static if (__traits(hasMember, C, name)) alias MemberFunctionTupleImpl!(C, name).result MemberFunctionsTuple; else alias TypeTuple!() MemberFunctionsTuple; } private template MemberFunctionTupleImpl(C, string name) { /* * First, collect all overloads in the class hierarchy. */ template CollectOverloads(Node) { static if (__traits(hasMember, Node, name)) { // Get all overloads in sight (not hidden). alias TypeTuple!(__traits(getVirtualFunctions, Node, name)) inSight; // And collect all overloads in ancestor classes to reveal hidden // methods. The result may contain duplicates. template walkThru(Parents...) { static if (Parents.length > 0) alias TypeTuple!( CollectOverloads!(Parents[0]).result, walkThru!(Parents[1 .. $]) ) walkThru; else alias TypeTuple!() walkThru; } static if (is(Node Parents == super)) alias TypeTuple!(inSight, walkThru!(Parents)) result; else alias TypeTuple!(inSight) result; } else alias TypeTuple!() result; // no overloads in this hierarchy } // duplicates in this tuple will be removed by shrink() alias CollectOverloads!(C).result overloads; /* * Now shrink covariant overloads into one. */ template shrink(overloads...) { static if (overloads.length > 0) { alias shrinkOne!(overloads).result temp; alias TypeTuple!(temp[0], shrink!(temp[1 .. $]).result) result; } else alias TypeTuple!() result; // done } // .result[0] = the most derived one in the covariant siblings of target // .result[1..$] = non-covariant others template shrinkOne(/+ alias target, rest... +/ args...) { alias args[0 .. 1] target; // prevent property functions from being evaluated alias args[1 .. $] rest; static if (rest.length > 0) { alias FunctionTypeOf!(target) Target; alias FunctionTypeOf!(rest[0]) Rest0; static if (isCovariantWith!(Target, Rest0)) // target overrides rest[0] -- erase rest[0]. alias shrinkOne!(target, rest[1 .. $]).result result; else static if (isCovariantWith!(Rest0, Target)) // rest[0] overrides target -- erase target. alias shrinkOne!(rest[0], rest[1 .. $]).result result; else // target and rest[0] are distinct. alias TypeTuple!( shrinkOne!(target, rest[1 .. $]).result, rest[0] // keep ) result; } else alias TypeTuple!(target) result; // done } // done. alias shrink!(overloads).result result; } unittest { interface I { I test(); } interface J : I { J test(); } interface K { K test(int); } class B : I, K { K test(int) { return this; } B test() { return this; } static void test(string) { } } class C : B, J { override C test() { return this; } } alias MemberFunctionsTuple!(C, "test") test; static assert(test.length == 2); static assert(is(FunctionTypeOf!(test[0]) == FunctionTypeOf!(C.test))); static assert(is(FunctionTypeOf!(test[1]) == FunctionTypeOf!(K.test))); alias MemberFunctionsTuple!(C, "noexist") noexist; static assert(noexist.length == 0); interface L { int prop() @property; } alias MemberFunctionsTuple!(L, "prop") prop; static assert(prop.length == 1); interface Test_I { void foo(); void foo(int); void foo(int, int); } interface Test : Test_I {} alias MemberFunctionsTuple!(Test, "foo") Test_foo; static assert(Test_foo.length == 3); static assert(is(typeof(&Test_foo[0]) == void function())); static assert(is(typeof(&Test_foo[2]) == void function(int))); static assert(is(typeof(&Test_foo[1]) == void function(int, int))); } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::// // Type Conversion //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::// /** Get the type that all types can be implicitly converted to. Useful e.g. in figuring out an array type from a bunch of initializing values. Returns $(D_PARAM void) if passed an empty list, or if the types have no common type. Example: ---- alias CommonType!(int, long, short) X; assert(is(X == long)); alias CommonType!(int, char[], short) Y; assert(is(Y == void)); ---- */ template CommonType(T...) { static if (!T.length) alias void CommonType; else static if (T.length == 1) { static if(is(typeof(T[0]))) { alias typeof(T[0]) CommonType; } else { alias T[0] CommonType; } } else static if (is(typeof(true ? T[0].init : T[1].init) U)) alias CommonType!(U, T[2 .. $]) CommonType; else alias void CommonType; } unittest { alias CommonType!(int, long, short) X; static assert(is(X == long)); alias CommonType!(char[], int, long, short) Y; static assert(is(Y == void), Y.stringof); static assert(is(CommonType!(3) == int)); static assert(is(CommonType!(double, 4, float) == double)); static assert(is(CommonType!(string, char[]) == const(char)[])); static assert(is(CommonType!(3, 3U) == uint)); } /** * Returns a tuple with all possible target types of an implicit * conversion of a value of type $(D_PARAM T). * * Important note: * * The possible targets are computed more conservatively than the D * 2.005 compiler does, eliminating all dangerous conversions. For * example, $(D_PARAM ImplicitConversionTargets!(double)) does not * include $(D_PARAM float). */ template ImplicitConversionTargets(T) { static if (is(T == bool)) alias TypeTuple!(byte, ubyte, short, ushort, int, uint, long, ulong, float, double, real, char, wchar, dchar) ImplicitConversionTargets; else static if (is(T == byte)) alias TypeTuple!(short, ushort, int, uint, long, ulong, float, double, real, char, wchar, dchar) ImplicitConversionTargets; else static if (is(T == ubyte)) alias TypeTuple!(short, ushort, int, uint, long, ulong, float, double, real, char, wchar, dchar) ImplicitConversionTargets; else static if (is(T == short)) alias TypeTuple!(ushort, int, uint, long, ulong, float, double, real) ImplicitConversionTargets; else static if (is(T == ushort)) alias TypeTuple!(int, uint, long, ulong, float, double, real) ImplicitConversionTargets; else static if (is(T == int)) alias TypeTuple!(long, ulong, float, double, real) ImplicitConversionTargets; else static if (is(T == uint)) alias TypeTuple!(long, ulong, float, double, real) ImplicitConversionTargets; else static if (is(T == long)) alias TypeTuple!(float, double, real) ImplicitConversionTargets; else static if (is(T == ulong)) alias TypeTuple!(float, double, real) ImplicitConversionTargets; else static if (is(T == float)) alias TypeTuple!(double, real) ImplicitConversionTargets; else static if (is(T == double)) alias TypeTuple!(real) ImplicitConversionTargets; else static if (is(T == char)) alias TypeTuple!(wchar, dchar, byte, ubyte, short, ushort, int, uint, long, ulong, float, double, real) ImplicitConversionTargets; else static if (is(T == wchar)) alias TypeTuple!(wchar, dchar, short, ushort, int, uint, long, ulong, float, double, real) ImplicitConversionTargets; else static if (is(T == dchar)) alias TypeTuple!(wchar, dchar, int, uint, long, ulong, float, double, real) ImplicitConversionTargets; else static if(is(T : Object)) alias TransitiveBaseTypeTuple!(T) ImplicitConversionTargets; // @@@BUG@@@ this should work // else static if (isDynamicArray!T && !is(typeof(T.init[0]) == const)) // alias TypeTuple!(const(typeof(T.init[0]))[]) ImplicitConversionTargets; else static if (is(T == char[])) alias TypeTuple!(const(char)[]) ImplicitConversionTargets; else static if (isDynamicArray!T && !is(typeof(T.init[0]) == const)) alias TypeTuple!(const(typeof(T.init[0]))[]) ImplicitConversionTargets; else static if (is(T : void*)) alias TypeTuple!(void*) ImplicitConversionTargets; else alias TypeTuple!() ImplicitConversionTargets; } unittest { assert(is(ImplicitConversionTargets!(double)[0] == real)); } /** Is $(D From) implicitly convertible to $(D To)? */ template isImplicitlyConvertible(From, To) { enum bool isImplicitlyConvertible = is(typeof({ void fun(ref From v) { void gun(To) {} gun(v); } }())); } unittest { static assert(isImplicitlyConvertible!(immutable(char), char)); static assert(isImplicitlyConvertible!(const(char), char)); static assert(isImplicitlyConvertible!(char, wchar)); static assert(!isImplicitlyConvertible!(wchar, char)); // bug6197 static assert(!isImplicitlyConvertible!(const(ushort), ubyte)); static assert(!isImplicitlyConvertible!(const(uint), ubyte)); static assert(!isImplicitlyConvertible!(const(ulong), ubyte)); // from std.conv.implicitlyConverts assert(!isImplicitlyConvertible!(const(char)[], string)); assert(isImplicitlyConvertible!(string, const(char)[])); } /** Returns $(D true) iff a value of type $(D Rhs) can be assigned to a variable of type $(D Lhs). Examples: --- static assert(isAssignable!(long, int)); static assert(!isAssignable!(int, long)); static assert(isAssignable!(const(char)[], string)); static assert(!isAssignable!(string, char[])); --- */ template isAssignable(Lhs, Rhs) { enum bool isAssignable = is(typeof({ Lhs l; Rhs r; l = r; return l; })); } unittest { static assert(isAssignable!(long, int)); static assert(!isAssignable!(int, long)); static assert(isAssignable!(const(char)[], string)); static assert(!isAssignable!(string, char[])); } /* Works like $(D isImplicitlyConvertible), except this cares only about storage classes of the arguments. */ private template isStorageClassImplicitlyConvertible(From, To) { enum isStorageClassImplicitlyConvertible = isImplicitlyConvertible!( ModifyTypePreservingSTC!(Pointify, From), ModifyTypePreservingSTC!(Pointify, To) ); } private template Pointify(T) { alias void* Pointify; } unittest { static assert(isStorageClassImplicitlyConvertible!( int, const int)); static assert(isStorageClassImplicitlyConvertible!(immutable int, const int)); static assert(! isStorageClassImplicitlyConvertible!(const int, int)); static assert(! isStorageClassImplicitlyConvertible!(const int, immutable int)); static assert(! isStorageClassImplicitlyConvertible!(int, shared int)); static assert(! isStorageClassImplicitlyConvertible!(shared int, int)); } /** Determines whether the function type $(D F) is covariant with $(D G), i.e., functions of the type $(D F) can override ones of the type $(D G). Example: -------------------- interface I { I clone(); } interface J { J clone(); } class C : I { override C clone() // covariant overriding of I.clone() { return new C; } } // C.clone() can override I.clone(), indeed. static assert(isCovariantWith!(typeof(C.clone), typeof(I.clone))); // C.clone() can't override J.clone(); the return type C is not implicitly // convertible to J. static assert(isCovariantWith!(typeof(C.clone), typeof(J.clone))); -------------------- */ template isCovariantWith(F, G) if (is(F == function) && is(G == function)) { static if (is(F : G)) enum isCovariantWith = true; else enum isCovariantWith = isCovariantWithImpl!(F, G).yes; } private template isCovariantWithImpl(Upr, Lwr) { /* * Check for calling convention: require exact match. */ template checkLinkage() { enum ok = functionLinkage!(Upr) == functionLinkage!(Lwr); } /* * Check for variadic parameter: require exact match. */ template checkVariadicity() { enum ok = variadicFunctionStyle!(Upr) == variadicFunctionStyle!(Lwr); } /* * Check for function storage class: * - overrider can have narrower storage class than base */ template checkSTC() { // Note the order of arguments. The convertion order Lwr -> Upr is // correct since Upr should be semantically 'narrower' than Lwr. enum ok = isStorageClassImplicitlyConvertible!(Lwr, Upr); } /* * Check for function attributes: * - require exact match for ref and @property * - overrider can add pure and nothrow, but can't remove them * - @safe and @trusted are covariant with each other, unremovable */ template checkAttributes() { alias FunctionAttribute FA; enum uprAtts = functionAttributes!(Upr); enum lwrAtts = functionAttributes!(Lwr); // enum wantExact = FA.ref_ | FA.property; enum safety = FA.safe | FA.trusted; enum ok = ( (uprAtts & wantExact) == (lwrAtts & wantExact)) && ( (uprAtts & FA.pure_ ) >= (lwrAtts & FA.pure_ )) && ( (uprAtts & FA.nothrow_) >= (lwrAtts & FA.nothrow_)) && (!!(uprAtts & safety ) >= !!(lwrAtts & safety )) ; } /* * Check for return type: usual implicit convertion. */ template checkReturnType() { enum ok = is(ReturnType!(Upr) : ReturnType!(Lwr)); } /* * Check for parameters: * - require exact match for types (cf. bugzilla 3075) * - require exact match for in, out, ref and lazy * - overrider can add scope, but can't remove */ template checkParameters() { alias ParameterStorageClass STC; alias ParameterTypeTuple!(Upr) UprParams; alias ParameterTypeTuple!(Lwr) LwrParams; alias ParameterStorageClassTuple!(Upr) UprPSTCs; alias ParameterStorageClassTuple!(Lwr) LwrPSTCs; // template checkNext(size_t i) { static if (i < UprParams.length) { enum uprStc = UprPSTCs[i]; enum lwrStc = LwrPSTCs[i]; // enum wantExact = STC.out_ | STC.ref_ | STC.lazy_; enum ok = ((uprStc & wantExact ) == (lwrStc & wantExact )) && ((uprStc & STC.scope_) >= (lwrStc & STC.scope_)) && checkNext!(i + 1).ok; } else enum ok = true; // done } static if (UprParams.length == LwrParams.length) enum ok = is(UprParams == LwrParams) && checkNext!(0).ok; else enum ok = false; } /* run all the checks */ enum bool yes = checkLinkage !().ok && checkVariadicity!().ok && checkSTC !().ok && checkAttributes !().ok && checkReturnType !().ok && checkParameters !().ok ; } version (unittest) private template isCovariantWith(alias f, alias g) { enum bool isCovariantWith = isCovariantWith!(typeof(f), typeof(g)); } unittest { // covariant return type interface I {} interface J : I {} interface BaseA { const(I) test(int); } interface DerivA_1 : BaseA { override const(J) test(int); } interface DerivA_2 : BaseA { override J test(int); } static assert(isCovariantWith!(DerivA_1.test, BaseA.test)); static assert(isCovariantWith!(DerivA_2.test, BaseA.test)); static assert(! isCovariantWith!(BaseA.test, DerivA_1.test)); static assert(! isCovariantWith!(BaseA.test, DerivA_2.test)); static assert(isCovariantWith!(BaseA.test, BaseA.test)); static assert(isCovariantWith!(DerivA_1.test, DerivA_1.test)); static assert(isCovariantWith!(DerivA_2.test, DerivA_2.test)); // scope parameter interface BaseB { void test( int, int); } interface DerivB_1 : BaseB { override void test(scope int, int); } interface DerivB_2 : BaseB { override void test( int, scope int); } interface DerivB_3 : BaseB { override void test(scope int, scope int); } static assert(isCovariantWith!(DerivB_1.test, BaseB.test)); static assert(isCovariantWith!(DerivB_2.test, BaseB.test)); static assert(isCovariantWith!(DerivB_3.test, BaseB.test)); static assert(! isCovariantWith!(BaseB.test, DerivB_1.test)); static assert(! isCovariantWith!(BaseB.test, DerivB_2.test)); static assert(! isCovariantWith!(BaseB.test, DerivB_3.test)); // function storage class interface BaseC { void test() ; } interface DerivC_1 : BaseC { override void test() const; } static assert(isCovariantWith!(DerivC_1.test, BaseC.test)); static assert(! isCovariantWith!(BaseC.test, DerivC_1.test)); // increasing safety interface BaseE { void test() ; } interface DerivE_1 : BaseE { override void test() @safe ; } interface DerivE_2 : BaseE { override void test() @trusted; } static assert(isCovariantWith!(DerivE_1.test, BaseE.test)); static assert(isCovariantWith!(DerivE_2.test, BaseE.test)); static assert(! isCovariantWith!(BaseE.test, DerivE_1.test)); static assert(! isCovariantWith!(BaseE.test, DerivE_2.test)); // @safe and @trusted interface BaseF { void test1() @safe; void test2() @trusted; } interface DerivF : BaseF { override void test1() @trusted; override void test2() @safe; } static assert(isCovariantWith!(DerivF.test1, BaseF.test1)); static assert(isCovariantWith!(DerivF.test2, BaseF.test2)); } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::// // isSomething //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::// /** * Detect whether T is a built-in integral type. Types $(D bool), $(D * char), $(D wchar), and $(D dchar) are not considered integral. */ template isIntegral(T) { enum bool isIntegral = staticIndexOf!(Unqual!(T), byte, ubyte, short, ushort, int, uint, long, ulong) >= 0; } unittest { static assert(isIntegral!(byte)); static assert(isIntegral!(const(byte))); static assert(isIntegral!(immutable(byte))); static assert(isIntegral!(shared(byte))); static assert(isIntegral!(shared(const(byte)))); static assert(isIntegral!(ubyte)); static assert(isIntegral!(const(ubyte))); static assert(isIntegral!(immutable(ubyte))); static assert(isIntegral!(shared(ubyte))); static assert(isIntegral!(shared(const(ubyte)))); static assert(isIntegral!(short)); static assert(isIntegral!(const(short))); static assert(isIntegral!(immutable(short))); static assert(isIntegral!(shared(short))); static assert(isIntegral!(shared(const(short)))); static assert(isIntegral!(ushort)); static assert(isIntegral!(const(ushort))); static assert(isIntegral!(immutable(ushort))); static assert(isIntegral!(shared(ushort))); static assert(isIntegral!(shared(const(ushort)))); static assert(isIntegral!(int)); static assert(isIntegral!(const(int))); static assert(isIntegral!(immutable(int))); static assert(isIntegral!(shared(int))); static assert(isIntegral!(shared(const(int)))); static assert(isIntegral!(uint)); static assert(isIntegral!(const(uint))); static assert(isIntegral!(immutable(uint))); static assert(isIntegral!(shared(uint))); static assert(isIntegral!(shared(const(uint)))); static assert(isIntegral!(long)); static assert(isIntegral!(const(long))); static assert(isIntegral!(immutable(long))); static assert(isIntegral!(shared(long))); static assert(isIntegral!(shared(const(long)))); static assert(isIntegral!(ulong)); static assert(isIntegral!(const(ulong))); static assert(isIntegral!(immutable(ulong))); static assert(isIntegral!(shared(ulong))); static assert(isIntegral!(shared(const(ulong)))); static assert(!isIntegral!(float)); } /** * Detect whether T is a built-in floating point type. */ template isFloatingPoint(T) { enum bool isFloatingPoint = staticIndexOf!(Unqual!(T), float, double, real) >= 0; } unittest { foreach (F; TypeTuple!(float, double, real)) { F a = 5.5; static assert(isFloatingPoint!(typeof(a))); const F b = 5.5; static assert(isFloatingPoint!(typeof(b))); immutable F c = 5.5; static assert(isFloatingPoint!(typeof(c))); } foreach (T; TypeTuple!(int, long, char)) { T a; static assert(!isFloatingPoint!(typeof(a))); const T b = 0; static assert(!isFloatingPoint!(typeof(b))); immutable T c = 0; static assert(!isFloatingPoint!(typeof(c))); } } /** Detect whether T is a built-in numeric type (integral or floating point). */ template isNumeric(T) { enum bool isNumeric = isIntegral!(T) || isFloatingPoint!(T); } /** Detect whether $(D T) is a built-in unsigned numeric type. */ template isUnsigned(T) { enum bool isUnsigned = staticIndexOf!(Unqual!T, ubyte, ushort, uint, ulong) >= 0; } /** Detect whether $(D T) is a built-in signed numeric type. */ template isSigned(T) { enum bool isSigned = staticIndexOf!(Unqual!T, byte, short, int, long, float, double, real) >= 0; } /** Detect whether T is one of the built-in string types */ template isSomeString(T) { enum isSomeString = isNarrowString!T || is(T : const(dchar[])); } unittest { static assert(!isSomeString!(int)); static assert(!isSomeString!(int[])); static assert(!isSomeString!(byte[])); static assert(isSomeString!(char[])); static assert(isSomeString!(dchar[])); static assert(isSomeString!(string)); static assert(isSomeString!(wstring)); static assert(isSomeString!(dstring)); static assert(isSomeString!(char[4])); } template isNarrowString(T) { enum isNarrowString = is(T : const(char[])) || is(T : const(wchar[])); } unittest { static assert(!isNarrowString!(int)); static assert(!isNarrowString!(int[])); static assert(!isNarrowString!(byte[])); static assert(isNarrowString!(char[])); static assert(!isNarrowString!(dchar[])); static assert(isNarrowString!(string)); static assert(isNarrowString!(wstring)); static assert(!isNarrowString!(dstring)); static assert(isNarrowString!(char[4])); } /** Detect whether T is one of the built-in character types */ template isSomeChar(T) { enum isSomeChar = staticIndexOf!(Unqual!T, char, wchar, dchar) >= 0; } unittest { static assert(!isSomeChar!(int)); static assert(!isSomeChar!(int)); static assert(!isSomeChar!(byte)); static assert(isSomeChar!(char)); static assert(isSomeChar!(dchar)); static assert(!isSomeChar!(string)); static assert(!isSomeChar!(wstring)); static assert(!isSomeChar!(dstring)); static assert(!isSomeChar!(char[4])); static assert(isSomeChar!(immutable(char))); } /** * Detect whether T is an associative array type */ template isAssociativeArray(T) { enum bool isAssociativeArray = __traits(isAssociativeArray, T); } unittest { struct Foo { @property uint[] keys() { return null; } @property uint[] values() { return null; } } static assert(!isAssociativeArray!(Foo)); static assert(!isAssociativeArray!(int)); static assert(!isAssociativeArray!(int[])); static assert(isAssociativeArray!(int[int])); static assert(isAssociativeArray!(int[string])); static assert(isAssociativeArray!(immutable(char[5])[int])); } /** * Detect whether type T is a static array. */ template isStaticArray(T : U[N], U, size_t N) { enum bool isStaticArray = true; } template isStaticArray(T) { enum bool isStaticArray = false; } unittest { static assert (isStaticArray!(int[51])); static assert (isStaticArray!(int[][2])); static assert (isStaticArray!(char[][int][11])); static assert (!isStaticArray!(const(int)[])); static assert (!isStaticArray!(immutable(int)[])); static assert (!isStaticArray!(const(int)[4][])); static assert (!isStaticArray!(int[])); static assert (!isStaticArray!(int[char])); static assert (!isStaticArray!(int[1][])); static assert (isStaticArray!(immutable char[13u])); static assert (isStaticArray!(const(real)[1])); static assert (isStaticArray!(const(real)[1][1])); static assert (isStaticArray!(void[0])); static assert (!isStaticArray!(int[int])); static assert (!isStaticArray!(int)); } /** * Detect whether type T is a dynamic array. */ template isDynamicArray(T, U = void) { enum bool isDynamicArray = false; } template isDynamicArray(T : U[], U) { enum bool isDynamicArray = !isStaticArray!(T); } unittest { static assert(isDynamicArray!(int[])); static assert(!isDynamicArray!(int[5])); } /** * Detect whether type T is an array. */ template isArray(T) { enum bool isArray = isStaticArray!(T) || isDynamicArray!(T); } unittest { static assert(isArray!(int[])); static assert(isArray!(int[5])); static assert(!isArray!(uint)); static assert(!isArray!(uint[uint])); static assert(isArray!(void[])); } /** * Detect whether type $(D T) is a pointer. */ template isPointer(T) { static if (is(T P == U*, U)) { enum bool isPointer = true; } else { enum bool isPointer = false; } } unittest { static assert(isPointer!(int*)); static assert(!isPointer!(uint)); static assert(!isPointer!(uint[uint])); static assert(!isPointer!(char[])); static assert(isPointer!(void*)); } /** Returns the target type of a pointer. */ template pointerTarget(T : T*) { alias T pointerTarget; } unittest { static assert(is(pointerTarget!(int*) == int)); static assert(!is(pointerTarget!int)); static assert(is(pointerTarget!(long*) == long)); } /** * Returns $(D true) if T can be iterated over using a $(D foreach) loop with * a single loop variable of automatically inferred type, regardless of how * the $(D foreach) loop is implemented. This includes ranges, structs/classes * that define $(D opApply) with a single loop variable, and builtin dynamic, * static and associative arrays. */ template isIterable(T) { static if (is(typeof({foreach(elem; T.init) {}}))) { enum bool isIterable = true; } else { enum bool isIterable = false; } } unittest { struct OpApply { int opApply(int delegate(ref uint) dg) { assert(0); } } struct Range { uint front() { assert(0); } void popFront() { assert(0); } enum bool empty = false; } static assert(isIterable!(uint[])); static assert(!isIterable!(uint)); static assert(isIterable!(OpApply)); static assert(isIterable!(uint[string])); static assert(isIterable!(Range)); } /* * Returns true if T is not const or immutable. Note that isMutable is true for * string, or immutable(char)[], because the 'head' is mutable. */ template isMutable(T) { enum isMutable = !is(T == const) && !is(T == immutable); } unittest { static assert(isMutable!int); static assert(isMutable!string); static assert(isMutable!(shared int)); static assert(isMutable!(shared const(int)[])); static assert(!isMutable!(const int)); static assert(!isMutable!(shared(const int))); static assert(!isMutable!(immutable string)); } /** * Tells whether the tuple T is an expression tuple. */ template isExpressionTuple(T ...) { static if (T.length > 0) enum bool isExpressionTuple = !is(T[0]) && __traits(compiles, { auto ex = T[0]; }) && isExpressionTuple!(T[1 .. $]); else enum bool isExpressionTuple = true; // default } unittest { void foo(); static int bar() { return 42; } enum aa = [ 1: -1 ]; alias int myint; static assert(isExpressionTuple!(42)); static assert(isExpressionTuple!(aa)); static assert(isExpressionTuple!("cattywampus", 2.7, aa)); static assert(isExpressionTuple!(bar())); static assert(! isExpressionTuple!(isExpressionTuple)); static assert(! isExpressionTuple!(foo)); static assert(! isExpressionTuple!( (a) { } )); static assert(! isExpressionTuple!(int)); static assert(! isExpressionTuple!(myint)); } /** Detect whether tuple $(D T) is a type tuple. */ template isTypeTuple(T...) { static if (T.length > 0) enum bool isTypeTuple = is(T[0]) && isTypeTuple!(T[1 .. $]); else enum bool isTypeTuple = true; // default } unittest { class C {} void func(int) {} auto c = new C; enum CONST = 42; static assert(isTypeTuple!(int)); static assert(isTypeTuple!(string)); static assert(isTypeTuple!(C)); static assert(isTypeTuple!(typeof(func))); static assert(isTypeTuple!(int, char, double)); static assert(! isTypeTuple!(c)); static assert(! isTypeTuple!(isTypeTuple)); static assert(! isTypeTuple!(CONST)); } /** Detect whether symbol or type $(D T) is a function pointer. */ template isFunctionPointer(T...) if (T.length == 1) { static if (is(T[0] U) || is(typeof(T[0]) U)) { static if (is(U F : F*) && is(F == function)) enum bool isFunctionPointer = true; else enum bool isFunctionPointer = false; } else enum bool isFunctionPointer = false; } unittest { static void foo() {} void bar() {} auto fpfoo = &foo; static assert(isFunctionPointer!(fpfoo)); static assert(isFunctionPointer!(void function())); auto dgbar = &bar; static assert(! isFunctionPointer!(dgbar)); static assert(! isFunctionPointer!(void delegate())); static assert(! isFunctionPointer!(foo)); static assert(! isFunctionPointer!(bar)); static assert(!isFunctionPointer!((int a) {})); } /** Detect whether $(D T) is a delegate. */ template isDelegate(T...) if(T.length == 1) { enum bool isDelegate = is(T[0] == delegate); } unittest { static assert(isDelegate!(void delegate())); static assert(isDelegate!(uint delegate(uint))); static assert(isDelegate!(shared uint delegate(uint))); static assert(!isDelegate!(uint)); static assert(!isDelegate!(void function())); } /** Detect whether symbol or type $(D T) is a function, a function pointer or a delegate. */ template isSomeFunction(T...) if (T.length == 1) { static if (is(typeof(& T[0]) U : U*) && is(U == function) || is(typeof(& T[0]) U == delegate)) { // T is a (nested) function symbol. enum bool isSomeFunction = true; } else static if (is(T[0] W) || is(typeof(T[0]) W)) { // T is an expression or a type. Take the type of it and examine. static if (is(W F : F*) && is(F == function)) enum bool isSomeFunction = true; // function pointer else enum bool isSomeFunction = is(W == function) || is(W == delegate); } else enum bool isSomeFunction = false; } unittest { static real func(ref int) { return 0; } static void prop() @property { } void nestedFunc() { } void nestedProp() @property { } class C { real method(ref int) { return 0; } real prop() @property { return 0; } } auto c = new C; auto fp = &func; auto dg = &c.method; real val; static assert(isSomeFunction!(func)); static assert(isSomeFunction!(prop)); static assert(isSomeFunction!(nestedFunc)); static assert(isSomeFunction!(nestedProp)); static assert(isSomeFunction!(C.method)); static assert(isSomeFunction!(C.prop)); static assert(isSomeFunction!(c.prop)); static assert(isSomeFunction!(c.prop)); static assert(isSomeFunction!(fp)); static assert(isSomeFunction!(dg)); static assert(isSomeFunction!(typeof(func))); static assert(isSomeFunction!(real function(ref int))); static assert(isSomeFunction!(real delegate(ref int))); static assert(! isSomeFunction!(int)); static assert(! isSomeFunction!(val)); static assert(! isSomeFunction!(isSomeFunction)); static assert(isSomeFunction!((int a) { return a; })); } /** Detect whether $(D T) is a callable object, which can be called with the function call operator $(D $(LPAREN)...$(RPAREN)). */ template isCallable(T...) if (T.length == 1) { static if (is(typeof(& T[0].opCall) == delegate)) // T is a object which has a member function opCall(). enum bool isCallable = true; else static if (is(typeof(& T[0].opCall) V : V*) && is(V == function)) // T is a type which has a static member function opCall(). enum bool isCallable = true; else enum bool isCallable = isSomeFunction!(T); } unittest { interface I { real value() @property; } struct S { static int opCall(int) { return 0; } } class C { int opCall(int) { return 0; } } auto c = new C; static assert( isCallable!(c)); static assert( isCallable!(S)); static assert( isCallable!(c.opCall)); static assert( isCallable!(I.value)); static assert(!isCallable!(I)); static assert(isCallable!((int a) { return a; })); } /** Exactly the same as the builtin traits: $(D ___traits(_isAbstractFunction, method)). */ template isAbstractFunction(method...) if (method.length == 1) { enum bool isAbstractFunction = __traits(isAbstractFunction, method[0]); } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::// // General Types //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::// /** Removes all qualifiers, if any, from type $(D T). Example: ---- static assert(is(Unqual!(int) == int)); static assert(is(Unqual!(const int) == int)); static assert(is(Unqual!(immutable int) == int)); static assert(is(Unqual!(shared int) == int)); static assert(is(Unqual!(shared(const int)) == int)); ---- */ template Unqual(T) { version (none) // Error: recursive alias declaration @@@BUG1308@@@ { static if (is(T U == const U)) alias Unqual!U Unqual; else static if (is(T U == immutable U)) alias Unqual!U Unqual; else static if (is(T U == inout U)) alias Unqual!U Unqual; else static if (is(T U == shared U)) alias Unqual!U Unqual; else alias T Unqual; } else // workaround { static if (is(T U == shared(const U))) alias U Unqual; else static if (is(T U == const U )) alias U Unqual; else static if (is(T U == immutable U )) alias U Unqual; else static if (is(T U == inout U )) alias U Unqual; else static if (is(T U == shared U )) alias U Unqual; else alias T Unqual; } } unittest { static assert(is(Unqual!(int) == int)); static assert(is(Unqual!(const int) == int)); static assert(is(Unqual!(immutable int) == int)); static assert(is(Unqual!(inout int) == int)); static assert(is(Unqual!(shared int) == int)); static assert(is(Unqual!(shared(const int)) == int)); alias immutable(int[]) ImmIntArr; static assert(is(Unqual!(ImmIntArr) == immutable(int)[])); } // [For internal use] private template ModifyTypePreservingSTC(alias Modifier, T) { static if (is(T U == shared(const U))) alias shared(const Modifier!U) ModifyTypePreservingSTC; else static if (is(T U == const U )) alias const(Modifier!U) ModifyTypePreservingSTC; else static if (is(T U == immutable U )) alias immutable(Modifier!U) ModifyTypePreservingSTC; else static if (is(T U == shared U )) alias shared(Modifier!U) ModifyTypePreservingSTC; else alias Modifier!T ModifyTypePreservingSTC; } unittest { static assert(is(ModifyTypePreservingSTC!(Intify, const real) == const int)); static assert(is(ModifyTypePreservingSTC!(Intify, immutable real) == immutable int)); static assert(is(ModifyTypePreservingSTC!(Intify, shared real) == shared int)); static assert(is(ModifyTypePreservingSTC!(Intify, shared(const real)) == shared(const int))); } version (unittest) private template Intify(T) { alias int Intify; } /* */ template StringTypeOf(T) if (isSomeString!T) { alias typeof(T.init[]) StringTypeOf; } unittest { foreach (Ch; TypeTuple!(char, wchar, dchar)) { foreach (Char; TypeTuple!(Ch, const(Ch), immutable(Ch))) { foreach (Str; TypeTuple!(Char[], const(Char)[], immutable(Char)[])) { class C(Str) { Str val; alias val this; } struct S(Str) { Str val; alias val this; } static assert(is(StringTypeOf!(C!Str) == Str)); static assert(is(StringTypeOf!(S!Str) == Str)); } } } } /** Returns the inferred type of the loop variable when a variable of type T is iterated over using a $(D foreach) loop with a single loop variable and automatically inferred return type. Note that this may not be the same as $(D std.range.ElementType!(Range)) in the case of narrow strings, or if T has both opApply and a range interface. */ template ForeachType(T) { alias ReturnType!(typeof( { foreach(elem; T.init) { return elem; } assert(0); })) ForeachType; } unittest { static assert(is(ForeachType!(uint[]) == uint)); static assert(is(ForeachType!(string) == immutable(char))); static assert(is(ForeachType!(string[string]) == string)); } /** Strips off all $(D typedef)s (including $(D enum) ones) from type $(D T). Example: -------------------- enum E : int { a } typedef E F; typedef const F G; static assert(is(OriginalType!G == const int)); -------------------- */ template OriginalType(T) { alias ModifyTypePreservingSTC!(OriginalTypeImpl, T) OriginalType; } private template OriginalTypeImpl(T) { static if (is(T U == typedef)) alias OriginalType!U OriginalTypeImpl; else static if (is(T U == enum)) alias OriginalType!U OriginalTypeImpl; else alias T OriginalTypeImpl; } unittest { //typedef real T; //typedef T U; //enum V : U { a } //static assert(is(OriginalType!T == real)); //static assert(is(OriginalType!U == real)); //static assert(is(OriginalType!V == real)); enum E : real { a } enum F : E { a = E.a } //typedef const F G; static assert(is(OriginalType!E == real)); static assert(is(OriginalType!F == real)); //static assert(is(OriginalType!G == const real)); } /** * Returns the corresponding unsigned type for T. T must be a numeric * integral type, otherwise a compile-time error occurs. */ template Unsigned(T) { alias ModifyTypePreservingSTC!(UnsignedImpl, OriginalType!T) Unsigned; } private template UnsignedImpl(T) { static if (isUnsigned!(T)) alias T UnsignedImpl; else static if (is(T == byte)) alias ubyte UnsignedImpl; else static if (is(T == short)) alias ushort UnsignedImpl; else static if (is(T == int)) alias uint UnsignedImpl; else static if (is(T == long)) alias ulong UnsignedImpl; else static assert(false, "Type " ~ T.stringof ~ " does not have an Unsigned counterpart"); } unittest { alias Unsigned!(int) U; assert(is(U == uint)); alias Unsigned!(const(int)) U1; assert(is(U1 == const(uint)), U1.stringof); alias Unsigned!(immutable(int)) U2; assert(is(U2 == immutable(uint)), U2.stringof); //struct S {} //alias Unsigned!(S) U2; //alias Unsigned!(double) U3; } /** Returns the largest type, i.e. T such that T.sizeof is the largest. If more than one type is of the same size, the leftmost argument of these in will be returned. */ template Largest(T...) if(T.length >= 1) { static if(T.length == 1) { alias T[0] Largest; } static if(T.length == 2) { static if(T[0].sizeof >= T[1].sizeof) { alias T[0] Largest; } else { alias T[1] Largest; } } else { alias Largest!(Largest!(T[0], T[1]), T[2..$]) Largest; } } unittest { static assert(is(Largest!(uint, ubyte, ulong, real) == real)); static assert(is(Largest!(ulong, double) == ulong)); static assert(is(Largest!(double, ulong) == double)); static assert(is(Largest!(uint, byte, double, short) == double)); } /** Returns the corresponding signed type for T. T must be a numeric integral type, otherwise a compile-time error occurs. */ template Signed(T) { alias ModifyTypePreservingSTC!(SignedImpl, OriginalType!T) Signed; } private template SignedImpl(T) { static if (isSigned!(T)) alias T SignedImpl; else static if (is(T == ubyte)) alias byte SignedImpl; else static if (is(T == ushort)) alias short SignedImpl; else static if (is(T == uint)) alias int SignedImpl; else static if (is(T == ulong)) alias long SignedImpl; else static assert(false, "Type " ~ T.stringof ~ " does not have an Signed counterpart"); } unittest { alias Signed!(uint) S; assert(is(S == int)); alias Signed!(const(uint)) S1; assert(is(S1 == const(int)), S1.stringof); alias Signed!(immutable(uint)) S2; assert(is(S2 == immutable(int)), S2.stringof); } /** * Returns the corresponding unsigned value for $(D x), e.g. if $(D x) * has type $(D int), returns $(D cast(uint) x). The advantage * compared to the cast is that you do not need to rewrite the cast if * $(D x) later changes type to e.g. $(D long). */ auto unsigned(T)(T x) if (isIntegral!T) { static if (is(Unqual!T == byte)) return cast(ubyte) x; else static if (is(Unqual!T == short)) return cast(ushort) x; else static if (is(Unqual!T == int)) return cast(uint) x; else static if (is(Unqual!T == long)) return cast(ulong) x; else { static assert(T.min == 0, "Bug in either unsigned or isIntegral"); return x; } } unittest { static assert(is(typeof(unsigned(1 + 1)) == uint)); } auto unsigned(T)(T x) if (isSomeChar!T) { // All characters are unsigned static assert(T.min == 0); return x; } /** Returns the most negative value of the numeric type T. */ template mostNegative(T) { static if (is(typeof(T.min_normal))) enum mostNegative = -T.max; else static if (T.min == 0) enum byte mostNegative = 0; else enum mostNegative = T.min; } unittest { static assert(mostNegative!(float) == -float.max); static assert(mostNegative!(uint) == 0); static assert(mostNegative!(long) == long.min); } //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::// // Misc. //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::// /** Returns the mangled name of symbol or type $(D sth). $(D mangledName) is the same as builtin $(D .mangleof) property, except that the correct names of property functions are obtained. -------------------- module test; import std.traits : mangledName; class C { int value() @property; } pragma(msg, C.value.mangleof); // prints "i" pragma(msg, mangledName!(C.value)); // prints "_D4test1C5valueMFNdZi" -------------------- */ template mangledName(sth...) if (sth.length == 1) { enum string mangledName = removeDummyEnvelope(Dummy!(sth).Hook.mangleof); } private template Dummy(T...) { struct Hook {} } private string removeDummyEnvelope(string s) { // remove --> S3std6traits ... Z4Hook s = s[12 .. $ - 6]; // remove --> DIGIT+ __T5Dummy foreach (i, c; s) { if (c < '0' || '9' < c) { s = s[i .. $]; break; } } s = s[9 .. $]; // __T5Dummy // remove --> T | V | S immutable kind = s[0]; s = s[1 .. $]; if (kind == 'S') // it's a symbol { /* * The mangled symbol name is packed in LName --> Number Name. Here * we are chopping off the useless preceding Number, which is the * length of Name in decimal notation. * * NOTE: n = m + Log(m) + 1; n = LName.length, m = Name.length. */ immutable n = s.length; size_t m_upb = 10; foreach (k; 1 .. 5) // k = Log(m_upb) { if (n < m_upb + k + 1) { // Now m_upb/10 <= m < m_upb; hence k = Log(m) + 1. s = s[k .. $]; break; } m_upb *= 10; } } return s; } unittest { //typedef int MyInt; //MyInt test() { return 0; } class C { int value() @property { return 0; } } static assert(mangledName!(int) == int.mangleof); static assert(mangledName!(C) == C.mangleof); //static assert(mangledName!(MyInt)[$ - 7 .. $] == "T5MyInt"); // XXX depends on bug 4237 //static assert(mangledName!(test)[$ - 7 .. $] == "T5MyInt"); static assert(mangledName!(C.value)[$ - 12 .. $] == "5valueMFNdZi"); static assert(mangledName!(mangledName) == "3std6traits11mangledName"); static assert(mangledName!(removeDummyEnvelope) == "_D3std6traits19removeDummyEnvelopeFAyaZAya"); int x; static assert(mangledName!((int a) { return a+x; })[$ - 9 .. $] == "MFNbNfiZi"); // nothrow safe } /* workaround for @@@BUG2997@@@ "allMembers does not return interface members" */ package template traits_allMembers(Agg) { static if (is(Agg == class) || is(Agg == interface)) alias NoDuplicates!( __traits(allMembers, Agg), traits_allMembers_ifaces!(InterfacesTuple!(Agg)) ) traits_allMembers; else alias TypeTuple!(__traits(allMembers, Agg)) traits_allMembers; } private template traits_allMembers_ifaces(I...) { static if (I.length > 0) alias TypeTuple!( __traits(allMembers, I[0]), traits_allMembers_ifaces!(I[1 .. $]) ) traits_allMembers_ifaces; else alias TypeTuple!() traits_allMembers_ifaces; } unittest { interface I { void test(); } interface J : I { } interface K : J { } alias traits_allMembers!(K) names; static assert(names.length == 1); static assert(names[0] == "test"); } // XXX Select & select should go to another module. (functional or algorithm?) /** Aliases itself to $(D T) if the boolean $(D condition) is $(D true) and to $(D F) otherwise. Example: ---- alias Select!(size_t.sizeof == 4, int, long) Int; ---- */ template Select(bool condition, T, F) { static if (condition) alias T Select; else alias F Select; } unittest { static assert(is(Select!(true, int, long) == int)); static assert(is(Select!(false, int, long) == long)); } /** If $(D cond) is $(D true), returns $(D a) without evaluating $(D b). Otherwise, returns $(D b) without evaluating $(D a). */ A select(bool cond : true, A, B)(A a, lazy B b) { return a; } /// Ditto B select(bool cond : false, A, B)(lazy A a, B b) { return b; } unittest { real pleasecallme() { return 0; } int dontcallme() { assert(0); } auto a = select!true(pleasecallme(), dontcallme()); auto b = select!false(dontcallme(), pleasecallme()); static assert(is(typeof(a) == real)); static assert(is(typeof(b) == real)); }
D
p sp-255761747 4 4 a 1 2 5907 20 a 4 1 7744 13 a 2 3 807 14 a 3 4 7834 16
D
module dmd.astbase; /** * Documentation: https://dlang.org/phobos/dmd_astbase.html * Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/astbase.d */ import dmd.parsetimevisitor; /** The ASTBase family defines a family of AST nodes appropriate for parsing with * no semantic information. It defines all the AST nodes that the parser needs * and also all the conveniance methods and variables. The resulting AST can be * visited with the strict, permissive and transitive visitors. * The ASTBase family is used to instantiate the parser in the parser library. */ struct ASTBase { import dmd.root.file; import dmd.root.filename; import dmd.root.array; import dmd.root.rootobject; import dmd.root.outbuffer; import dmd.root.ctfloat; import dmd.root.rmem; import dmd.root.stringtable; import dmd.tokens; import dmd.identifier; import dmd.globals; import dmd.id; import dmd.errors; import dmd.lexer; import dmd.utils : toDString; import core.stdc.string; import core.stdc.stdarg; alias Dsymbols = Array!(Dsymbol); alias Objects = Array!(RootObject); alias Expressions = Array!(Expression); alias TemplateParameters = Array!(TemplateParameter); alias BaseClasses = Array!(BaseClass*); alias Parameters = Array!(Parameter); alias Statements = Array!(Statement); alias Catches = Array!(Catch); alias Identifiers = Array!(Identifier); alias Initializers = Array!(Initializer); alias Ensures = Array!(Ensure); enum Sizeok : int { none, // size of aggregate is not yet able to compute fwd, // size of aggregate is ready to compute done, // size of aggregate is set correctly } enum Baseok : int { none, // base classes not computed yet start, // in process of resolving base classes done, // all base classes are resolved semanticdone, // all base classes semantic done } enum MODFlags : int { const_ = 1, // type is const immutable_ = 4, // type is immutable shared_ = 2, // type is shared wild = 8, // type is wild wildconst = (MODFlags.wild | MODFlags.const_), // type is wild const mutable = 0x10, // type is mutable (only used in wildcard matching) } alias MOD = ubyte; enum STC : long { undefined_ = 0L, static_ = (1L << 0), extern_ = (1L << 1), const_ = (1L << 2), final_ = (1L << 3), abstract_ = (1L << 4), parameter = (1L << 5), field = (1L << 6), override_ = (1L << 7), auto_ = (1L << 8), synchronized_ = (1L << 9), deprecated_ = (1L << 10), in_ = (1L << 11), // in parameter out_ = (1L << 12), // out parameter lazy_ = (1L << 13), // lazy parameter foreach_ = (1L << 14), // variable for foreach loop //(1L << 15) variadic = (1L << 16), // the 'variadic' parameter in: T foo(T a, U b, V variadic...) ctorinit = (1L << 17), // can only be set inside constructor templateparameter = (1L << 18), // template parameter scope_ = (1L << 19), immutable_ = (1L << 20), ref_ = (1L << 21), init = (1L << 22), // has explicit initializer manifest = (1L << 23), // manifest constant nodtor = (1L << 24), // don't run destructor nothrow_ = (1L << 25), // never throws exceptions pure_ = (1L << 26), // pure function tls = (1L << 27), // thread local alias_ = (1L << 28), // alias parameter shared_ = (1L << 29), // accessible from multiple threads gshared = (1L << 30), // accessible from multiple threads, but not typed as "shared" wild = (1L << 31), // for "wild" type constructor property = (1L << 32), safe = (1L << 33), trusted = (1L << 34), system = (1L << 35), ctfe = (1L << 36), // can be used in CTFE, even if it is static disable = (1L << 37), // for functions that are not callable result = (1L << 38), // for result variables passed to out contracts nodefaultctor = (1L << 39), // must be set inside constructor temp = (1L << 40), // temporary variable rvalue = (1L << 41), // force rvalue for variables nogc = (1L << 42), // @nogc volatile_ = (1L << 43), // destined for volatile in the back end return_ = (1L << 44), // 'return ref' or 'return scope' for function parameters autoref = (1L << 45), // Mark for the already deduced 'auto ref' parameter inference = (1L << 46), // do attribute inference exptemp = (1L << 47), // temporary variable that has lifetime restricted to an expression maybescope = (1L << 48), // parameter might be 'scope' scopeinferred = (1L << 49), // 'scope' has been inferred and should not be part of mangling future = (1L << 50), // introducing new base class function local = (1L << 51), // do not forward (see dmd.dsymbol.ForwardingScopeDsymbol). returninferred = (1L << 52), // 'return' has been inferred and should not be part of mangling safeGroup = STC.safe | STC.trusted | STC.system, TYPECTOR = (STC.const_ | STC.immutable_ | STC.shared_ | STC.wild), FUNCATTR = (STC.ref_ | STC.nothrow_ | STC.nogc | STC.pure_ | STC.property | safeGroup), } extern (C++) __gshared const(StorageClass) STCStorageClass = (STC.auto_ | STC.scope_ | STC.static_ | STC.extern_ | STC.const_ | STC.final_ | STC.abstract_ | STC.synchronized_ | STC.deprecated_ | STC.override_ | STC.lazy_ | STC.alias_ | STC.out_ | STC.in_ | STC.manifest | STC.immutable_ | STC.shared_ | STC.wild | STC.nothrow_ | STC.nogc | STC.pure_ | STC.ref_ | STC.return_ | STC.tls | STC.gshared | STC.property | STC.safeGroup | STC.disable); enum ENUMTY : int { Tarray, // slice array, aka T[] Tsarray, // static array, aka T[dimension] Taarray, // associative array, aka T[type] Tpointer, Treference, Tfunction, Tident, Tclass, Tstruct, Tenum, Tdelegate, Tnone, Tvoid, Tint8, Tuns8, Tint16, Tuns16, Tint32, Tuns32, Tint64, Tuns64, Tfloat32, Tfloat64, Tfloat80, Timaginary32, Timaginary64, Timaginary80, Tcomplex32, Tcomplex64, Tcomplex80, Tbool, Tchar, Twchar, Tdchar, Terror, Tinstance, Ttypeof, Ttuple, Tslice, Treturn, Tnull, Tvector, Tint128, Tuns128, Tmixin, TMAX } alias Tarray = ENUMTY.Tarray; alias Tsarray = ENUMTY.Tsarray; alias Taarray = ENUMTY.Taarray; alias Tpointer = ENUMTY.Tpointer; alias Treference = ENUMTY.Treference; alias Tfunction = ENUMTY.Tfunction; alias Tident = ENUMTY.Tident; alias Tclass = ENUMTY.Tclass; alias Tstruct = ENUMTY.Tstruct; alias Tenum = ENUMTY.Tenum; alias Tdelegate = ENUMTY.Tdelegate; alias Tnone = ENUMTY.Tnone; alias Tvoid = ENUMTY.Tvoid; alias Tint8 = ENUMTY.Tint8; alias Tuns8 = ENUMTY.Tuns8; alias Tint16 = ENUMTY.Tint16; alias Tuns16 = ENUMTY.Tuns16; alias Tint32 = ENUMTY.Tint32; alias Tuns32 = ENUMTY.Tuns32; alias Tint64 = ENUMTY.Tint64; alias Tuns64 = ENUMTY.Tuns64; alias Tfloat32 = ENUMTY.Tfloat32; alias Tfloat64 = ENUMTY.Tfloat64; alias Tfloat80 = ENUMTY.Tfloat80; alias Timaginary32 = ENUMTY.Timaginary32; alias Timaginary64 = ENUMTY.Timaginary64; alias Timaginary80 = ENUMTY.Timaginary80; alias Tcomplex32 = ENUMTY.Tcomplex32; alias Tcomplex64 = ENUMTY.Tcomplex64; alias Tcomplex80 = ENUMTY.Tcomplex80; alias Tbool = ENUMTY.Tbool; alias Tchar = ENUMTY.Tchar; alias Twchar = ENUMTY.Twchar; alias Tdchar = ENUMTY.Tdchar; alias Terror = ENUMTY.Terror; alias Tinstance = ENUMTY.Tinstance; alias Ttypeof = ENUMTY.Ttypeof; alias Ttuple = ENUMTY.Ttuple; alias Tslice = ENUMTY.Tslice; alias Treturn = ENUMTY.Treturn; alias Tnull = ENUMTY.Tnull; alias Tvector = ENUMTY.Tvector; alias Tint128 = ENUMTY.Tint128; alias Tuns128 = ENUMTY.Tuns128; alias Tmixin = ENUMTY.Tmixin; alias TMAX = ENUMTY.TMAX; alias TY = ubyte; enum TFlags { integral = 1, floating = 2, unsigned = 4, real_ = 8, imaginary = 0x10, complex = 0x20, char_ = 0x40, } enum PKG : int { unknown, // not yet determined whether it's a package.d or not module_, // already determined that's an actual package.d package_, // already determined that's an actual package } enum StructPOD : int { no, // struct is not POD yes, // struct is POD fwd, // POD not yet computed } enum TRUST : int { default_ = 0, system = 1, // @system (same as TRUST.default) trusted = 2, // @trusted safe = 3, // @safe } enum PURE : int { impure = 0, // not pure at all fwdref = 1, // it's pure, but not known which level yet weak = 2, // no mutable globals are read or written const_ = 3, // parameters are values or const strong = 4, // parameters are values or immutable } enum AliasThisRec : int { no = 0, // no alias this recursion yes = 1, // alias this has recursive dependency fwdref = 2, // not yet known typeMask = 3, // mask to read no/yes/fwdref tracing = 0x4, // mark in progress of implicitConvTo/deduceWild tracingDT = 0x8, // mark in progress of deduceType } enum VarArg { none = 0, /// fixed number of arguments variadic = 1, /// T t, ...) can be C-style (core.stdc.stdarg) or D-style (core.vararg) typesafe = 2, /// T t ...) typesafe https://dlang.org/spec/function.html#typesafe_variadic_functions /// or https://dlang.org/spec/function.html#typesafe_variadic_functions } alias Visitor = ParseTimeVisitor!ASTBase; extern (C++) abstract class ASTNode : RootObject { abstract void accept(Visitor v); } extern (C++) class Dsymbol : ASTNode { Loc loc; Identifier ident; UnitTestDeclaration ddocUnittest; UserAttributeDeclaration userAttribDecl; Dsymbol parent; const(char)* comment; final extern (D) this() {} final extern (D) this(Identifier ident) { this.ident = ident; } void addComment(const(char)* comment) { if (!this.comment) this.comment = comment; else if (comment && strcmp(cast(char*)comment, cast(char*)this.comment) != 0) this.comment = Lexer.combineComments(this.comment.toDString(), comment.toDString(), true); } override const(char)* toChars() const { return ident ? ident.toChars() : "__anonymous"; } bool oneMember(Dsymbol *ps, Identifier ident) { *ps = this; return true; } extern (D) static bool oneMembers(ref Dsymbols members, Dsymbol* ps, Identifier ident) { Dsymbol s = null; for (size_t i = 0; i < members.dim; i++) { Dsymbol sx = members[i]; bool x = sx.oneMember(ps, ident); if (!x) { assert(*ps is null); return false; } if (*ps) { assert(ident); if (!(*ps).ident || !(*ps).ident.equals(ident)) continue; if (!s) s = *ps; else if (s.isOverloadable() && (*ps).isOverloadable()) { // keep head of overload set FuncDeclaration f1 = s.isFuncDeclaration(); FuncDeclaration f2 = (*ps).isFuncDeclaration(); if (f1 && f2) { for (; f1 != f2; f1 = f1.overnext0) { if (f1.overnext0 is null) { f1.overnext0 = f2; break; } } } } else // more than one symbol { *ps = null; //printf("\tfalse 2\n"); return false; } } } *ps = s; return true; } bool isOverloadable() const { return false; } const(char)* kind() const { return "symbol"; } final void error(const(char)* format, ...) { va_list ap; va_start(ap, format); // last parameter : toPrettyChars verror(loc, format, ap, kind(), ""); va_end(ap); } inout(AttribDeclaration) isAttribDeclaration() inout { return null; } inout(TemplateDeclaration) isTemplateDeclaration() inout { return null; } inout(FuncLiteralDeclaration) isFuncLiteralDeclaration() inout { return null; } inout(FuncDeclaration) isFuncDeclaration() inout { return null; } inout(VarDeclaration) isVarDeclaration() inout { return null; } inout(TemplateInstance) isTemplateInstance() inout { return null; } inout(Declaration) isDeclaration() inout { return null; } inout(ClassDeclaration) isClassDeclaration() inout { return null; } inout(AggregateDeclaration) isAggregateDeclaration() inout { return null; } Dsymbol syntaxCopy(Dsymbol s) { return null; } override final DYNCAST dyncast() const { return DYNCAST.dsymbol; } override void accept(Visitor v) { v.visit(this); } } extern (C++) class AliasThis : Dsymbol { Identifier ident; extern (D) this(const ref Loc loc, Identifier ident) { super(null); this.loc = loc; this.ident = ident; } override void accept(Visitor v) { v.visit(this); } } extern (C++) abstract class Declaration : Dsymbol { StorageClass storage_class; Prot protection; LINK linkage; Type type; final extern (D) this(Identifier id) { super(id); storage_class = STC.undefined_; protection = Prot(Prot.Kind.undefined); linkage = LINK.default_; } override final inout(Declaration) isDeclaration() inout { return this; } override void accept(Visitor v) { v.visit(this); } } extern (C++) class ScopeDsymbol : Dsymbol { Dsymbols* members; final extern (D) this() {} final extern (D) this(Identifier id) { super(id); } override void accept(Visitor v) { v.visit(this); } } extern (C++) class Import : Dsymbol { Identifiers* packages; Identifier id; Identifier aliasId; int isstatic; Prot protection; Identifiers names; Identifiers aliases; extern (D) this(const ref Loc loc, Identifiers* packages, Identifier id, Identifier aliasId, int isstatic) { super(null); this.loc = loc; this.packages = packages; this.id = id; this.aliasId = aliasId; this.isstatic = isstatic; this.protection = Prot(Prot.Kind.private_); if (aliasId) { // import [cstdio] = std.stdio; this.ident = aliasId; } else if (packages && packages.dim) { // import [std].stdio; this.ident = (*packages)[0]; } else { // import [foo]; this.ident = id; } } void addAlias(Identifier name, Identifier _alias) { if (isstatic) error("cannot have an import bind list"); if (!aliasId) this.ident = null; names.push(name); aliases.push(_alias); } override void accept(Visitor v) { v.visit(this); } } extern (C++) abstract class AttribDeclaration : Dsymbol { Dsymbols* decl; final extern (D) this(Dsymbols *decl) { this.decl = decl; } override final inout(AttribDeclaration) isAttribDeclaration() inout { return this; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class StaticAssert : Dsymbol { Expression exp; Expression msg; extern (D) this(const ref Loc loc, Expression exp, Expression msg) { super(Id.empty); this.loc = loc; this.exp = exp; this.msg = msg; } } extern (C++) final class DebugSymbol : Dsymbol { uint level; extern (D) this(const ref Loc loc, Identifier ident) { super(ident); this.loc = loc; } extern (D) this(const ref Loc loc, uint level) { this.level = level; this.loc = loc; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class VersionSymbol : Dsymbol { uint level; extern (D) this(const ref Loc loc, Identifier ident) { super(ident); this.loc = loc; } extern (D) this(const ref Loc loc, uint level) { this.level = level; this.loc = loc; } override void accept(Visitor v) { v.visit(this); } } extern (C++) class VarDeclaration : Declaration { Type type; Initializer _init; StorageClass storage_class; enum AdrOnStackNone = ~0u; uint ctfeAdrOnStack; uint sequenceNumber; __gshared uint nextSequenceNumber; final extern (D) this(const ref Loc loc, Type type, Identifier id, Initializer _init, StorageClass st = STC.undefined_) { super(id); this.type = type; this._init = _init; this.loc = loc; this.storage_class = st; sequenceNumber = ++nextSequenceNumber; ctfeAdrOnStack = AdrOnStackNone; } override final inout(VarDeclaration) isVarDeclaration() inout { return this; } override void accept(Visitor v) { v.visit(this); } } extern (C++) struct Ensure { Identifier id; Statement ensure; } extern (C++) class FuncDeclaration : Declaration { Statement fbody; Statements* frequires; Ensures* fensures; Loc endloc; StorageClass storage_class; Type type; bool inferRetType; ForeachStatement fes; FuncDeclaration overnext0; final extern (D) this(const ref Loc loc, Loc endloc, Identifier id, StorageClass storage_class, Type type) { super(id); this.storage_class = storage_class; this.type = type; if (type) { // Normalize storage_class, because function-type related attributes // are already set in the 'type' in parsing phase. this.storage_class &= ~(STC.TYPECTOR | STC.FUNCATTR); } this.loc = loc; this.endloc = endloc; inferRetType = (type && type.nextOf() is null); } FuncLiteralDeclaration isFuncLiteralDeclaration() { return null; } override bool isOverloadable() const { return true; } override final inout(FuncDeclaration) isFuncDeclaration() inout { return this; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class AliasDeclaration : Declaration { Dsymbol aliassym; extern (D) this(const ref Loc loc, Identifier id, Dsymbol s) { super(id); this.loc = loc; this.aliassym = s; } extern (D) this(const ref Loc loc, Identifier id, Type type) { super(id); this.loc = loc; this.type = type; } override bool isOverloadable() const { //assume overloadable until alias is resolved; // should be modified when semantic analysis is added return true; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TupleDeclaration : Declaration { Objects* objects; extern (D) this(const ref Loc loc, Identifier id, Objects* objects) { super(id); this.loc = loc; this.objects = objects; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class FuncLiteralDeclaration : FuncDeclaration { TOK tok; extern (D) this(const ref Loc loc, Loc endloc, Type type, TOK tok, ForeachStatement fes, Identifier id = null) { super(loc, endloc, null, STC.undefined_, type); this.ident = id ? id : Id.empty; this.tok = tok; this.fes = fes; } override inout(FuncLiteralDeclaration) isFuncLiteralDeclaration() inout { return this; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class PostBlitDeclaration : FuncDeclaration { extern (D) this(const ref Loc loc, Loc endloc, StorageClass stc, Identifier id) { super(loc, endloc, id, stc, null); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class CtorDeclaration : FuncDeclaration { extern (D) this(const ref Loc loc, Loc endloc, StorageClass stc, Type type, bool isCopyCtor = false) { super(loc, endloc, Id.ctor, stc, type); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class DtorDeclaration : FuncDeclaration { extern (D) this(const ref Loc loc, Loc endloc) { super(loc, endloc, Id.dtor, STC.undefined_, null); } extern (D) this(const ref Loc loc, Loc endloc, StorageClass stc, Identifier id) { super(loc, endloc, id, stc, null); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class InvariantDeclaration : FuncDeclaration { extern (D) this(const ref Loc loc, Loc endloc, StorageClass stc, Identifier id, Statement fbody) { super(loc, endloc, id ? id : Identifier.generateId("__invariant"), stc, null); this.fbody = fbody; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class UnitTestDeclaration : FuncDeclaration { char* codedoc; extern (D) this(const ref Loc loc, Loc endloc, StorageClass stc, char* codedoc) { super(loc, endloc, Identifier.generateIdWithLoc("__unittest", loc), stc, null); this.codedoc = codedoc; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class NewDeclaration : FuncDeclaration { Parameters* parameters; VarArg varargs; extern (D) this(const ref Loc loc, Loc endloc, StorageClass stc, Parameters* fparams, VarArg varargs) { super(loc, endloc, Id.classNew, STC.static_ | stc, null); this.parameters = fparams; this.varargs = varargs; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class DeleteDeclaration : FuncDeclaration { Parameters* parameters; extern (D) this(const ref Loc loc, Loc endloc, StorageClass stc, Parameters* fparams) { super(loc, endloc, Id.classDelete, STC.static_ | stc, null); this.parameters = fparams; } override void accept(Visitor v) { v.visit(this); } } extern (C++) class StaticCtorDeclaration : FuncDeclaration { final extern (D) this(const ref Loc loc, Loc endloc, StorageClass stc) { super(loc, endloc, Identifier.generateIdWithLoc("_staticCtor", loc), STC.static_ | stc, null); } final extern (D) this(const ref Loc loc, Loc endloc, string name, StorageClass stc) { super(loc, endloc, Identifier.generateIdWithLoc(name, loc), STC.static_ | stc, null); } override void accept(Visitor v) { v.visit(this); } } extern (C++) class StaticDtorDeclaration : FuncDeclaration { final extern (D) this()(Loc loc, Loc endloc, StorageClass stc) { super(loc, endloc, Identifier.generateIdWithLoc("__staticDtor", loc), STC.static_ | stc, null); } final extern (D) this(const ref Loc loc, Loc endloc, string name, StorageClass stc) { super(loc, endloc, Identifier.generateIdWithLoc(name, loc), STC.static_ | stc, null); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class SharedStaticCtorDeclaration : StaticCtorDeclaration { extern (D) this(const ref Loc loc, Loc endloc, StorageClass stc) { super(loc, endloc, "_sharedStaticCtor", stc); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class SharedStaticDtorDeclaration : StaticDtorDeclaration { extern (D) this(const ref Loc loc, Loc endloc, StorageClass stc) { super(loc, endloc, "_sharedStaticDtor", stc); } override void accept(Visitor v) { v.visit(this); } } extern (C++) class Package : ScopeDsymbol { PKG isPkgMod; uint tag; final extern (D) this(Identifier ident) { super(ident); this.isPkgMod = PKG.unknown; __gshared uint packageTag; this.tag = packageTag++; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class EnumDeclaration : ScopeDsymbol { Type type; Type memtype; Prot protection; extern (D) this(const ref Loc loc, Identifier id, Type memtype) { super(id); this.loc = loc; type = new TypeEnum(this); this.memtype = memtype; protection = Prot(Prot.Kind.undefined); } override void accept(Visitor v) { v.visit(this); } } extern (C++) abstract class AggregateDeclaration : ScopeDsymbol { Prot protection; Sizeok sizeok; Type type; final extern (D) this(const ref Loc loc, Identifier id) { super(id); this.loc = loc; protection = Prot(Prot.Kind.public_); sizeok = Sizeok.none; } override final inout(AggregateDeclaration) isAggregateDeclaration() inout { return this; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TemplateDeclaration : ScopeDsymbol { TemplateParameters* parameters; TemplateParameters* origParameters; Expression constraint; bool literal; bool ismixin; bool isstatic; Prot protection; Dsymbol onemember; extern (D) this(const ref Loc loc, Identifier id, TemplateParameters* parameters, Expression constraint, Dsymbols* decldefs, bool ismixin = false, bool literal = false) { super(id); this.loc = loc; this.parameters = parameters; this.origParameters = parameters; this.members = decldefs; this.literal = literal; this.ismixin = ismixin; this.isstatic = true; this.protection = Prot(Prot.Kind.undefined); if (members && ident) { Dsymbol s; if (Dsymbol.oneMembers(*members, &s, ident) && s) { onemember = s; s.parent = this; } } } override bool isOverloadable() const { return true; } override inout(TemplateDeclaration) isTemplateDeclaration () inout { return this; } override void accept(Visitor v) { v.visit(this); } } extern (C++) class TemplateInstance : ScopeDsymbol { Identifier name; Objects* tiargs; Dsymbol tempdecl; bool semantictiargsdone; bool havetempdecl; TemplateInstance inst; final extern (D) this(const ref Loc loc, Identifier ident, Objects* tiargs) { super(null); this.loc = loc; this.name = ident; this.tiargs = tiargs; } final extern (D) this(const ref Loc loc, TemplateDeclaration td, Objects* tiargs) { super(null); this.loc = loc; this.name = td.ident; this.tempdecl = td; this.semantictiargsdone = true; this.havetempdecl = true; } override final inout(TemplateInstance) isTemplateInstance() inout { return this; } Objects* arraySyntaxCopy(Objects* objs) { Objects* a = null; if (objs) { a = new Objects(); a.setDim(objs.dim); for (size_t i = 0; i < objs.dim; i++) (*a)[i] = objectSyntaxCopy((*objs)[i]); } return a; } RootObject objectSyntaxCopy(RootObject o) { if (!o) return null; if (Type t = isType(o)) return t.syntaxCopy(); if (Expression e = isExpression(o)) return e.syntaxCopy(); return o; } override Dsymbol syntaxCopy(Dsymbol s) { TemplateInstance ti = s ? cast(TemplateInstance)s : new TemplateInstance(loc, name, null); ti.tiargs = arraySyntaxCopy(tiargs); TemplateDeclaration td; if (inst && tempdecl && (td = tempdecl.isTemplateDeclaration()) !is null) td.ScopeDsymbol.syntaxCopy(ti); else ScopeDsymbol.syntaxCopy(ti); return ti; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class Nspace : ScopeDsymbol { /** * Namespace identifier resolved during semantic. */ Expression identExp; extern (D) this(const ref Loc loc, Identifier ident, Expression identExp, Dsymbols* members) { super(ident); this.loc = loc; this.members = members; this.identExp = identExp; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class CompileDeclaration : AttribDeclaration { Expressions* exps; extern (D) this(const ref Loc loc, Expressions* exps) { super(null); this.loc = loc; this.exps = exps; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class UserAttributeDeclaration : AttribDeclaration { Expressions* atts; extern (D) this(Expressions* atts, Dsymbols* decl) { super(decl); this.atts = atts; } extern (D) static Expressions* concat(Expressions* udas1, Expressions* udas2) { Expressions* udas; if (!udas1 || udas1.dim == 0) udas = udas2; else if (!udas2 || udas2.dim == 0) udas = udas1; else { udas = new Expressions(2); (*udas)[0] = new TupleExp(Loc.initial, udas1); (*udas)[1] = new TupleExp(Loc.initial, udas2); } return udas; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class LinkDeclaration : AttribDeclaration { LINK linkage; extern (D) this(LINK p, Dsymbols* decl) { super(decl); linkage = p; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class AnonDeclaration : AttribDeclaration { bool isunion; extern (D) this(const ref Loc loc, bool isunion, Dsymbols* decl) { super(decl); this.loc = loc; this.isunion = isunion; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class AlignDeclaration : AttribDeclaration { Expression ealign; extern (D) this(const ref Loc loc, Expression ealign, Dsymbols* decl) { super(decl); this.loc = loc; this.ealign = ealign; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class CPPMangleDeclaration : AttribDeclaration { CPPMANGLE cppmangle; extern (D) this(CPPMANGLE p, Dsymbols* decl) { super(decl); cppmangle = p; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class CPPNamespaceDeclaration : AttribDeclaration { Expression exp; extern (D) this(Identifier ident, Dsymbols* decl) { super(decl); this.ident = ident; } extern (D) this(Expression exp, Dsymbols* decl) { super(decl); this.exp = exp; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ProtDeclaration : AttribDeclaration { Prot protection; Identifiers* pkg_identifiers; extern (D) this(const ref Loc loc, Prot p, Dsymbols* decl) { super(decl); this.loc = loc; this.protection = p; } extern (D) this(const ref Loc loc, Identifiers* pkg_identifiers, Dsymbols* decl) { super(decl); this.loc = loc; this.protection.kind = Prot.Kind.package_; this.protection.pkg = null; this.pkg_identifiers = pkg_identifiers; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class PragmaDeclaration : AttribDeclaration { Expressions* args; extern (D) this(const ref Loc loc, Identifier ident, Expressions* args, Dsymbols* decl) { super(decl); this.loc = loc; this.ident = ident; this.args = args; } override void accept(Visitor v) { v.visit(this); } } extern (C++) class StorageClassDeclaration : AttribDeclaration { StorageClass stc; final extern (D) this(StorageClass stc, Dsymbols* decl) { super(decl); this.stc = stc; } override void accept(Visitor v) { v.visit(this); } } extern (C++) class ConditionalDeclaration : AttribDeclaration { Condition condition; Dsymbols* elsedecl; final extern (D) this(Condition condition, Dsymbols* decl, Dsymbols* elsedecl) { super(decl); this.condition = condition; this.elsedecl = elsedecl; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class DeprecatedDeclaration : StorageClassDeclaration { Expression msg; extern (D) this(Expression msg, Dsymbols* decl) { super(STC.deprecated_, decl); this.msg = msg; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class StaticIfDeclaration : ConditionalDeclaration { extern (D) this(Condition condition, Dsymbols* decl, Dsymbols* elsedecl) { super(condition, decl, elsedecl); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class StaticForeachDeclaration : AttribDeclaration { StaticForeach sfe; extern (D) this(StaticForeach sfe, Dsymbols* decl) { super(decl); this.sfe = sfe; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class EnumMember : VarDeclaration { Expression origValue; Type origType; @property ref value() { return (cast(ExpInitializer)_init).exp; } extern (D) this(const ref Loc loc, Identifier id, Expression value, Type origType) { super(loc, null, id ? id : Id.empty, new ExpInitializer(loc, value)); this.origValue = value; this.origType = origType; } extern(D) this(const ref Loc loc, Identifier id, Expression value, Type memtype, StorageClass stc, UserAttributeDeclaration uad, DeprecatedDeclaration dd) { this(loc, id, value, memtype); storage_class = stc; userAttribDecl = uad; // just ignore `dd` } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class Module : Package { extern (C++) __gshared AggregateDeclaration moduleinfo; const FileName srcfile; const(char)* arg; extern (D) this(const(char)* filename, Identifier ident, int doDocComment, int doHdrGen) { super(ident); this.arg = filename; srcfile = FileName(FileName.defaultExt(filename.toDString, global.mars_ext)); } override void accept(Visitor v) { v.visit(this); } } extern (C++) class StructDeclaration : AggregateDeclaration { int zeroInit; StructPOD ispod; final extern (D) this(const ref Loc loc, Identifier id, bool inObject) { super(loc, id); zeroInit = 0; ispod = StructPOD.fwd; type = new TypeStruct(this); if (inObject) { if (id == Id.ModuleInfo && !Module.moduleinfo) Module.moduleinfo = this; } } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class UnionDeclaration : StructDeclaration { extern (D) this(const ref Loc loc, Identifier id) { super(loc, id, false); } override void accept(Visitor v) { v.visit(this); } } extern (C++) class ClassDeclaration : AggregateDeclaration { extern (C++) __gshared { // Names found by reading object.d in druntime ClassDeclaration object; ClassDeclaration throwable; ClassDeclaration exception; ClassDeclaration errorException; ClassDeclaration cpp_type_info_ptr; // Object.__cpp_type_info_ptr } BaseClasses* baseclasses; Baseok baseok; final extern (D) this(const ref Loc loc, Identifier id, BaseClasses* baseclasses, Dsymbols* members, bool inObject) { if(!id) id = Identifier.generateId("__anonclass"); assert(id); super(loc, id); __gshared const(char)* msg = "only object.d can define this reserved class name"; if (baseclasses) { // Actually, this is a transfer this.baseclasses = baseclasses; } else this.baseclasses = new BaseClasses(); this.members = members; //printf("ClassDeclaration(%s), dim = %d\n", id.toChars(), this.baseclasses.dim); // For forward references type = new TypeClass(this); if (id) { // Look for special class names if (id == Id.__sizeof || id == Id.__xalignof || id == Id._mangleof) error("illegal class name"); // BUG: What if this is the wrong TypeInfo, i.e. it is nested? if (id.toChars()[0] == 'T') { if (id == Id.TypeInfo) { if (!inObject) error("%s", msg); Type.dtypeinfo = this; } if (id == Id.TypeInfo_Class) { if (!inObject) error("%s", msg); Type.typeinfoclass = this; } if (id == Id.TypeInfo_Interface) { if (!inObject) error("%s", msg); Type.typeinfointerface = this; } if (id == Id.TypeInfo_Struct) { if (!inObject) error("%s", msg); Type.typeinfostruct = this; } if (id == Id.TypeInfo_Pointer) { if (!inObject) error("%s", msg); Type.typeinfopointer = this; } if (id == Id.TypeInfo_Array) { if (!inObject) error("%s", msg); Type.typeinfoarray = this; } if (id == Id.TypeInfo_StaticArray) { //if (!inObject) // Type.typeinfostaticarray.error("%s", msg); Type.typeinfostaticarray = this; } if (id == Id.TypeInfo_AssociativeArray) { if (!inObject) error("%s", msg); Type.typeinfoassociativearray = this; } if (id == Id.TypeInfo_Enum) { if (!inObject) error("%s", msg); Type.typeinfoenum = this; } if (id == Id.TypeInfo_Function) { if (!inObject) error("%s", msg); Type.typeinfofunction = this; } if (id == Id.TypeInfo_Delegate) { if (!inObject) error("%s", msg); Type.typeinfodelegate = this; } if (id == Id.TypeInfo_Tuple) { if (!inObject) error("%s", msg); Type.typeinfotypelist = this; } if (id == Id.TypeInfo_Const) { if (!inObject) error("%s", msg); Type.typeinfoconst = this; } if (id == Id.TypeInfo_Invariant) { if (!inObject) error("%s", msg); Type.typeinfoinvariant = this; } if (id == Id.TypeInfo_Shared) { if (!inObject) error("%s", msg); Type.typeinfoshared = this; } if (id == Id.TypeInfo_Wild) { if (!inObject) error("%s", msg); Type.typeinfowild = this; } if (id == Id.TypeInfo_Vector) { if (!inObject) error("%s", msg); Type.typeinfovector = this; } } if (id == Id.Object) { if (!inObject) error("%s", msg); object = this; } if (id == Id.Throwable) { if (!inObject) error("%s", msg); throwable = this; } if (id == Id.Exception) { if (!inObject) error("%s", msg); exception = this; } if (id == Id.Error) { if (!inObject) error("%s", msg); errorException = this; } if (id == Id.cpp_type_info_ptr) { if (!inObject) error("%s", msg); cpp_type_info_ptr = this; } } baseok = Baseok.none; } override final inout(ClassDeclaration) isClassDeclaration() inout { return this; } override void accept(Visitor v) { v.visit(this); } } extern (C++) class InterfaceDeclaration : ClassDeclaration { final extern (D) this(const ref Loc loc, Identifier id, BaseClasses* baseclasses) { super(loc, id, baseclasses, null, false); } override void accept(Visitor v) { v.visit(this); } } extern (C++) class TemplateMixin : TemplateInstance { TypeQualified tqual; extern (D) this(const ref Loc loc, Identifier ident, TypeQualified tqual, Objects *tiargs) { super(loc, tqual.idents.dim ? cast(Identifier)tqual.idents[tqual.idents.dim - 1] : (cast(TypeIdentifier)tqual).ident, tiargs ? tiargs : new Objects()); this.ident = ident; this.tqual = tqual; } override void accept(Visitor v) { v.visit(this); } } extern (C++) struct ParameterList { Parameters* parameters; VarArg varargs = VarArg.none; } extern (C++) final class Parameter : ASTNode { StorageClass storageClass; Type type; Identifier ident; Expression defaultArg; UserAttributeDeclaration userAttribDecl; // user defined attributes extern (D) alias ForeachDg = int delegate(size_t idx, Parameter param); final extern (D) this(StorageClass storageClass, Type type, Identifier ident, Expression defaultArg, UserAttributeDeclaration userAttribDecl) { this.storageClass = storageClass; this.type = type; this.ident = ident; this.defaultArg = defaultArg; this.userAttribDecl = userAttribDecl; } static size_t dim(Parameters* parameters) { size_t nargs = 0; int dimDg(size_t n, Parameter p) { ++nargs; return 0; } _foreach(parameters, &dimDg); return nargs; } static Parameter getNth(Parameters* parameters, size_t nth, size_t* pn = null) { Parameter param; int getNthParamDg(size_t n, Parameter p) { if (n == nth) { param = p; return 1; } return 0; } int res = _foreach(parameters, &getNthParamDg); return res ? param : null; } extern (D) static int _foreach(Parameters* parameters, scope ForeachDg dg, size_t* pn = null) { assert(dg); if (!parameters) return 0; size_t n = pn ? *pn : 0; // take over index int result = 0; foreach (i; 0 .. parameters.dim) { Parameter p = (*parameters)[i]; Type t = p.type.toBasetype(); if (t.ty == Ttuple) { TypeTuple tu = cast(TypeTuple)t; result = _foreach(tu.arguments, dg, &n); } else result = dg(n++, p); if (result) break; } if (pn) *pn = n; // update index return result; } Parameter syntaxCopy() { return new Parameter(storageClass, type ? type.syntaxCopy() : null, ident, defaultArg ? defaultArg.syntaxCopy() : null, userAttribDecl ? cast(UserAttributeDeclaration) userAttribDecl.syntaxCopy(null) : null); } override void accept(Visitor v) { v.visit(this); } static Parameters* arraySyntaxCopy(Parameters* parameters) { Parameters* params = null; if (parameters) { params = new Parameters(); params.setDim(parameters.dim); for (size_t i = 0; i < params.dim; i++) (*params)[i] = (*parameters)[i].syntaxCopy(); } return params; } } enum STMT : ubyte { Error, Peel, Exp, DtorExp, Compile, Compound, CompoundDeclaration, CompoundAsm, UnrolledLoop, Scope, Forwarding, While, Do, For, Foreach, ForeachRange, If, Conditional, StaticForeach, Pragma, StaticAssert, Switch, Case, CaseRange, Default, GotoDefault, GotoCase, SwitchError, Return, Break, Continue, Synchronized, With, TryCatch, TryFinally, ScopeGuard, Throw, Debug, Goto, Label, Asm, InlineAsm, GccAsm, Import, } extern (C++) abstract class Statement : ASTNode { Loc loc; STMT stmt; final extern (D) this(const ref Loc loc, STMT stmt) { this.loc = loc; this.stmt = stmt; } nothrow pure @nogc inout(ExpStatement) isExpStatement() inout { return stmt == STMT.Exp ? cast(typeof(return))this : null; } nothrow pure @nogc inout(CompoundStatement) isCompoundStatement() inout { return stmt == STMT.Compound ? cast(typeof(return))this : null; } nothrow pure @nogc inout(ReturnStatement) isReturnStatement() inout { return stmt == STMT.Return ? cast(typeof(return))this : null; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ImportStatement : Statement { Dsymbols* imports; extern (D) this(const ref Loc loc, Dsymbols* imports) { super(loc, STMT.Import); this.imports = imports; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ScopeStatement : Statement { Statement statement; Loc endloc; extern (D) this(const ref Loc loc, Statement s, Loc endloc) { super(loc, STMT.Scope); this.statement = s; this.endloc = endloc; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ReturnStatement : Statement { Expression exp; extern (D) this(const ref Loc loc, Expression exp) { super(loc, STMT.Return); this.exp = exp; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class LabelStatement : Statement { Identifier ident; Statement statement; final extern (D) this(const ref Loc loc, Identifier ident, Statement statement) { super(loc, STMT.Label); this.ident = ident; this.statement = statement; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class StaticAssertStatement : Statement { StaticAssert sa; final extern (D) this(StaticAssert sa) { super(sa.loc, STMT.StaticAssert); this.sa = sa; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class CompileStatement : Statement { Expressions* exps; final extern (D) this(const ref Loc loc, Expressions* exps) { super(loc, STMT.Compile); this.exps = exps; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class WhileStatement : Statement { Expression condition; Statement _body; Loc endloc; extern (D) this(const ref Loc loc, Expression c, Statement b, Loc endloc) { super(loc, STMT.While); condition = c; _body = b; this.endloc = endloc; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ForStatement : Statement { Statement _init; Expression condition; Expression increment; Statement _body; Loc endloc; extern (D) this(const ref Loc loc, Statement _init, Expression condition, Expression increment, Statement _body, Loc endloc) { super(loc, STMT.For); this._init = _init; this.condition = condition; this.increment = increment; this._body = _body; this.endloc = endloc; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class DoStatement : Statement { Statement _body; Expression condition; Loc endloc; extern (D) this(const ref Loc loc, Statement b, Expression c, Loc endloc) { super(loc, STMT.Do); _body = b; condition = c; this.endloc = endloc; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ForeachRangeStatement : Statement { TOK op; // TOK.foreach_ or TOK.foreach_reverse_ Parameter prm; // loop index variable Expression lwr; Expression upr; Statement _body; Loc endloc; // location of closing curly bracket extern (D) this(const ref Loc loc, TOK op, Parameter prm, Expression lwr, Expression upr, Statement _body, Loc endloc) { super(loc, STMT.ForeachRange); this.op = op; this.prm = prm; this.lwr = lwr; this.upr = upr; this._body = _body; this.endloc = endloc; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ForeachStatement : Statement { TOK op; // TOK.foreach_ or TOK.foreach_reverse_ Parameters* parameters; // array of Parameter*'s Expression aggr; Statement _body; Loc endloc; // location of closing curly bracket extern (D) this(const ref Loc loc, TOK op, Parameters* parameters, Expression aggr, Statement _body, Loc endloc) { super(loc, STMT.Foreach); this.op = op; this.parameters = parameters; this.aggr = aggr; this._body = _body; this.endloc = endloc; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class IfStatement : Statement { Parameter prm; Expression condition; Statement ifbody; Statement elsebody; VarDeclaration match; // for MatchExpression results Loc endloc; // location of closing curly bracket extern (D) this(const ref Loc loc, Parameter prm, Expression condition, Statement ifbody, Statement elsebody, Loc endloc) { super(loc, STMT.If); this.prm = prm; this.condition = condition; this.ifbody = ifbody; this.elsebody = elsebody; this.endloc = endloc; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ScopeGuardStatement : Statement { TOK tok; Statement statement; extern (D) this(const ref Loc loc, TOK tok, Statement statement) { super(loc, STMT.ScopeGuard); this.tok = tok; this.statement = statement; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ConditionalStatement : Statement { Condition condition; Statement ifbody; Statement elsebody; extern (D) this(const ref Loc loc, Condition condition, Statement ifbody, Statement elsebody) { super(loc, STMT.Conditional); this.condition = condition; this.ifbody = ifbody; this.elsebody = elsebody; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class StaticForeachStatement : Statement { StaticForeach sfe; extern (D) this(const ref Loc loc, StaticForeach sfe) { super(loc, STMT.StaticForeach); this.sfe = sfe; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class PragmaStatement : Statement { Identifier ident; Expressions* args; // array of Expression's Statement _body; extern (D) this(const ref Loc loc, Identifier ident, Expressions* args, Statement _body) { super(loc, STMT.Pragma); this.ident = ident; this.args = args; this._body = _body; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class SwitchStatement : Statement { Expression condition; Statement _body; bool isFinal; extern (D) this(const ref Loc loc, Expression c, Statement b, bool isFinal) { super(loc, STMT.Switch); this.condition = c; this._body = b; this.isFinal = isFinal; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class CaseRangeStatement : Statement { Expression first; Expression last; Statement statement; extern (D) this(const ref Loc loc, Expression first, Expression last, Statement s) { super(loc, STMT.CaseRange); this.first = first; this.last = last; this.statement = s; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class CaseStatement : Statement { Expression exp; Statement statement; extern (D) this(const ref Loc loc, Expression exp, Statement s) { super(loc, STMT.Case); this.exp = exp; this.statement = s; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class DefaultStatement : Statement { Statement statement; extern (D) this(const ref Loc loc, Statement s) { super(loc, STMT.Default); this.statement = s; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class BreakStatement : Statement { Identifier ident; extern (D) this(const ref Loc loc, Identifier ident) { super(loc, STMT.Break); this.ident = ident; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ContinueStatement : Statement { Identifier ident; extern (D) this(const ref Loc loc, Identifier ident) { super(loc, STMT.Continue); this.ident = ident; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class GotoDefaultStatement : Statement { extern (D) this(const ref Loc loc) { super(loc, STMT.GotoDefault); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class GotoCaseStatement : Statement { Expression exp; extern (D) this(const ref Loc loc, Expression exp) { super(loc, STMT.GotoCase); this.exp = exp; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class GotoStatement : Statement { Identifier ident; extern (D) this(const ref Loc loc, Identifier ident) { super(loc, STMT.Goto); this.ident = ident; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class SynchronizedStatement : Statement { Expression exp; Statement _body; extern (D) this(const ref Loc loc, Expression exp, Statement _body) { super(loc, STMT.Synchronized); this.exp = exp; this._body = _body; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class WithStatement : Statement { Expression exp; Statement _body; Loc endloc; extern (D) this(const ref Loc loc, Expression exp, Statement _body, Loc endloc) { super(loc, STMT.With); this.exp = exp; this._body = _body; this.endloc = endloc; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TryCatchStatement : Statement { Statement _body; Catches* catches; extern (D) this(const ref Loc loc, Statement _body, Catches* catches) { super(loc, STMT.TryCatch); this._body = _body; this.catches = catches; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TryFinallyStatement : Statement { Statement _body; Statement finalbody; extern (D) this(const ref Loc loc, Statement _body, Statement finalbody) { super(loc, STMT.TryFinally); this._body = _body; this.finalbody = finalbody; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ThrowStatement : Statement { Expression exp; extern (D) this(const ref Loc loc, Expression exp) { super(loc, STMT.Throw); this.exp = exp; } override void accept(Visitor v) { v.visit(this); } } extern (C++) class AsmStatement : Statement { Token* tokens; extern (D) this(const ref Loc loc, Token* tokens) { super(loc, STMT.Asm); this.tokens = tokens; } extern (D) this(const ref Loc loc, Token* tokens, STMT stmt) { super(loc, stmt); this.tokens = tokens; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class InlineAsmStatement : AsmStatement { extern (D) this(const ref Loc loc, Token* tokens) { super(loc, tokens, STMT.InlineAsm); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class GccAsmStatement : AsmStatement { extern (D) this(const ref Loc loc, Token* tokens) { super(loc, tokens, STMT.GccAsm); } override void accept(Visitor v) { v.visit(this); } } extern (C++) class ExpStatement : Statement { Expression exp; final extern (D) this(const ref Loc loc, Expression exp) { super(loc, STMT.Exp); this.exp = exp; } final extern (D) this(const ref Loc loc, Dsymbol declaration) { super(loc, STMT.Exp); this.exp = new DeclarationExp(loc, declaration); } override void accept(Visitor v) { v.visit(this); } } extern (C++) class CompoundStatement : Statement { Statements* statements; final extern (D) this(const ref Loc loc, Statements* statements) { super(loc, STMT.Compound); this.statements = statements; } final extern (D) this(const ref Loc loc, Statements* statements, STMT stmt) { super(loc, stmt); this.statements = statements; } final extern (D) this(const ref Loc loc, Statement[] sts...) { super(loc, STMT.Compound); statements = new Statements(); statements.reserve(sts.length); foreach (s; sts) statements.push(s); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class CompoundDeclarationStatement : CompoundStatement { final extern (D) this(const ref Loc loc, Statements* statements) { super(loc, statements, STMT.CompoundDeclaration); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class CompoundAsmStatement : CompoundStatement { StorageClass stc; final extern (D) this(const ref Loc loc, Statements* s, StorageClass stc) { super(loc, s, STMT.CompoundAsm); this.stc = stc; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class Catch : RootObject { Loc loc; Type type; Identifier ident; Statement handler; extern (D) this(const ref Loc loc, Type t, Identifier id, Statement handler) { this.loc = loc; this.type = t; this.ident = id; this.handler = handler; } } extern (C++) abstract class Type : ASTNode { TY ty; MOD mod; char* deco; extern (C++) __gshared Type tvoid; extern (C++) __gshared Type tint8; extern (C++) __gshared Type tuns8; extern (C++) __gshared Type tint16; extern (C++) __gshared Type tuns16; extern (C++) __gshared Type tint32; extern (C++) __gshared Type tuns32; extern (C++) __gshared Type tint64; extern (C++) __gshared Type tuns64; extern (C++) __gshared Type tint128; extern (C++) __gshared Type tuns128; extern (C++) __gshared Type tfloat32; extern (C++) __gshared Type tfloat64; extern (C++) __gshared Type tfloat80; extern (C++) __gshared Type timaginary32; extern (C++) __gshared Type timaginary64; extern (C++) __gshared Type timaginary80; extern (C++) __gshared Type tcomplex32; extern (C++) __gshared Type tcomplex64; extern (C++) __gshared Type tcomplex80; extern (C++) __gshared Type tbool; extern (C++) __gshared Type tchar; extern (C++) __gshared Type twchar; extern (C++) __gshared Type tdchar; extern (C++) __gshared Type[TMAX] basic; extern (C++) __gshared Type tshiftcnt; extern (C++) __gshared Type tvoidptr; // void* extern (C++) __gshared Type tstring; // immutable(char)[] extern (C++) __gshared Type twstring; // immutable(wchar)[] extern (C++) __gshared Type tdstring; // immutable(dchar)[] extern (C++) __gshared Type tvalist; // va_list alias extern (C++) __gshared Type terror; // for error recovery extern (C++) __gshared Type tnull; // for null type extern (C++) __gshared Type tsize_t; // matches size_t alias extern (C++) __gshared Type tptrdiff_t; // matches ptrdiff_t alias extern (C++) __gshared Type thash_t; // matches hash_t alias extern (C++) __gshared ClassDeclaration dtypeinfo; extern (C++) __gshared ClassDeclaration typeinfoclass; extern (C++) __gshared ClassDeclaration typeinfointerface; extern (C++) __gshared ClassDeclaration typeinfostruct; extern (C++) __gshared ClassDeclaration typeinfopointer; extern (C++) __gshared ClassDeclaration typeinfoarray; extern (C++) __gshared ClassDeclaration typeinfostaticarray; extern (C++) __gshared ClassDeclaration typeinfoassociativearray; extern (C++) __gshared ClassDeclaration typeinfovector; extern (C++) __gshared ClassDeclaration typeinfoenum; extern (C++) __gshared ClassDeclaration typeinfofunction; extern (C++) __gshared ClassDeclaration typeinfodelegate; extern (C++) __gshared ClassDeclaration typeinfotypelist; extern (C++) __gshared ClassDeclaration typeinfoconst; extern (C++) __gshared ClassDeclaration typeinfoinvariant; extern (C++) __gshared ClassDeclaration typeinfoshared; extern (C++) __gshared ClassDeclaration typeinfowild; extern (C++) __gshared StringTable stringtable; extern (C++) __gshared ubyte[TMAX] sizeTy = () { ubyte[TMAX] sizeTy = __traits(classInstanceSize, TypeBasic); sizeTy[Tsarray] = __traits(classInstanceSize, TypeSArray); sizeTy[Tarray] = __traits(classInstanceSize, TypeDArray); sizeTy[Taarray] = __traits(classInstanceSize, TypeAArray); sizeTy[Tpointer] = __traits(classInstanceSize, TypePointer); sizeTy[Treference] = __traits(classInstanceSize, TypeReference); sizeTy[Tfunction] = __traits(classInstanceSize, TypeFunction); sizeTy[Tdelegate] = __traits(classInstanceSize, TypeDelegate); sizeTy[Tident] = __traits(classInstanceSize, TypeIdentifier); sizeTy[Tinstance] = __traits(classInstanceSize, TypeInstance); sizeTy[Ttypeof] = __traits(classInstanceSize, TypeTypeof); sizeTy[Tenum] = __traits(classInstanceSize, TypeEnum); sizeTy[Tstruct] = __traits(classInstanceSize, TypeStruct); sizeTy[Tclass] = __traits(classInstanceSize, TypeClass); sizeTy[Ttuple] = __traits(classInstanceSize, TypeTuple); sizeTy[Tslice] = __traits(classInstanceSize, TypeSlice); sizeTy[Treturn] = __traits(classInstanceSize, TypeReturn); sizeTy[Terror] = __traits(classInstanceSize, TypeError); sizeTy[Tnull] = __traits(classInstanceSize, TypeNull); sizeTy[Tvector] = __traits(classInstanceSize, TypeVector); sizeTy[Tmixin] = __traits(classInstanceSize, TypeMixin); return sizeTy; }(); Type cto; Type ito; Type sto; Type scto; Type wto; Type wcto; Type swto; Type swcto; Type pto; Type rto; Type arrayof; // These members are probably used in semnatic analysis //TypeInfoDeclaration vtinfo; //type* ctype; final extern (D) this(TY ty) { this.ty = ty; } override const(char)* toChars() const { return "type"; } static void _init() { stringtable._init(14000); // Set basic types __gshared TY* basetab = [ Tvoid, Tint8, Tuns8, Tint16, Tuns16, Tint32, Tuns32, Tint64, Tuns64, Tint128, Tuns128, Tfloat32, Tfloat64, Tfloat80, Timaginary32, Timaginary64, Timaginary80, Tcomplex32, Tcomplex64, Tcomplex80, Tbool, Tchar, Twchar, Tdchar, Terror ]; for (size_t i = 0; basetab[i] != Terror; i++) { Type t = new TypeBasic(basetab[i]); t = t.merge(); basic[basetab[i]] = t; } basic[Terror] = new TypeError(); tvoid = basic[Tvoid]; tint8 = basic[Tint8]; tuns8 = basic[Tuns8]; tint16 = basic[Tint16]; tuns16 = basic[Tuns16]; tint32 = basic[Tint32]; tuns32 = basic[Tuns32]; tint64 = basic[Tint64]; tuns64 = basic[Tuns64]; tint128 = basic[Tint128]; tuns128 = basic[Tuns128]; tfloat32 = basic[Tfloat32]; tfloat64 = basic[Tfloat64]; tfloat80 = basic[Tfloat80]; timaginary32 = basic[Timaginary32]; timaginary64 = basic[Timaginary64]; timaginary80 = basic[Timaginary80]; tcomplex32 = basic[Tcomplex32]; tcomplex64 = basic[Tcomplex64]; tcomplex80 = basic[Tcomplex80]; tbool = basic[Tbool]; tchar = basic[Tchar]; twchar = basic[Twchar]; tdchar = basic[Tdchar]; tshiftcnt = tint32; terror = basic[Terror]; tnull = basic[Tnull]; tnull = new TypeNull(); tnull.deco = tnull.merge().deco; tvoidptr = tvoid.pointerTo(); tstring = tchar.immutableOf().arrayOf(); twstring = twchar.immutableOf().arrayOf(); tdstring = tdchar.immutableOf().arrayOf(); tvalist = Target.va_listType(); const isLP64 = global.params.isLP64; tsize_t = basic[isLP64 ? Tuns64 : Tuns32]; tptrdiff_t = basic[isLP64 ? Tint64 : Tint32]; thash_t = tsize_t; } final Type pointerTo() { if (ty == Terror) return this; if (!pto) { Type t = new TypePointer(this); if (ty == Tfunction) { t.deco = t.merge().deco; pto = t; } else pto = t.merge(); } return pto; } final Type arrayOf() { if (ty == Terror) return this; if (!arrayof) { Type t = new TypeDArray(this); arrayof = t.merge(); } return arrayof; } final bool isImmutable() const { return (mod & MODFlags.immutable_) != 0; } final Type nullAttributes() { uint sz = sizeTy[ty]; Type t = cast(Type)mem.xmalloc(sz); memcpy(cast(void*)t, cast(void*)this, sz); // t.mod = NULL; // leave mod unchanged t.deco = null; t.arrayof = null; t.pto = null; t.rto = null; t.cto = null; t.ito = null; t.sto = null; t.scto = null; t.wto = null; t.wcto = null; t.swto = null; t.swcto = null; //t.vtinfo = null; these aren't used in parsing //t.ctype = null; if (t.ty == Tstruct) (cast(TypeStruct)t).att = AliasThisRec.fwdref; if (t.ty == Tclass) (cast(TypeClass)t).att = AliasThisRec.fwdref; return t; } Type makeConst() { if (cto) return cto; Type t = this.nullAttributes(); t.mod = MODFlags.const_; return t; } Type makeWildConst() { if (wcto) return wcto; Type t = this.nullAttributes(); t.mod = MODFlags.wildconst; return t; } Type makeShared() { if (sto) return sto; Type t = this.nullAttributes(); t.mod = MODFlags.shared_; return t; } Type makeSharedConst() { if (scto) return scto; Type t = this.nullAttributes(); t.mod = MODFlags.shared_ | MODFlags.const_; return t; } Type makeImmutable() { if (ito) return ito; Type t = this.nullAttributes(); t.mod = MODFlags.immutable_; return t; } Type makeWild() { if (wto) return wto; Type t = this.nullAttributes(); t.mod = MODFlags.wild; return t; } Type makeSharedWildConst() { if (swcto) return swcto; Type t = this.nullAttributes(); t.mod = MODFlags.shared_ | MODFlags.wildconst; return t; } Type makeSharedWild() { if (swto) return swto; Type t = this.nullAttributes(); t.mod = MODFlags.shared_ | MODFlags.wild; return t; } // Truncated final Type merge() { if (ty == Terror) return this; if (ty == Ttypeof) return this; if (ty == Tident) return this; if (ty == Tinstance) return this; if (ty == Taarray && !(cast(TypeAArray)this).index.merge().deco) return this; if (ty != Tenum && nextOf() && !nextOf().deco) return this; // if (!deco) - code missing Type t = this; assert(t); return t; } final Type addSTC(StorageClass stc) { Type t = this; if (t.isImmutable()) { } else if (stc & STC.immutable_) { t = t.makeImmutable(); } else { if ((stc & STC.shared_) && !t.isShared()) { if (t.isWild()) { if (t.isConst()) t = t.makeSharedWildConst(); else t = t.makeSharedWild(); } else { if (t.isConst()) t = t.makeSharedConst(); else t = t.makeShared(); } } if ((stc & STC.const_) && !t.isConst()) { if (t.isShared()) { if (t.isWild()) t = t.makeSharedWildConst(); else t = t.makeSharedConst(); } else { if (t.isWild()) t = t.makeWildConst(); else t = t.makeConst(); } } if ((stc & STC.wild) && !t.isWild()) { if (t.isShared()) { if (t.isConst()) t = t.makeSharedWildConst(); else t = t.makeSharedWild(); } else { if (t.isConst()) t = t.makeWildConst(); else t = t.makeWild(); } } } return t; } Expression toExpression() { return null; } Type syntaxCopy() { return null; } final Type sharedWildConstOf() { if (mod == (MODFlags.shared_ | MODFlags.wildconst)) return this; if (swcto) { assert(swcto.mod == (MODFlags.shared_ | MODFlags.wildconst)); return swcto; } Type t = makeSharedWildConst(); t = t.merge(); t.fixTo(this); return t; } final Type sharedConstOf() { if (mod == (MODFlags.shared_ | MODFlags.const_)) return this; if (scto) { assert(scto.mod == (MODFlags.shared_ | MODFlags.const_)); return scto; } Type t = makeSharedConst(); t = t.merge(); t.fixTo(this); return t; } final Type wildConstOf() { if (mod == MODFlags.wildconst) return this; if (wcto) { assert(wcto.mod == MODFlags.wildconst); return wcto; } Type t = makeWildConst(); t = t.merge(); t.fixTo(this); return t; } final Type constOf() { if (mod == MODFlags.const_) return this; if (cto) { assert(cto.mod == MODFlags.const_); return cto; } Type t = makeConst(); t = t.merge(); t.fixTo(this); return t; } final Type sharedWildOf() { if (mod == (MODFlags.shared_ | MODFlags.wild)) return this; if (swto) { assert(swto.mod == (MODFlags.shared_ | MODFlags.wild)); return swto; } Type t = makeSharedWild(); t = t.merge(); t.fixTo(this); return t; } final Type wildOf() { if (mod == MODFlags.wild) return this; if (wto) { assert(wto.mod == MODFlags.wild); return wto; } Type t = makeWild(); t = t.merge(); t.fixTo(this); return t; } final Type sharedOf() { if (mod == MODFlags.shared_) return this; if (sto) { assert(sto.mod == MODFlags.shared_); return sto; } Type t = makeShared(); t = t.merge(); t.fixTo(this); return t; } final Type immutableOf() { if (isImmutable()) return this; if (ito) { assert(ito.isImmutable()); return ito; } Type t = makeImmutable(); t = t.merge(); t.fixTo(this); return t; } final void fixTo(Type t) { Type mto = null; Type tn = nextOf(); if (!tn || ty != Tsarray && tn.mod == t.nextOf().mod) { switch (t.mod) { case 0: mto = t; break; case MODFlags.const_: cto = t; break; case MODFlags.wild: wto = t; break; case MODFlags.wildconst: wcto = t; break; case MODFlags.shared_: sto = t; break; case MODFlags.shared_ | MODFlags.const_: scto = t; break; case MODFlags.shared_ | MODFlags.wild: swto = t; break; case MODFlags.shared_ | MODFlags.wildconst: swcto = t; break; case MODFlags.immutable_: ito = t; break; default: break; } } assert(mod != t.mod); auto X(T, U)(T m, U n) { return ((m << 4) | n); } switch (mod) { case 0: break; case MODFlags.const_: cto = mto; t.cto = this; break; case MODFlags.wild: wto = mto; t.wto = this; break; case MODFlags.wildconst: wcto = mto; t.wcto = this; break; case MODFlags.shared_: sto = mto; t.sto = this; break; case MODFlags.shared_ | MODFlags.const_: scto = mto; t.scto = this; break; case MODFlags.shared_ | MODFlags.wild: swto = mto; t.swto = this; break; case MODFlags.shared_ | MODFlags.wildconst: swcto = mto; t.swcto = this; break; case MODFlags.immutable_: t.ito = this; if (t.cto) t.cto.ito = this; if (t.sto) t.sto.ito = this; if (t.scto) t.scto.ito = this; if (t.wto) t.wto.ito = this; if (t.wcto) t.wcto.ito = this; if (t.swto) t.swto.ito = this; if (t.swcto) t.swcto.ito = this; break; default: assert(0); } } final Type addMod(MOD mod) { Type t = this; if (!t.isImmutable()) { switch (mod) { case 0: break; case MODFlags.const_: if (isShared()) { if (isWild()) t = sharedWildConstOf(); else t = sharedConstOf(); } else { if (isWild()) t = wildConstOf(); else t = constOf(); } break; case MODFlags.wild: if (isShared()) { if (isConst()) t = sharedWildConstOf(); else t = sharedWildOf(); } else { if (isConst()) t = wildConstOf(); else t = wildOf(); } break; case MODFlags.wildconst: if (isShared()) t = sharedWildConstOf(); else t = wildConstOf(); break; case MODFlags.shared_: if (isWild()) { if (isConst()) t = sharedWildConstOf(); else t = sharedWildOf(); } else { if (isConst()) t = sharedConstOf(); else t = sharedOf(); } break; case MODFlags.shared_ | MODFlags.const_: if (isWild()) t = sharedWildConstOf(); else t = sharedConstOf(); break; case MODFlags.shared_ | MODFlags.wild: if (isConst()) t = sharedWildConstOf(); else t = sharedWildOf(); break; case MODFlags.shared_ | MODFlags.wildconst: t = sharedWildConstOf(); break; case MODFlags.immutable_: t = immutableOf(); break; default: assert(0); } } return t; } // TypeEnum overrides this method Type nextOf() { return null; } // TypeBasic, TypeVector, TypePointer, TypeEnum override this method bool isscalar() { return false; } final bool isConst() const { return (mod & MODFlags.const_) != 0; } final bool isWild() const { return (mod & MODFlags.wild) != 0; } final bool isShared() const { return (mod & MODFlags.shared_) != 0; } Type toBasetype() { return this; } // TypeIdentifier, TypeInstance, TypeTypeOf, TypeReturn, TypeStruct, TypeEnum, TypeClass override this method Dsymbol toDsymbol(Scope* sc) { return null; } override void accept(Visitor v) { v.visit(this); } } // missing functionality in constructor, but that's ok // since the class is needed only for its size; need to add all method definitions extern (C++) final class TypeBasic : Type { const(char)* dstring; uint flags; extern (D) this(TY ty) { super(ty); const(char)* d; uint flags = 0; switch (ty) { case Tvoid: d = Token.toChars(TOK.void_); break; case Tint8: d = Token.toChars(TOK.int8); flags |= TFlags.integral; break; case Tuns8: d = Token.toChars(TOK.uns8); flags |= TFlags.integral | TFlags.unsigned; break; case Tint16: d = Token.toChars(TOK.int16); flags |= TFlags.integral; break; case Tuns16: d = Token.toChars(TOK.uns16); flags |= TFlags.integral | TFlags.unsigned; break; case Tint32: d = Token.toChars(TOK.int32); flags |= TFlags.integral; break; case Tuns32: d = Token.toChars(TOK.uns32); flags |= TFlags.integral | TFlags.unsigned; break; case Tfloat32: d = Token.toChars(TOK.float32); flags |= TFlags.floating | TFlags.real_; break; case Tint64: d = Token.toChars(TOK.int64); flags |= TFlags.integral; break; case Tuns64: d = Token.toChars(TOK.uns64); flags |= TFlags.integral | TFlags.unsigned; break; case Tint128: d = Token.toChars(TOK.int128); flags |= TFlags.integral; break; case Tuns128: d = Token.toChars(TOK.uns128); flags |= TFlags.integral | TFlags.unsigned; break; case Tfloat64: d = Token.toChars(TOK.float64); flags |= TFlags.floating | TFlags.real_; break; case Tfloat80: d = Token.toChars(TOK.float80); flags |= TFlags.floating | TFlags.real_; break; case Timaginary32: d = Token.toChars(TOK.imaginary32); flags |= TFlags.floating | TFlags.imaginary; break; case Timaginary64: d = Token.toChars(TOK.imaginary64); flags |= TFlags.floating | TFlags.imaginary; break; case Timaginary80: d = Token.toChars(TOK.imaginary80); flags |= TFlags.floating | TFlags.imaginary; break; case Tcomplex32: d = Token.toChars(TOK.complex32); flags |= TFlags.floating | TFlags.complex; break; case Tcomplex64: d = Token.toChars(TOK.complex64); flags |= TFlags.floating | TFlags.complex; break; case Tcomplex80: d = Token.toChars(TOK.complex80); flags |= TFlags.floating | TFlags.complex; break; case Tbool: d = "bool"; flags |= TFlags.integral | TFlags.unsigned; break; case Tchar: d = Token.toChars(TOK.char_); flags |= TFlags.integral | TFlags.unsigned | TFlags.char_; break; case Twchar: d = Token.toChars(TOK.wchar_); flags |= TFlags.integral | TFlags.unsigned | TFlags.char_; break; case Tdchar: d = Token.toChars(TOK.dchar_); flags |= TFlags.integral | TFlags.unsigned | TFlags.char_; break; default: assert(0); } this.dstring = d; this.flags = flags; merge(); } override bool isscalar() const { return (flags & (TFlags.integral | TFlags.floating)) != 0; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TypeError : Type { extern (D) this() { super(Terror); } override Type syntaxCopy() { return this; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TypeNull : Type { extern (D) this() { super(Tnull); } override Type syntaxCopy() { // No semantic analysis done, no need to copy return this; } override void accept(Visitor v) { v.visit(this); } } extern (C++) class TypeVector : Type { Type basetype; extern (D) this(Type baseType) { super(Tvector); this.basetype = basetype; } override Type syntaxCopy() { return new TypeVector(basetype.syntaxCopy()); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TypeEnum : Type { EnumDeclaration sym; extern (D) this(EnumDeclaration sym) { super(Tenum); this.sym = sym; } override Type syntaxCopy() { return this; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TypeTuple : Type { Parameters* arguments; extern (D) this(Parameters* arguments) { super(Ttuple); this.arguments = arguments; } extern (D) this(Expressions* exps) { super(Ttuple); auto arguments = new Parameters(); if (exps) { arguments.setDim(exps.dim); for (size_t i = 0; i < exps.dim; i++) { Expression e = (*exps)[i]; if (e.type.ty == Ttuple) e.error("cannot form tuple of tuples"); auto arg = new Parameter(STC.undefined_, e.type, null, null, null); (*arguments)[i] = arg; } } this.arguments = arguments; } override Type syntaxCopy() { Parameters* args = Parameter.arraySyntaxCopy(arguments); Type t = new TypeTuple(args); t.mod = mod; return t; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TypeClass : Type { ClassDeclaration sym; AliasThisRec att = AliasThisRec.fwdref; extern (D) this (ClassDeclaration sym) { super(Tclass); this.sym = sym; } override Type syntaxCopy() { return this; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TypeStruct : Type { StructDeclaration sym; AliasThisRec att = AliasThisRec.fwdref; extern (D) this(StructDeclaration sym) { super(Tstruct); this.sym = sym; } override Type syntaxCopy() { return this; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TypeReference : TypeNext { extern (D) this(Type t) { super(Treference, t); // BUG: what about references to static arrays? } override Type syntaxCopy() { Type t = next.syntaxCopy(); if (t == next) t = this; else { t = new TypeReference(t); t.mod = mod; } return t; } override void accept(Visitor v) { v.visit(this); } } extern (C++) abstract class TypeNext : Type { Type next; final extern (D) this(TY ty, Type next) { super(ty); this.next = next; } override final Type nextOf() { return next; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TypeSlice : TypeNext { Expression lwr; Expression upr; extern (D) this(Type next, Expression lwr, Expression upr) { super(Tslice, next); this.lwr = lwr; this.upr = upr; } override Type syntaxCopy() { Type t = new TypeSlice(next.syntaxCopy(), lwr.syntaxCopy(), upr.syntaxCopy()); t.mod = mod; return t; } override void accept(Visitor v) { v.visit(this); } } extern (C++) class TypeDelegate : TypeNext { extern (D) this(Type t) { super(Tfunction, t); ty = Tdelegate; } override Type syntaxCopy() { Type t = next.syntaxCopy(); if (t == next) t = this; else { t = new TypeDelegate(t); t.mod = mod; } return t; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TypePointer : TypeNext { extern (D) this(Type t) { super(Tpointer, t); } override Type syntaxCopy() { Type t = next.syntaxCopy(); if (t == next) t = this; else { t = new TypePointer(t); t.mod = mod; } return t; } override void accept(Visitor v) { v.visit(this); } } extern (C++) class TypeFunction : TypeNext { ParameterList parameterList; // function parameters bool isnothrow; // true: nothrow bool isnogc; // true: is @nogc bool isproperty; // can be called without parentheses bool isref; // true: returns a reference bool isreturn; // true: 'this' is returned by ref bool isscope; // true: 'this' is scope LINK linkage; // calling convention TRUST trust; // level of trust PURE purity = PURE.impure; ubyte iswild; Expressions* fargs; extern (D) this(ParameterList pl, Type treturn, LINK linkage, StorageClass stc = 0) { super(Tfunction, treturn); assert(VarArg.none <= pl.varargs && pl.varargs <= VarArg.typesafe); this.parameterList = pl; this.linkage = linkage; if (stc & STC.pure_) this.purity = PURE.fwdref; if (stc & STC.nothrow_) this.isnothrow = true; if (stc & STC.nogc) this.isnogc = true; if (stc & STC.property) this.isproperty = true; if (stc & STC.ref_) this.isref = true; if (stc & STC.return_) this.isreturn = true; if (stc & STC.scope_) this.isscope = true; this.trust = TRUST.default_; if (stc & STC.safe) this.trust = TRUST.safe; if (stc & STC.system) this.trust = TRUST.system; if (stc & STC.trusted) this.trust = TRUST.trusted; } override Type syntaxCopy() { Type treturn = next ? next.syntaxCopy() : null; Parameters* params = Parameter.arraySyntaxCopy(parameterList.parameters); auto t = new TypeFunction(ParameterList(params, parameterList.varargs), treturn, linkage); t.mod = mod; t.isnothrow = isnothrow; t.isnogc = isnogc; t.purity = purity; t.isproperty = isproperty; t.isref = isref; t.isreturn = isreturn; t.isscope = isscope; t.iswild = iswild; t.trust = trust; t.fargs = fargs; return t; } override void accept(Visitor v) { v.visit(this); } } extern (C++) class TypeArray : TypeNext { final extern (D) this(TY ty, Type next) { super(ty, next); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TypeDArray : TypeArray { extern (D) this(Type t) { super(Tarray, t); } override Type syntaxCopy() { Type t = next.syntaxCopy(); if (t == next) t = this; else { t = new TypeDArray(t); t.mod = mod; } return t; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TypeAArray : TypeArray { Type index; Loc loc; extern (D) this(Type t, Type index) { super(Taarray, t); this.index = index; } override Type syntaxCopy() { Type t = next.syntaxCopy(); Type ti = index.syntaxCopy(); if (t == next && ti == index) t = this; else { t = new TypeAArray(t, ti); t.mod = mod; } return t; } override Expression toExpression() { Expression e = next.toExpression(); if (e) { Expression ei = index.toExpression(); if (ei) return new ArrayExp(loc, e, ei); } return null; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TypeSArray : TypeArray { Expression dim; final extern (D) this(Type t, Expression dim) { super(Tsarray, t); this.dim = dim; } override Type syntaxCopy() { Type t = next.syntaxCopy(); Expression e = dim.syntaxCopy(); t = new TypeSArray(t, e); t.mod = mod; return t; } override Expression toExpression() { Expression e = next.toExpression(); if (e) e = new ArrayExp(dim.loc, e, dim); return e; } override void accept(Visitor v) { v.visit(this); } } extern (C++) abstract class TypeQualified : Type { Objects idents; Loc loc; final extern (D) this(TY ty, Loc loc) { super(ty); this.loc = loc; } final void addIdent(Identifier id) { idents.push(id); } final void addInst(TemplateInstance ti) { idents.push(ti); } final void addIndex(RootObject e) { idents.push(e); } final void syntaxCopyHelper(TypeQualified t) { idents.setDim(t.idents.dim); for (size_t i = 0; i < idents.dim; i++) { RootObject id = t.idents[i]; if (id.dyncast() == DYNCAST.dsymbol) { TemplateInstance ti = cast(TemplateInstance)id; ti = cast(TemplateInstance)ti.syntaxCopy(null); id = ti; } else if (id.dyncast() == DYNCAST.expression) { Expression e = cast(Expression)id; e = e.syntaxCopy(); id = e; } else if (id.dyncast() == DYNCAST.type) { Type tx = cast(Type)id; tx = tx.syntaxCopy(); id = tx; } idents[i] = id; } } final Expression toExpressionHelper(Expression e, size_t i = 0) { for (; i < idents.dim; i++) { RootObject id = idents[i]; switch (id.dyncast()) { case DYNCAST.identifier: e = new DotIdExp(e.loc, e, cast(Identifier)id); break; case DYNCAST.dsymbol: auto ti = (cast(Dsymbol)id).isTemplateInstance(); assert(ti); e = new DotTemplateInstanceExp(e.loc, e, ti.name, ti.tiargs); break; case DYNCAST.type: // Bugzilla 1215 e = new ArrayExp(loc, e, new TypeExp(loc, cast(Type)id)); break; case DYNCAST.expression: // Bugzilla 1215 e = new ArrayExp(loc, e, cast(Expression)id); break; default: assert(0); } } return e; } override void accept(Visitor v) { v.visit(this); } } extern (C++) class TypeTraits : Type { TraitsExp exp; Loc loc; extern (D) this(const ref Loc loc, TraitsExp exp) { super(Tident); this.loc = loc; this.exp = exp; } override void accept(Visitor v) { v.visit(this); } override Type syntaxCopy() { TraitsExp te = cast(TraitsExp) exp.syntaxCopy(); TypeTraits tt = new TypeTraits(loc, te); tt.mod = mod; return tt; } } extern (C++) final class TypeMixin : Type { Expressions* exps; extern (D) this(Expressions* exps) { super(Tmixin); this.exps = exps; } override Type syntaxCopy() { static Expressions* arraySyntaxCopy(Expressions* exps) { Expressions* a = null; if (exps) { a = new Expressions(exps.dim); foreach (i, e; *exps) { (*a)[i] = e ? e.syntaxCopy() : null; } } return a; } return new TypeMixin(arraySyntaxCopy(exps)); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TypeIdentifier : TypeQualified { Identifier ident; extern (D) this(const ref Loc loc, Identifier ident) { super(Tident, loc); this.ident = ident; } override Type syntaxCopy() { auto t = new TypeIdentifier(loc, ident); t.syntaxCopyHelper(this); t.mod = mod; return t; } override Expression toExpression() { return toExpressionHelper(new IdentifierExp(loc, ident)); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TypeReturn : TypeQualified { extern (D) this(const ref Loc loc) { super(Treturn, loc); } override Type syntaxCopy() { auto t = new TypeReturn(loc); t.syntaxCopyHelper(this); t.mod = mod; return t; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TypeTypeof : TypeQualified { Expression exp; extern (D) this(const ref Loc loc, Expression exp) { super(Ttypeof, loc); this.exp = exp; } override Type syntaxCopy() { auto t = new TypeTypeof(loc, exp.syntaxCopy()); t.syntaxCopyHelper(this); t.mod = mod; return t; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TypeInstance : TypeQualified { TemplateInstance tempinst; final extern (D) this(const ref Loc loc, TemplateInstance tempinst) { super(Tinstance, loc); this.tempinst = tempinst; } override Type syntaxCopy() { auto t = new TypeInstance(loc, cast(TemplateInstance)tempinst.syntaxCopy(null)); t.syntaxCopyHelper(this); t.mod = mod; return t; } override Expression toExpression() { return toExpressionHelper(new ScopeExp(loc, tempinst)); } override void accept(Visitor v) { v.visit(this); } } extern (C++) abstract class Expression : ASTNode { TOK op; ubyte size; ubyte parens; Type type; Loc loc; final extern (D) this(const ref Loc loc, TOK op, int size) { this.loc = loc; this.op = op; this.size = cast(ubyte)size; } Expression syntaxCopy() { return copy(); } final void error(const(char)* format, ...) const { if (type != Type.terror) { va_list ap; va_start(ap, format); verror(loc, format, ap); va_end(ap); } } final Expression copy() { Expression e; if (!size) { assert(0); } e = cast(Expression)mem.xmalloc(size); return cast(Expression)memcpy(cast(void*)e, cast(void*)this, size); } override final DYNCAST dyncast() const { return DYNCAST.expression; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class DeclarationExp : Expression { Dsymbol declaration; extern (D) this(const ref Loc loc, Dsymbol declaration) { super(loc, TOK.declaration, __traits(classInstanceSize, DeclarationExp)); this.declaration = declaration; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class IntegerExp : Expression { dinteger_t value; extern (D) this(const ref Loc loc, dinteger_t value, Type type) { super(loc, TOK.int64, __traits(classInstanceSize, IntegerExp)); assert(type); if (!type.isscalar()) { if (type.ty != Terror) error("integral constant must be scalar type, not %s", type.toChars()); type = Type.terror; } this.type = type; setInteger(value); } void setInteger(dinteger_t value) { this.value = value; normalize(); } void normalize() { /* 'Normalize' the value of the integer to be in range of the type */ switch (type.toBasetype().ty) { case Tbool: value = (value != 0); break; case Tint8: value = cast(d_int8)value; break; case Tchar: case Tuns8: value = cast(d_uns8)value; break; case Tint16: value = cast(d_int16)value; break; case Twchar: case Tuns16: value = cast(d_uns16)value; break; case Tint32: value = cast(d_int32)value; break; case Tdchar: case Tuns32: value = cast(d_uns32)value; break; case Tint64: value = cast(d_int64)value; break; case Tuns64: value = cast(d_uns64)value; break; case Tpointer: if (Target.ptrsize == 8) goto case Tuns64; if (Target.ptrsize == 4) goto case Tuns32; if (Target.ptrsize == 2) goto case Tuns16; assert(0); default: break; } } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class NewAnonClassExp : Expression { Expression thisexp; // if !=null, 'this' for class being allocated Expressions* newargs; // Array of Expression's to call new operator ClassDeclaration cd; // class being instantiated Expressions* arguments; // Array of Expression's to call class constructor extern (D) this(const ref Loc loc, Expression thisexp, Expressions* newargs, ClassDeclaration cd, Expressions* arguments) { super(loc, TOK.newAnonymousClass, __traits(classInstanceSize, NewAnonClassExp)); this.thisexp = thisexp; this.newargs = newargs; this.cd = cd; this.arguments = arguments; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class IsExp : Expression { Type targ; Identifier id; // can be null Type tspec; // can be null TemplateParameters* parameters; TOK tok; // ':' or '==' TOK tok2; // 'struct', 'union', etc. extern (D) this(const ref Loc loc, Type targ, Identifier id, TOK tok, Type tspec, TOK tok2, TemplateParameters* parameters) { super(loc, TOK.is_, __traits(classInstanceSize, IsExp)); this.targ = targ; this.id = id; this.tok = tok; this.tspec = tspec; this.tok2 = tok2; this.parameters = parameters; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class RealExp : Expression { real_t value; extern (D) this(const ref Loc loc, real_t value, Type type) { super(loc, TOK.float64, __traits(classInstanceSize, RealExp)); this.value = value; this.type = type; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class NullExp : Expression { extern (D) this(const ref Loc loc, Type type = null) { super(loc, TOK.null_, __traits(classInstanceSize, NullExp)); this.type = type; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TypeidExp : Expression { RootObject obj; extern (D) this(const ref Loc loc, RootObject o) { super(loc, TOK.typeid_, __traits(classInstanceSize, TypeidExp)); this.obj = o; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TraitsExp : Expression { Identifier ident; Objects* args; extern (D) this(const ref Loc loc, Identifier ident, Objects* args) { super(loc, TOK.traits, __traits(classInstanceSize, TraitsExp)); this.ident = ident; this.args = args; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class StringExp : Expression { union { char* string; // if sz == 1 wchar* wstring; // if sz == 2 dchar* dstring; // if sz == 4 } // (const if ownedByCtfe == OwnedBy.code) size_t len; // number of code units ubyte sz = 1; // 1: char, 2: wchar, 4: dchar char postfix = 0; // 'c', 'w', 'd' extern (D) this(const ref Loc loc, char* string) { super(loc, TOK.string_, __traits(classInstanceSize, StringExp)); this.string = string; this.len = strlen(string); this.sz = 1; // work around LDC bug #1286 } extern (D) this(const ref Loc loc, void* string, size_t len) { super(loc, TOK.string_, __traits(classInstanceSize, StringExp)); this.string = cast(char*)string; this.len = len; this.sz = 1; // work around LDC bug #1286 } extern (D) this(const ref Loc loc, void* string, size_t len, char postfix) { super(loc, TOK.string_, __traits(classInstanceSize, StringExp)); this.string = cast(char*)string; this.len = len; this.postfix = postfix; this.sz = 1; // work around LDC bug #1286 } /********************************************** * Write the contents of the string to dest. * Use numberOfCodeUnits() to determine size of result. * Params: * dest = destination * tyto = encoding type of the result * zero = add terminating 0 */ void writeTo(void* dest, bool zero, int tyto = 0) const { int encSize; switch (tyto) { case 0: encSize = sz; break; case Tchar: encSize = 1; break; case Twchar: encSize = 2; break; case Tdchar: encSize = 4; break; default: assert(0); } if (sz == encSize) { memcpy(dest, string, len * sz); if (zero) memset(dest + len * sz, 0, sz); } else assert(0); } extern (D) const(char)[] toStringz() const { auto nbytes = len * sz; char* s = cast(char*)mem.xmalloc_noscan(nbytes + sz); writeTo(s, true); return s[0 .. nbytes]; } override void accept(Visitor v) { v.visit(this); } } extern (C++) class NewExp : Expression { Expression thisexp; // if !=null, 'this' for class being allocated Expressions* newargs; // Array of Expression's to call new operator Type newtype; Expressions* arguments; // Array of Expression's extern (D) this(const ref Loc loc, Expression thisexp, Expressions* newargs, Type newtype, Expressions* arguments) { super(loc, TOK.new_, __traits(classInstanceSize, NewExp)); this.thisexp = thisexp; this.newargs = newargs; this.newtype = newtype; this.arguments = arguments; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class AssocArrayLiteralExp : Expression { Expressions* keys; Expressions* values; extern (D) this(const ref Loc loc, Expressions* keys, Expressions* values) { super(loc, TOK.assocArrayLiteral, __traits(classInstanceSize, AssocArrayLiteralExp)); assert(keys.dim == values.dim); this.keys = keys; this.values = values; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ArrayLiteralExp : Expression { Expression basis; Expressions* elements; extern (D) this(const ref Loc loc, Expressions* elements) { super(loc, TOK.arrayLiteral, __traits(classInstanceSize, ArrayLiteralExp)); this.elements = elements; } extern (D) this(const ref Loc loc, Expression e) { super(loc, TOK.arrayLiteral, __traits(classInstanceSize, ArrayLiteralExp)); elements = new Expressions(); elements.push(e); } extern (D) this(const ref Loc loc, Expression basis, Expressions* elements) { super(loc, TOK.arrayLiteral, __traits(classInstanceSize, ArrayLiteralExp)); this.basis = basis; this.elements = elements; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class FuncExp : Expression { FuncLiteralDeclaration fd; TemplateDeclaration td; TOK tok; extern (D) this(const ref Loc loc, Dsymbol s) { super(loc, TOK.function_, __traits(classInstanceSize, FuncExp)); this.td = s.isTemplateDeclaration(); this.fd = s.isFuncLiteralDeclaration(); if (td) { assert(td.literal); assert(td.members && td.members.dim == 1); fd = (*td.members)[0].isFuncLiteralDeclaration(); } tok = fd.tok; // save original kind of function/delegate/(infer) assert(fd.fbody); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class IntervalExp : Expression { Expression lwr; Expression upr; extern (D) this(const ref Loc loc, Expression lwr, Expression upr) { super(loc, TOK.interval, __traits(classInstanceSize, IntervalExp)); this.lwr = lwr; this.upr = upr; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TypeExp : Expression { extern (D) this(const ref Loc loc, Type type) { super(loc, TOK.type, __traits(classInstanceSize, TypeExp)); this.type = type; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ScopeExp : Expression { ScopeDsymbol sds; extern (D) this(const ref Loc loc, ScopeDsymbol sds) { super(loc, TOK.scope_, __traits(classInstanceSize, ScopeExp)); this.sds = sds; assert(!sds.isTemplateDeclaration()); } override void accept(Visitor v) { v.visit(this); } } extern (C++) class IdentifierExp : Expression { Identifier ident; final extern (D) this(const ref Loc loc, Identifier ident) { super(loc, TOK.identifier, __traits(classInstanceSize, IdentifierExp)); this.ident = ident; } override void accept(Visitor v) { v.visit(this); } } extern (C++) class UnaExp : Expression { Expression e1; final extern (D) this(const ref Loc loc, TOK op, int size, Expression e1) { super(loc, op, size); this.e1 = e1; } override void accept(Visitor v) { v.visit(this); } } extern (C++) class DefaultInitExp : Expression { TOK subop; // which of the derived classes this is final extern (D) this(const ref Loc loc, TOK subop, int size) { super(loc, TOK.default_, size); this.subop = subop; } override void accept(Visitor v) { v.visit(this); } } extern (C++) abstract class BinExp : Expression { Expression e1; Expression e2; final extern (D) this(const ref Loc loc, TOK op, int size, Expression e1, Expression e2) { super(loc, op, size); this.e1 = e1; this.e2 = e2; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class DsymbolExp : Expression { Dsymbol s; bool hasOverloads; extern (D) this(const ref Loc loc, Dsymbol s, bool hasOverloads = true) { super(loc, TOK.dSymbol, __traits(classInstanceSize, DsymbolExp)); this.s = s; this.hasOverloads = hasOverloads; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TemplateExp : Expression { TemplateDeclaration td; FuncDeclaration fd; extern (D) this(const ref Loc loc, TemplateDeclaration td, FuncDeclaration fd = null) { super(loc, TOK.template_, __traits(classInstanceSize, TemplateExp)); //printf("TemplateExp(): %s\n", td.toChars()); this.td = td; this.fd = fd; } override void accept(Visitor v) { v.visit(this); } } extern (C++) class SymbolExp : Expression { Declaration var; bool hasOverloads; final extern (D) this(const ref Loc loc, TOK op, int size, Declaration var, bool hasOverloads) { super(loc, op, size); assert(var); this.var = var; this.hasOverloads = hasOverloads; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class VarExp : SymbolExp { extern (D) this(const ref Loc loc, Declaration var, bool hasOverloads = true) { if (var.isVarDeclaration()) hasOverloads = false; super(loc, TOK.variable, __traits(classInstanceSize, VarExp), var, hasOverloads); this.type = var.type; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TupleExp : Expression { Expression e0; Expressions* exps; extern (D) this(const ref Loc loc, Expression e0, Expressions* exps) { super(loc, TOK.tuple, __traits(classInstanceSize, TupleExp)); //printf("TupleExp(this = %p)\n", this); this.e0 = e0; this.exps = exps; } extern (D) this(const ref Loc loc, Expressions* exps) { super(loc, TOK.tuple, __traits(classInstanceSize, TupleExp)); //printf("TupleExp(this = %p)\n", this); this.exps = exps; } extern (D) this(const ref Loc loc, TupleDeclaration tup) { super(loc, TOK.tuple, __traits(classInstanceSize, TupleExp)); this.exps = new Expressions(); this.exps.reserve(tup.objects.dim); for (size_t i = 0; i < tup.objects.dim; i++) { RootObject o = (*tup.objects)[i]; if (Dsymbol s = getDsymbol(o)) { Expression e = new DsymbolExp(loc, s); this.exps.push(e); } else if (o.dyncast() == DYNCAST.expression) { auto e = (cast(Expression)o).copy(); e.loc = loc; // Bugzilla 15669 this.exps.push(e); } else if (o.dyncast() == DYNCAST.type) { Type t = cast(Type)o; Expression e = new TypeExp(loc, t); this.exps.push(e); } else { error("%s is not an expression", o.toChars()); } } } extern (C++) Dsymbol isDsymbol(RootObject o) { if (!o || o.dyncast || DYNCAST.dsymbol) return null; return cast(Dsymbol)o; } extern (C++) Dsymbol getDsymbol(RootObject oarg) { Dsymbol sa; Expression ea = isExpression(oarg); if (ea) { // Try to convert Expression to symbol if (ea.op == TOK.variable) sa = (cast(VarExp)ea).var; else if (ea.op == TOK.function_) { if ((cast(FuncExp)ea).td) sa = (cast(FuncExp)ea).td; else sa = (cast(FuncExp)ea).fd; } else if (ea.op == TOK.template_) sa = (cast(TemplateExp)ea).td; else sa = null; } else { // Try to convert Type to symbol Type ta = isType(oarg); if (ta) sa = ta.toDsymbol(null); else sa = isDsymbol(oarg); // if already a symbol } return sa; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class DollarExp : IdentifierExp { extern (D) this(const ref Loc loc) { super(loc, Id.dollar); } override void accept(Visitor v) { v.visit(this); } } extern (C++) class ThisExp : Expression { final extern (D) this(const ref Loc loc) { super(loc, TOK.this_, __traits(classInstanceSize, ThisExp)); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class SuperExp : ThisExp { extern (D) this(const ref Loc loc) { super(loc); op = TOK.super_; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class AddrExp : UnaExp { extern (D) this(const ref Loc loc, Expression e) { super(loc, TOK.address, __traits(classInstanceSize, AddrExp), e); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class PreExp : UnaExp { extern (D) this(TOK op, Loc loc, Expression e) { super(loc, op, __traits(classInstanceSize, PreExp), e); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class PtrExp : UnaExp { extern (D) this(const ref Loc loc, Expression e) { super(loc, TOK.star, __traits(classInstanceSize, PtrExp), e); } extern (D) this(const ref Loc loc, Expression e, Type t) { super(loc, TOK.star, __traits(classInstanceSize, PtrExp), e); type = t; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class NegExp : UnaExp { extern (D) this(const ref Loc loc, Expression e) { super(loc, TOK.negate, __traits(classInstanceSize, NegExp), e); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class UAddExp : UnaExp { extern (D) this(const ref Loc loc, Expression e) { super(loc, TOK.uadd, __traits(classInstanceSize, UAddExp), e); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class NotExp : UnaExp { extern (D) this(const ref Loc loc, Expression e) { super(loc, TOK.not, __traits(classInstanceSize, NotExp), e); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ComExp : UnaExp { extern (D) this(const ref Loc loc, Expression e) { super(loc, TOK.tilde, __traits(classInstanceSize, ComExp), e); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class DeleteExp : UnaExp { bool isRAII; extern (D) this(const ref Loc loc, Expression e, bool isRAII) { super(loc, TOK.delete_, __traits(classInstanceSize, DeleteExp), e); this.isRAII = isRAII; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class CastExp : UnaExp { Type to; ubyte mod = cast(ubyte)~0; extern (D) this(const ref Loc loc, Expression e, Type t) { super(loc, TOK.cast_, __traits(classInstanceSize, CastExp), e); this.to = t; } extern (D) this(const ref Loc loc, Expression e, ubyte mod) { super(loc, TOK.cast_, __traits(classInstanceSize, CastExp), e); this.mod = mod; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class CallExp : UnaExp { Expressions* arguments; extern (D) this(const ref Loc loc, Expression e, Expressions* exps) { super(loc, TOK.call, __traits(classInstanceSize, CallExp), e); this.arguments = exps; } extern (D) this(const ref Loc loc, Expression e) { super(loc, TOK.call, __traits(classInstanceSize, CallExp), e); } extern (D) this(const ref Loc loc, Expression e, Expression earg1) { super(loc, TOK.call, __traits(classInstanceSize, CallExp), e); auto arguments = new Expressions(); if (earg1) { arguments.setDim(1); (*arguments)[0] = earg1; } this.arguments = arguments; } extern (D) this(const ref Loc loc, Expression e, Expression earg1, Expression earg2) { super(loc, TOK.call, __traits(classInstanceSize, CallExp), e); auto arguments = new Expressions(); arguments.setDim(2); (*arguments)[0] = earg1; (*arguments)[1] = earg2; this.arguments = arguments; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class DotIdExp : UnaExp { Identifier ident; extern (D) this(const ref Loc loc, Expression e, Identifier ident) { super(loc, TOK.dotIdentifier, __traits(classInstanceSize, DotIdExp), e); this.ident = ident; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class AssertExp : UnaExp { Expression msg; extern (D) this(const ref Loc loc, Expression e, Expression msg = null) { super(loc, TOK.assert_, __traits(classInstanceSize, AssertExp), e); this.msg = msg; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class CompileExp : Expression { Expressions* exps; extern (D) this(const ref Loc loc, Expressions* exps) { super(loc, TOK.mixin_, __traits(classInstanceSize, CompileExp)); this.exps = exps; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ImportExp : UnaExp { extern (D) this(const ref Loc loc, Expression e) { super(loc, TOK.import_, __traits(classInstanceSize, ImportExp), e); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class DotTemplateInstanceExp : UnaExp { TemplateInstance ti; extern (D) this(const ref Loc loc, Expression e, Identifier name, Objects* tiargs) { super(loc, TOK.dotTemplateInstance, __traits(classInstanceSize, DotTemplateInstanceExp), e); this.ti = new TemplateInstance(loc, name, tiargs); } extern (D) this(const ref Loc loc, Expression e, TemplateInstance ti) { super(loc, TOK.dotTemplateInstance, __traits(classInstanceSize, DotTemplateInstanceExp), e); this.ti = ti; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ArrayExp : UnaExp { Expressions* arguments; extern (D) this(const ref Loc loc, Expression e1, Expression index = null) { super(loc, TOK.array, __traits(classInstanceSize, ArrayExp), e1); arguments = new Expressions(); if (index) arguments.push(index); } extern (D) this(const ref Loc loc, Expression e1, Expressions* args) { super(loc, TOK.array, __traits(classInstanceSize, ArrayExp), e1); arguments = args; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class FuncInitExp : DefaultInitExp { extern (D) this(const ref Loc loc) { super(loc, TOK.functionString, __traits(classInstanceSize, FuncInitExp)); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class PrettyFuncInitExp : DefaultInitExp { extern (D) this(const ref Loc loc) { super(loc, TOK.prettyFunction, __traits(classInstanceSize, PrettyFuncInitExp)); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class FileInitExp : DefaultInitExp { extern (D) this(const ref Loc loc, TOK tok) { super(loc, tok, __traits(classInstanceSize, FileInitExp)); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class LineInitExp : DefaultInitExp { extern (D) this(const ref Loc loc) { super(loc, TOK.line, __traits(classInstanceSize, LineInitExp)); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ModuleInitExp : DefaultInitExp { extern (D) this(const ref Loc loc) { super(loc, TOK.moduleString, __traits(classInstanceSize, ModuleInitExp)); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class CommaExp : BinExp { const bool isGenerated; bool allowCommaExp; extern (D) this(const ref Loc loc, Expression e1, Expression e2, bool generated = true) { super(loc, TOK.comma, __traits(classInstanceSize, CommaExp), e1, e2); allowCommaExp = isGenerated = generated; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class PostExp : BinExp { extern (D) this(TOK op, Loc loc, Expression e) { super(loc, op, __traits(classInstanceSize, PostExp), e, new IntegerExp(loc, 1, Type.tint32)); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class PowExp : BinExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.pow, __traits(classInstanceSize, PowExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class MulExp : BinExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.mul, __traits(classInstanceSize, MulExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class DivExp : BinExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.div, __traits(classInstanceSize, DivExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ModExp : BinExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.mod, __traits(classInstanceSize, ModExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class AddExp : BinExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.add, __traits(classInstanceSize, AddExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class MinExp : BinExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.min, __traits(classInstanceSize, MinExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class CatExp : BinExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.concatenate, __traits(classInstanceSize, CatExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ShlExp : BinExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.leftShift, __traits(classInstanceSize, ShlExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ShrExp : BinExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.rightShift, __traits(classInstanceSize, ShrExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class UshrExp : BinExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.unsignedRightShift, __traits(classInstanceSize, UshrExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class EqualExp : BinExp { extern (D) this(TOK op, Loc loc, Expression e1, Expression e2) { super(loc, op, __traits(classInstanceSize, EqualExp), e1, e2); assert(op == TOK.equal || op == TOK.notEqual); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class InExp : BinExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.in_, __traits(classInstanceSize, InExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class IdentityExp : BinExp { extern (D) this(TOK op, Loc loc, Expression e1, Expression e2) { super(loc, op, __traits(classInstanceSize, IdentityExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class CmpExp : BinExp { extern (D) this(TOK op, Loc loc, Expression e1, Expression e2) { super(loc, op, __traits(classInstanceSize, CmpExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class AndExp : BinExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.and, __traits(classInstanceSize, AndExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class XorExp : BinExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.xor, __traits(classInstanceSize, XorExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class OrExp : BinExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.or, __traits(classInstanceSize, OrExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class LogicalExp : BinExp { extern (D) this(const ref Loc loc, TOK op, Expression e1, Expression e2) { super(loc, op, __traits(classInstanceSize, LogicalExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class CondExp : BinExp { Expression econd; extern (D) this(const ref Loc loc, Expression econd, Expression e1, Expression e2) { super(loc, TOK.question, __traits(classInstanceSize, CondExp), e1, e2); this.econd = econd; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class AssignExp : BinExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.assign, __traits(classInstanceSize, AssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) class BinAssignExp : BinExp { final extern (D) this(const ref Loc loc, TOK op, int size, Expression e1, Expression e2) { super(loc, op, size, e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class AddAssignExp : BinAssignExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.addAssign, __traits(classInstanceSize, AddAssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class MinAssignExp : BinAssignExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.minAssign, __traits(classInstanceSize, MinAssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class MulAssignExp : BinAssignExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.mulAssign, __traits(classInstanceSize, MulAssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class DivAssignExp : BinAssignExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.divAssign, __traits(classInstanceSize, DivAssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ModAssignExp : BinAssignExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.modAssign, __traits(classInstanceSize, ModAssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class PowAssignExp : BinAssignExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.powAssign, __traits(classInstanceSize, PowAssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class AndAssignExp : BinAssignExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.andAssign, __traits(classInstanceSize, AndAssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class OrAssignExp : BinAssignExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.orAssign, __traits(classInstanceSize, OrAssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class XorAssignExp : BinAssignExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.xorAssign, __traits(classInstanceSize, XorAssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ShlAssignExp : BinAssignExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.leftShiftAssign, __traits(classInstanceSize, ShlAssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ShrAssignExp : BinAssignExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.rightShiftAssign, __traits(classInstanceSize, ShrAssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class UshrAssignExp : BinAssignExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.unsignedRightShiftAssign, __traits(classInstanceSize, UshrAssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class CatAssignExp : BinAssignExp { extern (D) this(const ref Loc loc, Expression e1, Expression e2) { super(loc, TOK.concatenateAssign, __traits(classInstanceSize, CatAssignExp), e1, e2); } override void accept(Visitor v) { v.visit(this); } } extern (C++) class TemplateParameter : ASTNode { Loc loc; Identifier ident; final extern (D) this(const ref Loc loc, Identifier ident) { this.loc = loc; this.ident = ident; } TemplateParameter syntaxCopy(){ return null;} override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TemplateAliasParameter : TemplateParameter { Type specType; RootObject specAlias; RootObject defaultAlias; extern (D) this(const ref Loc loc, Identifier ident, Type specType, RootObject specAlias, RootObject defaultAlias) { super(loc, ident); this.ident = ident; this.specType = specType; this.specAlias = specAlias; this.defaultAlias = defaultAlias; } override void accept(Visitor v) { v.visit(this); } } extern (C++) class TemplateTypeParameter : TemplateParameter { Type specType; Type defaultType; final extern (D) this(const ref Loc loc, Identifier ident, Type specType, Type defaultType) { super(loc, ident); this.ident = ident; this.specType = specType; this.defaultType = defaultType; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TemplateTupleParameter : TemplateParameter { extern (D) this(const ref Loc loc, Identifier ident) { super(loc, ident); this.ident = ident; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TemplateValueParameter : TemplateParameter { Type valType; Expression specValue; Expression defaultValue; extern (D) this(const ref Loc loc, Identifier ident, Type valType, Expression specValue, Expression defaultValue) { super(loc, ident); this.ident = ident; this.valType = valType; this.specValue = specValue; this.defaultValue = defaultValue; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class TemplateThisParameter : TemplateTypeParameter { extern (D) this(const ref Loc loc, Identifier ident, Type specType, Type defaultType) { super(loc, ident, specType, defaultType); } override void accept(Visitor v) { v.visit(this); } } extern (C++) abstract class Condition : ASTNode { Loc loc; final extern (D) this(const ref Loc loc) { this.loc = loc; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class StaticForeach : RootObject { Loc loc; ForeachStatement aggrfe; ForeachRangeStatement rangefe; final extern (D) this(const ref Loc loc, ForeachStatement aggrfe, ForeachRangeStatement rangefe) in { assert(!!aggrfe ^ !!rangefe); } body { this.loc = loc; this.aggrfe = aggrfe; this.rangefe = rangefe; } } extern (C++) final class StaticIfCondition : Condition { Expression exp; final extern (D) this(const ref Loc loc, Expression exp) { super(loc); this.exp = exp; } override void accept(Visitor v) { v.visit(this); } } extern (C++) class DVCondition : Condition { uint level; Identifier ident; Module mod; final extern (D) this(Module mod, uint level, Identifier ident) { super(Loc.initial); this.mod = mod; this.ident = ident; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class DebugCondition : DVCondition { extern (D) this(Module mod, uint level, Identifier ident) { super(mod, level, ident); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class VersionCondition : DVCondition { extern (D) this(Module mod, uint level, Identifier ident) { super(mod, level, ident); } override void accept(Visitor v) { v.visit(this); } } enum InitKind : ubyte { void_, error, struct_, array, exp, } extern (C++) class Initializer : ASTNode { Loc loc; InitKind kind; final extern (D) this(const ref Loc loc, InitKind kind) { this.loc = loc; this.kind = kind; } // this should be abstract and implemented in child classes Expression toExpression(Type t = null) { return null; } final ExpInitializer isExpInitializer() { return kind == InitKind.exp ? cast(ExpInitializer)cast(void*)this : null; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ExpInitializer : Initializer { Expression exp; extern (D) this(const ref Loc loc, Expression exp) { super(loc, InitKind.exp); this.exp = exp; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class StructInitializer : Initializer { Identifiers field; Initializers value; extern (D) this(const ref Loc loc) { super(loc, InitKind.struct_); } void addInit(Identifier field, Initializer value) { this.field.push(field); this.value.push(value); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class ArrayInitializer : Initializer { Expressions index; Initializers value; uint dim; Type type; extern (D) this(const ref Loc loc) { super(loc, InitKind.array); } void addInit(Expression index, Initializer value) { this.index.push(index); this.value.push(value); dim = 0; type = null; } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class VoidInitializer : Initializer { extern (D) this(const ref Loc loc) { super(loc, InitKind.void_); } override void accept(Visitor v) { v.visit(this); } } extern (C++) final class Tuple : RootObject { Objects objects; // kludge for template.isType() override DYNCAST dyncast() const { return DYNCAST.tuple; } override const(char)* toChars() const { return objects.toChars(); } } struct BaseClass { Type type; } struct ModuleDeclaration { Loc loc; Identifier id; Identifiers *packages; bool isdeprecated; Expression msg; extern (D) this(const ref Loc loc, Identifiers* packages, Identifier id, Expression msg, bool isdeprecated) { this.loc = loc; this.packages = packages; this.id = id; this.msg = msg; this.isdeprecated = isdeprecated; } extern (C++) const(char)* toChars() const { OutBuffer buf; if (packages && packages.dim) { for (size_t i = 0; i < packages.dim; i++) { const Identifier pid = (*packages)[i]; buf.writestring(pid.toString()); buf.writeByte('.'); } } buf.writestring(id.toString()); return buf.extractChars(); } } struct Prot { enum Kind : int { undefined, none, private_, package_, protected_, public_, export_, } Kind kind; Package pkg; } struct Scope { } static extern (C++) Tuple isTuple(RootObject o) { //return dynamic_cast<Tuple *>(o); if (!o || o.dyncast() != DYNCAST.tuple) return null; return cast(Tuple)o; } static extern (C++) Type isType(RootObject o) { if (!o || o.dyncast() != DYNCAST.type) return null; return cast(Type)o; } static extern (C++) Expression isExpression(RootObject o) { if (!o || o.dyncast() != DYNCAST.expression) return null; return cast(Expression)o; } static extern (C++) TemplateParameter isTemplateParameter(RootObject o) { if (!o || o.dyncast() != DYNCAST.templateparameter) return null; return cast(TemplateParameter)o; } static const(char)* protectionToChars(Prot.Kind kind) { final switch (kind) { case Prot.Kind.undefined: return null; case Prot.Kind.none: return "none"; case Prot.Kind.private_: return "private"; case Prot.Kind.package_: return "package"; case Prot.Kind.protected_: return "protected"; case Prot.Kind.public_: return "public"; case Prot.Kind.export_: return "export"; } } static bool stcToBuffer(OutBuffer* buf, StorageClass stc) { bool result = false; if ((stc & (STC.return_ | STC.scope_)) == (STC.return_ | STC.scope_)) stc &= ~STC.scope_; while (stc) { const(char)* p = stcToChars(stc); if (!p) // there's no visible storage classes break; if (!result) result = true; else buf.writeByte(' '); buf.writestring(p); } return result; } static extern (C++) Expression typeToExpression(Type t) { return t.toExpression; } static const(char)* stcToChars(ref StorageClass stc) { struct SCstring { StorageClass stc; TOK tok; const(char)* id; } __gshared SCstring* table = [ SCstring(STC.auto_, TOK.auto_), SCstring(STC.scope_, TOK.scope_), SCstring(STC.static_, TOK.static_), SCstring(STC.extern_, TOK.extern_), SCstring(STC.const_, TOK.const_), SCstring(STC.final_, TOK.final_), SCstring(STC.abstract_, TOK.abstract_), SCstring(STC.synchronized_, TOK.synchronized_), SCstring(STC.deprecated_, TOK.deprecated_), SCstring(STC.override_, TOK.override_), SCstring(STC.lazy_, TOK.lazy_), SCstring(STC.alias_, TOK.alias_), SCstring(STC.out_, TOK.out_), SCstring(STC.in_, TOK.in_), SCstring(STC.manifest, TOK.enum_), SCstring(STC.immutable_, TOK.immutable_), SCstring(STC.shared_, TOK.shared_), SCstring(STC.nothrow_, TOK.nothrow_), SCstring(STC.wild, TOK.inout_), SCstring(STC.pure_, TOK.pure_), SCstring(STC.ref_, TOK.ref_), SCstring(STC.tls), SCstring(STC.gshared, TOK.gshared), SCstring(STC.nogc, TOK.at, "@nogc"), SCstring(STC.property, TOK.at, "@property"), SCstring(STC.safe, TOK.at, "@safe"), SCstring(STC.trusted, TOK.at, "@trusted"), SCstring(STC.system, TOK.at, "@system"), SCstring(STC.disable, TOK.at, "@disable"), SCstring(STC.future, TOK.at, "@__future"), SCstring(0, TOK.reserved) ]; for (int i = 0; table[i].stc; i++) { StorageClass tbl = table[i].stc; assert(tbl & STCStorageClass); if (stc & tbl) { stc &= ~tbl; if (tbl == STC.tls) // TOKtls was removed return "__thread"; TOK tok = table[i].tok; if (tok == TOK.at) return table[i].id; else return Token.toChars(tok); } } //printf("stc = %llx\n", stc); return null; } static const(char)* linkageToChars(LINK linkage) { final switch (linkage) { case LINK.default_: case LINK.system: return null; case LINK.d: return "D"; case LINK.c: return "C"; case LINK.cpp: return "C++"; case LINK.windows: return "Windows"; case LINK.pascal: return "Pascal"; case LINK.objc: return "Objective-C"; } } struct Target { extern (C++) __gshared int ptrsize; extern (C++) static Type va_listType() { if (global.params.isWindows) { return Type.tchar.pointerTo(); } else if (global.params.isLinux || global.params.isFreeBSD || global.params.isOpenBSD || global.params.isDragonFlyBSD || global.params.isSolaris || global.params.isOSX) { if (global.params.is64bit) { return (new TypeIdentifier(Loc.initial, Identifier.idPool("__va_list_tag"))).pointerTo(); } else { return Type.tchar.pointerTo(); } } else { assert(0); } } } }
D
INSTANCE Info_Mod_Giselle_RLMord (C_INFO) { npc = Mod_7234_OUT_Giselle_NW; nr = 1; condition = Info_Mod_Giselle_RLMord_Condition; information = Info_Mod_Giselle_RLMord_Info; permanent = 0; important = 0; description = "Du bist Giselle?"; }; FUNC INT Info_Mod_Giselle_RLMord_Condition() { if (Npc_KnowsInfo(hero, Info_Mod_Pablo_RLMord)) { return 1; }; }; FUNC VOID Info_Mod_Giselle_RLMord_Info() { AI_Output(hero, self, "Info_Mod_Giselle_RLMord_15_00"); //Du bist Giselle? AI_Output(self, hero, "Info_Mod_Giselle_RLMord_17_01"); //In Fleisch und Blut, mein Hübscher. AI_Output(hero, self, "Info_Mod_Giselle_RLMord_15_02"); //Was geschah letzte Nacht? AI_Output(self, hero, "Info_Mod_Giselle_RLMord_17_03"); //Nun, Jason kam, wie jeden Monat, zu mir und wollte das Übliche. AI_Output(self, hero, "Info_Mod_Giselle_RLMord_17_04"); //Da kam plötzlich jemand in das Zimmer hineingestürmt und Streckte Jason ohne Vorwarnung nieder. AI_Output(self, hero, "Info_Mod_Giselle_RLMord_17_05"); //Danach verschwand er einfach wieder, ohne ein Wort zu sagen. Gleich darauf rief weckte ich Bromor, den Besitzer, der die Miliz verständigte. AI_Output(hero, self, "Info_Mod_Giselle_RLMord_15_06"); //Was ist „Das Übliche“? AI_Output(self, hero, "Info_Mod_Giselle_RLMord_17_07"); //Nur Gutes über die Toten. Wir in der roten Laterne sind diskret. B_StartOtherRoutine (Mod_744_MIL_Pablo_NW, "ZIMMER"); Info_ClearChoices (Info_Mod_Giselle_RLMord); Info_AddChoice (Info_Mod_Giselle_RLMord, "Wenn du es mir nicht augenblicklich sagst (...)", Info_Mod_Giselle_RLMord_C); if (Npc_HasItems(hero, ItMi_GoldRing) >= 1) { Info_AddChoice (Info_Mod_Giselle_RLMord, "Sag's mir Bitte!", Info_Mod_Giselle_RLMord_B); }; Info_AddChoice (Info_Mod_Giselle_RLMord, "Jason wird’s nicht mehr stören, wo er jetzt ist.", Info_Mod_Giselle_RLMord_A); }; FUNC VOID Info_Mod_Giselle_RLMord_D() { AI_Output(self, hero, "Info_Mod_Giselle_RLMord_D_17_00"); //Er stand auf Brutalitäten, wollte geschlagen verletzt werden. Einmal hat er sogar extra 'ne Feuerball-Spruchrolle mitgebracht. AI_Output(self, hero, "Info_Mod_Giselle_RLMord_D_17_01"); //Er selbst hat mich aber nie angerührt, war immer passiv. AI_Output(hero, self, "Info_Mod_Giselle_RLMord_D_15_02"); //Ich seh' mich mal am Tatort um. Ihr wart in Zimmer 2? AI_Output(self, hero, "Info_Mod_Giselle_RLMord_D_17_03"); //Genau Süßer. Info_ClearChoices (Info_Mod_Giselle_RLMord); }; FUNC VOID Info_Mod_Giselle_RLMord_C() { AI_Output(hero, self, "Info_Mod_Giselle_RLMord_C_15_00"); //Wenn du es mir nicht augenblicklich sagst, lass ich dich wegen „Behinderung der Ermittlungsarbeiten“ in den Kerker werfen. AI_Output(self, hero, "Info_Mod_Giselle_RLMord_C_17_01"); //Ist ja schon gut, ich sag’s dir ja. Info_Mod_Giselle_RLMord_D(); }; FUNC VOID Info_Mod_Giselle_RLMord_B() { AI_Output(hero, self, "Info_Mod_Giselle_RLMord_B_15_00"); //Sag's mir Bitte! AI_Output(self, hero, "Info_Mod_Giselle_RLMord_B_17_01"); //Wenn man mich so nett bittet kann ich kaum Nein sagen ... AI_Output(self, hero, "Info_Mod_Giselle_RLMord_B_17_02"); //Ich mach dir n Vorschlag, du bringst mir ein kleines Zeichen deiner Wertschätzung, dann sag ich's dir. AI_Output(hero, self, "Info_Mod_Giselle_RLMord_B_15_03"); //Hier ist ein goldener Ring. B_GiveInvItems (hero, self, ItMi_GoldRing, 1); AI_Output(self, hero, "Info_Mod_Giselle_RLMord_B_17_04"); //Der ist ja wunderschön. Na gut, ich werde es dir erzählen. Info_Mod_Giselle_RLMord_D(); }; FUNC VOID Info_Mod_Giselle_RLMord_A() { AI_Output(hero, self, "Info_Mod_Giselle_RLMord_A_15_00"); //Jason wird’s nicht mehr stören, wo er jetzt ist. AI_Output(self, hero, "Info_Mod_Giselle_RLMord_A_17_01"); //Na gut. Info_Mod_Giselle_RLMord_D(); }; INSTANCE Info_Mod_Giselle_Jason (C_INFO) { npc = Mod_7234_OUT_Giselle_NW; nr = 1; condition = Info_Mod_Giselle_Jason_Condition; information = Info_Mod_Giselle_Jason_Info; permanent = 0; important = 0; description = "Bist du dir sicher, dass Jason überrascht wurde?"; }; FUNC INT Info_Mod_Giselle_Jason_Condition() { if (Npc_KnowsInfo(hero, Info_Mod_Pablo_Giselle)) { return 1; }; }; FUNC VOID Info_Mod_Giselle_Jason_Info() { AI_Output(hero, self, "Info_Mod_Giselle_Jason_15_00"); //Bist du dir sicher, dass Jason überrascht wurde? AI_Output(self, hero, "Info_Mod_Giselle_Jason_17_01"); //Natürlich. Wenn ich etwas kann, dann ist es die ganze Aufmerksamkeit eines Mannes auf mich zu lenken. AI_Output(hero, self, "Info_Mod_Giselle_Jason_15_02"); //Warum hatte er dann seine Waffe gezogen, bevor er starb? AI_Output(self, hero, "Info_Mod_Giselle_Jason_17_03"); //Er hatte ...? Na ... weil ... er auf Rollenspiele stand und sein Schwert dabei gerne gezogen hatte. AI_Output(hero, self, "Info_Mod_Giselle_Jason_15_04"); //Das klingt aber nicht nach dem „Üblichem“ von dem du mir vorhin erzählt hast. AI_Output(self, hero, "Info_Mod_Giselle_Jason_17_05"); //Ich ... ah ... AI_StopProcessInfos (self); B_LogEntry (TOPIC_MOD_PAL_RL, "Giselle hat sich nun im Zimmer von Bromor versteckt. Sie scheint etwas zu verbergen. Ich sollte Pablo Bescheid geben."); B_StartOtherRoutine (self, "ZIMMER"); }; INSTANCE Info_Mod_Giselle_Galf (C_INFO) { npc = Mod_7234_OUT_Giselle_NW; nr = 1; condition = Info_Mod_Giselle_Galf_Condition; information = Info_Mod_Giselle_Galf_Info; permanent = 0; important = 1; }; FUNC INT Info_Mod_Giselle_Galf_Condition() { if (Npc_KnowsInfo(hero, Info_Mod_Pablo_GalfCall)) { return 1; }; }; FUNC VOID Info_Mod_Giselle_Galf_Info() { AI_Output(self, hero, "Info_Mod_Giselle_Galf_17_00"); //Ihr habt Galf? Lasst ihn in Ruhe, ihr Schweine! AI_Output(hero, self, "Info_Mod_Giselle_Galf_15_01"); //Du kennst ihn? AI_Output(self, hero, "Info_Mod_Giselle_Galf_17_02"); //Er ist mein Bruder ... dieser Dummkopf hätte schon lange abhauen sollen. AI_Output(hero, self, "Info_Mod_Giselle_Galf_15_03"); //Was wird hier gespielt? AI_Output(self, hero, "Info_Mod_Giselle_Galf_17_04"); //Na schön, du hast gewonnen. Jason kommt schon lange zu mir und Galf hatte die Idee, ihn zu erpressen. Also kam er letzte Nacht ins Zimmer und drohte Jason, die Miliz zu rufen. AI_Output(self, hero, "Info_Mod_Giselle_Galf_17_05"); //Ihr Idioten hättet ihn natürlich achtkantig aus eurem Verein geworfen, wenn ihr erfahren hättet was er hier treibt. Also wurde er aggressiv, nahm sein Schwert und wollte auf Galf losgehen. AI_Output(self, hero, "Info_Mod_Giselle_Galf_17_06"); //Da kam jedoch eine dunkle Gestalt zur Türe herein, streckte Jason nieder und verschwand wieder, mitsamt Jasons Uniform. Und dann ... AI_Output(hero, self, "Info_Mod_Giselle_Galf_15_07"); //Habt ihr euch diese Geschichte ausgedacht, um von euch abzulenken. AI_Output(self, hero, "Info_Mod_Giselle_Galf_17_08"); //Genau ... aber das hat ja wohl nicht so gut funktioniert, Süßer. AI_Output(hero, self, "Info_Mod_Giselle_Galf_15_09"); //Aber warum hast du auch die Sache mit der dunklen Gestalt verschwiegen? AI_Output(self, hero, "Info_Mod_Giselle_Galf_17_10"); //Weil ihr einer Hure das wirklich abkaufen würdet? Da musst du doch selbst lachen. AI_StopProcessInfos (self); B_LogEntry (TOPIC_MOD_PAL_RL, "Giselle hat mir die wahre Geschichte erzählt. Ich sollte jetzt zu Lord Andre gehen."); }; INSTANCE Info_Mod_Giselle_Satz (C_INFO) { npc = Mod_7234_OUT_Giselle_NW; nr = 1; condition = Info_Mod_Giselle_Satz_Condition; information = Info_Mod_Giselle_Satz_Info; permanent = 0; important = 1; }; FUNC INT Info_Mod_Giselle_Satz_Condition() { if (Npc_KnowsInfo(hero, Info_Mod_Andre_HeroBot)) { return 1; }; }; FUNC VOID Info_Mod_Giselle_Satz_Info() { AI_Output(self, hero, "Info_Mod_Giselle_Satz_17_00"); //Du kommst mich besuchen? Wie überaus reizend von dir. AI_Output(hero, self, "Info_Mod_Giselle_Satz_15_01"); //Ich hab eine Frage. AI_Output(self, hero, "Info_Mod_Giselle_Satz_17_02"); //Ich bin normalerweise herzlichere Begrüßungen von Männern gewohnt. Worum geht's? AI_Output(hero, self, "Info_Mod_Giselle_Satz_15_03"); //Hat die Dunkle Gestalt, die Jason getötet hat, irgendetwas gesagt? AI_Output(self, hero, "Info_Mod_Giselle_Satz_17_04"); //Schon möglich ... Info_ClearChoices (Info_Mod_Giselle_Satz); Info_AddChoice (Info_Mod_Giselle_Satz, "Was willst du?", Info_Mod_Giselle_Satz_C); Info_AddChoice (Info_Mod_Giselle_Satz, "Vielleicht würde das ein harter Schlag auf den Hinterkopf auch schaffen.", Info_Mod_Giselle_Satz_B); Info_AddChoice (Info_Mod_Giselle_Satz, "Wenn du es mir nicht sofort sagst brech ich deinem Bruder beide Beine.", Info_Mod_Giselle_Satz_A); }; FUNC VOID B_SayBotSentenceGiselle() { AI_Output(self, hero, "Info_Mod_Giselle_Satz_Say_17_00"); //Er hat etwas gesagt wie "Milizen ist es in ihrer Vorbildwirkung nicht erlaubt unlautere Taten auszuüben". B_LogEntry (TOPIC_MOD_PAL_RL, "Der Satz des Roboters, den Giselle gehört hat, ist 'Milizen ist es in ihrer Vorbildwirkung nicht erlaubt unlautere Taten auszuüben'."); Mod_PAL_HeroBot = 3; }; FUNC VOID Info_Mod_Giselle_Satz_D() { AI_Output(self, hero, "Info_Mod_Giselle_Satz_D_17_00"); //Jaja ... schon gut, ich wollte ja nicht viel. Auf deine brutale Art steh' ich überhaupt nicht, Süßer. Info_ClearChoices (Info_Mod_Giselle_Satz); B_SayBotSentenceGiselle(); }; FUNC VOID Info_Mod_Giselle_Satz_C() { AI_Output(hero, self, "Info_Mod_Giselle_Satz_C_15_00"); //Was willst du? AI_Output(self, hero, "Info_Mod_Giselle_Satz_C_17_01"); //Ich will eine Kerze ... du glaubst nicht, wie dunkel es nachts in einem Kerker ist. B_LogEntry (TOPIC_MOD_PAL_RL, "Bevor mir Giselle etwas zum Roboter verrät, soll ich ihr eine Kerze bringen."); Info_ClearChoices (Info_Mod_Giselle_Satz); }; FUNC VOID Info_Mod_Giselle_Satz_B() { AI_Output(hero, self, "Info_Mod_Giselle_Satz_B_15_00"); //Vielleicht würde das ein harter Schlag auf den Hinterkopf auch schaffen. Info_Mod_Giselle_Satz_D(); }; FUNC VOID Info_Mod_Giselle_Satz_A() { AI_Output(hero, self, "Info_Mod_Giselle_Satz_A_15_00"); //Wenn du es mir nicht sofort sagst brech ich deinem Bruder beide Beine. Info_Mod_Giselle_Satz_D(); }; INSTANCE Info_Mod_Giselle_Kerze (C_INFO) { npc = Mod_7234_OUT_Giselle_NW; nr = 1; condition = Info_Mod_Giselle_Kerze_Condition; information = Info_Mod_Giselle_Kerze_Info; permanent = 0; important = 0; description = "Ich habe hier eine Kerze für dich."; }; FUNC INT Info_Mod_Giselle_Kerze_Condition() { if (Npc_KnowsInfo(hero, Info_Mod_Giselle_Satz)) && (Mod_PAL_HeroBot == 2) && (Npc_HasItems(hero, ItMi_Kerze) >= 1) { return 1; }; }; FUNC VOID Info_Mod_Giselle_Kerze_Info() { AI_Output(hero, self, "Info_Mod_Giselle_Kerze_15_00"); //Ich habe hier eine Kerze für dich. B_GiveInvItems (hero, self, ItMi_Kerze, 1); AI_Output(self, hero, "Info_Mod_Giselle_Kerze_17_01"); //Danke, jetzt habe ich hier wenigstens ein Licht in dieser dunklen Stunde. AI_Output(hero, self, "Info_Mod_Giselle_Kerze_15_02"); //Was hat der Mörder nun gesagt? B_GivePlayerXP (250); Mod_PAL_GiselleKerze = 1; B_SayBotSentenceGiselle(); }; INSTANCE Info_Mod_Giselle_Pickpocket (C_INFO) { npc = Mod_7234_OUT_Giselle_NW; nr = 1; condition = Info_Mod_Giselle_Pickpocket_Condition; information = Info_Mod_Giselle_Pickpocket_Info; permanent = 1; important = 0; description = Pickpocket_60_Female; }; FUNC INT Info_Mod_Giselle_Pickpocket_Condition() { C_Beklauen (38, ItMi_Gold, 70); }; FUNC VOID Info_Mod_Giselle_Pickpocket_Info() { Info_ClearChoices (Info_Mod_Giselle_Pickpocket); Info_AddChoice (Info_Mod_Giselle_Pickpocket, DIALOG_BACK, Info_Mod_Giselle_Pickpocket_BACK); Info_AddChoice (Info_Mod_Giselle_Pickpocket, DIALOG_PICKPOCKET, Info_Mod_Giselle_Pickpocket_DoIt); }; FUNC VOID Info_Mod_Giselle_Pickpocket_BACK() { Info_ClearChoices (Info_Mod_Giselle_Pickpocket); }; FUNC VOID Info_Mod_Giselle_Pickpocket_DoIt() { if (B_Beklauen() == TRUE) { Info_ClearChoices (Info_Mod_Giselle_Pickpocket); } else { Info_ClearChoices (Info_Mod_Giselle_Pickpocket); Info_AddChoice (Info_Mod_Giselle_Pickpocket, DIALOG_PP_BESCHIMPFEN, Info_Mod_Giselle_Pickpocket_Beschimpfen); Info_AddChoice (Info_Mod_Giselle_Pickpocket, DIALOG_PP_BESTECHUNG, Info_Mod_Giselle_Pickpocket_Bestechung); Info_AddChoice (Info_Mod_Giselle_Pickpocket, DIALOG_PP_HERAUSREDEN, Info_Mod_Giselle_Pickpocket_Herausreden); }; }; FUNC VOID Info_Mod_Giselle_Pickpocket_Beschimpfen() { B_Say (hero, self, "$PICKPOCKET_BESCHIMPFEN"); B_Say (self, hero, "$DIRTYTHIEF"); Info_ClearChoices (Info_Mod_Giselle_Pickpocket); AI_StopProcessInfos (self); B_Attack (self, hero, AR_Theft, 1); }; FUNC VOID Info_Mod_Giselle_Pickpocket_Bestechung() { B_Say (hero, self, "$PICKPOCKET_BESTECHUNG"); var int rnd; rnd = r_max(99); if (rnd < 25) || ((rnd >= 25) && (rnd < 50) && (Npc_HasItems(hero, ItMi_Gold) < 50)) || ((rnd >= 50) && (rnd < 75) && (Npc_HasItems(hero, ItMi_Gold) < 100)) || ((rnd >= 75) && (rnd < 100) && (Npc_HasItems(hero, ItMi_Gold) < 200)) { B_Say (self, hero, "$DIRTYTHIEF"); Info_ClearChoices (Info_Mod_Giselle_Pickpocket); AI_StopProcessInfos (self); B_Attack (self, hero, AR_Theft, 1); } else { if (rnd >= 75) { B_GiveInvItems (hero, self, ItMi_Gold, 200); } else if (rnd >= 50) { B_GiveInvItems (hero, self, ItMi_Gold, 100); } else if (rnd >= 25) { B_GiveInvItems (hero, self, ItMi_Gold, 50); }; B_Say (self, hero, "$PICKPOCKET_BESTECHUNG_01"); Info_ClearChoices (Info_Mod_Giselle_Pickpocket); AI_StopProcessInfos (self); }; }; FUNC VOID Info_Mod_Giselle_Pickpocket_Herausreden() { B_Say (hero, self, "$PICKPOCKET_HERAUSREDEN"); if (r_max(99) < Mod_Verhandlungsgeschick) { B_Say (self, hero, "$PICKPOCKET_HERAUSREDEN_01"); Info_ClearChoices (Info_Mod_Giselle_Pickpocket); } else { B_Say (self, hero, "$PICKPOCKET_HERAUSREDEN_02"); }; }; INSTANCE Info_Mod_Giselle_EXIT (C_INFO) { npc = Mod_7234_OUT_Giselle_NW; nr = 1; condition = Info_Mod_Giselle_EXIT_Condition; information = Info_Mod_Giselle_EXIT_Info; permanent = 1; important = 0; description = DIALOG_ENDE; }; FUNC INT Info_Mod_Giselle_EXIT_Condition() { return 1; }; FUNC VOID Info_Mod_Giselle_EXIT_Info() { AI_StopProcessInfos (self); };
D
module io.protocol.Allocator; private import io.protocol.model; class КопияКучи : ИРазместитель { this (ИПротокол протокол); final ИПротокол протокол (); final проц сбрось (); final проц[] размести (ИПротокол.Читатель читатель, бцел байты, ИПротокол.Тип тип); } class СрезКучи : ИРазместитель { this (ИПротокол протокол, бцел width=4096, бул autoreset=нет); final ИПротокол протокол (); final проц сбрось (); final проц[] размести (ИПротокол.Читатель читатель, бцел байты, ИПротокол.Тип тип); } class СрезБуфера : ИРазместитель { this (ИПротокол протокол); final ИПротокол протокол (); final проц сбрось (); final проц[] размести (ИПротокол.Читатель читатель, бцел байты, ИПротокол.Тип тип); }
D
/* TEST_OUTPUT: --- fail_compilation/ice10938.d(12): Error: no property `opts` for type `ice10938.C` --- */ class C { this() { this.opts["opts"] = 1; } auto opDispatch(string field : "opts")() { return this.opts; // ICE -> compile time error } } void main() { }
D
a city in central Italy on the Arno a town in northeast South Carolina
D
/* area2048 source 'ENEMY-03' 'enemy03.d' 2004/04/11 jumpei isshiki */ private import std.math; private import main; private import SDL; version (USE_GLES) { private import opengles; } else { private import opengl; } private import util_sdl; private import util_pad; private import util_snd; private import bulletcommand; private import define; private import task; private import gctrl; private import effect; private import stg; private import bg; private import ship; private import enemy; private const float ENEMY_AREAMAX = (1024.0f - 22.0f); private const float MAX_SPEED = (6.0f); private const float SPEED_RATE = (60.0f); private float[] enemy_poly = [ /* BODY */ -4.0f, +4.0f, -4.0f, -4.0f, +4.0f, -4.0f, +4.0f, +4.0f, /* WING-1 */ -4.0f, +1.0f, -8.0f, +8.0f, -1.0f, +4.0f, +0.0f, +0.0f, /* WING-2 */ +4.0f, +1.0f, +8.0f, +8.0f, +1.0f, +4.0f, +0.0f, +0.0f, /* WING-3 */ -8.0f, -8.0f, -4.0f, -1.0f, +0.0f, -0.0f, -1.0f, -4.0f, /* WING-4 */ +1.0f, -4.0f, +0.0f, -0.0f, +4.0f, -1.0f, +8.0f, -8.0f, ]; void TSKenemy03(int id) { BulletCommand cmd = TskBuf[id].bullet_command; double[XY] tpos; switch(TskBuf[id].step){ case 0: TskBuf[id].tskid |= TSKID_ZAKO; TskBuf[id].px = (Rand() % 1536) - 768.0f; TskBuf[id].py = (Rand() % 1536) - 768.0f; TskBuf[id].tid = ship_id; TskBuf[id].fp_int = null; TskBuf[id].fp_draw = &TSKenemy03Draw; TskBuf[id].fp_exit = &TSKenemy03Exit; TskBuf[id].simple = &TSKeshotSimple; TskBuf[id].active = &TSKeshotActive; TskBuf[id].target = &getShipDirection; TskBuf[id].pz = 0.0f; TskBuf[id].vx = 0.0f; TskBuf[id].vy = 0.0f; TskBuf[id].cx = 16.0f; TskBuf[id].cy = 16.0f; TskBuf[id].rot = 0.0f; TskBuf[id].alpha = 0.0f; TskBuf[id].body_list.length = enemy_poly.length / 2; TskBuf[id].body_ang.length = enemy_poly.length / 2; for(int i = 0; i < TskBuf[id].body_list.length; i++){ tpos[X] = enemy_poly[i*2+0]; tpos[Y] = enemy_poly[i*2+1]; TskBuf[id].body_ang[i][X] = atan2(tpos[X], tpos[Y]); TskBuf[id].body_ang[i][Y] = atan2(tpos[X], tpos[Y]); TskBuf[id].body_ang[i][Z] = 0.0f; tpos[X] = fabs(tpos[X]); tpos[Y] = fabs(tpos[Y]); TskBuf[id].body_ang[i][W] = sqrt(pow(tpos[X],2.0) + pow(tpos[Y],2.0)); } TskBuf[id].energy = 2; TskBuf[id].bullet_length = 128; TskBuf[id].wait = 120; TskBuf[id].step++; break; case 1: TskBuf[id].wait--; TskBuf[id].alpha += 1.0f / 120.0f; if(!TskBuf[id].wait){ cmd = new BulletCommand(); TskBuf[id].bullet_command = cmd; TskBuf[id].bullet_wait = 0; TskBuf[id].fp_int = &TSKenemy03Int; TskBuf[id].alpha = 1.0f; TskBuf[id].step++; } case 2: /* 弾撃ち */ if(cmd){ if(TskBuf[id].bullet_wait){ if(cmd.isEnd()) TskBuf[id].bullet_wait--; }else{ TskBuf[id].bullet_wait = 180; cmd.set(id, BULLET_ZAKO03); } if(!cmd.isEnd()){ if(getShipLength(TskBuf[id].px, TskBuf[id].py) > TskBuf[id].bullet_length){ int flag = 0; switch(game_level){ case GLEVEL_EASY: if(getShipLength(TskBuf[id].px, TskBuf[id].py) < eshot_easy) flag = 1; break; case GLEVEL_NORMAL: if(getShipLength(TskBuf[id].px, TskBuf[id].py) < eshot_normal) flag = 1; break; case GLEVEL_HARD: flag = 1; break; default: flag = 1; break; } if(flag) cmd.run(); } } } /* 座標更新 */ if(TskBuf[id].px < ship_px){ if(TskBuf[id].vx > +0.0f) TskBuf[id].vx += 1.0f / SPEED_RATE * 1.5f; else TskBuf[id].vx += 1.0f / SPEED_RATE * 2.0f; if(TskBuf[id].vx > +MAX_SPEED) TskBuf[id].vx = +MAX_SPEED; }else{ if(TskBuf[id].vx < +0.0f) TskBuf[id].vx -= 1.0f / SPEED_RATE * 1.5f; else TskBuf[id].vx -= 1.0f / SPEED_RATE * 2.0f; if(TskBuf[id].vx < -MAX_SPEED) TskBuf[id].vx = -MAX_SPEED; } if(TskBuf[id].py < ship_py){ if(TskBuf[id].vy > +0.0f) TskBuf[id].vy += 1.0f / SPEED_RATE * 1.5f; else TskBuf[id].vy += 1.0f / SPEED_RATE * 2.0f; if(TskBuf[id].vy > +MAX_SPEED) TskBuf[id].vy = +MAX_SPEED; }else{ if(TskBuf[id].vy < +0.0f) TskBuf[id].vy -= 1.0f / SPEED_RATE * 1.5f; else TskBuf[id].vy -= 1.0f / SPEED_RATE * 2.0f; if(TskBuf[id].vy < -MAX_SPEED) TskBuf[id].vy = -MAX_SPEED; } TskBuf[id].px += TskBuf[id].vx; TskBuf[id].py += TskBuf[id].vy; if(TskBuf[id].px < -ENEMY_AREAMAX){ TskBuf[id].px = -ENEMY_AREAMAX; TskBuf[id].vx = -TskBuf[id].vx / 2; TskBuf[id].ax = +0.0f; } if(TskBuf[id].px > +ENEMY_AREAMAX){ TskBuf[id].px = +ENEMY_AREAMAX; TskBuf[id].vx = -TskBuf[id].vx / 2; TskBuf[id].ax = +0.0f; } if(TskBuf[id].py < -ENEMY_AREAMAX){ TskBuf[id].py = -ENEMY_AREAMAX; TskBuf[id].vy = -TskBuf[id].vy / 2; TskBuf[id].ay = +0.0f; } if(TskBuf[id].py > +ENEMY_AREAMAX){ TskBuf[id].py = +ENEMY_AREAMAX; TskBuf[id].vy = -TskBuf[id].vy / 2; TskBuf[id].ay = +0.0f; } TskBuf[id].rot = atan2(-TskBuf[id].vx, -TskBuf[id].vy); break; default: if(cmd){ cmd.vanish(); delete cmd; TskBuf[id].bullet_command = null; } clrTSK(id); break; } return; } void TSKenemy03Int(int id) { if(TskBuf[id].energy > 0){ playSNDse(SND_SE_EDMG); TskBuf[id].energy -= TskBuf[TskBuf[id].trg_id].energy; } if(TskBuf[id].energy <= 0 && TskBuf[id].step != -1){ shipLockOff(id); TSKenemyDest(id,50); effSetBrokenBody(id, enemy_poly, 0, 4,+0.0f,+0.0f); effSetBrokenBody(id, enemy_poly, 4, 4,+0.0f,+0.0f); effSetBrokenBody(id, enemy_poly, 8, 4,+0.0f,+0.0f); effSetBrokenBody(id, enemy_poly, 12, 4,+0.0f,+0.0f); effSetBrokenBody(id, enemy_poly, 16, 4,+0.0f,+0.0f); effSetBrokenLine(id, enemy_poly, 0, 4,+0.0f,+0.0f); effSetBrokenLine(id, enemy_poly, 4, 4,+0.0f,+0.0f); effSetBrokenLine(id, enemy_poly, 8, 4,+0.0f,+0.0f); effSetBrokenLine(id, enemy_poly, 12, 4,+0.0f,+0.0f); effSetBrokenLine(id, enemy_poly, 16, 4,+0.0f,+0.0f); }else{ effSetParticle01(id, 0.0f, 0.0f, 4); } return; } void TSKenemy03Draw(int id) { float[XYZ] pos; /* BODY */ GLfloat[4*XYZ] bodyVertices; glEnableClientState(GL_VERTEX_ARRAY); foreach(k; 0..5){ int bodyNumVertices = (k == 0)?4:4; int startOffset = (k == 0)?0:(4+4*(k-1)); foreach(j; 0..bodyNumVertices){ int i = startOffset + j; pos[X] = sin(TskBuf[id].body_ang[i][X] + TskBuf[id].rot) * getPointX(TskBuf[id].body_ang[i][W] * 3.0f, TskBuf[id].pz); pos[Y] = cos(TskBuf[id].body_ang[i][Y] + TskBuf[id].rot) * getPointY(TskBuf[id].body_ang[i][W] * 3.0f, TskBuf[id].pz); pos[Z] = TskBuf[id].body_ang[i][Z]; bodyVertices[j*XYZ + X] = pos[X] - getPointX(TskBuf[id].px - scr_pos[X], TskBuf[id].pz); bodyVertices[j*XYZ + Y] = pos[Y] - getPointY(TskBuf[id].py - scr_pos[Y], TskBuf[id].pz); bodyVertices[j*XYZ + Z] = pos[Z]; } glColor4f(0.65f,0.65f,0.25f,TskBuf[id].alpha); glVertexPointer(XYZ, GL_FLOAT, 0, cast(void *)(bodyVertices.ptr)); glDrawArrays(GL_TRIANGLE_FAN, 0, bodyNumVertices); glColor4f(1.0f,1.0f,1.0f,TskBuf[id].alpha); glVertexPointer(XYZ, GL_FLOAT, 0, cast(void *)(bodyVertices.ptr)); glDrawArrays(GL_LINE_LOOP, 0, bodyNumVertices); } glDisableClientState(GL_VERTEX_ARRAY); } void TSKenemy03Exit(int id) { TskBuf[id].body_list.length = 0; TskBuf[id].body_ang.length = 0; if(TskBuf[id].bullet_command) delete TskBuf[id].bullet_command; }
D
/Users/williamtomaz/Downloads/Projetos/SearchPostalCode/DerivedData/SearchPostalCode/Build/Intermediates.noindex/SearchPostalCode.build/Debug-iphonesimulator/SearchPostalCode.build/Objects-normal/x86_64/REST.o : /Users/williamtomaz/Downloads/Projetos/SearchPostalCode/SearchPostalCode/REST.swift /Users/williamtomaz/Downloads/Projetos/SearchPostalCode/SearchPostalCode/PostalCode.swift /Users/williamtomaz/Downloads/Projetos/SearchPostalCode/SearchPostalCode/SearchPostalCode.swift /Users/williamtomaz/Downloads/Projetos/SearchPostalCode/SearchPostalCode/AppDelegate.swift /Users/williamtomaz/Downloads/Projetos/SearchPostalCode/SearchPostalCode/Controllers/SearchViewController.swift /Users/williamtomaz/Downloads/Projetos/SearchPostalCode/SearchPostalCode/Controllers/SearchResultViewController.swift /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes /Users/williamtomaz/Downloads/Projetos/SearchPostalCode/DerivedData/SearchPostalCode/Build/Intermediates.noindex/SearchPostalCode.build/Debug-iphonesimulator/SearchPostalCode.build/Objects-normal/x86_64/REST~partial.swiftmodule : /Users/williamtomaz/Downloads/Projetos/SearchPostalCode/SearchPostalCode/REST.swift /Users/williamtomaz/Downloads/Projetos/SearchPostalCode/SearchPostalCode/PostalCode.swift /Users/williamtomaz/Downloads/Projetos/SearchPostalCode/SearchPostalCode/SearchPostalCode.swift /Users/williamtomaz/Downloads/Projetos/SearchPostalCode/SearchPostalCode/AppDelegate.swift /Users/williamtomaz/Downloads/Projetos/SearchPostalCode/SearchPostalCode/Controllers/SearchViewController.swift /Users/williamtomaz/Downloads/Projetos/SearchPostalCode/SearchPostalCode/Controllers/SearchResultViewController.swift /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes /Users/williamtomaz/Downloads/Projetos/SearchPostalCode/DerivedData/SearchPostalCode/Build/Intermediates.noindex/SearchPostalCode.build/Debug-iphonesimulator/SearchPostalCode.build/Objects-normal/x86_64/REST~partial.swiftdoc : /Users/williamtomaz/Downloads/Projetos/SearchPostalCode/SearchPostalCode/REST.swift /Users/williamtomaz/Downloads/Projetos/SearchPostalCode/SearchPostalCode/PostalCode.swift /Users/williamtomaz/Downloads/Projetos/SearchPostalCode/SearchPostalCode/SearchPostalCode.swift /Users/williamtomaz/Downloads/Projetos/SearchPostalCode/SearchPostalCode/AppDelegate.swift /Users/williamtomaz/Downloads/Projetos/SearchPostalCode/SearchPostalCode/Controllers/SearchViewController.swift /Users/williamtomaz/Downloads/Projetos/SearchPostalCode/SearchPostalCode/Controllers/SearchResultViewController.swift /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Users/williamtomaz/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
D
/* * hunt-proton: AMQP Protocol library for D programming language. * * Copyright (C) 2018-2019 HuntLabs * * Website: https://www.huntlabs.net/ * * Licensed under the Apache-2.0 License. * */ module hunt.proton.engine.impl.ssl.SslHandshakeSniffingTransportWrapper; import hunt.proton.engine.impl.HandshakeSniffingTransportWrapper; import hunt.proton.engine.impl.TransportWrapper; import hunt.proton.engine.impl.ssl.SslTransportWrapper; import std.conv:to; import hunt.Exceptions; import hunt.io.ByteBuffer; /** * SslHandshakeSniffingTransportWrapper * */ class SslHandshakeSniffingTransportWrapper : HandshakeSniffingTransportWrapper!(SslTransportWrapper, TransportWrapper) , SslTransportWrapper { this(SslTransportWrapper ssl, TransportWrapper plain) { super(ssl, plain); } public string getCipherName() { if(isSecureWrapperSelected()) { return _wrapper1.getCipherName(); } else { return null; } } public string getProtocolName() { if (isSecureWrapperSelected()) { return _wrapper1.getProtocolName(); } else { return null; } } override int pending() { return super.pending(); } override ByteBuffer head() { return super.head(); } override void pop(int bytes) { return super.pop(bytes); } override void close_head() { super.close_head(); } private bool isSecureWrapperSelected() { return _selectedTransportWrapper == _wrapper1; } override protected int bufferSize() { // minimum length for determination return 5; } override protected void makeDetermination(byte[] bytesInput) { bool isSecure = checkForSslHandshake(bytesInput); if (isSecure) { _selectedTransportWrapper = _wrapper1; } else { _selectedTransportWrapper = _wrapper2; } } // TODO perhaps the sniffer should save up the bytes from each // input call until it has sufficient bytes to make the determination // and only then pass them to the secure or plain wrapped transport? private bool checkForSslHandshake(byte[] buf) { if (buf.length >= bufferSize()) { /* * SSLv2 Client Hello format * http://www.mozilla.org/projects/security/pki/nss/ssl/draft02.html * * Bytes 0-1: RECORD-LENGTH Byte 2: MSG-CLIENT-HELLO (1) Byte 3: * CLIENT-VERSION-MSB Byte 4: CLIENT-VERSION-LSB * * Allowed versions: 2.0 - SSLv2 3.0 - SSLv3 3.1 - TLS 1.0 3.2 - TLS * 1.1 3.3 - TLS 1.2 * * The version sent in the Client-Hello is the latest version * supported by the client. NSS may send version 3.x in an SSLv2 * header for maximum compatibility. */ bool isSSL2Handshake = buf[2] == 1 && // MSG-CLIENT-HELLO ((buf[3] == 3 && buf[4] <= 3) || // SSL 3.0 & TLS 1.0-1.2 // (v3.1-3.3) (buf[3] == 2 && buf[4] == 0)); // SSL 2 /* * SSLv3/TLS Client Hello format RFC 2246 * * Byte 0: ContentType (handshake - 22) Bytes 1-2: ProtocolVersion * {major, minor} * * Allowed versions: 3.0 - SSLv3 3.1 - TLS 1.0 3.2 - TLS 1.1 3.3 - * TLS 1.2 */ bool isSSL3Handshake = buf[0] == 22 && // handshake (buf[1] == 3 && buf[2] <= 3); // SSL 3.0 & TLS 1.0-1.2 // (v3.1-3.3) return (isSSL2Handshake || isSSL3Handshake); } else { throw new IllegalArgumentException("Too few bytes (" ~ to!string(buf.length) ~ ") to make SSL/plain determination."); } } }
D
/** * Handles target-specific parameters * * In order to allow for cross compilation, when the compiler produces a binary * for a different platform than it is running on, target information needs * to be abstracted. This is done in this module, primarily through `Target`. * * Note: * While DMD itself does not support cross-compilation, GDC and LDC do. * Hence, this module is (sometimes heavily) modified by them, * and contributors should review how their changes affect them. * * See_Also: * - $(LINK2 https://wiki.osdev.org/Target_Triplet, Target Triplets) * - $(LINK2 https://github.com/ldc-developers/ldc, LDC repository) * - $(LINK2 https://github.com/D-Programming-GDC/gcc, GDC repository) * * 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/target.d, _target.d) * Documentation: https://dlang.org/phobos/dmd_target.html * Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/target.d */ module dmd.target; import dmd.globals : Param; enum CPU : ubyte { x87, mmx, sse, sse2, sse3, ssse3, sse4_1, sse4_2, avx, // AVX1 instruction set avx2, // AVX2 instruction set avx512, // AVX-512 instruction set // Special values that don't survive past the command line processing baseline, // (default) the minimum capability CPU native // the machine the compiler is being run on } Target.OS defaultTargetOS() { version (Windows) return Target.OS.Windows; else version (linux) return Target.OS.linux; else version (OSX) return Target.OS.OSX; else version (FreeBSD) return Target.OS.FreeBSD; else version (OpenBSD) return Target.OS.OpenBSD; else version (Solaris) return Target.OS.Solaris; else version (DragonFlyBSD) return Target.OS.DragonFlyBSD; else static assert(0, "unknown TARGET"); } ubyte defaultTargetOSMajor() { version (FreeBSD) { version (TARGET_FREEBSD10) return 10; else version (TARGET_FREEBSD11) return 11; else version (TARGET_FREEBSD12) return 12; else version (TARGET_FREEBSD13) return 13; else return 0; } else return 0; } //////////////////////////////////////////////////////////////////////////////// /** * Describes a back-end target. At present it is incomplete, but in the future * it should grow to contain most or all target machine and target O/S specific * information. * * In many cases, calls to sizeof() can't be used directly for getting data type * sizes since cross compiling is supported and would end up using the host * sizes rather than the target sizes. */ extern (C++) struct Target { import dmd.dscope : Scope; import dmd.expression : Expression; import dmd.func : FuncDeclaration; import dmd.globals : Loc; import dmd.astenums : LINK, TY; import dmd.mtype : Type, TypeFunction, TypeTuple; import dmd.root.ctfloat : real_t; import dmd.statement : Statement; import dmd.tokens : EXP; /// Bit decoding of the Target.OS enum OS : ubyte { /* These are mutually exclusive; one and only one is set. * Match spelling and casing of corresponding version identifiers */ none = 0, linux = 1, Windows = 2, OSX = 4, OpenBSD = 8, FreeBSD = 0x10, Solaris = 0x20, DragonFlyBSD = 0x40, // Combination masks all = linux | Windows | OSX | OpenBSD | FreeBSD | Solaris | DragonFlyBSD, Posix = linux | OSX | OpenBSD | FreeBSD | Solaris | DragonFlyBSD, } extern(D) enum ObjectFormat : ubyte { elf, macho, coff, omf } OS os = defaultTargetOS(); ubyte osMajor = defaultTargetOSMajor(); // D ABI ubyte ptrsize; /// size of a pointer in bytes ubyte realsize; /// size a real consumes in memory ubyte realpad; /// padding added to the CPU real size to bring it up to realsize ubyte realalignsize; /// alignment for reals ubyte classinfosize; /// size of `ClassInfo` ulong maxStaticDataSize; /// maximum size of static data /// C ABI TargetC c; /// C++ ABI TargetCPP cpp; /// Objective-C ABI TargetObjC objc; /// Architecture name const(char)[] architectureName; CPU cpu = CPU.baseline; // CPU instruction set to target bool is64bit = (size_t.sizeof == 8); // generate 64 bit code for x86_64; true by default for 64 bit dmd bool isLP64; // pointers are 64 bits // Environmental const(char)[] obj_ext; /// extension for object files const(char)[] lib_ext; /// extension for static library files const(char)[] dll_ext; /// extension for dynamic library files bool run_noext; /// allow -run sources without extensions bool omfobj = false; // for Win32: write OMF object files instead of MsCoff /** * Values representing all properties for floating point types */ extern (C++) struct FPTypeProperties(T) { real_t max; /// largest representable value that's not infinity real_t min_normal; /// smallest representable normalized value that's not 0 real_t nan; /// NaN value real_t infinity; /// infinity value real_t epsilon; /// smallest increment to the value 1 long dig; /// number of decimal digits of precision long mant_dig; /// number of bits in mantissa long max_exp; /// maximum int value such that 2$(SUPERSCRIPT `max_exp-1`) is representable long min_exp; /// minimum int value such that 2$(SUPERSCRIPT `min_exp-1`) is representable as a normalized value long max_10_exp; /// maximum int value such that 10$(SUPERSCRIPT `max_10_exp` is representable) long min_10_exp; /// minimum int value such that 10$(SUPERSCRIPT `min_10_exp`) is representable as a normalized value extern (D) void initialize() { max = T.max; min_normal = T.min_normal; nan = T.nan; infinity = T.infinity; epsilon = T.epsilon; dig = T.dig; mant_dig = T.mant_dig; max_exp = T.max_exp; min_exp = T.min_exp; max_10_exp = T.max_10_exp; min_10_exp = T.min_10_exp; } } FPTypeProperties!float FloatProperties; /// FPTypeProperties!double DoubleProperties; /// FPTypeProperties!real_t RealProperties; /// private Type tvalist; // cached lazy result of va_listType() private const(Param)* params; // cached reference to global.params /** * Initialize the Target */ extern (C++) void _init(ref const Param params) { // is64bit, omfobj and cpu are initialized in parseCommandLine this.params = &params; FloatProperties.initialize(); DoubleProperties.initialize(); RealProperties.initialize(); isLP64 = is64bit; // These have default values for 32 bit code, they get // adjusted for 64 bit code. ptrsize = 4; classinfosize = 0x4C; // 76 /* gcc uses int.max for 32 bit compilations, and long.max for 64 bit ones. * Set to int.max for both, because the rest of the compiler cannot handle * 2^64-1 without some pervasive rework. The trouble is that much of the * front and back end uses 32 bit ints for sizes and offsets. Since C++ * silently truncates 64 bit ints to 32, finding all these dependencies will be a problem. */ maxStaticDataSize = int.max; if (isLP64) { ptrsize = 8; classinfosize = 0x98; // 152 } if (os & (Target.OS.linux | Target.OS.FreeBSD | Target.OS.OpenBSD | Target.OS.DragonFlyBSD | Target.OS.Solaris)) { realsize = 12; realpad = 2; realalignsize = 4; } else if (os == Target.OS.OSX) { realsize = 16; realpad = 6; realalignsize = 16; } else if (os == Target.OS.Windows) { realsize = 10; realpad = 0; realalignsize = 2; if (ptrsize == 4) { /* Optlink cannot deal with individual data chunks * larger than 16Mb */ maxStaticDataSize = 0x100_0000; // 16Mb } } else assert(0); if (is64bit) { if (os & (Target.OS.linux | Target.OS.FreeBSD | Target.OS.OpenBSD | Target.OS.DragonFlyBSD | Target.OS.Solaris)) { realsize = 16; realpad = 6; realalignsize = 16; } } c.initialize(params, this); cpp.initialize(params, this); objc.initialize(params, this); if (is64bit) architectureName = "X86_64"; else architectureName = "X86"; if (os == Target.OS.Windows) { obj_ext = "obj"; lib_ext = "lib"; dll_ext = "dll"; run_noext = false; } else if (os & (Target.OS.linux | Target.OS.FreeBSD | Target.OS.OpenBSD | Target.OS.DragonFlyBSD | Target.OS.Solaris | Target.OS.OSX)) { obj_ext = "o"; lib_ext = "a"; if (os == Target.OS.OSX) dll_ext = "dylib"; else dll_ext = "so"; run_noext = true; } else assert(0, "unknown environment"); } /** Determine the object format to be used */ extern(D) Target.ObjectFormat objectFormat() { if (os == Target.OS.OSX) return Target.ObjectFormat.macho; else if (os & Target.OS.Posix) return Target.ObjectFormat.elf; else if (os == Target.OS.Windows) return omfobj ? Target.ObjectFormat.omf : Target.ObjectFormat.coff; else assert(0, "unkown object format"); } /** * Determine the instruction set to be used */ void setCPU() { if(!isXmmSupported()) { cpu = CPU.x87; // cannot support other instruction sets return; } switch (cpu) { case CPU.baseline: cpu = CPU.sse2; break; case CPU.native: { import core.cpuid; cpu = core.cpuid.avx2 ? CPU.avx2 : core.cpuid.avx ? CPU.avx : CPU.sse2; break; } default: break; } } /** * Deinitializes the global state of the compiler. * * This can be used to restore the state set by `_init` to its original * state. */ void deinitialize() { this = this.init; } /** * Requested target memory alignment size of the given type. * Params: * type = type to inspect * Returns: * alignment in bytes */ extern (C++) uint alignsize(Type type) { assert(type.isTypeBasic()); switch (type.ty) { case TY.Tfloat80: case TY.Timaginary80: case TY.Tcomplex80: return target.realalignsize; case TY.Tcomplex32: if (os & Target.OS.Posix) return 4; break; case TY.Tint64: case TY.Tuns64: case TY.Tfloat64: case TY.Timaginary64: case TY.Tcomplex64: if (os & Target.OS.Posix) return is64bit ? 8 : 4; break; default: break; } return cast(uint)type.size(Loc.initial); } /** * Requested target field alignment size of the given type. * Params: * type = type to inspect * Returns: * alignment in bytes */ extern (C++) uint fieldalign(Type type) { const size = type.alignsize(); if ((is64bit || os == Target.OS.OSX) && (size == 16 || size == 32)) return size; return (8 < size) ? 8 : size; } /** * Type for the `va_list` type for the target; e.g., required for `_argptr` * declarations. * NOTE: For Posix/x86_64 this returns the type which will really * be used for passing an argument of type va_list. * Returns: * `Type` that represents `va_list`. */ extern (C++) Type va_listType(const ref Loc loc, Scope* sc) { if (tvalist) return tvalist; if (os == Target.OS.Windows) { tvalist = Type.tchar.pointerTo(); } else if (os & Target.OS.Posix) { if (is64bit) { import dmd.identifier : Identifier; import dmd.mtype : TypeIdentifier; import dmd.typesem : typeSemantic; tvalist = new TypeIdentifier(Loc.initial, Identifier.idPool("__va_list_tag")).pointerTo(); tvalist = typeSemantic(tvalist, loc, sc); } else { tvalist = Type.tchar.pointerTo(); } } else { assert(0); } return tvalist; } /** * Checks whether the target supports a vector type. * Params: * sz = vector type size in bytes * type = vector element type * Returns: * 0 vector type is supported, * 1 vector type is not supported on the target at all * 2 vector element type is not supported * 3 vector size is not supported */ extern (C++) int isVectorTypeSupported(int sz, Type type) { if (!isXmmSupported()) return 1; // not supported switch (type.ty) { case TY.Tvoid: case TY.Tint8: case TY.Tuns8: case TY.Tint16: case TY.Tuns16: case TY.Tint32: case TY.Tuns32: case TY.Tfloat32: case TY.Tint64: case TY.Tuns64: case TY.Tfloat64: break; default: return 2; // wrong base type } // Whether a vector is really supported depends on the CPU being targeted. if (sz == 16) { switch (type.ty) { case TY.Tint32: case TY.Tuns32: case TY.Tfloat32: if (cpu < CPU.sse) return 3; // no SSE vector support break; case TY.Tvoid: case TY.Tint8: case TY.Tuns8: case TY.Tint16: case TY.Tuns16: case TY.Tint64: case TY.Tuns64: case TY.Tfloat64: if (cpu < CPU.sse2) return 3; // no SSE2 vector support break; default: assert(0); } } else if (sz == 32) { if (cpu < CPU.avx) return 3; // no AVX vector support } else return 3; // wrong size return 0; } /** * Checks whether the target supports the given operation for vectors. * Params: * type = target type of operation * op = the unary or binary op being done on the `type` * t2 = type of second operand if `op` is a binary operation * Returns: * true if the operation is supported or type is not a vector */ extern (C++) bool isVectorOpSupported(Type type, EXP op, Type t2 = null) { import dmd.hdrgen : EXPtoString; auto tvec = type.isTypeVector(); if (tvec is null) return true; // not a vector op const vecsize = cast(int)tvec.basetype.size(); const elemty = cast(int)tvec.elementType().ty; // Only operations on these sizes are supported (see isVectorTypeSupported) if (vecsize != 16 && vecsize != 32) return false; bool supported = false; switch (op) { case EXP.uadd: // Expression is a no-op, supported everywhere. supported = tvec.isscalar(); break; case EXP.negate: if (vecsize == 16) { // float[4] negate needs SSE support ({V}SUBPS) if (elemty == TY.Tfloat32 && cpu >= CPU.sse) supported = true; // double[2] negate needs SSE2 support ({V}SUBPD) else if (elemty == TY.Tfloat64 && cpu >= CPU.sse2) supported = true; // (u)byte[16]/short[8]/int[4]/long[2] negate needs SSE2 support ({V}PSUB[BWDQ]) else if (tvec.isintegral() && cpu >= CPU.sse2) supported = true; } else if (vecsize == 32) { // float[8]/double[4] negate needs AVX support (VSUBP[SD]) if (tvec.isfloating() && cpu >= CPU.avx) supported = true; // (u)byte[32]/short[16]/int[8]/long[4] negate needs AVX2 support (VPSUB[BWDQ]) else if (tvec.isintegral() && cpu >= CPU.avx2) supported = true; } break; case EXP.identity, EXP.notIdentity: supported = false; break; case EXP.lessThan, EXP.greaterThan, EXP.lessOrEqual, EXP.greaterOrEqual: case EXP.equal: case EXP.notEqual: supported = true; break; case EXP.leftShift, EXP.leftShiftAssign, EXP.rightShift, EXP.rightShiftAssign, EXP.unsignedRightShift, EXP.unsignedRightShiftAssign: supported = false; break; case EXP.add, EXP.addAssign, EXP.min, EXP.minAssign: if (vecsize == 16) { // float[4] add/sub needs SSE support ({V}ADDPS, {V}SUBPS) if (elemty == TY.Tfloat32 && cpu >= CPU.sse) supported = true; // double[2] add/sub needs SSE2 support ({V}ADDPD, {V}SUBPD) else if (elemty == TY.Tfloat64 && cpu >= CPU.sse2) supported = true; // (u)byte[16]/short[8]/int[4]/long[2] add/sub needs SSE2 support ({V}PADD[BWDQ], {V}PSUB[BWDQ]) else if (tvec.isintegral() && cpu >= CPU.sse2) supported = true; } else if (vecsize == 32) { // float[8]/double[4] add/sub needs AVX support (VADDP[SD], VSUBP[SD]) if (tvec.isfloating() && cpu >= CPU.avx) supported = true; // (u)byte[32]/short[16]/int[8]/long[4] add/sub needs AVX2 support (VPADD[BWDQ], VPSUB[BWDQ]) else if (tvec.isintegral() && cpu >= CPU.avx2) supported = true; } break; case EXP.mul, EXP.mulAssign: if (vecsize == 16) { // float[4] multiply needs SSE support ({V}MULPS) if (elemty == TY.Tfloat32 && cpu >= CPU.sse) supported = true; // double[2] multiply needs SSE2 support ({V}MULPD) else if (elemty == TY.Tfloat64 && cpu >= CPU.sse2) supported = true; // (u)short[8] multiply needs SSE2 support ({V}PMULLW) else if ((elemty == TY.Tint16 || elemty == TY.Tuns16) && cpu >= CPU.sse2) supported = true; // (u)int[4] multiply needs SSE4.1 support ({V}PMULLD) else if ((elemty == TY.Tint32 || elemty == TY.Tuns32) && cpu >= CPU.sse4_1) supported = true; } else if (vecsize == 32) { // float[8]/double[4] multiply needs AVX support (VMULP[SD]) if (tvec.isfloating() && cpu >= CPU.avx) supported = true; // (u)short[16] multiply needs AVX2 support (VPMULLW) else if ((elemty == TY.Tint16 || elemty == TY.Tuns16) && cpu >= CPU.avx2) supported = true; // (u)int[8] multiply needs AVX2 support (VPMULLD) else if ((elemty == TY.Tint32 || elemty == TY.Tuns32) && cpu >= CPU.avx2) supported = true; } break; case EXP.div, EXP.divAssign: if (vecsize == 16) { // float[4] divide needs SSE support ({V}DIVPS) if (elemty == TY.Tfloat32 && cpu >= CPU.sse) supported = true; // double[2] divide needs SSE2 support ({V}DIVPD) else if (elemty == TY.Tfloat64 && cpu >= CPU.sse2) supported = true; } else if (vecsize == 32) { // float[8]/double[4] multiply needs AVX support (VDIVP[SD]) if (tvec.isfloating() && cpu >= CPU.avx) supported = true; } break; case EXP.mod, EXP.modAssign: supported = false; break; case EXP.and, EXP.andAssign, EXP.or, EXP.orAssign, EXP.xor, EXP.xorAssign: // (u)byte[16]/short[8]/int[4]/long[2] bitwise ops needs SSE2 support ({V}PAND, {V}POR, {V}PXOR) if (vecsize == 16 && tvec.isintegral() && cpu >= CPU.sse2) supported = true; // (u)byte[32]/short[16]/int[8]/long[4] bitwise ops needs AVX2 support (VPAND, VPOR, VPXOR) else if (vecsize == 32 && tvec.isintegral() && cpu >= CPU.avx2) supported = true; break; case EXP.not: supported = false; break; case EXP.tilde: // (u)byte[16]/short[8]/int[4]/long[2] logical exclusive needs SSE2 support ({V}PXOR) if (vecsize == 16 && tvec.isintegral() && cpu >= CPU.sse2) supported = true; // (u)byte[32]/short[16]/int[8]/long[4] logical exclusive needs AVX2 support (VPXOR) else if (vecsize == 32 && tvec.isintegral() && cpu >= CPU.avx2) supported = true; break; case EXP.pow, EXP.powAssign: supported = false; break; default: // import std.stdio : stderr, writeln; // stderr.writeln(op); assert(0, "unhandled op " ~ EXPtoString(cast(EXP)op)); } return supported; } /** * Default system linkage for the target. * Returns: * `LINK` to use for `extern(System)` */ extern (C++) LINK systemLinkage() { return os == Target.OS.Windows ? LINK.windows : LINK.c; } /** * Describes how an argument type is passed to a function on target. * Params: * t = type to break down * Returns: * tuple of types if type is passed in one or more registers * empty tuple if type is always passed on the stack * null if the type is a `void` or argtypes aren't supported by the target */ extern (C++) TypeTuple toArgTypes(Type t) { import dmd.argtypes_x86 : toArgTypes_x86; import dmd.argtypes_sysv_x64 : toArgTypes_sysv_x64; if (is64bit) { // no argTypes for Win64 yet return isPOSIX ? toArgTypes_sysv_x64(t) : null; } return toArgTypes_x86(t); } /** * Determine return style of function - whether in registers or * through a hidden pointer to the caller's stack. * Params: * tf = function type to check * needsThis = true if the function type is for a non-static member function * Returns: * true if return value from function is on the stack */ extern (C++) bool isReturnOnStack(TypeFunction tf, bool needsThis) { import dmd.id : Id; import dmd.argtypes_sysv_x64 : toArgTypes_sysv_x64; if (tf.isref) { //printf(" ref false\n"); return false; // returns a pointer } Type tn = tf.next; if (auto te = tn.isTypeEnum()) { if (te.sym.isSpecial()) { // Special enums with target-specific return style if (te.sym.ident == Id.__c_complex_float) tn = Type.tcomplex32.castMod(tn.mod); else if (te.sym.ident == Id.__c_complex_double) tn = Type.tcomplex64.castMod(tn.mod); else if (te.sym.ident == Id.__c_complex_real) tn = Type.tcomplex80.castMod(tn.mod); } } tn = tn.toBasetype(); //printf("tn = %s\n", tn.toChars()); const sz = tn.size(); Type tns = tn; if (os == Target.OS.Windows && is64bit) { // https://msdn.microsoft.com/en-us/library/7572ztz4%28v=vs.100%29.aspx if (tns.ty == TY.Tcomplex32) return true; if (tns.isscalar()) return false; tns = tns.baseElemOf(); if (auto ts = tns.isTypeStruct()) { auto sd = ts.sym; if (tf.linkage == LINK.cpp && needsThis) return true; if (!sd.isPOD() || sz > 8) return true; if (sd.fields.length == 0) return true; } if (sz <= 16 && !(sz & (sz - 1))) return false; return true; } else if (os == Target.OS.Windows) { Type tb = tns.baseElemOf(); if (tb.ty == TY.Tstruct) { if (tf.linkage == LINK.cpp && needsThis) return true; } } else if (is64bit && isPOSIX) { TypeTuple tt = toArgTypes_sysv_x64(tn); if (!tt) return false; // void else return !tt.arguments.length; } Lagain: if (tns.ty == TY.Tsarray) { tns = tns.baseElemOf(); if (tns.ty != TY.Tstruct) { L2: if (os == Target.OS.linux && tf.linkage != LINK.d && !is64bit) { // 32 bit C/C++ structs always on stack } else { switch (sz) { case 1: case 2: case 4: case 8: //printf(" sarray false\n"); return false; // return small structs in regs // (not 3 byte structs!) default: break; } } //printf(" sarray true\n"); return true; } } if (auto ts = tns.isTypeStruct()) { auto sd = ts.sym; if (os == Target.OS.linux && tf.linkage != LINK.d && !is64bit) { //printf(" 2 true\n"); return true; // 32 bit C/C++ structs always on stack } if (os == Target.OS.Windows && tf.linkage == LINK.cpp && !is64bit && sd.isPOD() && sd.ctor) { // win32 returns otherwise POD structs with ctors via memory return true; } if (sd.numArgTypes() == 1) { tns = sd.argType(0); if (tns.ty != TY.Tstruct) goto L2; goto Lagain; } else if (is64bit && sd.numArgTypes() == 0) return true; else if (sd.isPOD()) { switch (sz) { case 1: case 2: case 4: case 8: //printf(" 3 false\n"); return false; // return small structs in regs // (not 3 byte structs!) case 16: if (os & Target.OS.Posix && is64bit) return false; break; default: break; } } //printf(" 3 true\n"); return true; } else if (os & Target.OS.Posix && (tf.linkage == LINK.c || tf.linkage == LINK.cpp) && tns.iscomplex()) { if (tns.ty == TY.Tcomplex32) return false; // in EDX:EAX, not ST1:ST0 else return true; } else if (os == Target.OS.Windows && !is64bit && tf.linkage == LINK.cpp && tf.isfloating()) { /* See DMC++ function exp2_retmethod() * https://github.com/DigitalMars/Compiler/blob/master/dm/src/dmc/dexp2.d#L149 */ return true; } else { //assert(sz <= 16); //printf(" 4 false\n"); return false; } } /** * Decides whether an `in` parameter of the specified POD type is to be * passed by reference or by value. To be used with `-preview=in` only! * Params: * t = type of the `in` parameter, must be a POD * Returns: * `true` if the `in` parameter is to be passed by reference */ extern (C++) bool preferPassByRef(Type t) { const size = t.size(); if (is64bit) { if (os == Target.OS.Windows) { // Win64 special case: by-value for slices and delegates due to // high number of usages in druntime/Phobos (compiled without // -preview=in but supposed to link against -preview=in code) const ty = t.toBasetype().ty; if (ty == TY.Tarray || ty == TY.Tdelegate) return false; // If size is larger than 8 or not a power-of-2, the Win64 ABI // would require a hidden reference anyway. return size > 8 || (size > 0 && (size & (size - 1)) != 0); } else // SysV x86_64 ABI { // Prefer a ref if the POD cannot be passed in registers, i.e., // would be passed on the stack, *and* the size is > 16. if (size <= 16) return false; TypeTuple getArgTypes() { import dmd.astenums : Sizeok; if (auto ts = t.toBasetype().isTypeStruct()) { auto sd = ts.sym; assert(sd.sizeok == Sizeok.done); return sd.argTypes; } return toArgTypes(t); } TypeTuple argTypes = getArgTypes(); assert(argTypes !is null, "size == 0 should already be handled"); return argTypes.arguments.length == 0; // cannot be passed in registers } } else // 32-bit x86 ABI { // Prefer a ref if the size is > 2 machine words. return size > 8; } } // this guarantees `getTargetInfo` and `allTargetInfos` remain in sync private enum TargetInfoKeys { cppRuntimeLibrary, cppStd, floatAbi, objectFormat, } /** * Get targetInfo by key * Params: * name = name of targetInfo to get * loc = location to use for error messages * Returns: * Expression for the requested targetInfo */ extern (C++) Expression getTargetInfo(const(char)* name, const ref Loc loc) { import dmd.dmdparams : driverParams; import dmd.expression : IntegerExp, StringExp; import dmd.root.string : toDString; StringExp stringExp(const(char)[] sval) { return new StringExp(loc, sval); } switch (name.toDString) with (TargetInfoKeys) { case objectFormat.stringof: if (os == Target.OS.Windows) return stringExp(omfobj ? "omf" : "coff" ); else if (os == Target.OS.OSX) return stringExp("macho"); else return stringExp("elf"); case floatAbi.stringof: return stringExp("hard"); case cppRuntimeLibrary.stringof: if (os == Target.OS.Windows) { if (omfobj) return stringExp("snn"); return stringExp(driverParams.mscrtlib); } return stringExp(""); case cppStd.stringof: return new IntegerExp(params.cplusplus); default: return null; } } /** * Params: * tf = type of function being called * Returns: `true` if the callee invokes destructors for arguments. */ extern (C++) bool isCalleeDestroyingArgs(TypeFunction tf) { // On windows, the callee destroys arguments always regardless of function linkage, // and regardless of whether the caller or callee cleans the stack. return os == Target.OS.Windows || // C++ on non-Windows platforms has the caller destroying the arguments tf.linkage != LINK.cpp; } /** * Returns true if the implementation for object monitors is always defined * in the D runtime library (rt/monitor_.d). * Params: * fd = function with `synchronized` storage class. * fbody = entire function body of `fd` * Returns: * `false` if the target backend handles synchronizing monitors. */ extern (C++) bool libraryObjectMonitors(FuncDeclaration fd, Statement fbody) { if (!is64bit && os == Target.OS.Windows && !fd.isStatic() && !fbody.usesEH() && !params.trace) { /* The back end uses the "jmonitor" hack for syncing; * no need to do the sync in the library. */ return false; } return true; } /** * Returns true if the target supports `pragma(linkerDirective)`. * Returns: * `false` if the target does not support `pragma(linkerDirective)`. */ extern (C++) bool supportsLinkerDirective() const { return os == Target.OS.Windows && !omfobj; } //////////////////////////////////////////////////////////////////////////// /* All functions after this point are extern (D), as they are only relevant * for targets of DMD, and should not be used in front-end code. */ /****************** * Returns: * true if xmm usage is supported */ extern (D) bool isXmmSupported() { return is64bit || os == Target.OS.OSX; } /** * Returns: * true if generating code for POSIX */ extern (D) @property bool isPOSIX() scope const nothrow @nogc out(result) { assert(result || os == Target.OS.Windows); } do { return (os & Target.OS.Posix) != 0; } } //////////////////////////////////////////////////////////////////////////////// /** * Functions and variables specific to interfacing with extern(C) ABI. */ struct TargetC { enum Runtime : ubyte { Unspecified, Bionic, DigitalMars, Glibc, Microsoft, Musl, Newlib, UClibc, WASI, } enum BitFieldStyle : ubyte { Unspecified, DM, /// Digital Mars 32 bit C compiler MS, /// Microsoft 32 and 64 bit C compilers /// https://docs.microsoft.com/en-us/cpp/c-language/c-bit-fields?view=msvc-160 /// https://docs.microsoft.com/en-us/cpp/cpp/cpp-bit-fields?view=msvc-160 Gcc_Clang, /// gcc and clang } bool crtDestructorsSupported = true; /// Not all platforms support crt_destructor ubyte boolsize; /// size of a C `_Bool` type ubyte shortsize; /// size of a C `short` or `unsigned short` type ubyte intsize; /// size of a C `int` or `unsigned int` type ubyte longsize; /// size of a C `long` or `unsigned long` type ubyte long_longsize; /// size of a C `long long` or `unsigned long long` type ubyte long_doublesize; /// size of a C `long double` ubyte wchar_tsize; /// size of a C `wchar_t` type Runtime runtime; /// vendor of the C runtime to link against BitFieldStyle bitFieldStyle; /// different C compilers do it differently extern (D) void initialize(ref const Param params, ref const Target target) { const os = target.os; boolsize = 1; shortsize = 2; intsize = 4; long_longsize = 8; if (os & (Target.OS.linux | Target.OS.FreeBSD | Target.OS.OpenBSD | Target.OS.DragonFlyBSD | Target.OS.Solaris)) longsize = 4; else if (os == Target.OS.OSX) longsize = 4; else if (os == Target.OS.Windows) longsize = 4; else assert(0); if (target.is64bit) { if (os & (Target.OS.linux | Target.OS.FreeBSD | Target.OS.OpenBSD | Target.OS.DragonFlyBSD | Target.OS.Solaris)) longsize = 8; else if (os == Target.OS.OSX) longsize = 8; } if (target.is64bit && os == Target.OS.Windows) long_doublesize = 8; else long_doublesize = target.realsize; if (os == Target.OS.Windows) wchar_tsize = 2; else wchar_tsize = 4; if (os == Target.OS.Windows) runtime = target.omfobj ? Runtime.DigitalMars : Runtime.Microsoft; else if (os == Target.OS.linux) { // Note: This is overridden later by `-target=<triple>` if supplied. // For now, choose the sensible default. version (CRuntime_Musl) runtime = Runtime.Musl; else runtime = Runtime.Glibc; } if (os == Target.OS.Windows) bitFieldStyle = target.omfobj ? BitFieldStyle.DM : BitFieldStyle.MS; else if (os & (Target.OS.linux | Target.OS.FreeBSD | Target.OS.OSX | Target.OS.OpenBSD | Target.OS.DragonFlyBSD | Target.OS.Solaris)) bitFieldStyle = BitFieldStyle.Gcc_Clang; else assert(0); /* MacOS Monterey (12) does not support C runtime destructors. */ if (os == Target.OS.OSX) { crtDestructorsSupported = false; } } } //////////////////////////////////////////////////////////////////////////////// /** * Functions and variables specific to interface with extern(C++) ABI. */ struct TargetCPP { import dmd.dsymbol : Dsymbol; import dmd.dclass : ClassDeclaration; import dmd.func : FuncDeclaration; import dmd.mtype : Type; enum Runtime : ubyte { Unspecified, Clang, DigitalMars, Gcc, Microsoft, Sun } bool reverseOverloads; /// set if overloaded functions are grouped and in reverse order (such as in dmc and cl) bool exceptions; /// set if catching C++ exceptions is supported bool twoDtorInVtable; /// target C++ ABI puts deleting and non-deleting destructor into vtable bool splitVBasetable; /// set if C++ ABI uses separate tables for virtual functions and virtual bases bool wrapDtorInExternD; /// set if C++ dtors require a D wrapper to be callable from runtime Runtime runtime; /// vendor of the C++ runtime to link against extern (D) void initialize(ref const Param params, ref const Target target) { const os = target.os; if (os & (Target.OS.linux | Target.OS.FreeBSD | Target.OS.OpenBSD | Target.OS.DragonFlyBSD | Target.OS.Solaris)) twoDtorInVtable = true; else if (os == Target.OS.OSX) twoDtorInVtable = true; else if (os == Target.OS.Windows) { reverseOverloads = true; splitVBasetable = !target.omfobj; } else assert(0); exceptions = (os & Target.OS.Posix) != 0; if (os == Target.OS.Windows) runtime = target.omfobj ? Runtime.DigitalMars : Runtime.Microsoft; else if (os & (Target.OS.linux | Target.OS.DragonFlyBSD)) runtime = Runtime.Gcc; else if (os & (Target.OS.OSX | Target.OS.FreeBSD | Target.OS.OpenBSD)) runtime = Runtime.Clang; else if (os == Target.OS.Solaris) runtime = Runtime.Gcc; else assert(0); // C++ and D ABI incompatible on all (?) x86 32-bit platforms wrapDtorInExternD = !target.is64bit; } /** * Mangle the given symbol for C++ ABI. * Params: * s = declaration with C++ linkage * Returns: * string mangling of symbol */ extern (C++) const(char)* toMangle(Dsymbol s) { import dmd.cppmangle : toCppMangleItanium; import dmd.cppmanglewin : toCppMangleDMC, toCppMangleMSVC; if (target.os & (Target.OS.linux | Target.OS.OSX | Target.OS.FreeBSD | Target.OS.OpenBSD | Target.OS.Solaris | Target.OS.DragonFlyBSD)) return toCppMangleItanium(s); if (target.os == Target.OS.Windows) { if (target.omfobj) return toCppMangleDMC(s); else return toCppMangleMSVC(s); } else assert(0, "fix this"); } /** * Get RTTI mangling of the given class declaration for C++ ABI. * Params: * cd = class with C++ linkage * Returns: * string mangling of C++ typeinfo */ extern (C++) const(char)* typeInfoMangle(ClassDeclaration cd) { import dmd.cppmangle : cppTypeInfoMangleItanium; import dmd.cppmanglewin : cppTypeInfoMangleDMC, cppTypeInfoMangleMSVC; if (target.os & (Target.OS.linux | Target.OS.OSX | Target.OS.FreeBSD | Target.OS.OpenBSD | Target.OS.Solaris | Target.OS.DragonFlyBSD)) return cppTypeInfoMangleItanium(cd); if (target.os == Target.OS.Windows) { if (target.omfobj) return cppTypeInfoMangleDMC(cd); else return cppTypeInfoMangleMSVC(cd); } else assert(0, "fix this"); } /** * Get mangle name of a this-adjusting thunk to the given function * declaration for C++ ABI. * Params: * fd = function with C++ linkage * offset = call offset to the vptr * Returns: * string mangling of C++ thunk, or null if unhandled */ extern (C++) const(char)* thunkMangle(FuncDeclaration fd, int offset) { return null; } /** * Gets vendor-specific type mangling for C++ ABI. * Params: * t = type to inspect * Returns: * string if type is mangled specially on target * null if unhandled */ extern (C++) const(char)* typeMangle(Type t) { return null; } /** * Get the type that will really be used for passing the given argument * to an `extern(C++)` function, or `null` if unhandled. * Params: * t = type to be passed. * Returns: * `Type` to use for type `t`. */ extern (C++) Type parameterType(Type t) { return null; } /** * Checks whether type is a vendor-specific fundamental type. * Params: * t = type to inspect * isFundamental = where to store result * Returns: * true if isFundamental was set by function */ extern (C++) bool fundamentalType(const Type t, ref bool isFundamental) { return false; } /** * Get the starting offset position for fields of an `extern(C++)` class * that is derived from the given base class. * Params: * baseClass = base class with C++ linkage * Returns: * starting offset to lay out derived class fields */ extern (C++) uint derivedClassOffset(ClassDeclaration baseClass) { // MSVC adds padding between base and derived fields if required. if (target.os == Target.OS.Windows) return (baseClass.structsize + baseClass.alignsize - 1) & ~(baseClass.alignsize - 1); else return baseClass.structsize; } } //////////////////////////////////////////////////////////////////////////////// /** * Functions and variables specific to interface with extern(Objective-C) ABI. */ struct TargetObjC { bool supported; /// set if compiler can interface with Objective-C extern (D) void initialize(ref const Param params, ref const Target target) { if (target.os == Target.OS.OSX && target.is64bit) supported = true; } } //////////////////////////////////////////////////////////////////////////////// extern (C++) __gshared Target target;
D
have a daydream experience while sleeping conceived of or imagined or hoped for
D
module Windows.UI.Xaml.Printing; import dwinrt; @uuid("d4b57970-57a0-4209-847c-c093b54bc729") interface AddPagesEventHandler : IUnknown { extern(Windows): HRESULT abi_Invoke(IInspectable sender, Windows.UI.Xaml.Printing.AddPagesEventArgs e); } @uuid("ccb3e9ed-9c11-4e50-ab49-e98086bbfdef") interface GetPreviewPageEventHandler : IUnknown { extern(Windows): HRESULT abi_Invoke(IInspectable sender, Windows.UI.Xaml.Printing.GetPreviewPageEventArgs e); } @uuid("0cc05b61-811b-4a32-9965-13eb78dbb01b") interface PaginateEventHandler : IUnknown { extern(Windows): HRESULT abi_Invoke(IInspectable sender, Windows.UI.Xaml.Printing.PaginateEventArgs e); } @uuid("e2e52be5-056c-4420-9795-cb3526ce0c20") @WinrtFactory("Windows.UI.Xaml.Printing.AddPagesEventArgs") interface IAddPagesEventArgs : IInspectable { extern(Windows): HRESULT get_PrintTaskOptions(Windows.Graphics.Printing.PrintTaskOptions* return_value); } @uuid("a43d703d-dea9-4df6-a7ed-35049cd485c7") @WinrtFactory("Windows.UI.Xaml.Printing.GetPreviewPageEventArgs") interface IGetPreviewPageEventArgs : IInspectable { extern(Windows): HRESULT get_PageNumber(INT32* return_value); } @uuid("ed945fd6-79ab-42b7-930a-3d6e09011d21") @WinrtFactory("Windows.UI.Xaml.Printing.PaginateEventArgs") interface IPaginateEventArgs : IInspectable { extern(Windows): HRESULT get_PrintTaskOptions(Windows.Graphics.Printing.PrintTaskOptions* return_value); HRESULT get_CurrentPreviewPageNumber(INT32* return_value); } @uuid("e44327c3-a999-485b-b1d8-72dc517821e6") @WinrtFactory("Windows.UI.Xaml.Printing.PrintDocument") interface IPrintDocument : IInspectable { extern(Windows): HRESULT get_DocumentSource(Windows.Graphics.Printing.IPrintDocumentSource* return_value); HRESULT add_Paginate(Windows.UI.Xaml.Printing.PaginateEventHandler value, EventRegistrationToken* return_token); HRESULT remove_Paginate(EventRegistrationToken token); HRESULT add_GetPreviewPage(Windows.UI.Xaml.Printing.GetPreviewPageEventHandler value, EventRegistrationToken* return_token); HRESULT remove_GetPreviewPage(EventRegistrationToken token); HRESULT add_AddPages(Windows.UI.Xaml.Printing.AddPagesEventHandler value, EventRegistrationToken* return_token); HRESULT remove_AddPages(EventRegistrationToken token); HRESULT abi_AddPage(Windows.UI.Xaml.UIElement pageVisual); HRESULT abi_AddPagesComplete(); HRESULT abi_SetPreviewPageCount(INT32 count, Windows.UI.Xaml.Printing.PreviewPageCountType type); HRESULT abi_SetPreviewPage(INT32 pageNumber, Windows.UI.Xaml.UIElement pageVisual); HRESULT abi_InvalidatePreview(); } @uuid("fb87b18f-2606-4a2f-99d4-a7cdbc35d7c7") @WinrtFactory("Windows.UI.Xaml.Printing.PrintDocument") interface IPrintDocumentFactory : IInspectable { extern(Windows): HRESULT abi_CreateInstance(IInspectable outer, IInspectable* out_inner, Windows.UI.Xaml.Printing.PrintDocument* return_instance); } @uuid("fd970a3c-b152-49e0-a6bd-6aa6477e43c7") @WinrtFactory("Windows.UI.Xaml.Printing.PrintDocument") interface IPrintDocumentStatics : IInspectable { extern(Windows): HRESULT get_DocumentSourceProperty(Windows.UI.Xaml.DependencyProperty* return_value); } interface AddPagesEventArgs : Windows.UI.Xaml.Printing.IAddPagesEventArgs { extern(Windows): final Windows.Graphics.Printing.PrintTaskOptions PrintTaskOptions() { Windows.Graphics.Printing.PrintTaskOptions _ret; Debug.OK((cast(Windows.UI.Xaml.Printing.IAddPagesEventArgs)this.asInterface(uuid("e2e52be5-056c-4420-9795-cb3526ce0c20"))).get_PrintTaskOptions(&_ret)); return _ret; } static AddPagesEventArgs New() { IInspectable ret; Debug.OK(activationFactory!(AddPagesEventArgs).abi_ActivateInstance(&ret)); return cast(AddPagesEventArgs) ret; } } interface GetPreviewPageEventArgs : Windows.UI.Xaml.Printing.IGetPreviewPageEventArgs { extern(Windows): final INT32 PageNumber() { INT32 _ret; Debug.OK((cast(Windows.UI.Xaml.Printing.IGetPreviewPageEventArgs)this.asInterface(uuid("a43d703d-dea9-4df6-a7ed-35049cd485c7"))).get_PageNumber(&_ret)); return _ret; } static GetPreviewPageEventArgs New() { IInspectable ret; Debug.OK(activationFactory!(GetPreviewPageEventArgs).abi_ActivateInstance(&ret)); return cast(GetPreviewPageEventArgs) ret; } } interface PaginateEventArgs : Windows.UI.Xaml.Printing.IPaginateEventArgs { extern(Windows): final Windows.Graphics.Printing.PrintTaskOptions PrintTaskOptions() { Windows.Graphics.Printing.PrintTaskOptions _ret; Debug.OK((cast(Windows.UI.Xaml.Printing.IPaginateEventArgs)this.asInterface(uuid("ed945fd6-79ab-42b7-930a-3d6e09011d21"))).get_PrintTaskOptions(&_ret)); return _ret; } final INT32 CurrentPreviewPageNumber() { INT32 _ret; Debug.OK((cast(Windows.UI.Xaml.Printing.IPaginateEventArgs)this.asInterface(uuid("ed945fd6-79ab-42b7-930a-3d6e09011d21"))).get_CurrentPreviewPageNumber(&_ret)); return _ret; } static PaginateEventArgs New() { IInspectable ret; Debug.OK(activationFactory!(PaginateEventArgs).abi_ActivateInstance(&ret)); return cast(PaginateEventArgs) ret; } } interface PrintDocument : Windows.UI.Xaml.DependencyObject, Windows.UI.Xaml.Printing.IPrintDocument { extern(Windows): final Windows.Graphics.Printing.IPrintDocumentSource DocumentSource() { Windows.Graphics.Printing.IPrintDocumentSource _ret; Debug.OK((cast(Windows.UI.Xaml.Printing.IPrintDocument)this.asInterface(uuid("e44327c3-a999-485b-b1d8-72dc517821e6"))).get_DocumentSource(&_ret)); return _ret; } final EventRegistrationToken OnPaginate(void delegate(IInspectable, Windows.UI.Xaml.Printing.PaginateEventArgs) fn) { EventRegistrationToken tok; Debug.OK((cast(Windows.UI.Xaml.Printing.IPrintDocument)this.asInterface(uuid("e44327c3-a999-485b-b1d8-72dc517821e6"))).add_Paginate(event!(Windows.UI.Xaml.Printing.PaginateEventHandler, IInspectable, Windows.UI.Xaml.Printing.PaginateEventArgs)(fn), &tok)); return tok; } final void removePaginate(EventRegistrationToken token) { Debug.OK((cast(Windows.UI.Xaml.Printing.IPrintDocument)this.asInterface(uuid("e44327c3-a999-485b-b1d8-72dc517821e6"))).remove_Paginate(token)); } final EventRegistrationToken OnGetPreviewPage(void delegate(IInspectable, Windows.UI.Xaml.Printing.GetPreviewPageEventArgs) fn) { EventRegistrationToken tok; Debug.OK((cast(Windows.UI.Xaml.Printing.IPrintDocument)this.asInterface(uuid("e44327c3-a999-485b-b1d8-72dc517821e6"))).add_GetPreviewPage(event!(Windows.UI.Xaml.Printing.GetPreviewPageEventHandler, IInspectable, Windows.UI.Xaml.Printing.GetPreviewPageEventArgs)(fn), &tok)); return tok; } final void removeGetPreviewPage(EventRegistrationToken token) { Debug.OK((cast(Windows.UI.Xaml.Printing.IPrintDocument)this.asInterface(uuid("e44327c3-a999-485b-b1d8-72dc517821e6"))).remove_GetPreviewPage(token)); } final EventRegistrationToken OnAddPages(void delegate(IInspectable, Windows.UI.Xaml.Printing.AddPagesEventArgs) fn) { EventRegistrationToken tok; Debug.OK((cast(Windows.UI.Xaml.Printing.IPrintDocument)this.asInterface(uuid("e44327c3-a999-485b-b1d8-72dc517821e6"))).add_AddPages(event!(Windows.UI.Xaml.Printing.AddPagesEventHandler, IInspectable, Windows.UI.Xaml.Printing.AddPagesEventArgs)(fn), &tok)); return tok; } final void removeAddPages(EventRegistrationToken token) { Debug.OK((cast(Windows.UI.Xaml.Printing.IPrintDocument)this.asInterface(uuid("e44327c3-a999-485b-b1d8-72dc517821e6"))).remove_AddPages(token)); } final void AddPage(Windows.UI.Xaml.UIElement pageVisual) { Debug.OK((cast(Windows.UI.Xaml.Printing.IPrintDocument)this.asInterface(uuid("e44327c3-a999-485b-b1d8-72dc517821e6"))).abi_AddPage(pageVisual)); } final void AddPagesComplete() { Debug.OK((cast(Windows.UI.Xaml.Printing.IPrintDocument)this.asInterface(uuid("e44327c3-a999-485b-b1d8-72dc517821e6"))).abi_AddPagesComplete()); } final void SetPreviewPageCount(INT32 count, Windows.UI.Xaml.Printing.PreviewPageCountType type) { Debug.OK((cast(Windows.UI.Xaml.Printing.IPrintDocument)this.asInterface(uuid("e44327c3-a999-485b-b1d8-72dc517821e6"))).abi_SetPreviewPageCount(count, type)); } final void SetPreviewPage(INT32 pageNumber, Windows.UI.Xaml.UIElement pageVisual) { Debug.OK((cast(Windows.UI.Xaml.Printing.IPrintDocument)this.asInterface(uuid("e44327c3-a999-485b-b1d8-72dc517821e6"))).abi_SetPreviewPage(pageNumber, pageVisual)); } final void InvalidatePreview() { Debug.OK((cast(Windows.UI.Xaml.Printing.IPrintDocument)this.asInterface(uuid("e44327c3-a999-485b-b1d8-72dc517821e6"))).abi_InvalidatePreview()); } private static Windows.UI.Xaml.Printing.IPrintDocumentStatics _staticInstance; public static Windows.UI.Xaml.Printing.IPrintDocumentStatics staticInstance() { if (_staticInstance is null) _staticInstance = factory!(Windows.UI.Xaml.Printing.IPrintDocumentStatics); return _staticInstance; } static Windows.UI.Xaml.DependencyProperty DocumentSourceProperty() { Windows.UI.Xaml.DependencyProperty _ret; Debug.OK(staticInstance.get_DocumentSourceProperty(&_ret)); return _ret; } static PrintDocument New() { IInspectable outer, inner; PrintDocument ret; Debug.OK(activationFactory!(PrintDocument, Windows.UI.Xaml.Printing.IPrintDocumentFactory).abi_CreateInstance(outer, &inner, &ret)); return ret; } } @makable!(PrintDocument, PrintDocument, Windows.UI.Xaml.Printing.IPrintDocumentFactory) class PrintDocumentT(Base) : AgileObject!Base, PrintDocument { override HRESULT QueryInterface(const(IID)* riid, void** ppv) { auto ret = super.QueryInterface(riid, ppv); if (ret == E_NOINTERFACE) return m_inner.QueryInterface(riid, ppv); return ret; } override HRESULT get_DocumentSource(Windows.Graphics.Printing.IPrintDocumentSource* return_value) { return (cast(Windows.UI.Xaml.Printing.IPrintDocument)m_inner.asInterface(uuid("e44327c3-a999-485b-b1d8-72dc517821e6"))).get_DocumentSource(return_value); } override HRESULT add_Paginate(Windows.UI.Xaml.Printing.PaginateEventHandler value, EventRegistrationToken* return_token) { return (cast(Windows.UI.Xaml.Printing.IPrintDocument)m_inner.asInterface(uuid("e44327c3-a999-485b-b1d8-72dc517821e6"))).add_Paginate(value, return_token); } override HRESULT remove_Paginate(EventRegistrationToken token) { return (cast(Windows.UI.Xaml.Printing.IPrintDocument)m_inner.asInterface(uuid("e44327c3-a999-485b-b1d8-72dc517821e6"))).remove_Paginate(token); } override HRESULT add_GetPreviewPage(Windows.UI.Xaml.Printing.GetPreviewPageEventHandler value, EventRegistrationToken* return_token) { return (cast(Windows.UI.Xaml.Printing.IPrintDocument)m_inner.asInterface(uuid("e44327c3-a999-485b-b1d8-72dc517821e6"))).add_GetPreviewPage(value, return_token); } override HRESULT remove_GetPreviewPage(EventRegistrationToken token) { return (cast(Windows.UI.Xaml.Printing.IPrintDocument)m_inner.asInterface(uuid("e44327c3-a999-485b-b1d8-72dc517821e6"))).remove_GetPreviewPage(token); } override HRESULT add_AddPages(Windows.UI.Xaml.Printing.AddPagesEventHandler value, EventRegistrationToken* return_token) { return (cast(Windows.UI.Xaml.Printing.IPrintDocument)m_inner.asInterface(uuid("e44327c3-a999-485b-b1d8-72dc517821e6"))).add_AddPages(value, return_token); } override HRESULT remove_AddPages(EventRegistrationToken token) { return (cast(Windows.UI.Xaml.Printing.IPrintDocument)m_inner.asInterface(uuid("e44327c3-a999-485b-b1d8-72dc517821e6"))).remove_AddPages(token); } override HRESULT abi_AddPage(Windows.UI.Xaml.UIElement pageVisual) { return (cast(Windows.UI.Xaml.Printing.IPrintDocument)m_inner.asInterface(uuid("e44327c3-a999-485b-b1d8-72dc517821e6"))).abi_AddPage(pageVisual); } override HRESULT abi_AddPagesComplete() { return (cast(Windows.UI.Xaml.Printing.IPrintDocument)m_inner.asInterface(uuid("e44327c3-a999-485b-b1d8-72dc517821e6"))).abi_AddPagesComplete(); } override HRESULT abi_SetPreviewPageCount(INT32 count, Windows.UI.Xaml.Printing.PreviewPageCountType type) { return (cast(Windows.UI.Xaml.Printing.IPrintDocument)m_inner.asInterface(uuid("e44327c3-a999-485b-b1d8-72dc517821e6"))).abi_SetPreviewPageCount(count, type); } override HRESULT abi_SetPreviewPage(INT32 pageNumber, Windows.UI.Xaml.UIElement pageVisual) { return (cast(Windows.UI.Xaml.Printing.IPrintDocument)m_inner.asInterface(uuid("e44327c3-a999-485b-b1d8-72dc517821e6"))).abi_SetPreviewPage(pageNumber, pageVisual); } override HRESULT abi_InvalidatePreview() { return (cast(Windows.UI.Xaml.Printing.IPrintDocument)m_inner.asInterface(uuid("e44327c3-a999-485b-b1d8-72dc517821e6"))).abi_InvalidatePreview(); } override HRESULT abi_GetValue(Windows.UI.Xaml.DependencyProperty dp, IInspectable* return_returnValue) { return (cast(Windows.UI.Xaml.IDependencyObject)m_inner.asInterface(uuid("5c526665-f60e-4912-af59-5fe0680f089d"))).abi_GetValue(dp, return_returnValue); } override HRESULT abi_SetValue(Windows.UI.Xaml.DependencyProperty dp, IInspectable value) { return (cast(Windows.UI.Xaml.IDependencyObject)m_inner.asInterface(uuid("5c526665-f60e-4912-af59-5fe0680f089d"))).abi_SetValue(dp, value); } override HRESULT abi_ClearValue(Windows.UI.Xaml.DependencyProperty dp) { return (cast(Windows.UI.Xaml.IDependencyObject)m_inner.asInterface(uuid("5c526665-f60e-4912-af59-5fe0680f089d"))).abi_ClearValue(dp); } override HRESULT abi_ReadLocalValue(Windows.UI.Xaml.DependencyProperty dp, IInspectable* return_returnValue) { return (cast(Windows.UI.Xaml.IDependencyObject)m_inner.asInterface(uuid("5c526665-f60e-4912-af59-5fe0680f089d"))).abi_ReadLocalValue(dp, return_returnValue); } override HRESULT abi_GetAnimationBaseValue(Windows.UI.Xaml.DependencyProperty dp, IInspectable* return_returnValue) { return (cast(Windows.UI.Xaml.IDependencyObject)m_inner.asInterface(uuid("5c526665-f60e-4912-af59-5fe0680f089d"))).abi_GetAnimationBaseValue(dp, return_returnValue); } override HRESULT get_Dispatcher(Windows.UI.Core.CoreDispatcher* return_value) { return (cast(Windows.UI.Xaml.IDependencyObject)m_inner.asInterface(uuid("5c526665-f60e-4912-af59-5fe0680f089d"))).get_Dispatcher(return_value); } override HRESULT abi_RegisterPropertyChangedCallback(Windows.UI.Xaml.DependencyProperty dp, Windows.UI.Xaml.DependencyPropertyChangedCallback callback, INT64* return_returnValue) { return (cast(Windows.UI.Xaml.IDependencyObject2)m_inner.asInterface(uuid("29fed85d-3d22-43a1-add0-17027c08b212"))).abi_RegisterPropertyChangedCallback(dp, callback, return_returnValue); } override HRESULT abi_UnregisterPropertyChangedCallback(Windows.UI.Xaml.DependencyProperty dp, INT64 token) { return (cast(Windows.UI.Xaml.IDependencyObject2)m_inner.asInterface(uuid("29fed85d-3d22-43a1-add0-17027c08b212"))).abi_UnregisterPropertyChangedCallback(dp, token); } this() {} IInspectable m_inner; } enum PreviewPageCountType { Final = 0, Intermediate = 1 }
D
# FIXED F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/source/F2837xD_PieCtrl.c F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_device.h F2837xD_PieCtrl.obj: S:/ti/ccsv8/tools/compiler/ti-cgt-c2000_18.1.1.LTS/include/assert.h F2837xD_PieCtrl.obj: S:/ti/ccsv8/tools/compiler/ti-cgt-c2000_18.1.1.LTS/include/_ti_config.h F2837xD_PieCtrl.obj: S:/ti/ccsv8/tools/compiler/ti-cgt-c2000_18.1.1.LTS/include/linkage.h F2837xD_PieCtrl.obj: S:/ti/ccsv8/tools/compiler/ti-cgt-c2000_18.1.1.LTS/include/stdarg.h F2837xD_PieCtrl.obj: S:/ti/ccsv8/tools/compiler/ti-cgt-c2000_18.1.1.LTS/include/stdbool.h F2837xD_PieCtrl.obj: S:/ti/ccsv8/tools/compiler/ti-cgt-c2000_18.1.1.LTS/include/stddef.h F2837xD_PieCtrl.obj: S:/ti/ccsv8/tools/compiler/ti-cgt-c2000_18.1.1.LTS/include/stdint.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_adc.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_analogsubsys.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_cla.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_cmpss.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_cputimer.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_dac.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_dcsm.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_dma.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_ecap.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_emif.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_epwm.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_epwm_xbar.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_eqep.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_flash.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_gpio.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_i2c.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_input_xbar.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_ipc.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_mcbsp.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_memconfig.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_nmiintrupt.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_output_xbar.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_piectrl.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_pievect.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_sci.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_sdfm.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_spi.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_sysctrl.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_upp.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_xbar.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_xint.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_can.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_Examples.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_GlobalPrototypes.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_cputimervars.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_Cla_defines.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_EPwm_defines.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_Adc_defines.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_Emif_defines.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_Gpio_defines.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_I2c_defines.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_Ipc_defines.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_Pie_defines.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_Dma_defines.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_SysCtrl_defines.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_Upp_defines.h F2837xD_PieCtrl.obj: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_defaultisr.h S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/source/F2837xD_PieCtrl.c: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_device.h: S:/ti/ccsv8/tools/compiler/ti-cgt-c2000_18.1.1.LTS/include/assert.h: S:/ti/ccsv8/tools/compiler/ti-cgt-c2000_18.1.1.LTS/include/_ti_config.h: S:/ti/ccsv8/tools/compiler/ti-cgt-c2000_18.1.1.LTS/include/linkage.h: S:/ti/ccsv8/tools/compiler/ti-cgt-c2000_18.1.1.LTS/include/stdarg.h: S:/ti/ccsv8/tools/compiler/ti-cgt-c2000_18.1.1.LTS/include/stdbool.h: S:/ti/ccsv8/tools/compiler/ti-cgt-c2000_18.1.1.LTS/include/stddef.h: S:/ti/ccsv8/tools/compiler/ti-cgt-c2000_18.1.1.LTS/include/stdint.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_adc.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_analogsubsys.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_cla.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_cmpss.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_cputimer.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_dac.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_dcsm.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_dma.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_ecap.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_emif.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_epwm.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_epwm_xbar.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_eqep.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_flash.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_gpio.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_i2c.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_input_xbar.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_ipc.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_mcbsp.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_memconfig.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_nmiintrupt.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_output_xbar.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_piectrl.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_pievect.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_sci.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_sdfm.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_spi.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_sysctrl.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_upp.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_xbar.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_xint.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/headers/include/F2837xD_can.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_Examples.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_GlobalPrototypes.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_cputimervars.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_Cla_defines.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_EPwm_defines.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_Adc_defines.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_Emif_defines.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_Gpio_defines.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_I2c_defines.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_Ipc_defines.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_Pie_defines.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_Dma_defines.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_SysCtrl_defines.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_Upp_defines.h: S:/ti/c2000/C2000Ware_1_00_04_00/device_support/f2837xd/common/include/F2837xD_defaultisr.h:
D
/Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/NIO.build/TypeAssistedChannelHandler.swift.o : /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/IO.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/NonBlockingFileIO.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/IOData.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Codec.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Thread.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Embedded.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Selectable.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/FileHandle.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ChannelPipeline.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/AddressedEnvelope.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ByteBuffer-core.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/EventLoopFuture.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/PriorityQueue.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Channel.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/DeadChannel.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/SocketChannel.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/BaseSocketChannel.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/MulticastChannel.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/BlockingIOThreadPool.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/System.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/FileRegion.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ContiguousCollection.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ChannelOption.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Heap.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Bootstrap.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/EventLoop.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/SocketOptionProvider.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/CircularBuffer.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/MarkedCircularBuffer.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/PendingWritesManager.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/PendingDatagramWritesManager.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ChannelInvoker.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ChannelHandler.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/TypeAssistedChannelHandler.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Resolver.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/GetaddrinfoResolver.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/CompositeError.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/RecvByteBufferAllocator.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Selector.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/FileDescriptor.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Interfaces.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Utilities.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/IntegerTypes.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/SocketAddresses.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/HappyEyeballs.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ChannelHandlers.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ByteBuffer-views.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/LinuxCPUSet.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Socket.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/BaseSocket.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ServerSocket.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ByteBuffer-int.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ByteBuffer-aux.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Linux.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/NIOAny.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio-zlib-support/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/Darwin.apinotes /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/NIO.build/TypeAssistedChannelHandler~partial.swiftmodule : /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/IO.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/NonBlockingFileIO.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/IOData.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Codec.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Thread.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Embedded.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Selectable.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/FileHandle.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ChannelPipeline.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/AddressedEnvelope.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ByteBuffer-core.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/EventLoopFuture.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/PriorityQueue.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Channel.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/DeadChannel.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/SocketChannel.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/BaseSocketChannel.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/MulticastChannel.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/BlockingIOThreadPool.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/System.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/FileRegion.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ContiguousCollection.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ChannelOption.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Heap.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Bootstrap.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/EventLoop.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/SocketOptionProvider.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/CircularBuffer.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/MarkedCircularBuffer.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/PendingWritesManager.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/PendingDatagramWritesManager.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ChannelInvoker.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ChannelHandler.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/TypeAssistedChannelHandler.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Resolver.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/GetaddrinfoResolver.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/CompositeError.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/RecvByteBufferAllocator.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Selector.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/FileDescriptor.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Interfaces.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Utilities.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/IntegerTypes.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/SocketAddresses.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/HappyEyeballs.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ChannelHandlers.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ByteBuffer-views.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/LinuxCPUSet.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Socket.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/BaseSocket.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ServerSocket.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ByteBuffer-int.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ByteBuffer-aux.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Linux.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/NIOAny.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio-zlib-support/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/Darwin.apinotes /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/NIO.build/TypeAssistedChannelHandler~partial.swiftdoc : /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/IO.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/NonBlockingFileIO.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/IOData.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Codec.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Thread.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Embedded.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Selectable.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/FileHandle.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ChannelPipeline.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/AddressedEnvelope.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ByteBuffer-core.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/EventLoopFuture.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/PriorityQueue.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Channel.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/DeadChannel.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/SocketChannel.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/BaseSocketChannel.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/MulticastChannel.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/BlockingIOThreadPool.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/System.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/FileRegion.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ContiguousCollection.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ChannelOption.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Heap.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Bootstrap.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/EventLoop.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/SocketOptionProvider.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/CircularBuffer.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/MarkedCircularBuffer.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/PendingWritesManager.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/PendingDatagramWritesManager.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ChannelInvoker.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ChannelHandler.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/TypeAssistedChannelHandler.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Resolver.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/GetaddrinfoResolver.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/CompositeError.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/RecvByteBufferAllocator.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Selector.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/FileDescriptor.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Interfaces.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Utilities.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/IntegerTypes.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/SocketAddresses.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/HappyEyeballs.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ChannelHandlers.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ByteBuffer-views.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/LinuxCPUSet.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Socket.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/BaseSocket.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ServerSocket.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ByteBuffer-int.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/ByteBuffer-aux.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/Linux.swift /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/NIO/NIOAny.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/nathanwhite/Desktop/vaporserver/simpleVapor/.build/checkouts/swift-nio-zlib-support/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/Darwin.apinotes
D
a vehicle carrying many passengers the topology of a network whose components are connected by a busbar an electrical conductor that makes a common connection between several circuits a car that is old and unreliable touch with the lips or press the lips (against someone's mouth or other body part) as an expression of love, greeting, etc.
D
/* [The "BSD licence"] Copyright (c) 2005-2008 Terence Parr All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ module antlr.runtime.tree.CommonTree; import antlr.runtime.tree.Tree; import antlr.runtime.tree.BaseTree; import antlr.runtime.Token; import antlr.runtime.CharStream; import antlr.runtime.RuntimeException; /** A tree node that is wrapper for a Token object. After 3.0 release * while building tree rewrite stuff, it became clear that computing * parent and child index is very difficult and cumbersome. Better to * spend the space in every tree node. If you don't want these extra * fields, it's easy to cut them out in your own BaseTree subclass. */ class CommonTree(char_t) : BaseTree!(char_t) { alias CommonTree!(char_t) CommonTreeT; /** What token indexes bracket all tokens associated with this node * and below? */ protected int startIndex=-1, stopIndex=-1; /** Who is the parent node of this node; if null, implies node is root */ public CommonTreeT parent; /** What index is this node in the child list? Range: 0..n-1 */ public int childIndex = -1; this() { /* Empty */ } this(CommonTreeT node) { //super(node); this.token = node.token; this.startIndex = node.startIndex; this.stopIndex = node.stopIndex; } this(TokenT t) { this.token = t; } public TokenT getToken() { return token; } public TreeT dupNode() { return new CommonTreeT(this); } override bool isNil() const { return token is null; } override int Type() const { if ( token is null ) { return TokenT.INVALID_TOKEN_TYPE; } return token.Type; } override int Type(const int type) { return token.Type(type); } @property immutable(char_t)[] Text() const { if ( token is null ) { return ""; } return token.Text(); } override int Line() const { if ( token is null || token.Line == 0 ) { if ( getChildCount()>0 ) { return getChild(0).Line(); } return 0; } return token.Line; } override int CharPositionInLine() const { if ( token is null || token.CharPositionInLine()==-1 ) { if ( getChildCount()>0 ) { return getChild(0).CharPositionInLine(); } return 0; } return token.CharPositionInLine(); } public int TokenStartIndex() { if ( startIndex==-1 && token !is null ) { return token.TokenIndex(); } return startIndex; } public int TokenStartIndex(int index) { return startIndex = index; } public int TokenStopIndex() { if ( stopIndex==-1 && token !is null ) { return token.TokenIndex(); } return stopIndex; } public int TokenStopIndex(int index) { return stopIndex = index; } override int getChildIndex() { return childIndex; } override TreeT getParent() { return parent; } override void setParent(TreeT t) { this.parent = cast(CommonTreeT)t; } override void setChildIndex(int index) { this.childIndex = index; } override immutable(char_t)[] toStringT() const { if ( isNil() ) { return "nil"; } if ( Type()==TokenT.INVALID_TOKEN_TYPE ) { return "<errornode>"; } if ( token is null ) { return ""; } return token.Text(); } }
D
module speech.audio.exception; class AudioException : Exception { this(string msg, string file = __FILE__, uint line = __LINE__, Exception next = null) { super(msg, file, line, next); } }
D
module android.java.android.telephony.VisualVoicemailSmsFilterSettings_Builder_d_interface; import arsd.jni : IJavaObjectImplementation, JavaPackageId, JavaName, IJavaObject, ImportExportImpl, JavaInterfaceMembers; static import arsd.jni; import import0 = android.java.android.telephony.VisualVoicemailSmsFilterSettings_d_interface; import import1 = android.java.android.telephony.VisualVoicemailSmsFilterSettings_Builder_d_interface; import import2 = android.java.java.util.List_d_interface; import import3 = android.java.java.lang.Class_d_interface; @JavaName("VisualVoicemailSmsFilterSettings$Builder") final class VisualVoicemailSmsFilterSettings_Builder : IJavaObject { static immutable string[] _d_canCastTo = [ ]; @Import this(arsd.jni.Default); @Import import0.VisualVoicemailSmsFilterSettings build(); @Import import1.VisualVoicemailSmsFilterSettings_Builder setClientPrefix(string); @Import import1.VisualVoicemailSmsFilterSettings_Builder setOriginatingNumbers(import2.List); @Import import1.VisualVoicemailSmsFilterSettings_Builder setDestinationPort(int); @Import import3.Class getClass(); @Import int hashCode(); @Import bool equals(IJavaObject); @Import @JavaName("toString") string toString_(); override string toString() { return arsd.jni.javaObjectToString(this); } @Import void notify(); @Import void notifyAll(); @Import void wait(long); @Import void wait(long, int); @Import void wait(); mixin IJavaObjectImplementation!(false); public static immutable string _javaParameterString = "Landroid/telephony/VisualVoicemailSmsFilterSettings$Builder;"; }
D
//*************************** // Swampshark Prototype //*************************** PROTOTYPE Mst_Default_Swampshark(C_Npc) { //----- Monster ---- name = "Wąż błotny"; guild = GIL_SWAMPSHARK; aivar[AIV_MM_REAL_ID] = ID_SWAMPSHARK; level = 24; //----- Attribute ---- attribute [ATR_STRENGTH] = 120; attribute [ATR_DEXTERITY] = 120; attribute [ATR_HITPOINTS_MAX] = 240; attribute [ATR_HITPOINTS] = 240; attribute [ATR_MANA_MAX] = 0; attribute [ATR_MANA] = 0; //----- Protections ---- protection [PROT_BLUNT] = 100; protection [PROT_EDGE] = 100; protection [PROT_POINT] = 100; protection [PROT_FIRE] = 100; protection [PROT_FLY] = 100; protection [PROT_MAGIC] = 0; //----- Damage Types ---- damagetype = DAM_EDGE; // damage [DAM_INDEX_BLUNT] = 0; // damage [DAM_INDEX_EDGE] = 0; // damage [DAM_INDEX_POINT] = 0; // damage [DAM_INDEX_FIRE] = 0; // damage [DAM_INDEX_FLY] = 0; // damage [DAM_INDEX_MAGIC] = 0; //----- Kampf-Taktik ---- fight_tactic = FAI_SWAMPSHARK; //----- Sense & Ranges ---- senses = SENSE_HEAR | SENSE_SEE | SENSE_SMELL; senses_range = PERC_DIST_MONSTER_ACTIVE_MAX; aivar[AIV_MM_ThreatenBeforeAttack] = TRUE; aivar[AIV_MM_FollowTime] = FOLLOWTIME_MEDIUM; aivar[AIV_MM_FollowInWater] = TRUE; //----- Daily Routine ---- start_aistate = ZS_MM_AllScheduler; aivar[AIV_MM_RoamStart] = OnlyRoutine; }; //*************** // Visuals //*************** func void B_SetVisuals_Swampshark() { Mdl_SetVisual (self, "Swampshark.mds"); // Body-Mesh Body-Tex Skin-Color Head-MMS Head-Tex Teeth-Tex ARMOR Mdl_SetVisualBody (self, "Swa_Body", DEFAULT, DEFAULT, "", DEFAULT, DEFAULT, -1); }; /************************************************************************* ** Swampshark ** *************************************************************************/ INSTANCE Swampshark (Mst_Default_Swampshark) { B_SetVisuals_Swampshark(); Npc_SetToFistMode(self); }; /************************************************************************* ** Swampshark Mission Logan Sumpfhaijagd (MIS_HlpLogan) ** *************************************************************************/ INSTANCE MIS_Addon_Swampshark_01 (Mst_Default_Swampshark) { level = 20; //----- Attribute ---- attribute [ATR_STRENGTH] = 100; attribute [ATR_HITPOINTS_MAX] = 200; attribute [ATR_HITPOINTS] = 200; //----- Protections ---- protection [PROT_BLUNT] = 100; protection [PROT_EDGE] = 100; protection [PROT_POINT] = 100; B_SetVisuals_Swampshark(); Npc_SetToFistMode(self); }; INSTANCE MIS_Addon_Swampshark_02 (Mst_Default_Swampshark) { level = 20; //----- Attribute ---- attribute [ATR_STRENGTH] = 100; attribute [ATR_HITPOINTS_MAX] = 200; attribute [ATR_HITPOINTS] = 200; //----- Protections ---- protection [PROT_BLUNT] = 100; protection [PROT_EDGE] = 100; protection [PROT_POINT] = 100; B_SetVisuals_Swampshark(); Npc_SetToFistMode(self); }; INSTANCE MIS_Addon_Swampshark_03 (Mst_Default_Swampshark) { level = 20; //----- Attribute ---- attribute [ATR_STRENGTH] = 100; attribute [ATR_HITPOINTS_MAX] = 200; attribute [ATR_HITPOINTS] = 200; //----- Protections ---- protection [PROT_BLUNT] = 100; protection [PROT_EDGE] = 100; protection [PROT_POINT] = 100; B_SetVisuals_Swampshark(); Npc_SetToFistMode(self); }; INSTANCE MIS_Addon_Swampshark_Lou (Mst_Default_Swampshark) { B_SetVisuals_Swampshark(); Npc_SetToFistMode(self); CreateInvItems (self, ITKE_Addon_Tavern_01,1); };
D
#!/usr/bin/env rdmd /** DMD builder Usage: ./build.d dmd detab, tolf, install targets - require the D Language Tools (detab.exe, tolf.exe) https://github.com/dlang/tools. zip target - requires Info-ZIP or equivalent (zip32.exe) http://www.info-zip.org/Zip.html#Downloads */ version(CoreDdoc) {} else: import std.algorithm, std.conv, std.datetime, std.exception, std.file, std.format, std.functional, std.getopt, std.path, std.process, std.range, std.stdio, std.string, std.traits; import std.parallelism : TaskPool, totalCPUs; const thisBuildScript = __FILE_FULL_PATH__.buildNormalizedPath; const srcDir = thisBuildScript.dirName; const dmdRepo = srcDir.dirName; shared bool verbose; // output verbose logging shared bool force; // always build everything (ignores timestamp checking) shared bool dryRun; /// dont execute targets, just print command to be executed __gshared string[string] env; __gshared string[][string] flags; __gshared typeof(sourceFiles()) sources; __gshared TaskPool taskPool; /// Array of build rules through which all other build rules can be reached immutable rootRules = [ &dmdDefault, &autoTesterBuild, &runDmdUnittest, &clean, &checkwhitespace, &runCxxUnittest, &detab, &tolf, &zip, &html, &toolchainInfo, &style, &man, &installCopy, ]; int main(string[] args) { try { runMain(args); return 0; } catch (BuildException e) { writeln(e.msg); return 1; } } void runMain(string[] args) { int jobs = totalCPUs; bool calledFromMake = false; auto res = getopt(args, "j|jobs", "Specifies the number of jobs (commands) to run simultaneously (default: %d)".format(totalCPUs), &jobs, "v|verbose", "Verbose command output", (cast(bool*) &verbose), "f|force", "Force run (ignore timestamps and always run all tests)", (cast(bool*) &force), "d|dry-run", "Print commands instead of executing them", (cast(bool*) &dryRun), "called-from-make", "Calling the build script from the Makefile", &calledFromMake ); void showHelp() { defaultGetoptPrinter(`./build.d <targets>... Examples -------- ./build.d dmd # build DMD ./build.d unittest # runs internal unittests ./build.d clean # remove all generated files ./build.d generated/linux/release/64/dmd.conf Important variables: -------------------- HOST_DMD: Host D compiler to use for bootstrapping AUTO_BOOTSTRAP: Enable auto-boostrapping by downloading a stable DMD binary MODEL: Target architecture to build for (32,64) - defaults to the host architecture Build modes: ------------ BUILD: release (default) | debug (enabled a build with debug instructions) Opt-in build features: ENABLE_RELEASE: Optimized release built ENABLE_DEBUG: Add debug instructions and symbols (set if ENABLE_RELEASE isn't set) ENABLE_LTO: Enable link-time optimizations ENABLE_UNITTEST: Build dmd with unittests (sets ENABLE_COVERAGE=1) ENABLE_PROFILE: Build dmd with a profiling recorder (D) ENABLE_COVERAGE Build dmd with coverage counting ENABLE_SANITIZERS Build dmd with sanitizer (e.g. ENABLE_SANITIZERS=address,undefined) Targets ------- ` ~ targetsHelp ~ ` The generated files will be in generated/$(OS)/$(BUILD)/$(MODEL) (` ~ env["G"] ~ `) Command-line parameters ----------------------- `, res.options); return; } // workaround issue https://issues.dlang.org/show_bug.cgi?id=13727 version (CRuntime_DigitalMars) { pragma(msg, "Warning: Parallel builds disabled because of Issue 13727!"); jobs = min(jobs, 1); // Fall back to a sequential build } if (jobs <= 0) abortBuild("Invalid number of jobs: %d".format(jobs)); taskPool = new TaskPool(jobs - 1); // Main thread is active too scope (exit) taskPool.finish(); scope (failure) taskPool.stop(); // parse arguments args.popFront; args2Environment(args); parseEnvironment; processEnvironment; processEnvironmentCxx; sources = sourceFiles; if (res.helpWanted) return showHelp; // Since we're ultimately outputting to a TTY, force colored output // A more proper solution would be to redirect DMD's output to this script's // output using `std.process`', but it's more involved and the following // "just works" if (!flags["DFLAGS"].canFind("-color=off") && [env["HOST_DMD_RUN"], "-color=on", "-h"].tryRun().status == 0) flags["DFLAGS"] ~= "-color=on"; // default target if (!args.length) args = ["dmd"]; auto targets = predefinedTargets(args); // preprocess if (targets.length == 0) return showHelp; if (verbose) { log("================================================================================"); foreach (key, value; env) log("%s=%s", key, value); foreach (key, value; flags) log("%s=%-(%s %)", key, value); log("================================================================================"); } { File lockFile; if (calledFromMake) { // If called from make, use an interprocess lock so that parallel builds don't stomp on each other lockFile = File(env["GENERATED"].buildPath("build.lock"), "w"); lockFile.lock(); } scope (exit) { if (calledFromMake) { lockFile.unlock(); lockFile.close(); } } Scheduler.build(targets); } writeln("Success"); } /// Generate list of targets for use in the help message string targetsHelp() { string result = ""; foreach (rule; BuildRuleRange(rootRules.map!(a => a()).array)) { if (rule.name) { enum defaultPrefix = "\n "; result ~= rule.name; string prefix = defaultPrefix[1 + rule.name.length .. $]; void add(string msg) { result ~= format("%s%s", prefix, msg); prefix = defaultPrefix; } if (rule.description) add(rule.description); else if (rule.targets) { foreach (target; rule.targets) { add(target.relativePath); } } result ~= "\n"; } } return result; } /** D build rules ==================== The strategy of this script is to emulate what the Makefile is doing. Below all individual rules of DMD are defined. They have a target path, sources paths and an optional name. When a rule is needed either its command or custom commandFunction is executed. A rule will be skipped if all targets are older than all sources. This script is by default part of the sources and thus any change to the build script, will trigger a full rebuild. */ /// Returns: The rule that runs the autotester build alias autoTesterBuild = makeRule!((builder, rule) { builder .name("auto-tester-build") .description("Run the autotester build") .deps([toolchainInfo, dmdDefault, checkwhitespace]); version (Posix) rule.deps ~= runCxxUnittest; // unittests are currently not executed as part of `auto-tester-test` on windows // because changes to `win32.mak` require additional changes on the autotester // (see https://github.com/dlang/dmd/pull/7414). // This requires no further actions and avoids building druntime+phobos on unittest failure version (Windows) rule.deps ~= runDmdUnittest; }); /// Returns: the rule that builds the lexer object file alias lexer = makeRuleWithArgs!((MethodInitializer!BuildRule builder, BuildRule rule, string suffix, string[] extraFlags) => builder .name("lexer") .target(env["G"].buildPath("lexer" ~ suffix).objName) .sources(sources.lexer) .deps([versionFile, sysconfDirFile]) .msg("(DC) LEXER" ~ suffix) .command([env["HOST_DMD_RUN"], "-c", "-of" ~ rule.target, "-vtls"] .chain(flags["DFLAGS"], extraFlags, // source files need to have relative paths in order for the code coverage // .lst files to be named properly for CodeCov to find them rule.sources.map!(e => e.relativePath(dmdRepo)) ).array ) ); /// Returns: the rule that generates the dmd.conf/sc.ini file in the output folder alias dmdConf = makeRule!((builder, rule) { string exportDynamic; version(OSX) {} else exportDynamic = " -L--export-dynamic"; version (Windows) { enum confFile = "sc.ini"; enum conf = `[Environment] DFLAGS="-I%@P%\..\..\..\..\..\druntime\import" "-I%@P%\..\..\..\..\..\phobos" LIB="%@P%\..\..\..\..\..\phobos" [Environment64] DFLAGS=%DFLAGS% -L/OPT:NOICF [Environment32mscoff] DFLAGS=%DFLAGS% -L/OPT:NOICF `; } else { enum confFile = "dmd.conf"; enum conf = `[Environment32] DFLAGS=-I%@P%/../../../../../druntime/import -I%@P%/../../../../../phobos -L-L%@P%/../../../../../phobos/generated/{OS}/{BUILD}/32{exportDynamic} [Environment64] DFLAGS=-I%@P%/../../../../../druntime/import -I%@P%/../../../../../phobos -L-L%@P%/../../../../../phobos/generated/{OS}/{BUILD}/64{exportDynamic} -fPIC `; } builder .name("dmdconf") .target(env["G"].buildPath(confFile)) .msg("(TX) DMD_CONF") .commandFunction(() { const expConf = conf .replace("{exportDynamic}", exportDynamic) .replace("{BUILD}", env["BUILD"]) .replace("{OS}", env["OS"]); writeText(rule.target, expConf); }); }); /// Returns: the rule that builds the backend object file alias backend = makeRuleWithArgs!((MethodInitializer!BuildRule builder, BuildRule rule, string suffix, string[] extraFlags) => builder .name("backend") .target(env["G"].buildPath("backend" ~ suffix).objName) .sources(sources.backend) .msg("(DC) BACKEND" ~ suffix) .command([ env["HOST_DMD_RUN"], "-c", "-of" ~ rule.target, ] .chain( ( // Only use -betterC when it doesn't break other features extraFlags.canFind("-unittest", "-cov") || flags["DFLAGS"].canFind("-unittest", "-cov") ) ? [] : ["-betterC"], flags["DFLAGS"], extraFlags, // source files need to have relative paths in order for the code coverage // .lst files to be named properly for CodeCov to find them rule.sources.map!(e => e.relativePath(dmdRepo)) ).array) ); /// Returns: the rules that generate required string files: VERSION and SYSCONFDIR.imp alias versionFile = makeRule!((builder, rule) { alias contents = memoize!(() { if (dmdRepo.buildPath(".git").exists) { try { auto gitResult = [env["GIT"], "describe", "--dirty"].tryRun; if (gitResult.status == 0) return gitResult.output.strip; } catch (ProcessException) { // git not installed } } // version fallback return dmdRepo.buildPath("VERSION").readText; }); builder .target(env["G"].buildPath("VERSION")) .condition(() => !rule.target.exists || rule.target.readText != contents) .msg("(TX) VERSION") .commandFunction(() => writeText(rule.target, contents)); }); alias sysconfDirFile = makeRule!((builder, rule) => builder .target(env["G"].buildPath("SYSCONFDIR.imp")) .condition(() => !rule.target.exists || rule.target.readText != env["SYSCONFDIR"]) .msg("(TX) SYSCONFDIR") .commandFunction(() => writeText(rule.target, env["SYSCONFDIR"])) ); /// BuildRule to create a directory if it doesn't exist. alias directoryRule = makeRuleWithArgs!((MethodInitializer!BuildRule builder, BuildRule rule, string dir) => builder .target(dir) .condition(() => !exists(dir)) .msg("mkdirRecurse '%s'".format(dir)) .commandFunction(() => mkdirRecurse(dir)) ); /** BuildRule for the DMD executable. Params: extra_flags = Flags to apply to the main build but not the rules */ alias dmdExe = makeRuleWithArgs!((MethodInitializer!BuildRule builder, BuildRule rule, string targetSuffix, string[] extraFlags, string[] depFlags) { const dmdSources = sources.dmd.all.chain(sources.root).array; string[] platformArgs; version (Windows) platformArgs = ["-L/STACK:8388608"]; auto lexer = lexer(targetSuffix, depFlags); auto backend = backend(targetSuffix, depFlags); builder // include lexer.o and backend.o .sources(dmdSources.chain(lexer.targets, backend.targets).array) .target(env["DMD_PATH"] ~ targetSuffix) .msg("(DC) DMD" ~ targetSuffix) .deps([versionFile, sysconfDirFile, lexer, backend]) .command([ env["HOST_DMD_RUN"], "-of" ~ rule.target, "-vtls", "-J" ~ env["RES"], ].chain(extraFlags, platformArgs, flags["DFLAGS"], // source files need to have relative paths in order for the code coverage // .lst files to be named properly for CodeCov to find them rule.sources.map!(e => e.relativePath(dmdRepo)) ).array); }); alias dmdDefault = makeRule!((builder, rule) => builder .name("dmd") .description("Build dmd") .deps([dmdExe(null, null, null), dmdConf]) ); /// BuildRule to run the DMD unittest executable. alias runDmdUnittest = makeRule!((builder, rule) { auto dmdUnittestExe = dmdExe("-unittest", ["-version=NoMain", "-unittest", "-main"], ["-unittest"]); builder .name("unittest") .description("Run the dmd unittests") .msg("(RUN) DMD-UNITTEST") .deps([dmdUnittestExe]) .command(dmdUnittestExe.targets); }); /// Runs the C++ unittest executable alias runCxxUnittest = makeRule!((runCxxBuilder, runCxxRule) { /// Compiles the C++ frontend test files alias cxxFrontend = methodInit!(BuildRule, (frontendBuilder, frontendRule) => frontendBuilder .name("cxx-frontend") .description("Build the C++ frontend") .msg("(CXX) CXX-FRONTEND") .sources(srcDir.buildPath("tests", "cxxfrontend.c") ~ .sources.frontendHeaders ~ .sources.rootHeaders ~ .sources.dmd.frontend ~ .sources.root) .target(env["G"].buildPath("cxxfrontend").objName) // No explicit if since CXX_KIND will always be either g++ or clang++ .command([ env["CXX"], "-xc++", "-std=c++11", "-c", frontendRule.sources[0], "-o" ~ frontendRule.target, "-I" ~ env["D"] ] ~ flags["CXXFLAGS"]) ); alias cxxUnittestExe = methodInit!(BuildRule, (exeBuilder, exeRule) => exeBuilder .name("cxx-unittest") .description("Build the C++ unittests") .msg("(DMD) CXX-UNITTEST") .deps([lexer(null, null), cxxFrontend]) .sources(sources.dmd.frontend ~ sources.root) .target(env["G"].buildPath("cxx-unittest").exeName) .command([ env["HOST_DMD_RUN"], "-of=" ~ exeRule.target, "-vtls", "-J" ~ env["RES"], "-L-lstdc++", "-version=NoMain", "-version=NoBackend" ].chain( flags["DFLAGS"], exeRule.sources, exeRule.deps.map!(d => d.target) ).array) ); runCxxBuilder .name("cxx-unittest") .description("Run the C++ unittests") .msg("(RUN) CXX-UNITTEST"); version (Windows) runCxxBuilder .commandFunction({ abortBuild("Running the C++ unittests is not supported on Windows yet"); }); else runCxxBuilder .deps([cxxUnittestExe]) .command([cxxUnittestExe.target]); }); /// BuildRule that removes all generated files alias clean = makeRule!((builder, rule) => builder .name("clean") .description("Remove the generated directory") .msg("(RM) " ~ env["G"]) .commandFunction(delegate() { if (env["G"].exists) env["G"].rmdirRecurse; }) ); alias toolsRepo = makeRule!((builder, rule) => builder .target(env["TOOLS_DIR"]) .msg("(GIT) DLANG/TOOLS") .condition(() => !exists(rule.target)) .commandFunction(delegate() { auto toolsDir = env["TOOLS_DIR"]; version(Win32) // Win32-git seems to confuse C:\... as a relative path toolsDir = toolsDir.relativePath(dmdRepo); run([env["GIT"], "clone", "--depth=1", env["GIT_HOME"] ~ "/tools", toolsDir]); }) ); alias checkwhitespace = makeRule!((builder, rule) => builder .name("checkwhitespace") .description("Check for trailing whitespace and tabs") .msg("(RUN) checkwhitespace") .deps([toolsRepo]) .sources(allRepoSources) .commandFunction(delegate() { const cmdPrefix = [env["HOST_DMD_RUN"], "-run", env["TOOLS_DIR"].buildPath("checkwhitespace.d")]; auto chunkLength = allRepoSources.length; version (Win32) chunkLength = 80; // avoid command-line limit on win32 foreach (nextSources; taskPool.parallel(allRepoSources.chunks(chunkLength), 1)) { const nextCommand = cmdPrefix ~ nextSources; run(nextCommand); } }) ); alias style = makeRule!((builder, rule) { const dscannerDir = env["GENERATED"].buildPath("dscanner"); alias dscannerRepo = methodInit!(BuildRule, (repoBuilder, repoRule) => repoBuilder .msg("(GIT) DScanner") .target(dscannerDir) .condition(() => !exists(dscannerDir)) .command([ // FIXME: Omitted --shallow-submodules because it requires a more recent // git version which is not available on buildkite env["GIT"], "clone", "--depth=1", "--recurse-submodules", "--branch=v0.9.0", "https://github.com/dlang-community/Dscanner", dscannerDir ]) ); alias dscanner = methodInit!(BuildRule, (dscannerBuilder, dscannerRule) { dscannerBuilder .name("dscanner") .description("Build custom DScanner") .deps([dscannerRepo]); version (Windows) dscannerBuilder .msg("(CMD) DScanner") .target(dscannerDir.buildPath("bin", "dscanner".exeName)) .commandFunction(() { // The build script expects to be run inside dscannerDir run([dscannerDir.buildPath("build.bat")], dscannerDir); }); else dscannerBuilder .msg("(MAKE) DScanner") .target(dscannerDir.buildPath("dsc".exeName)) .command([ // debug build is faster but disable trace output env.get("MAKE", "make"), "-C", dscannerDir, "debug", "DEBUG_VERSIONS=-version=StdLoggerDisableWarning" ]); }); builder .name("style") .description("Check for style errors using D-Scanner") .msg("(DSCANNER) dmd") .deps([dscanner]) // Disabled because we need to build a patched dscanner version // .command([ // "dub", "-q", "run", "-y", "dscanner", "--", "--styleCheck", "--config", // srcDir.buildPath(".dscanner.ini"), srcDir.buildPath("dmd"), "-I" ~ srcDir // ]) .command([ dscanner.target, "--styleCheck", "--config", srcDir.buildPath(".dscanner.ini"), srcDir.buildPath("dmd"), "-I" ~ srcDir ]); }); /// BuildRule to generate man pages alias man = makeRule!((builder, rule) { alias genMan = methodInit!(BuildRule, (genManBuilder, genManRule) => genManBuilder .target(env["G"].buildPath("gen_man")) .sources([ dmdRepo.buildPath("docs", "gen_man.d"), env["D"].buildPath("cli.d")]) .command([ env["HOST_DMD_RUN"], "-I" ~ srcDir, "-of" ~ genManRule.target] ~ flags["DFLAGS"] ~ genManRule.sources) .msg(genManRule.command.join(" ")) ); const genManDir = env["GENERATED"].buildPath("docs", "man"); alias dmdMan = methodInit!(BuildRule, (dmdManBuilder, dmdManRule) => dmdManBuilder .target(genManDir.buildPath("man1", "dmd.1")) .deps([genMan, directoryRule(dmdManRule.target.dirName)]) .msg("(GEN_MAN) " ~ dmdManRule.target) .commandFunction(() { writeText(dmdManRule.target, genMan.target.execute.output); }) ); builder .name("man") .description("Generate and prepare man files") .deps([dmdMan].chain( "man1/dumpobj.1 man1/obj2asm.1 man5/dmd.conf.5".split .map!(e => methodInit!(BuildRule, (manFileBuilder, manFileRule) => manFileBuilder .target(genManDir.buildPath(e)) .sources([dmdRepo.buildPath("docs", "man", e)]) .deps([directoryRule(manFileRule.target.dirName)]) .commandFunction(() => copyAndTouch(manFileRule.sources[0], manFileRule.target)) .msg("copy '%s' to '%s'".format(manFileRule.sources[0], manFileRule.target)) )) ).array); }); alias detab = makeRule!((builder, rule) => builder .name("detab") .description("Replace hard tabs with spaces") .command([env["DETAB"]] ~ allRepoSources) .msg("(DETAB) DMD") ); alias tolf = makeRule!((builder, rule) => builder .name("tolf") .description("Convert to Unix line endings") .command([env["TOLF"]] ~ allRepoSources) .msg("(TOLF) DMD") ); alias zip = makeRule!((builder, rule) => builder .name("zip") .target(srcDir.buildPath("dmdsrc.zip")) .description("Archive all source files") .sources(allBuildSources) .msg("ZIP " ~ rule.target) .commandFunction(() { if (exists(rule.target)) remove(rule.target); run([env["ZIP"], rule.target, thisBuildScript] ~ rule.sources); }) ); alias html = makeRule!((htmlBuilder, htmlRule) { htmlBuilder .name("html") .description("Generate html docs, requires DMD and STDDOC to be set"); static string d2html(string sourceFile) { const ext = sourceFile.extension(); assert(ext == ".d" || ext == ".di", sourceFile); const htmlFilePrefix = (sourceFile.baseName == "package.d") ? sourceFile[0 .. $ - "package.d".length - 1] : sourceFile[0 .. $ - ext.length]; return htmlFilePrefix ~ ".html"; } const stddocs = env.get("STDDOC", "").split(); auto docSources = .sources.root ~ .sources.lexer ~ .sources.dmd.all ~ env["D"].buildPath("frontend.d"); htmlBuilder.deps(docSources.chunks(1).map!(sourceArray => methodInit!(BuildRule, (docBuilder, docRule) { const source = sourceArray[0]; docBuilder .sources(sourceArray) .target(env["DOC_OUTPUT_DIR"].buildPath(d2html(source)[srcDir.length + 1..$] .replace(dirSeparator, "_"))) .deps([dmdDefault, versionFile, sysconfDirFile]) .command([ dmdDefault.deps[0].target, "-o-", "-c", "-Dd" ~ env["DOCSRC"], "-J" ~ env["RES"], "-I" ~ env["D"], srcDir.buildPath("project.ddoc") ] ~ stddocs ~ [ "-Df" ~ docRule.target, // Need to use a short relative path to make sure ddoc links are correct source.relativePath(runDir) ] ~ flags["DFLAGS"]) .msg("(DDOC) " ~ source); }) ).array); }); alias toolchainInfo = makeRule!((builder, rule) => builder .name("toolchain-info") .description("Show informations about used tools") .commandFunction(() { scope Appender!(char[]) app; void show(string what, string[] cmd) { string output; try output = tryRun(cmd).output; catch (ProcessException) output = "<Not available>"; app.formattedWrite("%s (%s): %s\n", what, cmd[0], output); } app.put("==== Toolchain Information ====\n"); version (Windows) show("SYSTEM", ["systeminfo"]); else show("SYSTEM", ["uname", "-a"]); show("MAKE", [env.get("MAKE", "make"), "--version"]); version (Posix) show("SHELL", [env.get("SHELL", nativeShell), "--version"]); // cmd.exe --version hangs show("HOST_DMD", [env["HOST_DMD_RUN"], "--version"]); version (Posix) show("HOST_CXX", [env["CXX"], "--version"]); show("ld", ["ld", "-v"]); show("gdb", ["gdb", "--version"]); app.put("==== Toolchain Information ====\n\n"); writeln(app.data); }) ); alias installCopy = makeRule!((builder, rule) => builder .name("install-copy") .description("Legacy alias for install") .deps([install]) ); alias install = makeRule!((builder, rule) { const dmdExeFile = dmdDefault.deps[0].target; auto sourceFiles = allBuildSources ~ [ env["D"].buildPath("README.md"), env["D"].buildPath("boostlicense.txt"), ]; builder .name("install") .description("Installs dmd into $(INSTALL)") .deps([dmdDefault]) .sources(sourceFiles) .commandFunction(() { version (Windows) { enum conf = "sc.ini"; enum bin = "bin"; } else { enum conf = "dmd.conf"; version (OSX) enum bin = "bin"; else const bin = "bin" ~ env["MODEL"]; } installRelativeFiles(env["INSTALL"].buildPath(env["OS"], bin), dmdExeFile.dirName, dmdExeFile.only, octal!755); version (Windows) installRelativeFiles(env["INSTALL"], dmdRepo, sourceFiles); const scPath = buildPath(env["OS"], bin, conf); copyAndTouch(buildPath(dmdRepo, "ini", scPath), buildPath(env["INSTALL"], scPath)); version (Posix) copyAndTouch(sourceFiles[$-1], env["INSTALL"].buildPath("dmd-boostlicense.txt")); }); }); /** Goes through the target list and replaces short-hand targets with their expanded version. Special targets: - clean -> removes generated directory + immediately stops the builder Params: targets = the target list to process Returns: the expanded targets */ BuildRule[] predefinedTargets(string[] targets) { import std.functional : toDelegate; Appender!(BuildRule[]) newTargets; LtargetsLoop: foreach (t; targets) { t = t.buildNormalizedPath; // remove trailing slashes // check if `t` matches any rule names first foreach (rule; BuildRuleRange(rootRules.map!(a => a()).array)) { if (t == rule.name) { newTargets.put(rule); continue LtargetsLoop; } } switch (t) { case "all": // "all" must include dmd + dmd.conf newTargets ~= dmdDefault; break; default: // check this last, target paths should be checked after predefined names const tAbsolute = t.absolutePath.buildNormalizedPath; foreach (rule; BuildRuleRange(rootRules.map!(a => a()).array)) { foreach (ruleTarget; rule.targets) { if (ruleTarget.endsWith(t, tAbsolute)) { newTargets.put(rule); continue LtargetsLoop; } } } abortBuild("Target `" ~ t ~ "` is unknown."); } } return newTargets.data; } /// An input range for a recursive set of rules struct BuildRuleRange { private BuildRule[] next; private bool[BuildRule] added; this(BuildRule[] rules) { addRules(rules); } bool empty() const { return next.length == 0; } auto front() inout { return next[0]; } void popFront() { auto save = next[0]; next = next[1 .. $]; addRules(save.deps); } void addRules(BuildRule[] rules) { foreach (rule; rules) { if (!added.get(rule, false)) { next ~= rule; added[rule] = true; } } } } /// Sets the environment variables void parseEnvironment() { if (!verbose) verbose = "1" == env.getDefault("VERBOSE", null); // This block is temporary until we can remove the windows make files if ("DDEBUG" in environment) abortBuild("ERROR: the DDEBUG variable is deprecated!"); version (Windows) { // On windows, the OS environment variable is already being used by the system. // For example, on a default Windows7 system it's configured by the system // to be "Windows_NT". // // However, there are a good number of components in this repo and the other // repos that set this environment variable to "windows" without checking whether // it's already configured, i.e. // dmd\src\win32.mak (OS=windows) // druntime\win32.mak (OS=windows) // phobos\win32.mak (OS=windows) // // It's necessary to emulate the same behavior in this tool in order to make this // new tool compatible with existing tools. We can do this by also setting the // environment variable to "windows" whether or not it already has a value. // const os = env["OS"] = "windows"; } else const os = env.getDefault("OS", detectOS); auto build = env.getDefault("BUILD", "release"); enforce(build.among("release", "debug"), "BUILD must be 'debug' or 'release'"); if (build == "debug") env.getDefault("ENABLE_DEBUG", "1"); // detect Model auto model = env.getDefault("MODEL", detectModel); env["MODEL_FLAG"] = "-m" ~ env["MODEL"]; // detect PIC version(Posix) { // default to PIC on x86_64, use PIC=1/0 to en-/disable PIC. // Note that shared libraries and C files are always compiled with PIC. bool pic; version(X86_64) pic = true; else version(X86) pic = false; if (env.getNumberedBool("PIC")) pic = true; env["PIC_FLAG"] = pic ? "-fPIC" : ""; } else { env["PIC_FLAG"] = ""; } env.getDefault("GIT", "git"); env.getDefault("GIT_HOME", "https://github.com/dlang"); env.getDefault("SYSCONFDIR", "/etc"); env.getDefault("TMP", tempDir); env.getDefault("RES", dmdRepo.buildPath("src/dmd/res")); version (Windows) enum installPref = ""; else enum installPref = ".."; env.getDefault("INSTALL", environment.get("INSTALL_DIR", dmdRepo.buildPath(installPref, "install"))); env.getDefault("DOCSRC", dmdRepo.buildPath("dlang.org")); if (env.get("DOCDIR", null).length == 0) env["DOCDIR"] = srcDir; env.getDefault("DOC_OUTPUT_DIR", env["DOCDIR"]); auto d = env["D"] = srcDir.buildPath("dmd"); env["C"] = d.buildPath("backend"); env["ROOT"] = d.buildPath("root"); env["EX"] = srcDir.buildPath("examples"); auto generated = env["GENERATED"] = dmdRepo.buildPath("generated"); auto g = env["G"] = generated.buildPath(os, build, model); mkdirRecurse(g); env.getDefault("TOOLS_DIR", dmdRepo.dirName.buildPath("tools")); if (env.get("HOST_DMD", null).length == 0) { const hostDmd = env.get("HOST_DC", null); env["HOST_DMD"] = hostDmd.length ? hostDmd : "dmd"; } // Auto-bootstrapping of a specific host compiler if (env.getNumberedBool("AUTO_BOOTSTRAP")) { auto hostDMDVer = env.getDefault("HOST_DMD_VER", "2.088.0"); writefln("Using Bootstrap compiler: %s", hostDMDVer); auto hostDMDRoot = env["G"].buildPath("host_dmd-"~hostDMDVer); auto hostDMDBase = hostDMDVer~"."~os; auto hostDMDURL = "http://downloads.dlang.org/releases/2.x/"~hostDMDVer~"/dmd."~hostDMDBase; env["HOST_DMD"] = hostDMDRoot.buildPath("dmd2", os, os == "osx" ? "bin" : "bin"~model, "dmd"); env["HOST_DMD_PATH"] = env["HOST_DMD"]; // TODO: use dmd.conf from the host too (in case there's a global or user-level dmd.conf) env["HOST_DMD_RUN"] = env["HOST_DMD"]; if (!env["HOST_DMD"].exists) { writefln("Downloading DMD %s", hostDMDVer); auto curlFlags = "-fsSL --retry 5 --retry-max-time 120 --connect-timeout 5 --speed-time 30 --speed-limit 1024"; hostDMDRoot.mkdirRecurse; ("curl " ~ curlFlags ~ " " ~ hostDMDURL~".tar.xz | tar -C "~hostDMDRoot~" -Jxf - || rm -rf "~hostDMDRoot).spawnShell.wait; } } else { env["HOST_DMD_PATH"] = getHostDMDPath(env["HOST_DMD"]).strip.absolutePath; env["HOST_DMD_RUN"] = env["HOST_DMD_PATH"]; } if (!env["HOST_DMD_PATH"].exists) { abortBuild("No DMD compiler is installed. Try AUTO_BOOTSTRAP=1 or manually set the D host compiler with HOST_DMD"); } } /// Checks the environment variables and flags void processEnvironment() { import std.meta : AliasSeq; const os = env["OS"]; const hostDMDVersion = [env["HOST_DMD_RUN"], "--version"].execute.output; alias DMD = AliasSeq!("DMD"); alias LDC = AliasSeq!("LDC"); alias GDC = AliasSeq!("GDC", "gdmd", "gdc"); const kindIdx = hostDMDVersion.canFind(DMD, LDC, GDC); enforce(kindIdx, "Invalid Host DMD found: " ~ hostDMDVersion); if (kindIdx <= DMD.length) env["HOST_DMD_KIND"] = "dmd"; else if (kindIdx <= LDC.length + DMD.length) env["HOST_DMD_KIND"] = "ldc"; else env["HOST_DMD_KIND"] = "gdc"; env["DMD_PATH"] = env["G"].buildPath("dmd").exeName; env.getDefault("DETAB", "detab"); env.getDefault("TOLF", "tolf"); version (Windows) env.getDefault("ZIP", "zip32"); else env.getDefault("ZIP", "zip"); // TODO: this isn't being used for anything yet... env.getNumberedBool("ENABLE_WARNINGS"); string[] warnings; string[] dflags = ["-version=MARS", "-w", "-de", env["PIC_FLAG"], env["MODEL_FLAG"], "-J"~env["G"], "-I" ~ srcDir]; if (env["HOST_DMD_KIND"] != "gdc") dflags ~= ["-dip25"]; // gdmd doesn't support -dip25 // TODO: add support for dObjc auto dObjc = false; version(OSX) version(X86_64) dObjc = true; if (env.getNumberedBool("ENABLE_DEBUG")) { dflags ~= ["-g", "-debug"]; } if (env.getNumberedBool("ENABLE_RELEASE")) { dflags ~= ["-O", "-release", "-inline"]; } else { // add debug symbols for all non-release builds if (!dflags.canFind("-g")) dflags ~= ["-g"]; } if (env.getNumberedBool("ENABLE_LTO")) { dflags ~= ["-flto=full"]; } if (env.getNumberedBool("ENABLE_UNITTEST")) { dflags ~= ["-unittest"]; } if (env.getNumberedBool("ENABLE_PROFILE")) { dflags ~= ["-profile"]; } if (env.getNumberedBool("ENABLE_COVERAGE")) { dflags ~= ["-cov"]; } if (env.getDefault("ENABLE_SANITIZERS", "") != "") { dflags ~= ["-fsanitize="~env["ENABLE_SANITIZERS"]]; } // Retain user-defined flags flags["DFLAGS"] = dflags ~= flags.get("DFLAGS", []); } /// Setup environment for a C++ compiler void processEnvironmentCxx() { // Windows requires additional work to handle e.g. Cygwin on Azure version (Windows) return; const cxxKind = env["CXX_KIND"] = detectHostCxx(); string[] warnings = [ "-Wall", "-Werror", "-Wno-narrowing", "-Wwrite-strings", "-Wcast-qual", "-Wno-format", "-Wmissing-format-attribute", "-Woverloaded-virtual", "-pedantic", "-Wno-long-long", "-Wno-variadic-macros", "-Wno-overlength-strings", ]; auto cxxFlags = warnings ~ [ "-g", "-fno-exceptions", "-fno-rtti", "-fno-common", "-fasynchronous-unwind-tables", "-DMARS=1", env["MODEL_FLAG"], env["PIC_FLAG"], ]; if (env.getNumberedBool("ENABLE_COVERAGE")) cxxFlags ~= "--coverage"; if (env.getDefault("ENABLE_SANITIZERS", "") != "") cxxFlags ~= "-fsanitize=" ~ env["ENABLE_SANITIZERS"]; // Enable a temporary workaround in globals.h and rmem.h concerning // wrong name mangling using DMD. // Remove when the minimally required D version becomes 2.082 or later if (env["HOST_DMD_KIND"] == "dmd") { const output = run([ env["HOST_DMD_RUN"], "--version" ]); if (output.canFind("v2.079", "v2.080", "v2.081")) cxxFlags ~= "-DDMD_VERSION=2080"; } // Retain user-defined flags flags["CXXFLAGS"] = cxxFlags ~= flags.get("CXXFLAGS", []); } /// Returns: the host C++ compiler, either "g++" or "clang++" string detectHostCxx() { import std.meta: AliasSeq; const cxxVersion = [env.getDefault("CXX", "c++"), "--version"].execute.output; alias GCC = AliasSeq!("g++", "gcc", "Free Software"); alias CLANG = AliasSeq!("clang"); const cxxKindIdx = cxxVersion.canFind(GCC, CLANG); enforce(cxxKindIdx, "Invalid CXX found: " ~ cxxVersion); return cxxKindIdx <= GCC.length ? "g++" : "clang++"; } //////////////////////////////////////////////////////////////////////////////// // D source files //////////////////////////////////////////////////////////////////////////////// /// Returns: all source files in the repository alias allRepoSources = memoize!(() => srcDir.dirEntries("*.{d,h,di}", SpanMode.depth).map!(e => e.name).array); /// Returns: all make/build files alias buildFiles = memoize!(() => "win32.mak posix.mak osmodel.mak build.d".split().map!(e => srcDir.buildPath(e)).array); /// Returns: all sources used in the build alias allBuildSources = memoize!(() => buildFiles ~ sources.dmd.all ~ sources.lexer ~ sources.backend ~ sources.root ~ sources.frontendHeaders ~ sources.rootHeaders ); /// Returns: all source files for the compiler auto sourceFiles() { static struct DmdSources { string[] all, frontend, glue, backendHeaders; } static struct Sources { DmdSources dmd; string[] lexer, root, backend, frontendHeaders, rootHeaders; } static string[] fileArray(string dir, string files) { return files.split.map!(e => dir.buildPath(e)).array; } DmdSources dmd = { glue: fileArray(env["D"], " dmsc.d e2ir.d eh.d iasm.d iasmdmd.d iasmgcc.d glue.d objc_glue.d s2ir.d tocsym.d toctype.d tocvdebug.d todt.d toir.d toobj.d "), frontend: fileArray(env["D"], " access.d aggregate.d aliasthis.d apply.d argtypes.d argtypes_sysv_x64.d argtypes_aarch64.d arrayop.d arraytypes.d ast_node.d astcodegen.d asttypename.d attrib.d blockexit.d builtin.d canthrow.d chkformat.d cli.d clone.d compiler.d complex.d cond.d constfold.d cppmangle.d cppmanglewin.d ctfeexpr.d ctorflow.d dcast.d dclass.d declaration.d delegatize.d denum.d dimport.d dinifile.d dinterpret.d dmacro.d dmangle.d dmodule.d doc.d dscope.d dstruct.d dsymbol.d dsymbolsem.d dtemplate.d dtoh.d dversion.d env.d escape.d expression.d expressionsem.d func.d gluelayer.d hdrgen.d impcnvtab.d imphint.d init.d initsem.d inline.d inlinecost.d intrange.d json.d lambdacomp.d lib.d libelf.d libmach.d libmscoff.d libomf.d link.d mars.d mtype.d nogc.d nspace.d ob.d objc.d opover.d optimize.d parse.d parsetimevisitor.d permissivevisitor.d printast.d safe.d sapply.d scanelf.d scanmach.d scanmscoff.d scanomf.d semantic2.d semantic3.d sideeffect.d statement.d statement_rewrite_walker.d statementsem.d staticassert.d staticcond.d stmtstate.d target.d templateparamsem.d traits.d transitivevisitor.d typesem.d typinf.d utils.d visitor.d vsoptions.d foreachvar.d "), backendHeaders: fileArray(env["C"], " cc.d cdef.d cgcv.d code.d cv4.d dt.d el.d global.d obj.d oper.d outbuf.d rtlsym.d code_x86.d iasm.d codebuilder.d ty.d type.d exh.d mach.d mscoff.d dwarf.d dwarf2.d xmm.d dlist.d melf.d "), }; foreach (member; __traits(allMembers, DmdSources)) { if (member != "all") dmd.all ~= __traits(getMember, dmd, member); } Sources sources = { dmd: dmd, frontendHeaders: fileArray(env["D"], " aggregate.h aliasthis.h arraytypes.h attrib.h compiler.h complex_t.h cond.h ctfe.h declaration.h dsymbol.h doc.h enum.h errors.h expression.h globals.h hdrgen.h identifier.h id.h import.h init.h json.h mangle.h module.h mtype.h nspace.h objc.h scope.h statement.h staticassert.h target.h template.h tokens.h version.h visitor.h "), lexer: fileArray(env["D"], " console.d entity.d errors.d filecache.d globals.d id.d identifier.d lexer.d tokens.d utf.d ") ~ fileArray(env["ROOT"], " array.d bitarray.d ctfloat.d file.d filename.d hash.d outbuffer.d port.d region.d rmem.d rootobject.d stringtable.d "), root: fileArray(env["ROOT"], " aav.d longdouble.d man.d response.d speller.d string.d strtold.d "), rootHeaders: fileArray(env["ROOT"], " array.h bitarray.h ctfloat.h dcompat.h dsystem.h file.h filename.h longdouble.h object.h outbuffer.h port.h rmem.h root.h "), backend: fileArray(env["C"], " backend.d bcomplex.d evalu8.d divcoeff.d dvec.d go.d gsroa.d glocal.d gdag.d gother.d gflow.d out.d gloop.d compress.d cgelem.d cgcs.d ee.d cod4.d cod5.d nteh.d blockopt.d mem.d cg.d cgreg.d dtype.d debugprint.d fp.d symbol.d elem.d dcode.d cgsched.d cg87.d cgxmm.d cgcod.d cod1.d cod2.d cod3.d cv8.d dcgcv.d pdata.d util2.d var.d md5.d backconfig.d ph2.d drtlsym.d dwarfeh.d ptrntab.d dvarstats.d dwarfdbginf.d cgen.d os.d goh.d barray.d cgcse.d elpicpie.d machobj.d elfobj.d " ~ ((env["OS"] == "windows") ? "cgobj.d filespec.d mscoffobj.d newman.d" : "aarray.d") ), }; return sources; } /** Downloads a file from a given URL Params: to = Location to store the file downloaded from = The URL to the file to download tries = The number of times to try if an attempt to download fails Returns: `true` if download succeeded */ bool download(string to, string from, uint tries = 3) { import std.net.curl : download, HTTP, HTTPStatusException; foreach(i; 0..tries) { try { log("Downloading %s ...", from); auto con = HTTP(from); download(from, to, con); if (con.statusLine.code == 200) return true; } catch(HTTPStatusException e) { if (e.status == 404) throw e; } log("Failed to download %s (Attempt %s of %s)", from, i + 1, tries); } return false; } /** Detects the host OS. Returns: a string from `{windows, osx,linux,freebsd,openbsd,netbsd,dragonflybsd,solaris}` */ string detectOS() { version(Windows) return "windows"; else version(OSX) return "osx"; else version(linux) return "linux"; else version(FreeBSD) return "freebsd"; else version(OpenBSD) return "openbsd"; else version(NetBSD) return "netbsd"; else version(DragonFlyBSD) return "dragonflybsd"; else version(Solaris) return "solaris"; else static assert(0, "Unrecognized or unsupported OS."); } /** Detects the host model Returns: 32, 64 or throws an Exception */ auto detectModel() { string uname; if (detectOS == "solaris") uname = ["isainfo", "-n"].execute.output; else if (detectOS == "windows") { version (D_LP64) return "64"; // host must be 64-bit if this compiles else version (Windows) { import core.sys.windows.winbase; int is64; if (IsWow64Process(GetCurrentProcess(), &is64)) return is64 ? "64" : "32"; } } else uname = ["uname", "-m"].execute.output; if (uname.canFind("x86_64", "amd64", "64-bit", "64-Bit", "64 bit")) return "64"; if (uname.canFind("i386", "i586", "i686", "32-bit", "32-Bit", "32 bit")) return "32"; throw new Exception(`Cannot figure 32/64 model from "` ~ uname ~ `"`); } /** Gets the absolute path of the host's dmd executable Params: hostDmd = the command used to launch the host's dmd executable Returns: a string that is the absolute path of the host's dmd executable */ auto getHostDMDPath(string hostDmd) { version(Posix) return ["which", hostDmd].execute.output; else version(Windows) { if (hostDmd.canFind("/", "\\")) return hostDmd; return ["where", hostDmd].execute.output .lineSplitter.filter!(file => file != srcDir.buildPath("dmd.exe")).front; } else static assert(false, "Unrecognized or unsupported OS."); } /** Add the executable filename extension to the given `name` for the current OS. Params: name = the name to append the file extention to */ auto exeName(T)(T name) { version(Windows) return name ~ ".exe"; return name; } /** Add the object file extension to the given `name` for the current OS. Params: name = the name to append the file extention to */ auto objName(T)(T name) { version(Windows) return name ~ ".obj"; return name ~ ".o"; } /** Add the library file extension to the given `name` for the current OS. Params: name = the name to append the file extention to */ auto libName(T)(T name) { version(Windows) return name ~ ".lib"; return name ~ ".a"; } /** Filter additional make-like assignments from args and add them to the environment e.g. ./build.d ARGS=foo sets env["ARGS"] = environment["ARGS"] = "foo". The variables DLFAGS and CXXFLAGS may contain flags intended for the respective compiler and set flags instead, e.g. ./build.d DFLAGS="-w -version=foo" results in flags["DFLAGS"] = ["-w", "-version=foo"]. Params: args = the command-line arguments from which the assignments will be removed */ void args2Environment(ref string[] args) { bool tryToAdd(string arg) { auto parts = arg.findSplit("="); if (!parts) return false; const key = parts[0]; const value = parts[2]; if (key.among("DFLAGS", "CXXFLAGS")) { flags[key] = value.split(); } else { environment[key] = value; env[key] = value; } return true; } args = args.filter!(a => !tryToAdd(a)).array; } /** Ensures that env contains a mapping for key and returns the associated value. Searches the process environment if it is missing and creates an appropriate entry in env using either the found value or `default_` as a fallback. Params: env = environment to write the check to key = key to check for existence and write into the new env default_ = fallback value if the key doesn't exist in the global environment Returns: the value associated to key */ auto getDefault(ref string[string] env, string key, string default_) { if (auto ex = key in env) return *ex; if (key in environment) env[key] = environment[key]; else env[key] = default_; return env[key]; } /** Get the value of a build variable that should always be 0, 1 or empty. */ bool getNumberedBool(ref string[string] env, string varname) { const value = env.getDefault(varname, null); if (value.length == 0 || value == "0") return false; if (value == "1") return true; throw abortBuild(format("Variable '%s' should be '0', '1' or <empty> but got '%s'", varname, value)); } //////////////////////////////////////////////////////////////////////////////// // Mini build system //////////////////////////////////////////////////////////////////////////////// /** Checks whether any of the targets are older than the sources Params: targets = the targets to check sources = the source files to check against Returns: `true` if the target is up to date */ bool isUpToDate(R, S)(R targets, S sources) { if (force) return false; auto oldestTargetTime = SysTime.max; foreach (target; targets) { const time = target.timeLastModified.ifThrown(SysTime.init); if (time == SysTime.init) return false; oldestTargetTime = min(time, oldestTargetTime); } return sources.all!(s => s.timeLastModified.ifThrown(SysTime.init) <= oldestTargetTime); } /** Writes given the content to the given file. The content will only be written to the file specified in `path` if that file doesn't exist, or the content of the existing file is different from the given content. This makes sure the timestamp of the file is only updated when the content has changed. This will avoid rebuilding when the content hasn't changed. Params: path = the path to the file to write the content to content = the content to write to the file */ void updateIfChanged(const string path, const string content) { const existingContent = path.exists ? path.readText : ""; if (content != existingContent) writeText(path, content); } /** A rule has one or more sources and yields one or more targets. It knows how to build these target by invoking either the external command or the commandFunction. If a run fails, the entire build stops. */ class BuildRule { string target; // path to the resulting target file (if target is used, it will set targets) string[] targets; // list of all target files string[] sources; // list of all source files BuildRule[] deps; // dependencies to build before this one bool delegate() condition; // Optional condition to determine whether or not to run this rule string[] command; // the rule command void delegate() commandFunction; // a custom rule command which gets called instead of command string msg; // msg of the rule that is e.g. written to the CLI when it's executed string name; /// optional string that can be used to identify this rule string description; /// optional string to describe this rule rather than printing the target files /// Finish creating the rule by checking that it is configured properly void finalize() { if (target) { assert(!targets, "target and targets cannot both be set"); targets = [target]; } } /** Executes the rule Params: depUpdated = whether any dependency was built (skips isUpToDate) Returns: Whether the targets of this rule were (re)built **/ bool run(bool depUpdated = false) { if (condition !is null && !condition()) { log("Skipping build of %-(%s%) as its condition returned false", targets); return false; } if (!depUpdated && targets && targets.isUpToDate(this.sources.chain([thisBuildScript]))) { if (this.sources !is null) log("Skipping build of %-('%s' %)' because %s is newer than each of %-('%s' %)'", targets, targets.length > 1 ? "each of them" : "it", this.sources); return false; } // Display the execution of the rule if (msg) msg.writeln; if(dryRun) { scope writer = stdout.lockingTextWriter; if(commandFunction) { writer.put("\n => Executing commandFunction()"); if(name) writer.formattedWrite!" of %s"(name); if(targets.length) writer.formattedWrite!" to generate:\n%( - %s\n%)"(targets); writer.put('\n'); } if(command) writer.formattedWrite!"\n => %(%s %)\n\n"(command); } else { scope (failure) if (!verbose) dump(); if (commandFunction !is null) { commandFunction(); } else if (command.length) { command.run; } } return true; } /// Writes relevant informations about this rule to stdout private void dump() { scope writer = stdout.lockingTextWriter; void write(T)(string fmt, T what) { static if (is(T : bool)) bool print = what; else bool print = what.length != 0; if (print) writer.formattedWrite(fmt, what); } writer.put("\nThe following operation failed:\n"); write("Name: %s\n", name); write("Description: %s\n", description); write("Dependencies: %-(\n -> %s%)\n\n", deps.map!(d => d.name ? d.name : d.target)); write("Sources: %-(\n -> %s%)\n\n", sources); write("Targets: %-(\n -> %s%)\n\n", targets); write("Command: %-(%s %)\n\n", command); write("CommandFunction: %-s\n\n", commandFunction ? "Yes" : null); writer.put("-----------------------------------------------------------\n"); } } /// Fake namespace containing all utilities to execute many rules in parallel abstract final class Scheduler { /** Builds the supplied targets in parallel using the global taskPool. Params: targets = rules to build **/ static void build(BuildRule[] targets) { // Create an execution plan to build all targets Context[BuildRule] contexts; Context[] topSorted, leaves; foreach(target; targets) findLeafs(target, contexts, topSorted, leaves); // Start all leaves in parallel, they will submit the remaining tasks recursively foreach (leaf; leaves) taskPool.put(leaf.task); // Await execution of all targets while executing pending tasks. The // topological order of tasks guarantees that every tasks was already // submitted to taskPool before we call workForce. foreach (context; topSorted) context.task.workForce(); } /** Recursively creates contexts instances for rule and all of its dependencies and stores them in contexts, tasks and leaves for further usage. Params: rule = current rule contexts = already created context instances tasks = context instances in topological order implied by Dependency.deps leaves = contexts of rules without dependencies Returns: the context belonging to rule **/ private static Context findLeafs(BuildRule rule, ref Context[BuildRule] contexts, ref Context[] all, ref Context[] leaves) { // This implementation is based on Tarjan's algorithm for topological sorting. auto context = contexts.get(rule, null); // Check whether the current node wasn't already visited if (context is null) { context = contexts[rule] = new Context(rule); // Leafs are rules without further dependencies if (rule.deps.empty) { leaves ~= context; } else { // Recursively visit all dependencies foreach (dep; rule.deps) { auto depContext = findLeafs(dep, contexts, all, leaves); depContext.requiredBy ~= context; } } // Append the current rule AFTER all dependencies all ~= context; } return context; } /// Metadata required for parallel execution private static class Context { import std.parallelism: createTask = task; alias Task = typeof(createTask(&Context.init.buildRecursive)); /// Task type BuildRule target; /// the rule to execute Context[] requiredBy; /// rules relying on this one shared size_t pendingDeps; /// amount of rules to be built shared bool depUpdated; /// whether any dependency of target was updated Task task; /// corresponding task /// Creates a new context for rule this(BuildRule rule) { this.target = rule; this.pendingDeps = rule.deps.length; this.task = createTask(&buildRecursive); } /** Builds the rule given by this context and schedules other rules requiring it (if the current was the last missing dependency) **/ private void buildRecursive() { import core.atomic: atomicLoad, atomicOp, atomicStore; /// Stores whether the current build is stopping because some step failed static shared bool aborting; scope (failure) atomicStore(aborting, true); // Build the current rule unless another one failed if (!atomicLoad(aborting) && target.run(depUpdated)) { // Propagate that this rule's targets were (re)built foreach (parent; requiredBy) atomicStore(parent.depUpdated, true); } // Mark this rule as finished for all parent rules foreach (parent; requiredBy) { if (parent.pendingDeps.atomicOp!"-="(1) == 0) taskPool.put(parent.task); } } } } /** Initializes an object using a chain of method calls */ struct MethodInitializer(T) if (is(T == class)) // currenly only works with classes { private T obj; auto ref opDispatch(string name)(typeof(__traits(getMember, T, name)) arg) { mixin("obj." ~ name ~ " = arg;"); return this; } } /** Create an object using a chain of method calls for each field. */ T methodInit(T, alias Func, Args...)(Args args) if (is(T == class)) // currently only works with classes { auto initializer = MethodInitializer!T(new T()); Func(initializer, initializer.obj, args); initializer.obj.finalize(); return initializer.obj; } /** Takes a lambda and returns a memoized function to build a rule object. The lambda takes a builder and a rule object. This differs from makeRuleWithArgs in that the function literal does not need explicit parameter types. */ alias makeRule(alias Func) = memoize!(methodInit!(BuildRule, Func)); /** Takes a lambda and returns a memoized function to build a rule object. The lambda takes a builder, rule object and any extra arguments needed to create the rule. This differs from makeRule in that the function literal must contain explicit parameter types. */ alias makeRuleWithArgs(alias Func) = memoize!(methodInit!(BuildRule, Func, Parameters!Func[2..$])); /** Logging primitive Params: spec = a format specifier args = the data to format to the log */ auto log(T...)(string spec, T args) { if (verbose) writefln(spec, args); } /** Aborts the current build TODO: - Display detailed error messages Params: msg = error message to display Throws: BuildException with the supplied message Returns: nothing but enables `throw abortBuild` to convey the resulting behavior */ BuildException abortBuild(string msg = "Build failed!") { throw new BuildException(msg); } class BuildException : Exception { this(string msg) { super(msg); } } /** The directory where all run commands are executed from. All relative file paths in a `run` command must be relative to `runDir`. */ alias runDir = dmdRepo; /** Run a command which may not succeed and optionally log the invocation. Params: args = the command and command arguments to execute workDir = the commands working directory Returns: a tuple (status, output) */ auto tryRun(T)(T args, string workDir = runDir) { args = args.filter!(a => !a.empty).array; log("Run: %s", args.join(" ")); return execute(args, null, Config.none, size_t.max, workDir); } /** Wrapper around execute that logs the execution and throws an exception for a non-zero exit code. Params: args = the command and command arguments to execute workDir = the commands working directory Returns: any output of the executed command */ auto run(T)(T args, string workDir = runDir) { auto res = tryRun(args, workDir); if (res.status) { abortBuild(res.output ? res.output : format("Last command failed with exit code %s", res.status)); } return res.output; } /** Install `files` to `targetDir`. `files` in different directories but will be installed to the same relative location as they exist in the `sourceBase` directory. Params: targetDir = the directory to install files into sourceBase = the parent directory of all files. all files will be installed to the same relative directory in targetDir as they are from sourceBase files = the files to install. must be in sourceBase */ void installRelativeFiles(T)(string targetDir, string sourceBase, T files, uint attributes = octal!644) { struct FileToCopy { string name; string relativeName; string toString() { return relativeName; } } FileToCopy[][string] filesByDir; foreach (file; files) { assert(file.startsWith(sourceBase), "expected all files to be installed to be in '%s', but got '%s'".format(sourceBase, file)); const relativeFile = file.relativePath(sourceBase); filesByDir[relativeFile.dirName] ~= FileToCopy(file, relativeFile); } foreach (dirFilePair; filesByDir.byKeyValue) { const nextTargetDir = targetDir.buildPath(dirFilePair.key); writefln("copy these files %s from '%s' to '%s'", dirFilePair.value, sourceBase, nextTargetDir); mkdirRecurse(nextTargetDir); foreach (fileToCopy; dirFilePair.value) { std.file.copy(fileToCopy.name, targetDir.buildPath(fileToCopy.relativeName)); std.file.setAttributes(targetDir.buildPath(fileToCopy.relativeName), attributes); } } } /** Wrapper around std.file.copy that also updates the target timestamp. */ void copyAndTouch(RF, RT)(RF from, RT to) { std.file.copy(from, to); const now = Clock.currTime; to.setTimes(now, now); } version (OSX) { // FIXME: Parallel executions hangs reliably on Mac (esp. the 'macair' // host used by the autotester) for unknown reasons outside of this script. pragma(msg, "Warning: Syncing file access because of OSX!"); // Wrap standard library functions to ensure mutually exclusive file access alias readText = fileAccess!(std.file.readText, string); alias writeText = fileAccess!(std.file.write, string, string); alias timeLastModified = fileAccess!(std.file.timeLastModified, string); import core.sync.mutex; __gshared Mutex fileAccessMutex; shared static this() { fileAccessMutex = new Mutex(); } auto fileAccess(alias dg, T...)(T args) { fileAccessMutex.lock_nothrow(); scope (exit) fileAccessMutex.unlock_nothrow(); return dg(args); } } else { alias writeText = std.file.write; }
D
module wx.wxDateTime; public import wx.common; //private import std.date; alias wxDateTime DateTime; enum DayOfWeek { Sun, Mon, Tue, Wed, Thu, Fri, Sat, Inv_WeekDay }; /* wxDateTime imprementation is class { longlong } */ //! \cond EXTERN static extern (C) IntPtr wxDefaultDateTime_Get(); static extern (C) IntPtr wxDateTime_ctor(); static extern (C) IntPtr wxDateTime_Now(); static extern (C) void wxDateTime_dtor(IntPtr self); static extern (C) void wxDateTime_Set(IntPtr self, ushort day, int month, int year, ushort hour, ushort minute, ushort second, ushort millisec); static extern (C) ushort wxDateTime_GetYear(IntPtr self); static extern (C) int wxDateTime_GetMonth(IntPtr self); static extern (C) ushort wxDateTime_GetDay(IntPtr self); static extern (C) ushort wxDateTime_GetHour(IntPtr self); static extern (C) ushort wxDateTime_GetMinute(IntPtr self); static extern (C) ushort wxDateTime_GetSecond(IntPtr self); static extern (C) ushort wxDateTime_GetMillisecond(IntPtr self); //! \endcond //----------------------------------------------------------------------------- /// wxDateTime class represents an absolute moment in time. public class wxDateTime : wxObject { static wxDateTime wxDefaultDateTime; static this(); public this(IntPtr wxobj); private this(IntPtr wxobj, bool memOwn); public this(); override protected void dtor(); public void Set(ushort day, int month, int year, ushort hour, ushort minute, ushort second, ushort millisec); public ushort Year() ; public int Month(); public ushort Day(); public ushort Hour() ; public ushort Minute() ; public ushort Second(); public ushort Millisecond() ; static wxDateTime Now() ; //----------------------------------------------------------------------------- /+ public static implicit operator DateTime (wxDateTime wdt) { DateTime dt = new DateTime(wdt.Year, cast(int)wdt.Month+1, cast(int)wdt.Day, cast(int)wdt.Hour, cast(int)wdt.Minute, cast(int)wdt.Second, cast(int)wdt.Millisecond); return dt; } public static implicit operator wxDateTime (DateTime dt) { wxDateTime wdt = new wxDateTime(); wdt.Set((ushort)dt.Day, dt.Month-1, dt.Year, (ushort)dt.Hour, (ushort)dt.Minute, (ushort)dt.Second, (ushort)dt.Millisecond); return wdt; } +/ //----------------------------------------------------------------------------- }
D
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ module flow.bpmn.converter.converter.child.ConditionExpressionParser; import hunt.logging; import flow.bpmn.model.BaseElement; import flow.bpmn.model.BpmnModel; import flow.bpmn.model.SequenceFlow; import flow.bpmn.converter.converter.child.BaseChildElementParser; import flow.bpmn.converter.constants.BpmnXMLConstants; import hunt.xml; import std.uni; import hunt.logging; import std.string; /** * @author Tijs Rademakers */ class ConditionExpressionParser : BaseChildElementParser { override public string getElementName() { return ELEMENT_FLOW_CONDITION; } override public void parseChildElement(Element xtr, BaseElement parentElement, BpmnModel model) { if (cast(SequenceFlow)parentElement is null) return; if (xtr.firstNode !is null && xtr.firstNode.getType == NodeType.CDATA) { logInfo("ConditionExpressionParser : %s" ,strip(xtr.firstNode.getText())); (cast(SequenceFlow) parentElement).setConditionExpression(strip(xtr.firstNode.getText())); } } }
D
48 c7 c7 fa 97 b9 59 /* movq $0x59b997fa,%rbi */ 68 ec 17 40 00 /* push $0x4017ec */ c3 /* retq */ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 78 dc 61 55 00 00 00 00 /* address of mechine version of movq above */
D
instance VLK_534_Buddler(Npc_Default) { name[0] = NAME_Buddler; npcType = npctype_main; guild = GIL_VLK; level = 3; voice = 2; id = 534; attribute[ATR_STRENGTH] = 25; attribute[ATR_DEXTERITY] = 20; attribute[ATR_MANA_MAX] = 0; attribute[ATR_MANA] = 0; attribute[ATR_HITPOINTS_MAX] = 94; attribute[ATR_HITPOINTS] = 94; Mdl_SetVisual(self,"HUMANS.MDS"); Mdl_ApplyOverlayMds(self,"Humans_Tired.mds"); Mdl_SetVisualBody(self,"hum_body_Naked0",2,1,"Hum_Head_Bald",74,1,vlk_armor_l); B_Scale(self); Mdl_SetModelFatness(self,0); fight_tactic = FAI_HUMAN_COWARD; CreateInvItem(self,ItMw_1H_Nailmace_01); CreateInvItem(self,ItMwPickaxe); CreateInvItem(self,ItFoLoaf); CreateInvItem(self,ItFoBeer); CreateInvItem(self,ItLsTorch); daily_routine = Rtn_start_534; }; func void Rtn_start_534() { TA_SitCampfire(10,0,22,0,"OC_ROUND_22_CF_2"); TA_SitCampfire(10,0,22,0,"OC_ROUND_22_CF_2"); }; func void rtn_alternative_534() { TA_PlayTune(10,0,22,0,"OCR_COOK_AT_HUT_10"); TA_PlayTune(10,0,22,0,"OCR_COOK_AT_HUT_10"); };
D
/Users/dali/Documents/GitHub/rustlings/target/debug/deps/escargot-d111cdd4c8897c09.rmeta: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/escargot-0.4.0/src/lib.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/escargot-0.4.0/src/build.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/escargot-0.4.0/src/cargo.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/escargot-0.4.0/src/msg.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/escargot-0.4.0/src/run.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/escargot-0.4.0/src/error.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/escargot-0.4.0/src/format/mod.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/escargot-0.4.0/src/format/diagnostic.rs /Users/dali/Documents/GitHub/rustlings/target/debug/build/escargot-eaf18a1130e21acb/out/current_target.txt /Users/dali/Documents/GitHub/rustlings/target/debug/deps/escargot-d111cdd4c8897c09.d: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/escargot-0.4.0/src/lib.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/escargot-0.4.0/src/build.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/escargot-0.4.0/src/cargo.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/escargot-0.4.0/src/msg.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/escargot-0.4.0/src/run.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/escargot-0.4.0/src/error.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/escargot-0.4.0/src/format/mod.rs /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/escargot-0.4.0/src/format/diagnostic.rs /Users/dali/Documents/GitHub/rustlings/target/debug/build/escargot-eaf18a1130e21acb/out/current_target.txt /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/escargot-0.4.0/src/lib.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/escargot-0.4.0/src/build.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/escargot-0.4.0/src/cargo.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/escargot-0.4.0/src/msg.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/escargot-0.4.0/src/run.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/escargot-0.4.0/src/error.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/escargot-0.4.0/src/format/mod.rs: /Users/dali/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/escargot-0.4.0/src/format/diagnostic.rs: /Users/dali/Documents/GitHub/rustlings/target/debug/build/escargot-eaf18a1130e21acb/out/current_target.txt: # env-dep:OUT_DIR=/Users/dali/Documents/GitHub/rustlings/target/debug/build/escargot-eaf18a1130e21acb/out
D
module cgy.util.pos; import std.conv; //import cgy.stolen.aabbox3d; import gl3n.linalg : Vector, vec3d, vec3i, vec2i; import gl3n.aabb : AABBT; alias AABBT!float AABBf; alias AABBT!double AABBd; import cgy.math.math : negDiv, posMod, convert; //import cgy.math.aabb : aabb3d; //import cgy.math.vector; //import worldstate.sector; import cgy.util.sizes; //import cgy.util.util; import cgy.debug_.debug_ : BREAK_IF; mixin template ToStringMethod3D() { string toString() { return typeof(this).stringof ~ " (" ~ to!string(value.x) ~ ", " ~ to!string(value.y) ~ ", " ~ to!string(value.z) ~ ")"; } } mixin template ToStringMethod2D() { string toString(){ return typeof(this).stringof ~ " (" ~ to!string(value.x) ~ ", " ~ to!string(value.y) ~ ")"; } } // No need to make the wrapper classes introduce an extra scope level in json. mixin template SerializeValue() { import painlessjson : toJSON, fromJSON; import std.json : JSONValue; auto _toJSON() { value.toJSON; } void _fromJSON(JSONValue v) { value = fromJSON!(typeof(value))(v); } } // We no longer handle tileposes etc below 0 // So a simple cast to int will suffice vec3i getTilePos(T)(Vector!(T,3) v){ return vec3i( cast(int)v.x, cast(int)v.y, cast(int)v.z); } struct UnitPos { vec3d value; TilePos tilePos() const @property { return TilePos( getTilePos(value.convert!int) ); } alias tilePos this; mixin ToStringMethod3D; mixin SerializeValue; } struct EntityPos { vec3d value; // ToDo: fix so that the hoalls reada pao the side of the tile. TilePos tilePos() const @property { return TilePos( getTilePos(value) ); } alias tilePos this; mixin ToStringMethod3D; mixin SerializeValue; } struct SectorNum { vec3i value; BlockNum toBlockNum() const { return BlockNum(vec3i( value.x * BlocksPerSector.x, value.y * BlocksPerSector.y, value.z * BlocksPerSector.z)); } TilePos toTilePos() const { return TilePos(vec3i( value.x * SectorSize.x, value.y * SectorSize.y, value.z * SectorSize.z)); } TileXYPos toTileXYPos() const{ return TileXYPos(vec2i( value.x * SectorSize.x, value.y * SectorSize.y)); } AABBd getAABB(){ auto minPos = toTilePos().value.convert!double(); auto maxPos = minPos + vec3d(SectorSize.x, SectorSize.y, SectorSize.z); return aabb3d(minPos, maxPos); } mixin ToStringMethod3D; mixin SerializeValue; } struct BlockNum { vec3i value = vec3i(0,0,0); invariant() { BREAK_IF(value.x < 0 || value.y < 0); } SectorNum getSectorNum() const { return SectorNum(vec3i( negDiv(value.x, BlocksPerSector.x), negDiv(value.y, BlocksPerSector.y), negDiv(value.z, BlocksPerSector.z))); } TilePos toTilePos() const { return TilePos(vec3i( value.x * BlockSize.x, value.y * BlockSize.y, value.z * BlockSize.z)); } AABBd getAABB(){ auto minPos = toTilePos().value.convert!double(); auto maxPos = minPos + vec3d(BlockSize.x, BlockSize.y, BlockSize.z); return aabb3d(minPos, maxPos); } // Relative index vec3i rel() const out(x){ assert(0 <= x.x); assert(0 <= x.y); assert(0 <= x.z); assert(x.x < BlocksPerSector.x); assert(x.y < BlocksPerSector.y); assert(x.z < BlocksPerSector.z); } body{ return vec3i( posMod(value.x, BlocksPerSector.x), posMod(value.y, BlocksPerSector.y), posMod(value.z, BlocksPerSector.z) ); } mixin ToStringMethod3D; mixin SerializeValue; } struct TilePos { vec3i value; SectorNum getSectorNum() const { return SectorNum(vec3i( negDiv(value.x, SectorSize.x), negDiv(value.y, SectorSize.y), negDiv(value.z, SectorSize.z))); } BlockNum getBlockNum() const { return BlockNum(vec3i( negDiv(value.x, BlockSize.x), negDiv(value.y, BlockSize.y), negDiv(value.z, BlockSize.z))); } BlockNum[] getNeighboringBlockNums() const { BlockNum[] ret; auto thisNum = getBlockNum(); auto rel = vec3i( posMod(value.x, BlockSize.x), posMod(value.y, BlockSize.y), posMod(value.z, BlockSize.z), ); if (rel.x == 0) { auto tmp = thisNum; tmp.value.x -= 1; ret ~= tmp; } else if (rel.x == BlockSize.x-1) { auto tmp = thisNum; tmp.value.x += 1; ret ~= tmp; } if (rel.y == 0) { auto tmp = thisNum; tmp.value.y -= 1; ret ~= tmp; } else if (rel.y == BlockSize.y-1) { auto tmp = thisNum; tmp.value.y += 1; ret ~= tmp; } if (rel.z == 0) { auto tmp = thisNum; tmp.value.z -= 1; ret ~= tmp; } else if (rel.z == BlockSize.z-1) { auto tmp = thisNum; tmp.value.z += 1; ret ~= tmp; } return ret; } GraphRegionNum getGraphRegionNum() const{ return GraphRegionNum(vec3i( negDiv(value.x, GraphRegionSize.x), negDiv(value.y, GraphRegionSize.y), negDiv(value.z, GraphRegionSize.z), )); } GraphRegionNum[] getNeighboringGraphRegionNums() const { GraphRegionNum[] ret; auto thisNum = getGraphRegionNum(); auto rel = vec3i( posMod(value.x, GraphRegionSize.x), posMod(value.y, GraphRegionSize.y), posMod(value.z, GraphRegionSize.z), ); if (rel.x == 0) { auto tmp = thisNum; tmp.value.x -= 1; ret ~= tmp; } else if (rel.x == GraphRegionSize.x-1) { auto tmp = thisNum; tmp.value.x += 1; ret ~= tmp; } if (rel.y == 0) { auto tmp = thisNum; tmp.value.y -= 1; ret ~= tmp; } else if (rel.y == GraphRegionSize.y-1) { auto tmp = thisNum; tmp.value.y += 1; ret ~= tmp; } if (rel.z == 0) { auto tmp = thisNum; tmp.value.z -= 1; ret ~= tmp; } else if (rel.z == GraphRegionSize.z-1) { auto tmp = thisNum; tmp.value.z += 1; ret ~= tmp; } return ret; } UnitPos toUnitPos() const{ return UnitPos(vec3d(value.x + 0.5, value.y + 0.5, value.z + 0.5)); } EntityPos toEntityPos() const{ return EntityPos(vec3d(value.x + 0.5, value.y + 0.5, value.z + 0.5)); } TileXYPos toTileXYPos() const{ return TileXYPos(vec2i(value.x, value.y)); } AABBd getAABB(){ auto minPos = value.convert!double(); auto maxPos = minPos + vec3d(1.0, 1.0, 1.0); return aabb3d(minPos, maxPos); } // Relative index vec3i rel() const out(x){ assert(x.x >= 0, "rel.x < 0!!! :("); assert(x.y >= 0, "rel.y < 0!!! :("); assert(x.z >= 0, "rel.z < 0!!! :("); assert(x.x < TilesPerBlock.x, "rel.x > TilesPerBlock.x!!! :("); assert(x.y < TilesPerBlock.y, "rel.y > TilesPerBlock.y!!! :("); assert(x.z < TilesPerBlock.z, "rel.z > TilesPerBlock.z!!! :("); } body{ return vec3i( posMod(value.x, TilesPerBlock.x), posMod(value.y, TilesPerBlock.y), posMod(value.z, TilesPerBlock.z) ); } vec3i sectorRel() const out(x){ assert(x.x >= 0, "rel.x < 0!!! :("); assert(x.y >= 0, "rel.y < 0!!! :("); assert(x.z >= 0, "rel.z < 0!!! :("); assert(x.x < SectorSize.x, "rel.x > SectorSize.x!!! :("); assert(x.y < SectorSize.y, "rel.y > SectorSize.y!!! :("); assert(x.z < SectorSize.z, "rel.z > SectorSize.z!!! :("); } body{ return vec3i( posMod(value.x, SectorSize.x), posMod(value.y, SectorSize.y), posMod(value.z, SectorSize.z) ); } mixin ToStringMethod3D; mixin SerializeValue; } struct GraphRegionNum{ vec3i value; SectorNum getSectorNum() const { immutable divX = SectorSize.x / GraphRegionSize.x; immutable divY = SectorSize.y / GraphRegionSize.y; immutable divZ = SectorSize.z / GraphRegionSize.z; return SectorNum(vec3i( negDiv(value.x, divX), negDiv(value.y, divY), negDiv(value.z, divZ))); } TilePos max() const { auto ret = min(); ret.value += vec3i( GraphRegionSize.x-1, GraphRegionSize.y-1, GraphRegionSize.z-1); return ret; } TilePos min() const { return TilePos(vec3i( GraphRegionSize.x * value.x, GraphRegionSize.y * value.y, GraphRegionSize.z * value.z )); } alias min toTilePos; AABBd getAABB() const { auto minPos = min().value.convert!double(); auto maxPos = max().value.convert!double(); return aabb3d(minPos, maxPos); } mixin ToStringMethod3D; mixin SerializeValue; } struct SectorXYNum { vec2i value; this(vec2i v) { value = v; } this(SectorNum num) { value.set(num.value.x, num.value.y); } SectorNum getSectorNum(int z) const { return SectorNum(vec3i( value.x, value.y, z)); } TileXYPos getTileXYPos() const { return TileXYPos(vec2i( value.x * SectorSize.x, value.y * SectorSize.y)); } bool inside(TileXYPos tp) { auto val = tp.value; auto me = getTileXYPos().value; return (val.x >= me.x) && (val.x < me.x + SectorSize.x) && (val.y >= me.y) && (val.y < me.y + SectorSize.y); } mixin ToStringMethod2D; } struct TileXYPos { vec2i value; this(vec2i pos) { value = pos; } this(TilePos pos) { value.set(pos.value.x, pos.value.y); } SectorXYNum getSectorXYNum() const { return SectorXYNum(vec2i( negDiv(value.x, SectorSize.x), negDiv(value.y, SectorSize.y))); } vec2i sectorRel() const{ return vec2i(posMod(value.x, SectorSize.x), posMod(value.y, SectorSize.y)); } TilePos toTilePos(int z) const { return TilePos(vec3i(value.x, value.y, z)); } mixin ToStringMethod2D; mixin SerializeValue; }
D
module kw.kwbool; alias KW_bool = int; enum /*KW_bool*/{ KW_FALSE = 0, KW_TRUE = 1 }
D