content
stringlengths
23
1.05M
with Ada.Text_IO; use Ada.Text_IO; with Ada.Text_IO.Text_Streams; use Ada.Text_IO; with Ada.Streams; use Ada.Streams; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Command_Line; use Ada.Command_Line; with AWS.Default; with AWS.Net; use AWS; with AWS.Net.SSL; use AWS.Net; with Aids.Env; use Aids; with Aids.Utilities; use Aids.Utilities; procedure Freenode is type Irc_Credentials is record Host : Unbounded_String; Port : Positive; Nick : Unbounded_String; Pass : Unbounded_String; Channel : Unbounded_String; end record; procedure Print_Irc_Credentials(C: in Irc_Credentials) is begin Put_Line("Host: " & To_String(C.Host)); Put_Line("Port:" & Positive'Image(C.Port)); Put_Line("Nick: " & To_String(C.Nick)); Put_Line("Pass: [REDACTED]"); Put_Line("Channel: " & To_String(C.Channel)); end; function Irc_Credentials_From_File(File_Path: String) return Irc_Credentials is -- Key extraction functions. Function Extract ( Key : String ) return String with Inline; Function Extract ( Key : String ) return Unbounded_String with Inline; Function Extract ( Key : String ) return Positive with Inline; E: Env.Typ := Env.Slurp(File_Path); Key_Not_Found : exception; -- Base Extraction; provides for the key-not-found exception. Function Extract ( Key : String ) return String is Begin Return E(Key); Exception when Constraint_Error => raise Key_Not_Found with (File_Path & ": key `" & Key & "` not found"); End Extract; -- Extract & convert to an Unbounded_String. Function Extract ( Key : String ) return Unbounded_String is ( To_Unbounded_String( Source => Extract(Key) ) ); -- Extract and convert to a Positive. Function Extract ( Key : String ) return Positive is Value : String renames Extract( Key ); Begin Return Positive'Value( Value ); Exception when Constraint_Error => raise Constraint_Error with ''' & Value & "' could not be converted to a positive number."; End Extract; begin return Result : constant Irc_Credentials := ( Nick => Extract("NICK"), Pass => Extract("PASS"), Channel => Extract("CHANNEL"), Host => Extract("HOST"), Port => Extract("PORT") ); end; procedure Send_Line(Client: in out SSL.Socket_Type; Line: in String) is CRLF : Constant String := (Character'Val(13), Character'Val(10)); begin Client.Send(String_To_Chunk(Line & CRLF)); end; -- NOTE: stolen from https://github.com/AdaCore/aws/blob/master/regtests/0243_sshort/sshort.adb#L156 procedure Secure_Connection(Credentials: Irc_Credentials) is Client: SSL.Socket_Type; Config: SSL.Config; begin Put_Line("Establishing secure (Kapp) connection to " & To_String(Credentials.Host) & ":" & Integer'Image(Credentials.Port)); SSL.Initialize(Config, ""); Client.Set_Config(Config); Client.Connect(To_String(Credentials.Host), Credentials.Port); Send_Line( Client, "PASS oauth:" & To_String(Credentials.Pass)); Send_Line( Client, "NICK " & To_String(Credentials.Nick)); Send_Line( Client, "JOIN " & To_String(Credentials.Channel)); Send_Line( Client, "PRIVMSG " & To_String(Credentials.Channel) & " :tsodinPog"); while true loop declare Chunk: Stream_Element_Array := Client.Receive; begin Put(Chunk_Image(Chunk)); end; end loop; end; Not_Enough_Arguments: exception; begin if Argument_Count not in Positive then raise Not_Enough_Arguments; end if; declare Twitch: Irc_Credentials := Irc_Credentials_From_File(Argument(1)); begin Print_Irc_Credentials(Twitch); Secure_Connection(Twitch); end; end;
------------------------------------------------------------------------------- -- -- -- Coffee Clock -- -- -- -- Copyright (C) 2016-2017 Fabien Chouteau -- -- -- -- Coffee Clock 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. -- -- -- -- Coffee Clock 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 We Noise Maker. If not, see <http://www.gnu.org/licenses/>. -- -- -- ------------------------------------------------------------------------------- with Giza.Window; with Giza.Widget.Button; with Giza.Widget.Tiles; with Giza.Widget.Frame; use Giza.Widget; with Giza.Image; with Giza.Events; use Giza.Events; with Giza.Types; use Giza.Types; package Dialog_Window is type Answer_T is (Unknown_Answer, Answer_Top, Answer_Bottom); subtype Parent is Giza.Window.Instance; type Instance (Panel_Size : Natural) is abstract new Parent with private; subtype Class is Instance'Class; type Ref is access all Class; overriding procedure On_Init (This : in out Instance); overriding function On_Position_Event (This : in out Instance; Evt : Position_Event_Ref; Pos : Point_T) return Boolean; overriding function Get_Size (This : Instance) return Size_T; function Get_Answer (This : Instance) return Answer_T; procedure Clear_Answer (This : in out Instance); procedure Set_Top_Image (This : in out Instance; Img : Giza.Image.Ref); procedure Set_Icon_Image (This : in out Instance; Img : Giza.Image.Ref); procedure Set_Bottom_Image (This : in out Instance; Img : Giza.Image.Ref); private type Instance (Panel_Size : Natural) is abstract new Parent with record Top_Btn, Bottom_Btn : aliased Button.Instance; Icon : aliased Frame.Instance; Tile : aliased Tiles.Instance (3, Tiles.Top_Down); Answer : Answer_T := Unknown_Answer; end record; end Dialog_Window;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- SYSTEM.TASK_PRIMITIVES.INTERRUPT_OPERATIONS -- -- -- -- S p e c -- -- -- -- Copyright (C) 1998-2020, Free Software Foundation, Inc. -- -- -- -- GNARL is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNARL was developed by the GNARL team at Florida State University. -- -- Extensive contributions were provided by Ada Core Technologies, Inc. -- -- -- ------------------------------------------------------------------------------ with System.Interrupt_Management; with System.Tasking; package System.Task_Primitives.Interrupt_Operations is pragma Preelaborate; package IM renames System.Interrupt_Management; package ST renames System.Tasking; procedure Set_Interrupt_ID (Interrupt : IM.Interrupt_ID; T : ST.Task_Id); -- Associate an Interrupt_ID with a task function Get_Interrupt_ID (T : ST.Task_Id) return IM.Interrupt_ID; -- Return the Interrupt_ID associated with a task function Get_Task_Id (Interrupt : IM.Interrupt_ID) return ST.Task_Id; -- Return the Task_Id associated with an Interrupt end System.Task_Primitives.Interrupt_Operations;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S E M _ D I S P -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2006, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT 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 distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, -- -- Boston, MA 02110-1301, USA. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Atree; use Atree; with Debug; use Debug; with Elists; use Elists; with Einfo; use Einfo; with Exp_Disp; use Exp_Disp; with Exp_Ch7; use Exp_Ch7; with Exp_Tss; use Exp_Tss; with Exp_Util; use Exp_Util; with Errout; use Errout; with Hostparm; use Hostparm; with Nlists; use Nlists; with Nmake; use Nmake; with Opt; use Opt; with Output; use Output; with Restrict; use Restrict; with Rident; use Rident; with Sem; use Sem; with Sem_Ch6; use Sem_Ch6; with Sem_Eval; use Sem_Eval; with Sem_Type; use Sem_Type; with Sem_Util; use Sem_Util; with Snames; use Snames; with Stand; use Stand; with Sinfo; use Sinfo; with Tbuild; use Tbuild; with Uintp; use Uintp; package body Sem_Disp is ----------------------- -- Local Subprograms -- ----------------------- procedure Add_Dispatching_Operation (Tagged_Type : Entity_Id; New_Op : Entity_Id); -- Add New_Op in the list of primitive operations of Tagged_Type function Check_Controlling_Type (T : Entity_Id; Subp : Entity_Id) return Entity_Id; -- T is the tagged type of a formal parameter or the result of Subp. -- If the subprogram has a controlling parameter or result that matches -- the type, then returns the tagged type of that parameter or result -- (returning the designated tagged type in the case of an access -- parameter); otherwise returns empty. ------------------------------- -- Add_Dispatching_Operation -- ------------------------------- procedure Add_Dispatching_Operation (Tagged_Type : Entity_Id; New_Op : Entity_Id) is List : constant Elist_Id := Primitive_Operations (Tagged_Type); begin Append_Elmt (New_Op, List); end Add_Dispatching_Operation; ------------------------------- -- Check_Controlling_Formals -- ------------------------------- procedure Check_Controlling_Formals (Typ : Entity_Id; Subp : Entity_Id) is Formal : Entity_Id; Ctrl_Type : Entity_Id; Remote : constant Boolean := Is_Remote_Types (Current_Scope) and then Comes_From_Source (Subp) and then Scope (Typ) = Current_Scope; begin Formal := First_Formal (Subp); while Present (Formal) loop Ctrl_Type := Check_Controlling_Type (Etype (Formal), Subp); if Present (Ctrl_Type) then if Ctrl_Type = Typ then Set_Is_Controlling_Formal (Formal); -- Ada 2005 (AI-231):Anonymous access types used in controlling -- parameters exclude null because it is necessary to read the -- tag to dispatch, and null has no tag. if Ekind (Etype (Formal)) = E_Anonymous_Access_Type then Set_Can_Never_Be_Null (Etype (Formal)); Set_Is_Known_Non_Null (Etype (Formal)); end if; -- Check that the parameter's nominal subtype statically -- matches the first subtype. if Ekind (Etype (Formal)) = E_Anonymous_Access_Type then if not Subtypes_Statically_Match (Typ, Designated_Type (Etype (Formal))) then Error_Msg_N ("parameter subtype does not match controlling type", Formal); end if; elsif not Subtypes_Statically_Match (Typ, Etype (Formal)) then Error_Msg_N ("parameter subtype does not match controlling type", Formal); end if; if Present (Default_Value (Formal)) then if Ekind (Etype (Formal)) = E_Anonymous_Access_Type then Error_Msg_N ("default not allowed for controlling access parameter", Default_Value (Formal)); elsif not Is_Tag_Indeterminate (Default_Value (Formal)) then Error_Msg_N ("default expression must be a tag indeterminate" & " function call", Default_Value (Formal)); end if; end if; elsif Comes_From_Source (Subp) then Error_Msg_N ("operation can be dispatching in only one type", Subp); end if; -- Verify that the restriction in E.2.2 (14) is obeyed elsif Remote and then Ekind (Etype (Formal)) = E_Anonymous_Access_Type then Error_Msg_N ("access parameter of remote object primitive" & " must be controlling", Formal); end if; Next_Formal (Formal); end loop; if Present (Etype (Subp)) then Ctrl_Type := Check_Controlling_Type (Etype (Subp), Subp); if Present (Ctrl_Type) then if Ctrl_Type = Typ then Set_Has_Controlling_Result (Subp); -- Check that the result subtype statically matches -- the first subtype. if not Subtypes_Statically_Match (Typ, Etype (Subp)) then Error_Msg_N ("result subtype does not match controlling type", Subp); end if; elsif Comes_From_Source (Subp) then Error_Msg_N ("operation can be dispatching in only one type", Subp); end if; -- The following check is clearly required, although the RM says -- nothing about return types. If the return type is a limited -- class-wide type declared in the current scope, there is no way -- to declare stream procedures for it, so the return cannot be -- marshalled. elsif Remote and then Is_Limited_Type (Typ) and then Etype (Subp) = Class_Wide_Type (Typ) then Error_Msg_N ("return type has no stream attributes", Subp); end if; end if; end Check_Controlling_Formals; ---------------------------- -- Check_Controlling_Type -- ---------------------------- function Check_Controlling_Type (T : Entity_Id; Subp : Entity_Id) return Entity_Id is Tagged_Type : Entity_Id := Empty; begin if Is_Tagged_Type (T) then if Is_First_Subtype (T) then Tagged_Type := T; else Tagged_Type := Base_Type (T); end if; elsif Ekind (T) = E_Anonymous_Access_Type and then Is_Tagged_Type (Designated_Type (T)) then if Ekind (Designated_Type (T)) /= E_Incomplete_Type then if Is_First_Subtype (Designated_Type (T)) then Tagged_Type := Designated_Type (T); else Tagged_Type := Base_Type (Designated_Type (T)); end if; -- Ada 2005 (AI-50217) elsif From_With_Type (Designated_Type (T)) and then Present (Non_Limited_View (Designated_Type (T))) then if Is_First_Subtype (Non_Limited_View (Designated_Type (T))) then Tagged_Type := Non_Limited_View (Designated_Type (T)); else Tagged_Type := Base_Type (Non_Limited_View (Designated_Type (T))); end if; end if; end if; if No (Tagged_Type) or else Is_Class_Wide_Type (Tagged_Type) then return Empty; -- The dispatching type and the primitive operation must be defined -- in the same scope, except in the case of internal operations and -- formal abstract subprograms. elsif ((Scope (Subp) = Scope (Tagged_Type) or else Is_Internal (Subp)) and then (not Is_Generic_Type (Tagged_Type) or else not Comes_From_Source (Subp))) or else (Is_Formal_Subprogram (Subp) and then Is_Abstract (Subp)) or else (Nkind (Parent (Parent (Subp))) = N_Subprogram_Renaming_Declaration and then Present (Corresponding_Formal_Spec (Parent (Parent (Subp)))) and then Is_Abstract (Subp)) then return Tagged_Type; else return Empty; end if; end Check_Controlling_Type; ---------------------------- -- Check_Dispatching_Call -- ---------------------------- procedure Check_Dispatching_Call (N : Node_Id) is Actual : Node_Id; Formal : Entity_Id; Control : Node_Id := Empty; Func : Entity_Id; Subp_Entity : Entity_Id; Loc : constant Source_Ptr := Sloc (N); Indeterm_Ancestor_Call : Boolean := False; Indeterm_Ctrl_Type : Entity_Id; procedure Check_Dispatching_Context; -- If the call is tag-indeterminate and the entity being called is -- abstract, verify that the context is a call that will eventually -- provide a tag for dispatching, or has provided one already. ------------------------------- -- Check_Dispatching_Context -- ------------------------------- procedure Check_Dispatching_Context is Subp : constant Entity_Id := Entity (Name (N)); Par : Node_Id; begin if Is_Abstract (Subp) and then No (Controlling_Argument (N)) then if Present (Alias (Subp)) and then not Is_Abstract (Alias (Subp)) and then No (DTC_Entity (Subp)) then -- Private overriding of inherited abstract operation, -- call is legal. Set_Entity (Name (N), Alias (Subp)); return; else Par := Parent (N); while Present (Par) loop if (Nkind (Par) = N_Function_Call or else Nkind (Par) = N_Procedure_Call_Statement or else Nkind (Par) = N_Assignment_Statement or else Nkind (Par) = N_Op_Eq or else Nkind (Par) = N_Op_Ne) and then Is_Tagged_Type (Etype (Subp)) then return; elsif Nkind (Par) = N_Qualified_Expression or else Nkind (Par) = N_Unchecked_Type_Conversion then Par := Parent (Par); else if Ekind (Subp) = E_Function then Error_Msg_N ("call to abstract function must be dispatching", N); -- This error can occur for a procedure in the case of a -- call to an abstract formal procedure with a statically -- tagged operand. else Error_Msg_N ("call to abstract procedure must be dispatching", N); end if; return; end if; end loop; end if; end if; end Check_Dispatching_Context; -- Start of processing for Check_Dispatching_Call begin -- Find a controlling argument, if any if Present (Parameter_Associations (N)) then Actual := First_Actual (N); Subp_Entity := Entity (Name (N)); Formal := First_Formal (Subp_Entity); while Present (Actual) loop Control := Find_Controlling_Arg (Actual); exit when Present (Control); -- Check for the case where the actual is a tag-indeterminate call -- whose result type is different than the tagged type associated -- with the containing call, but is an ancestor of the type. if Is_Controlling_Formal (Formal) and then Is_Tag_Indeterminate (Actual) and then Base_Type (Etype (Actual)) /= Base_Type (Etype (Formal)) and then Is_Ancestor (Etype (Actual), Etype (Formal)) then Indeterm_Ancestor_Call := True; Indeterm_Ctrl_Type := Etype (Formal); end if; Next_Actual (Actual); Next_Formal (Formal); end loop; -- If the call doesn't have a controlling actual but does have -- an indeterminate actual that requires dispatching treatment, -- then an object is needed that will serve as the controlling -- argument for a dispatching call on the indeterminate actual. -- This can only occur in the unusual situation of a default -- actual given by a tag-indeterminate call and where the type -- of the call is an ancestor of the type associated with a -- containing call to an inherited operation (see AI-239). -- Rather than create an object of the tagged type, which would -- be problematic for various reasons (default initialization, -- discriminants), the tag of the containing call's associated -- tagged type is directly used to control the dispatching. if No (Control) and then Indeterm_Ancestor_Call then Control := Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Indeterm_Ctrl_Type, Loc), Attribute_Name => Name_Tag); Analyze (Control); end if; if Present (Control) then -- Verify that no controlling arguments are statically tagged if Debug_Flag_E then Write_Str ("Found Dispatching call"); Write_Int (Int (N)); Write_Eol; end if; Actual := First_Actual (N); while Present (Actual) loop if Actual /= Control then if not Is_Controlling_Actual (Actual) then null; -- Can be anything elsif Is_Dynamically_Tagged (Actual) then null; -- Valid parameter elsif Is_Tag_Indeterminate (Actual) then -- The tag is inherited from the enclosing call (the -- node we are currently analyzing). Explicitly expand -- the actual, since the previous call to Expand -- (from Resolve_Call) had no way of knowing about -- the required dispatching. Propagate_Tag (Control, Actual); else Error_Msg_N ("controlling argument is not dynamically tagged", Actual); return; end if; end if; Next_Actual (Actual); end loop; -- Mark call as a dispatching call Set_Controlling_Argument (N, Control); else -- The call is not dispatching, so check that there aren't any -- tag-indeterminate abstract calls left. Actual := First_Actual (N); while Present (Actual) loop if Is_Tag_Indeterminate (Actual) then -- Function call case if Nkind (Original_Node (Actual)) = N_Function_Call then Func := Entity (Name (Original_Node (Actual))); -- If the actual is an attribute then it can't be abstract -- (the only current case of a tag-indeterminate attribute -- is the stream Input attribute). elsif Nkind (Original_Node (Actual)) = N_Attribute_Reference then Func := Empty; -- Only other possibility is a qualified expression whose -- consituent expression is itself a call. else Func := Entity (Name (Original_Node (Expression (Original_Node (Actual))))); end if; if Present (Func) and then Is_Abstract (Func) then Error_Msg_N ( "call to abstract function must be dispatching", N); end if; end if; Next_Actual (Actual); end loop; Check_Dispatching_Context; end if; else -- If dispatching on result, the enclosing call, if any, will -- determine the controlling argument. Otherwise this is the -- primitive operation of the root type. Check_Dispatching_Context; end if; end Check_Dispatching_Call; --------------------------------- -- Check_Dispatching_Operation -- --------------------------------- procedure Check_Dispatching_Operation (Subp, Old_Subp : Entity_Id) is Tagged_Type : Entity_Id; Has_Dispatching_Parent : Boolean := False; Body_Is_Last_Primitive : Boolean := False; function Is_Visibly_Controlled (T : Entity_Id) return Boolean; -- Check whether T is derived from a visibly controlled type. -- This is true if the root type is declared in Ada.Finalization. -- If T is derived instead from a private type whose full view -- is controlled, an explicit Initialize/Adjust/Finalize subprogram -- does not override the inherited one. --------------------------- -- Is_Visibly_Controlled -- --------------------------- function Is_Visibly_Controlled (T : Entity_Id) return Boolean is Root : constant Entity_Id := Root_Type (T); begin return Chars (Scope (Root)) = Name_Finalization and then Chars (Scope (Scope (Root))) = Name_Ada and then Scope (Scope (Scope (Root))) = Standard_Standard; end Is_Visibly_Controlled; -- Start of processing for Check_Dispatching_Operation begin if Ekind (Subp) /= E_Procedure and then Ekind (Subp) /= E_Function then return; end if; Set_Is_Dispatching_Operation (Subp, False); Tagged_Type := Find_Dispatching_Type (Subp); -- Ada 2005 (AI-345) if Ada_Version = Ada_05 and then Present (Tagged_Type) and then Is_Concurrent_Type (Tagged_Type) then -- Protect the frontend against previously detected errors if No (Corresponding_Record_Type (Tagged_Type)) then return; end if; Tagged_Type := Corresponding_Record_Type (Tagged_Type); end if; -- If Subp is derived from a dispatching operation then it should -- always be treated as dispatching. In this case various checks -- below will be bypassed. Makes sure that late declarations for -- inherited private subprograms are treated as dispatching, even -- if the associated tagged type is already frozen. Has_Dispatching_Parent := Present (Alias (Subp)) and then Is_Dispatching_Operation (Alias (Subp)); if No (Tagged_Type) then return; -- The subprograms build internally after the freezing point (such as -- the Init procedure) are not primitives elsif Is_Frozen (Tagged_Type) and then not Comes_From_Source (Subp) and then not Has_Dispatching_Parent then return; -- The operation may be a child unit, whose scope is the defining -- package, but which is not a primitive operation of the type. elsif Is_Child_Unit (Subp) then return; -- If the subprogram is not defined in a package spec, the only case -- where it can be a dispatching op is when it overrides an operation -- before the freezing point of the type. elsif ((not Is_Package_Or_Generic_Package (Scope (Subp))) or else In_Package_Body (Scope (Subp))) and then not Has_Dispatching_Parent then if not Comes_From_Source (Subp) or else (Present (Old_Subp) and then not Is_Frozen (Tagged_Type)) then null; -- If the type is already frozen, the overriding is not allowed -- except when Old_Subp is not a dispatching operation (which -- can occur when Old_Subp was inherited by an untagged type). -- However, a body with no previous spec freezes the type "after" -- its declaration, and therefore is a legal overriding (unless -- the type has already been frozen). Only the first such body -- is legal. elsif Present (Old_Subp) and then Is_Dispatching_Operation (Old_Subp) then if Comes_From_Source (Subp) and then (Nkind (Unit_Declaration_Node (Subp)) = N_Subprogram_Body or else Nkind (Unit_Declaration_Node (Subp)) in N_Body_Stub) then declare Subp_Body : constant Node_Id := Unit_Declaration_Node (Subp); Decl_Item : Node_Id := Next (Parent (Tagged_Type)); begin -- ??? The checks here for whether the type has been -- frozen prior to the new body are not complete. It's -- not simple to check frozenness at this point since -- the body has already caused the type to be prematurely -- frozen in Analyze_Declarations, but we're forced to -- recheck this here because of the odd rule interpretation -- that allows the overriding if the type wasn't frozen -- prior to the body. The freezing action should probably -- be delayed until after the spec is seen, but that's -- a tricky change to the delicate freezing code. -- Look at each declaration following the type up -- until the new subprogram body. If any of the -- declarations is a body then the type has been -- frozen already so the overriding primitive is -- illegal. while Present (Decl_Item) and then (Decl_Item /= Subp_Body) loop if Comes_From_Source (Decl_Item) and then (Nkind (Decl_Item) in N_Proper_Body or else Nkind (Decl_Item) in N_Body_Stub) then Error_Msg_N ("overriding of& is too late!", Subp); Error_Msg_N ("\spec should appear immediately after the type!", Subp); exit; end if; Next (Decl_Item); end loop; -- If the subprogram doesn't follow in the list of -- declarations including the type then the type -- has definitely been frozen already and the body -- is illegal. if No (Decl_Item) then Error_Msg_N ("overriding of& is too late!", Subp); Error_Msg_N ("\spec should appear immediately after the type!", Subp); elsif Is_Frozen (Subp) then -- The subprogram body declares a primitive operation. -- if the subprogram is already frozen, we must update -- its dispatching information explicitly here. The -- information is taken from the overridden subprogram. Body_Is_Last_Primitive := True; if Present (DTC_Entity (Old_Subp)) then Set_DTC_Entity (Subp, DTC_Entity (Old_Subp)); Set_DT_Position (Subp, DT_Position (Old_Subp)); if not Restriction_Active (No_Dispatching_Calls) then Insert_After (Subp_Body, Fill_DT_Entry (Sloc (Subp_Body), Subp)); end if; end if; end if; end; else Error_Msg_N ("overriding of& is too late!", Subp); Error_Msg_N ("\subprogram spec should appear immediately after the type!", Subp); end if; -- If the type is not frozen yet and we are not in the overridding -- case it looks suspiciously like an attempt to define a primitive -- operation. elsif not Is_Frozen (Tagged_Type) then Error_Msg_N ("?not dispatching (must be defined in a package spec)", Subp); return; -- When the type is frozen, it is legitimate to define a new -- non-primitive operation. else return; end if; -- Now, we are sure that the scope is a package spec. If the subprogram -- is declared after the freezing point ot the type that's an error elsif Is_Frozen (Tagged_Type) and then not Has_Dispatching_Parent then Error_Msg_N ("this primitive operation is declared too late", Subp); Error_Msg_NE ("?no primitive operations for& after this line", Freeze_Node (Tagged_Type), Tagged_Type); return; end if; Check_Controlling_Formals (Tagged_Type, Subp); -- Now it should be a correct primitive operation, put it in the list if Present (Old_Subp) then Check_Subtype_Conformant (Subp, Old_Subp); if (Chars (Subp) = Name_Initialize or else Chars (Subp) = Name_Adjust or else Chars (Subp) = Name_Finalize) and then Is_Controlled (Tagged_Type) and then not Is_Visibly_Controlled (Tagged_Type) then Set_Is_Overriding_Operation (Subp, False); Error_Msg_NE ("operation does not override inherited&?", Subp, Subp); else Override_Dispatching_Operation (Tagged_Type, Old_Subp, Subp); Set_Is_Overriding_Operation (Subp); end if; -- If no old subprogram, then we add this as a dispatching operation, -- but we avoid doing this if an error was posted, to prevent annoying -- cascaded errors. elsif not Error_Posted (Subp) then Add_Dispatching_Operation (Tagged_Type, Subp); end if; Set_Is_Dispatching_Operation (Subp, True); if not Body_Is_Last_Primitive then Set_DT_Position (Subp, No_Uint); elsif Has_Controlled_Component (Tagged_Type) and then (Chars (Subp) = Name_Initialize or else Chars (Subp) = Name_Adjust or else Chars (Subp) = Name_Finalize) then declare F_Node : constant Node_Id := Freeze_Node (Tagged_Type); Decl : Node_Id; Old_P : Entity_Id; Old_Bod : Node_Id; Old_Spec : Entity_Id; C_Names : constant array (1 .. 3) of Name_Id := (Name_Initialize, Name_Adjust, Name_Finalize); D_Names : constant array (1 .. 3) of TSS_Name_Type := (TSS_Deep_Initialize, TSS_Deep_Adjust, TSS_Deep_Finalize); begin -- Remove previous controlled function, which was constructed -- and analyzed when the type was frozen. This requires -- removing the body of the redefined primitive, as well as -- its specification if needed (there is no spec created for -- Deep_Initialize, see exp_ch3.adb). We must also dismantle -- the exception information that may have been generated for -- it when front end zero-cost tables are enabled. for J in D_Names'Range loop Old_P := TSS (Tagged_Type, D_Names (J)); if Present (Old_P) and then Chars (Subp) = C_Names (J) then Old_Bod := Unit_Declaration_Node (Old_P); Remove (Old_Bod); Set_Is_Eliminated (Old_P); Set_Scope (Old_P, Scope (Current_Scope)); if Nkind (Old_Bod) = N_Subprogram_Body and then Present (Corresponding_Spec (Old_Bod)) then Old_Spec := Corresponding_Spec (Old_Bod); Set_Has_Completion (Old_Spec, False); end if; end if; end loop; Build_Late_Proc (Tagged_Type, Chars (Subp)); -- The new operation is added to the actions of the freeze -- node for the type, but this node has already been analyzed, -- so we must retrieve and analyze explicitly the one new body, if Present (F_Node) and then Present (Actions (F_Node)) then Decl := Last (Actions (F_Node)); Analyze (Decl); end if; end; end if; end Check_Dispatching_Operation; ------------------------------------------ -- Check_Operation_From_Incomplete_Type -- ------------------------------------------ procedure Check_Operation_From_Incomplete_Type (Subp : Entity_Id; Typ : Entity_Id) is Full : constant Entity_Id := Full_View (Typ); Parent_Typ : constant Entity_Id := Etype (Full); Old_Prim : constant Elist_Id := Primitive_Operations (Parent_Typ); New_Prim : constant Elist_Id := Primitive_Operations (Full); Op1, Op2 : Elmt_Id; Prev : Elmt_Id := No_Elmt; function Derives_From (Proc : Entity_Id) return Boolean; -- Check that Subp has the signature of an operation derived from Proc. -- Subp has an access parameter that designates Typ. ------------------ -- Derives_From -- ------------------ function Derives_From (Proc : Entity_Id) return Boolean is F1, F2 : Entity_Id; begin if Chars (Proc) /= Chars (Subp) then return False; end if; F1 := First_Formal (Proc); F2 := First_Formal (Subp); while Present (F1) and then Present (F2) loop if Ekind (Etype (F1)) = E_Anonymous_Access_Type then if Ekind (Etype (F2)) /= E_Anonymous_Access_Type then return False; elsif Designated_Type (Etype (F1)) = Parent_Typ and then Designated_Type (Etype (F2)) /= Full then return False; end if; elsif Ekind (Etype (F2)) = E_Anonymous_Access_Type then return False; elsif Etype (F1) /= Etype (F2) then return False; end if; Next_Formal (F1); Next_Formal (F2); end loop; return No (F1) and then No (F2); end Derives_From; -- Start of processing for Check_Operation_From_Incomplete_Type begin -- The operation may override an inherited one, or may be a new one -- altogether. The inherited operation will have been hidden by the -- current one at the point of the type derivation, so it does not -- appear in the list of primitive operations of the type. We have to -- find the proper place of insertion in the list of primitive opera- -- tions by iterating over the list for the parent type. Op1 := First_Elmt (Old_Prim); Op2 := First_Elmt (New_Prim); while Present (Op1) and then Present (Op2) loop if Derives_From (Node (Op1)) then if No (Prev) then Prepend_Elmt (Subp, New_Prim); else Insert_Elmt_After (Subp, Prev); end if; return; end if; Prev := Op2; Next_Elmt (Op1); Next_Elmt (Op2); end loop; -- Operation is a new primitive Append_Elmt (Subp, New_Prim); end Check_Operation_From_Incomplete_Type; --------------------------------------- -- Check_Operation_From_Private_View -- --------------------------------------- procedure Check_Operation_From_Private_View (Subp, Old_Subp : Entity_Id) is Tagged_Type : Entity_Id; begin if Is_Dispatching_Operation (Alias (Subp)) then Set_Scope (Subp, Current_Scope); Tagged_Type := Find_Dispatching_Type (Subp); if Present (Tagged_Type) and then Is_Tagged_Type (Tagged_Type) then Append_Elmt (Old_Subp, Primitive_Operations (Tagged_Type)); -- If Old_Subp isn't already marked as dispatching then -- this is the case of an operation of an untagged private -- type fulfilled by a tagged type that overrides an -- inherited dispatching operation, so we set the necessary -- dispatching attributes here. if not Is_Dispatching_Operation (Old_Subp) then -- If the untagged type has no discriminants, and the full -- view is constrained, there will be a spurious mismatch -- of subtypes on the controlling arguments, because the tagged -- type is the internal base type introduced in the derivation. -- Use the original type to verify conformance, rather than the -- base type. if not Comes_From_Source (Tagged_Type) and then Has_Discriminants (Tagged_Type) then declare Formal : Entity_Id; begin Formal := First_Formal (Old_Subp); while Present (Formal) loop if Tagged_Type = Base_Type (Etype (Formal)) then Tagged_Type := Etype (Formal); end if; Next_Formal (Formal); end loop; end; if Tagged_Type = Base_Type (Etype (Old_Subp)) then Tagged_Type := Etype (Old_Subp); end if; end if; Check_Controlling_Formals (Tagged_Type, Old_Subp); Set_Is_Dispatching_Operation (Old_Subp, True); Set_DT_Position (Old_Subp, No_Uint); end if; -- If the old subprogram is an explicit renaming of some other -- entity, it is not overridden by the inherited subprogram. -- Otherwise, update its alias and other attributes. if Present (Alias (Old_Subp)) and then Nkind (Unit_Declaration_Node (Old_Subp)) /= N_Subprogram_Renaming_Declaration then Set_Alias (Old_Subp, Alias (Subp)); -- The derived subprogram should inherit the abstractness -- of the parent subprogram (except in the case of a function -- returning the type). This sets the abstractness properly -- for cases where a private extension may have inherited -- an abstract operation, but the full type is derived from -- a descendant type and inherits a nonabstract version. if Etype (Subp) /= Tagged_Type then Set_Is_Abstract (Old_Subp, Is_Abstract (Alias (Subp))); end if; end if; end if; end if; end Check_Operation_From_Private_View; -------------------------- -- Find_Controlling_Arg -- -------------------------- function Find_Controlling_Arg (N : Node_Id) return Node_Id is Orig_Node : constant Node_Id := Original_Node (N); Typ : Entity_Id; begin if Nkind (Orig_Node) = N_Qualified_Expression then return Find_Controlling_Arg (Expression (Orig_Node)); end if; -- Dispatching on result case if Nkind (Orig_Node) = N_Function_Call and then Present (Controlling_Argument (Orig_Node)) and then Has_Controlling_Result (Entity (Name (Orig_Node))) then return Controlling_Argument (Orig_Node); -- Normal case elsif Is_Controlling_Actual (N) or else (Nkind (Parent (N)) = N_Qualified_Expression and then Is_Controlling_Actual (Parent (N))) then Typ := Etype (N); if Is_Access_Type (Typ) then -- In the case of an Access attribute, use the type of -- the prefix, since in the case of an actual for an -- access parameter, the attribute's type may be of a -- specific designated type, even though the prefix -- type is class-wide. if Nkind (N) = N_Attribute_Reference then Typ := Etype (Prefix (N)); -- An allocator is dispatching if the type of qualified -- expression is class_wide, in which case this is the -- controlling type. elsif Nkind (Orig_Node) = N_Allocator and then Nkind (Expression (Orig_Node)) = N_Qualified_Expression then Typ := Etype (Expression (Orig_Node)); else Typ := Designated_Type (Typ); end if; end if; if Is_Class_Wide_Type (Typ) or else (Nkind (Parent (N)) = N_Qualified_Expression and then Is_Access_Type (Etype (N)) and then Is_Class_Wide_Type (Designated_Type (Etype (N)))) then return N; end if; end if; return Empty; end Find_Controlling_Arg; --------------------------- -- Find_Dispatching_Type -- --------------------------- function Find_Dispatching_Type (Subp : Entity_Id) return Entity_Id is Formal : Entity_Id; Ctrl_Type : Entity_Id; begin if Present (DTC_Entity (Subp)) then return Scope (DTC_Entity (Subp)); else Formal := First_Formal (Subp); while Present (Formal) loop Ctrl_Type := Check_Controlling_Type (Etype (Formal), Subp); if Present (Ctrl_Type) then return Ctrl_Type; end if; Next_Formal (Formal); end loop; -- The subprogram may also be dispatching on result if Present (Etype (Subp)) then Ctrl_Type := Check_Controlling_Type (Etype (Subp), Subp); if Present (Ctrl_Type) then return Ctrl_Type; end if; end if; end if; return Empty; end Find_Dispatching_Type; --------------------------- -- Is_Dynamically_Tagged -- --------------------------- function Is_Dynamically_Tagged (N : Node_Id) return Boolean is begin return Find_Controlling_Arg (N) /= Empty; end Is_Dynamically_Tagged; -------------------------- -- Is_Tag_Indeterminate -- -------------------------- function Is_Tag_Indeterminate (N : Node_Id) return Boolean is Nam : Entity_Id; Actual : Node_Id; Orig_Node : constant Node_Id := Original_Node (N); begin if Nkind (Orig_Node) = N_Function_Call and then Is_Entity_Name (Name (Orig_Node)) then Nam := Entity (Name (Orig_Node)); if not Has_Controlling_Result (Nam) then return False; -- An explicit dereference means that the call has already been -- expanded and there is no tag to propagate. elsif Nkind (N) = N_Explicit_Dereference then return False; -- If there are no actuals, the call is tag-indeterminate elsif No (Parameter_Associations (Orig_Node)) then return True; else Actual := First_Actual (Orig_Node); while Present (Actual) loop if Is_Controlling_Actual (Actual) and then not Is_Tag_Indeterminate (Actual) then return False; -- one operand is dispatching end if; Next_Actual (Actual); end loop; return True; end if; elsif Nkind (Orig_Node) = N_Qualified_Expression then return Is_Tag_Indeterminate (Expression (Orig_Node)); -- Case of a call to the Input attribute (possibly rewritten), which is -- always tag-indeterminate except when its prefix is a Class attribute. elsif Nkind (Orig_Node) = N_Attribute_Reference and then Get_Attribute_Id (Attribute_Name (Orig_Node)) = Attribute_Input and then Nkind (Prefix (Orig_Node)) /= N_Attribute_Reference then return True; else return False; end if; end Is_Tag_Indeterminate; ------------------------------------ -- Override_Dispatching_Operation -- ------------------------------------ procedure Override_Dispatching_Operation (Tagged_Type : Entity_Id; Prev_Op : Entity_Id; New_Op : Entity_Id) is Op_Elmt : Elmt_Id := First_Elmt (Primitive_Operations (Tagged_Type)); Elmt : Elmt_Id; Found : Boolean; E : Entity_Id; function Is_Interface_Subprogram (Op : Entity_Id) return Boolean; -- Traverse the list of aliased entities to check if the overriden -- entity corresponds with a primitive operation of an abstract -- interface type. ----------------------------- -- Is_Interface_Subprogram -- ----------------------------- function Is_Interface_Subprogram (Op : Entity_Id) return Boolean is Aux : Entity_Id; begin Aux := Op; while Present (Alias (Aux)) and then Present (DTC_Entity (Alias (Aux))) loop if Is_Interface (Scope (DTC_Entity (Alias (Aux)))) then return True; end if; Aux := Alias (Aux); end loop; return False; end Is_Interface_Subprogram; -- Start of processing for Override_Dispatching_Operation begin -- Diagnose failure to match No_Return in parent (Ada-2005, AI-414, but -- we do it unconditionally in Ada 95 now, since this is our pragma!) if No_Return (Prev_Op) and then not No_Return (New_Op) then Error_Msg_N ("procedure & must have No_Return pragma", New_Op); Error_Msg_N ("\since overridden procedure has No_Return", New_Op); end if; -- Patch the primitive operation list while Present (Op_Elmt) and then Node (Op_Elmt) /= Prev_Op loop Next_Elmt (Op_Elmt); end loop; -- If there is no previous operation to override, the type declaration -- was malformed, and an error must have been emitted already. if No (Op_Elmt) then return; end if; -- Ada 2005 (AI-251): Do not replace subprograms inherited from -- abstract interfaces. They will be used later to generate the -- corresponding thunks to initialize the Vtable (see subprogram -- Freeze_Subprogram). The inherited operation itself must also -- become hidden, to avoid spurious ambiguities; name resolution -- must pick up only the operation that implements it, if Is_Interface_Subprogram (Prev_Op) then Set_DT_Position (Prev_Op, DT_Position (Alias (Prev_Op))); Set_Is_Abstract (Prev_Op, Is_Abstract (New_Op)); Set_Is_Overriding_Operation (Prev_Op); -- Traverse the list of aliased entities to look for the overriden -- abstract interface subprogram. E := Alias (Prev_Op); while Present (Alias (E)) and then Present (DTC_Entity (E)) and then not (Is_Abstract (E)) and then not Is_Interface (Scope (DTC_Entity (E))) loop E := Alias (E); end loop; Set_Abstract_Interface_Alias (Prev_Op, E); Set_Alias (Prev_Op, New_Op); Set_Is_Internal (Prev_Op); Set_Is_Hidden (Prev_Op); -- Override predefined primitive operations if Is_Predefined_Dispatching_Operation (Prev_Op) then Replace_Elmt (Op_Elmt, New_Op); return; end if; -- Check if this primitive operation was previously added for another -- interface. Elmt := First_Elmt (Primitive_Operations (Tagged_Type)); Found := False; while Present (Elmt) loop if Node (Elmt) = New_Op then Found := True; exit; end if; Next_Elmt (Elmt); end loop; if not Found then Append_Elmt (New_Op, Primitive_Operations (Tagged_Type)); end if; return; else Replace_Elmt (Op_Elmt, New_Op); end if; if (not Is_Package_Or_Generic_Package (Current_Scope)) or else not In_Private_Part (Current_Scope) then -- Not a private primitive null; else pragma Assert (Is_Inherited_Operation (Prev_Op)); -- Make the overriding operation into an alias of the implicit one. -- In this fashion a call from outside ends up calling the new body -- even if non-dispatching, and a call from inside calls the -- overriding operation because it hides the implicit one. To -- indicate that the body of Prev_Op is never called, set its -- dispatch table entity to Empty. Set_Alias (Prev_Op, New_Op); Set_DTC_Entity (Prev_Op, Empty); return; end if; end Override_Dispatching_Operation; ------------------- -- Propagate_Tag -- ------------------- procedure Propagate_Tag (Control : Node_Id; Actual : Node_Id) is Call_Node : Node_Id; Arg : Node_Id; begin if Nkind (Actual) = N_Function_Call then Call_Node := Actual; elsif Nkind (Actual) = N_Identifier and then Nkind (Original_Node (Actual)) = N_Function_Call then -- Call rewritten as object declaration when stack-checking -- is enabled. Propagate tag to expression in declaration, which -- is original call. Call_Node := Expression (Parent (Entity (Actual))); -- Only other possibilities are parenthesized or qualified expression, -- or an expander-generated unchecked conversion of a function call to -- a stream Input attribute. else Call_Node := Expression (Actual); end if; -- Do not set the Controlling_Argument if already set. This happens -- in the special case of _Input (see Exp_Attr, case Input). if No (Controlling_Argument (Call_Node)) then Set_Controlling_Argument (Call_Node, Control); end if; Arg := First_Actual (Call_Node); while Present (Arg) loop if Is_Tag_Indeterminate (Arg) then Propagate_Tag (Control, Arg); end if; Next_Actual (Arg); end loop; -- Expansion of dispatching calls is suppressed when Java_VM, because -- the JVM back end directly handles the generation of dispatching -- calls and would have to undo any expansion to an indirect call. if not Java_VM then Expand_Dispatching_Call (Call_Node); end if; end Propagate_Tag; end Sem_Disp;
package SomeClass is type SomeClass1 is record someAttribute : Integer := 1; end record; type SomeClass2 is record someAttribute2 : SomeClass1; end record; end SomeClass;
package body OpenGL.Vertex is -- -- Immediate mode. -- function Primitive_Type_To_Constant (Mode : in Primitive_Type_t) return Thin.Enumeration_t is begin case Mode is when Points => return Thin.GL_POINTS; when Lines => return Thin.GL_LINES; when Line_Strip => return Thin.GL_LINE_STRIP; when Line_Loop => return Thin.GL_LINE_LOOP; when Triangles => return Thin.GL_TRIANGLES; when Triangle_Strip => return Thin.GL_TRIANGLE_STRIP; when Triangle_Fan => return Thin.GL_TRIANGLE_FAN; when Quads => return Thin.GL_QUADS; when Quad_Strip => return Thin.GL_QUAD_STRIP; when Polygon => return Thin.GL_POLYGON; end case; end Primitive_Type_To_Constant; procedure GL_Begin (Mode : in Primitive_Type_t) is begin Thin.GL_Begin (Primitive_Type_To_Constant (Mode)); end GL_Begin; end OpenGL.Vertex;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2017-2020, Fabien Chouteau -- -- -- -- 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. Neither the name of the copyright holder 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 -- -- HOLDER 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. -- -- -- ------------------------------------------------------------------------------ private package AGATE.Traces is -- Tasks -- procedure Register (ID : Task_ID; Name : String); procedure Resume (ID : Task_ID); procedure Suspend (ID : Task_ID); procedure Fault (ID : Task_ID); procedure Running (ID : Task_ID); procedure Change_Priority (ID : Task_ID; New_Prio : Internal_Task_Priority); procedure Context_Switch (Old, Next : Task_ID); -- Semaphores -- procedure Register (ID : Semaphore_ID; Name : String); procedure Value_Changed (ID : Semaphore_ID; Count : Semaphore_Count; By : Task_ID); -- Mutexes -- procedure Register (ID : Mutex_ID; Name : String); procedure Lock (ID : Mutex_ID; By : Task_ID); procedure Release (ID : Mutex_ID; By : Task_ID); -- System -- procedure Shutdown; end AGATE.Traces;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- S Y S T E M . B B . B O A R D _ S U P P O R T -- -- -- -- B o d y -- -- -- -- Copyright (C) 1999-2002 Universidad Politecnica de Madrid -- -- Copyright (C) 2003-2005 The European Space Agency -- -- Copyright (C) 2003-2021, AdaCore -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- -- The port of GNARL to bare board targets was initially developed by the -- -- Real-Time Systems Group at the Technical University of Madrid. -- -- -- ------------------------------------------------------------------------------ -- This version supports the MPC5200B. Nested interrupts are not supported and -- critical interrupts are routed to core_int. with System.BB.Board_Parameters; with System.BB.CPU_Specific; with System.Machine_Code; pragma Warnings (off); -- Vectors and priorities are defined in Ada.Interrupts.Names, which is not -- preelaborated. Ignore this issue as we only reference static constants. with Ada.Interrupts; with Ada.Interrupts.Names; use Ada.Interrupts.Names; pragma Warnings (on); with Interfaces; use Interfaces; package body System.BB.Board_Support is use System.BB.Board_Parameters; use System.BB.Interrupts; pragma Warnings (Off, "*is not referenced*"); -- Disable warnings for unused register or register components -- CPU Registers type Hardware_Implementation_Register_0 is record Enable_Core_MCP : Boolean; Enable_Address_Parity_Check : Boolean; Enable_Data_Parity_Check : Boolean; SBCLK : Boolean; ECLK : Boolean; Disable_Precharge : Boolean; Doze : Boolean; Nap : Boolean; Sleep : Boolean; Dynamic_Power_Management : Boolean; Instruction_Cache_Enable : Boolean; Data_Cache_Enable : Boolean; Instruction_Cache_Lock : Boolean; Data_Cache_Lock : Boolean; Instruction_Cache_Flash_Invalidate : Boolean; Data_Cache_Flash_Invalidate : Boolean; IFEM : Boolean; FBIOB : Boolean; Address_Broadcast_Enable : Boolean; NOOPTI : Boolean; end record; for Hardware_Implementation_Register_0 use record Enable_Core_MCP at 0 range 0 .. 0; Enable_Address_Parity_Check at 0 range 2 .. 2; Enable_Data_Parity_Check at 0 range 3 .. 3; SBCLK at 0 range 4 .. 4; ECLK at 0 range 6 .. 6; Disable_Precharge at 0 range 7 .. 7; Doze at 0 range 8 .. 8; Nap at 0 range 9 .. 9; Sleep at 0 range 10 .. 10; Dynamic_Power_Management at 0 range 11 .. 11; Instruction_Cache_Enable at 0 range 16 .. 16; Data_Cache_Enable at 0 range 17 .. 17; Instruction_Cache_Lock at 0 range 18 .. 18; Data_Cache_Lock at 0 range 19 .. 19; Instruction_Cache_Flash_Invalidate at 0 range 20 .. 20; Data_Cache_Flash_Invalidate at 0 range 21 .. 21; IFEM at 0 range 24 .. 24; FBIOB at 0 range 27 .. 27; Address_Broadcast_Enable at 0 range 28 .. 28; NOOPTI at 0 range 31 .. 31; end record; -- Local Interrupt Types subtype Peripheral_ID is Interrupt_ID range 0 .. 23; subtype Main_ID is Interrupt_ID range 0 .. 16; subtype Critical_ID is Interrupt_ID range 0 .. 3; subtype IRQ_Number is Interrupt_ID range 0 .. 3; -- Hardware interrupt numbers First_Peripheral_ID : constant Interrupt_ID := Interrupt_ID (Ada.Interrupts.Names.Peripheral_Interrupt_ID'First); First_Main_ID : constant Interrupt_ID := Interrupt_ID (Ada.Interrupts.Names.Main_Interrupt_ID'First); First_Critical_ID : constant Interrupt_ID := Interrupt_ID (Ada.Interrupts.Names.Critical_Interrupt_ID'First); -- First interrupt ID of each of the Ada.Interrupt priority ranges -- Interrupt Controller ICTL Registers -- See MPC5200B User's Manual, Section 7.2 type Peripheral_Mask is array (Peripheral_ID) of Boolean with Pack; type ICTL_Peripheral_Interrupt_Mask is record Mask : Peripheral_Mask; end record with Size => 32; for ICTL_Peripheral_Interrupt_Mask use record Mask at 0 range 0 .. 23; end record; type IRQ_Set is array (IRQ_Number) of Boolean with Pack; type ICTL_External_Enable_and_External_Types is record Master_External_Enable : Boolean; IRQ_Enable : IRQ_Set; Critical_Enable : Boolean; end record; for ICTL_External_Enable_and_External_Types use record Master_External_Enable at 0 range 19 .. 19; IRQ_Enable at 0 range 20 .. 23; Critical_Enable at 0 range 31 .. 31; end record; type Critical_Priority is mod 2 ** 2; type Critical_Priorities is array (Critical_ID) of Critical_Priority with Pack; type Main_Mask is array (Main_ID) of Boolean with Pack; type ICTL_Critical_Priority_And_Main_Interrupt_Mask is record Critical_Interrupt : Critical_Priorities; Main_Interrupt_Mask : Main_Mask; end record; for ICTL_Critical_Priority_And_Main_Interrupt_Mask use record Critical_Interrupt at 0 range 0 .. 7; Main_Interrupt_Mask at 0 range 15 .. 31; end record; type ICTL_Status_Encoded is record Peripheral_Interrupt_Present : Boolean; Peripheral_Interrupt : Peripheral_ID; Main_Interrupt_Present : Boolean; Main_Interrupt : Main_ID; Critical_Interrupt_Present : Boolean; Critical_Interrupt : Critical_ID; Critical_Enable_Bar : Boolean; end record; for ICTL_Status_Encoded use record Peripheral_Interrupt_Present at 0 range 2 .. 2; Peripheral_Interrupt at 0 range 3 .. 7; Main_Interrupt_Present at 0 range 10 .. 10; Main_Interrupt at 0 range 11 .. 15; Critical_Interrupt_Present at 0 range 21 .. 21; Critical_Interrupt at 0 range 23 .. 24; Critical_Enable_Bar at 0 range 31 .. 31; end record; ICTL_Peripheral_Interrupt_Mask_Register : ICTL_Peripheral_Interrupt_Mask with Volatile_Full_Access, Address => System'To_Address (MBAR + 16#0500#); ICTL_External_Enable_and_External_Types_Register : ICTL_External_Enable_and_External_Types with Volatile_Full_Access, Address => System'To_Address (MBAR + 16#0510#); ICTL_Critical_Priority_And_Main_Interrupt_Mask_Register : ICTL_Critical_Priority_And_Main_Interrupt_Mask with Volatile_Full_Access, Address => System'To_Address (MBAR + 16#0514#); ICTL_Status_Encoded_Register : ICTL_Status_Encoded with Volatile_Full_Access, Address => System'To_Address (MBAR + 16#0524#); -- XLB Arbiter Register -- See MPC5200B User's Manual, Section 16 type Master is range 0 .. 7; type Parking is (No_Parking, Reserved, Recent, Programmed); type Arbiter_Configuration is record Pipeline_Disable : Boolean; BestComm_Snooping_Disable : Boolean; Snoop_Enable : Boolean; Force_Write_With_Flush : Boolean; Timebase_Enable : Boolean; Minimum_Wait_State : Boolean; Select_Parked_Master : Master; Parking_Mode : Parking; Bus_Activity_Time_Out_Enable : Boolean; Data_Tenure_Time_Out_Enable : Boolean; Address_Tenure_Time_Out_Enable : Boolean; end record; for Arbiter_Configuration use record Pipeline_Disable at 0 range 0 .. 0; BestComm_Snooping_Disable at 0 range 15 .. 15; Snoop_Enable at 0 range 16 .. 16; Force_Write_With_Flush at 0 range 17 .. 17; Timebase_Enable at 0 range 18 .. 18; Minimum_Wait_State at 0 range 20 .. 20; Select_Parked_Master at 0 range 21 .. 23; Parking_Mode at 0 range 25 .. 26; Bus_Activity_Time_Out_Enable at 0 range 28 .. 28; Data_Tenure_Time_Out_Enable at 0 range 29 .. 29; Address_Tenure_Time_Out_Enable at 0 range 30 .. 30; end record; Arbiter_Configuration_Register : Arbiter_Configuration with Volatile_Full_Access, Address => System'To_Address (MBAR + 16#1F40#); pragma Warnings (On, "*is not referenced*"); procedure Interrupt_Handler; -- Called by low-level handler in case of external interrupt procedure Clear_Alarm_Interrupt; pragma Inline (Clear_Alarm_Interrupt); -- Implementation of Time.Clear_Alarm_Interrupt ---------------------- -- Initialize_Board -- ---------------------- procedure Initialize_Board is use System.Machine_Code; HID0 : Hardware_Implementation_Register_0; begin -- Enable Time Base Clock Arbiter_Configuration_Register.Timebase_Enable := True; -- Route Critical Interrupts to External Interrupts ICTL_External_Enable_and_External_Types_Register := (Critical_Enable => True, Master_External_Enable => True, IRQ_Enable => (others => False)); -- Install hanlders CPU_Specific.Install_Exception_Handler (Interrupt_Handler'Address, CPU_Specific.External_Interrupt_Excp); CPU_Specific.Install_Exception_Handler (Interrupt_Handler'Address, CPU_Specific.System_Management_Excp); -- Configure HID0 enable the Doze power management mode when we sleep -- and enable the instruction caches. Asm ("mfspr %0, 1008", Outputs => Hardware_Implementation_Register_0'Asm_Output ("=r", HID0), Volatile => True); HID0.Doze := True; HID0.Instruction_Cache_Enable := True; -- Data and instruction sync instructions ensure that no memory is -- accessed when we enable the cache. Asm ("sync", Volatile => True); Asm ("isync", Volatile => True); Asm ("mtspr 1008, %0", Inputs => Hardware_Implementation_Register_0'Asm_Input ("r", HID0), Volatile => True); end Initialize_Board; --------------------------- -- Clear_Alarm_Interrupt -- --------------------------- procedure Clear_Alarm_Interrupt is begin -- The hardware automatically clears the decrementer exception null; end Clear_Alarm_Interrupt; ----------------------- -- Interrupt_Handler -- ----------------------- procedure Interrupt_Handler is Interrupt_Status : ICTL_Status_Encoded := ICTL_Status_Encoded_Register; -- Local copy of the ICTL_Status_Encoded_Register so that we do not have -- the overhead of reading the volatile register on each component -- access. Interrupt : Interrupt_ID; -- Interrupt to handle begin -- Since the SIU Interrupt Controller does not really supported nested -- interrupts, we check for any new interrupts at the end of the handler -- and service them to reduce the overhead of returning from the -- handler. loop if Interrupt_Status.Critical_Interrupt_Present then -- Convert the hardware Critical Interrupt to an Interrupt ID. If -- the Critical Interrupt is HI_INT then a Peripheral Interrupt -- has occurred and we look up the corresponding Peripheral -- Interrupt. Interrupt := First_Critical_ID + Interrupt_Status.Critical_Interrupt; if Interrupt = Interrupt_ID (HI_INT) then Interrupt := First_Peripheral_ID + Interrupt_Status.Peripheral_Interrupt; end if; elsif Interrupt_Status.Main_Interrupt_Present then -- Convert the hardware Main Interrupt to an Interrupt ID. If the -- Main Interrupt is LO_INT then a Peripheral Interrupt has -- occurred and we look up the corresponding Peripheral Interrupt. Interrupt := First_Main_ID + Interrupt_Status.Main_Interrupt; if Interrupt = Interrupt_ID (LO_INT) then Interrupt := First_Peripheral_ID + Interrupt_Status.Peripheral_Interrupt; end if; else -- Spurious interrupt, just return. return; end if; BB.Interrupts.Interrupt_Wrapper (Interrupt); -- Force the Interrupt Controller to reevaluate it's interrupts Interrupt_Status.Peripheral_Interrupt_Present := True; Interrupt_Status.Main_Interrupt_Present := True; Interrupt_Status.Critical_Interrupt_Present := True; ICTL_Status_Encoded_Register := Interrupt_Status; -- Update our local copy of the ICTL_Status_Encoded_Register Interrupt_Status := ICTL_Status_Encoded_Register; -- Exit if they're are no more remaining interrupts to service exit when not (Interrupt_Status.Peripheral_Interrupt_Present or Interrupt_Status.Main_Interrupt_Present or Interrupt_Status.Peripheral_Interrupt_Present); end loop; end Interrupt_Handler; package body Interrupts is ------------------------------- -- Install_Interrupt_Handler -- ------------------------------- procedure Install_Interrupt_Handler (Interrupt : BB.Interrupts.Interrupt_ID; Prio : Interrupt_Priority) is pragma Unreferenced (Prio); begin -- Unmask interrupts in the controller case Ada.Interrupts.Interrupt_ID (Interrupt) is when Peripheral_Interrupt_ID => ICTL_Peripheral_Interrupt_Mask_Register.Mask (Interrupt - First_Peripheral_ID) := False; ICTL_Critical_Priority_And_Main_Interrupt_Mask_Register. Main_Interrupt_Mask (Interrupt_ID (LO_INT) - First_Main_ID) := False; when Main_Interrupt_ID => ICTL_Critical_Priority_And_Main_Interrupt_Mask_Register. Main_Interrupt_Mask (Interrupt - First_Main_ID) := False; when Critical_Interrupt_ID => -- Critical interrupt are not maskable, so nothing to do here null; end case; end Install_Interrupt_Handler; --------------------------- -- Priority_Of_Interrupt -- --------------------------- function Priority_Of_Interrupt (Interrupt : System.BB.Interrupts.Interrupt_ID) return System.Any_Priority is pragma Unreferenced (Interrupt); begin return Interrupt_Priority'First; end Priority_Of_Interrupt; ---------------- -- Power_Down -- ---------------- procedure Power_Down is use System.Machine_Code; MSR : CPU_Specific.Machine_State_Register; begin -- Power down the core using the PowerPC power management feature -- Read MSR and set POW/WE bit Asm ("mfmsr %0", Outputs => CPU_Specific.Machine_State_Register'Asm_Output ("=r", MSR), Volatile => True); MSR.Power_Management_Enable := True; Asm ("sync", Volatile => True); -- Set MSR Asm ("mtmsr %0", Inputs => CPU_Specific.Machine_State_Register'Asm_Input ("r", MSR), Volatile => True); Asm ("isync", Volatile => True); end Power_Down; -------------------------- -- Set_Current_Priority -- -------------------------- procedure Set_Current_Priority (Priority : Integer) is begin null; end Set_Current_Priority; end Interrupts; package body Time is separate; package body Multiprocessors is separate; end System.BB.Board_Support;
with GL.Types; with GA_Maths; use GA_Maths; with Multivectors; use Multivectors; package E3GA is type Array_19F is array (1 .. 19) of float; -- subtype M_Vector is GA_Maths.Coords_Continuous_Array (1 .. 3); -- m_c[3] coordinate storage subtype E3_Vector is GL.Types.Singles.Vector3; -- m_c[3] coordinate storage -- types type G2_Type is (MVT_None, MVT_E1_T, MVT_E2_T, MVT_E3_T, MVT_Scalar, MVT_Vector_2D, MVT_Vector, MVT_Bivector, MVT_Trivector, MVT_Rotor, MVT_E1_CT, MVT_E2_CT, MVT_E3_CT, MVT_I3_CT, MVT_I3I_CT, MVT_MV, MVT_Last); -- Outermorphism types type OM_Type is (OMT_None, OMT_OM, OMT_Last); -- type Rotor_Coordinates_Type is (Rotor_Scalar_e1e2_e2e3_e3e1); -- type Scalar is private; -- type Bivector is private; type Outermorphism is private; type Syn_SMultivector is private; -- type Rotor is private; -- type Trivector is private; -- M_Vector corresponds to e3ga.Vector coordinate storage float m_c[3] -- type M_Vector is private; type MV_Coordinate_Array is new GA_Maths.Coords_Continuous_Array (1 .. 8); -- type Multivector (Grade_Use : Grade_Usage) is record -- Coordinates : MV_Coordinate_Array := (others => 0.0); -- m_c[8] -- end record; -- Joinable grade definitions Grade_0 : constant integer := 1; Grade_1 : constant integer := 2; Grade_2 : constant integer := 4; Grade_3 : constant integer := 8; -- function "=" (V1, V2 : M_Vector) return Boolean; function "+" (V1, V2 : E3_Vector) return E3_Vector; function "-" (V : E3_Vector) return E3_Vector; -- function "-" (VL, VR : E3_Vector) return E3_Vector; function "*" (Weight : float; V : E3_Vector) return E3_Vector; -- function "*" (Weight : float; BV : Bivector) return Bivector; function "*" (R1, R2 : Rotor) return Rotor; -- function "*" (R : Rotor; V : M_Vector) return Rotor; -- function "*" (V : M_Vector; R : Rotor) return Rotor; function "/" (R : Rotor; S : float) return Rotor; -- function "+" (W : float; BV : BiVector) return Rotor; function "+" (W : float; R : Rotor) return Rotor; function "-" (W : float; R : Rotor) return Rotor; -- function e1 (V : E2GA.M_Vector) return float; -- function e2 (V : E2GA.M_Vector) return float; -- function e1 return M_Vector; -- function e2 return M_Vector; -- function e3 return M_Vector; function e1 return Multivectors.M_Vector; function e2 return Multivectors.M_Vector; function e3 return Multivectors.M_Vector; function e1 (MV : Multivector) return float; function e2 (MV : Multivector) return float; function e3 (MV : Multivector) return float; function e1_e2 (MV : Multivector) return float; function e1_e3 (MV : Multivector) return float; function e2_e3 (MV : Multivector) return float; function e3_e1 (MV : Multivector) return float; function e1_e2_e3 (MV : Multivector) return float; -- -- function e1e2 (R : Rotor) return float; -- function e2e3 (R : Rotor) return float; -- function e3e1 (R : Rotor) return float; -- function R_Scalar (R : Rotor) return float; -- function Apply_Outermorphism (OM : Outermorphism; BV : Bivector) return Bivector; -- function Apply_Outermorphism (OM : Outermorphism; V : M_Vector) return M_Vector; function Dot_Product (R1, R2 : Rotor) return float; -- function Dot_Product (V1, V2 : M_Vector) return float; -- function Get_Coord (S : Scalar) return float; -- function Get_Coords (BV : Bivector) return Array_3D; function Get_Coords (MV : Multivector) return MV_Coordinate_Array; function Get_Coords (R : Rotor) return Float_4D; -- function Get_Coord_1 (V : M_Vector) return float; -- function Get_Coord_2 (V : M_Vector) return float; -- function Get_Coord_3 (V : M_Vector) return float; function Get_Coords (Vec : Multivectors.M_Vector) return E3_Vector; -- function Get_Coords (SMV : Syn_SMultivector) return Array_4D; function Get_Outermorphism (OM : Outermorphism) return Array_19F; -- function Get_Size (MV : Multivector) return Integer; -- function Geometric_Product (BV : Bivector; R : Rotor) return Rotor; -- function Geometric_Product (R : Rotor; BV : Bivector) return Rotor; -- function Geometric_Product (V : M_Vector; R : Rotor) return Syn_SMultivector; -- function Geometric_Product (R : Rotor; MV : Syn_SMultivector) return Syn_SMultivector; -- function Geometric_Product (V : M_Vector; MV : Syn_SMultivector) return Rotor; -- function Geometric_Product (R : Rotor; V : M_Vector) return Syn_SMultivector; -- function Geometric_Product (R1, R2 : Rotor) return Rotor; -- function Geometric_Product (V1, V2 : M_Vector) return Rotor; -- function Grade_Use (BV : Bivector) return GA_Maths.Unsigned_32; -- function Grade_Use (MV : Multivector) return GA_Maths.Unsigned_32; -- function Inverse (aRotor : Rotor) return Rotor; -- function Inverse (V : M_Vector) return M_Vector; function Is_Zero (V : E3_Vector) return Boolean; -- function Left_Contraction (BV1, BV2 : Bivector) return Scalar; -- function Left_Contraction (MV1, MV2 : Multivector) return Multivector; -- function Left_Contraction (V : M_Vector; BV : Bivector) return M_Vector; -- function Left_Contraction (V1 : M_Vector; V2 : M_Vector) return Scalar; -- function Magnitude (V : M_Vector) return float; -- function MV_String (MV : Multivector; Text : String := "") -- return Ada.Strings.Unbounded.Unbounded_String; function Outer_Product (V1, V2 : E3_Vector) return E3_Vector; -- function Norm_E2 (BV : Bivector) return Scalar; -- function Norm_E2 (V : M_Vector) return Scalar; -- function Norm_E2 (MV : E2GA.Multivector) return Scalar; -- function Norm_E2 (R : Rotor) return Scalar; -- function Norm_E2 (TV : Trivector) return Scalar; -- procedure Set_Coords (V : out M_Vector; C1, C2, C3 : float); procedure Set_Coords (MV : out Multivector; C1, C2, C3 : float); -- function Scalar_Product (V1, V2 : M_Vector) return Scalar; -- procedure Set_Bivector (BV : out Bivector; C1, C2, C3 : float); -- procedure Set_Rotor (X : out Rotor; C_Scalar, C2, C3, C4 : float); -- procedure Set_Rotor (X : out Rotor; C_Scalar : float); -- procedure Set_Rotor (X : out Rotor; MV : Multivector); -- procedure Set_Rotor (X : out Rotor; BV : Bivector); -- procedure Set_Rotor (X : out Rotor; C_Scalar : float; BV : Bivector); -- procedure Set_Scalar (S : out Scalar; Value : float); -- function To_Unsigned (V : M_Vector) return Vector_Unsigned; -- function To_2D (V : M_Vector) return E2GA.M_Vector; -- function To_3D (V : E2GA.M_Vector) return M_Vector; -- function To_Vector (MV : Syn_SMultivector) return M_Vector; function To_MV_Vector (V : E3_Vector) return Multivectors.M_Vector; -- Unit_e normalizes rotor R -- function Unit_e (R : Rotor) return Rotor; -- Unit_e normalizes M_Vector X function Unit_E (X : E3_Vector) return E3_Vector; private -- M_Vector corresponds to e3ga.M_Vector coordinate storage float m_c[3] -- type M_Vector is record -- Coordinates : Vector_Coords_3D := (0.0, 0.0, 0.0); -- m_c[3] -- end record; -- -- type Bivector is record -- Grade_Use : Grade_Usage := 7; -- 2^2 + 2^1 +2^0 -- C1_e1e2 : float := 0.0; -- C2_e2e3 : float := 0.0; -- C3_e3e1 : float := 0.0; -- end record; type Outermorphism is new Array_19F; -- type Rotor is record -- -- Coords_Type : Rotor_Coordinates_Type := Rotor_Scalar_e1e2_e2e3_e3e1; -- C1_Scalar : float := 0.0; -- C2_e1e2 : float := 0.0; -- C3_e2e3 : float := 0.0; -- C4_e3e1 : float := 0.0; -- end record; type Syn_SMultivector is record C1_e1 : float := 0.0; C2_e2 : float := 0.0; C3_e3 : float := 0.0; C4_e1e2e3 : float := 0.0; end record; end E3GA;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2018, Universidad Politécnica de Madrid -- -- -- -- This is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. This software is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- -- -- TABILITY 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 distributed with this software; see file -- -- COPYING3. If not, go to http://www.gnu.org/licenses for a complete copy -- -- of the license. -- -- -- ------------------------------------------------------------------------------ -- Temperature sensor implementation. -- This version is for a TMP36 sensor connected to GPIO pin 5 of -- the F429 Discovery Board. See the board user manual and the -- mapping in STM32.ADC. with STM32.Board; use STM32.Board; with STM32.Device; use STM32.Device; with HAL; use HAL; with STM32.ADC; use STM32.ADC; with STM32.GPIO; use STM32.GPIO; package body Sensor is -- ADC parameters Converter : Analog_To_Digital_Converter renames ADC_1; Input_Channel : constant Analog_Input_Channel := 5; Input : constant GPIO_Point := PA5; -- Local subprograms procedure Initialize; ---------------- -- Initialize -- ---------------- procedure Initialize is All_Regular_Conversions : constant Regular_Channel_Conversions := (1 => (Channel => Input_Channel, Sample_Time => Sample_144_Cycles)); -- needs 10 us minimum begin Initialize_LEDs; Enable_Clock (Input); Configure_IO (Input, (Mode => Mode_Analog, Resistors => Floating)); Enable_Clock (Converter); Reset_All_ADC_Units; Configure_Common_Properties (Mode => Independent, Prescalar => PCLK2_Div_2, DMA_Mode => Disabled, Sampling_Delay => Sampling_Delay_5_Cycles); Configure_Unit (Converter, Resolution => ADC_Resolution_12_Bits, Alignment => Right_Aligned); Configure_Regular_Conversions (Converter, Continuous => False, Trigger => Software_Triggered, Enable_EOC => True, Conversions => All_Regular_Conversions); Enable (Converter); end Initialize; --------- -- Get -- --------- procedure Get (Reading : out Sensor_Reading) is Successful : Boolean; begin Start_Conversion (Converter); Poll_For_Status (Converter, Regular_Channel_Conversion_Complete, Successful); if not Successful then Red_LED.Toggle; Reading := 0; else Green_LED.Toggle; Reading := Sensor_Reading (Conversion_Value (Converter)); end if; end Get; begin Initialize; end Sensor;
with STM32.Device; with STM32.SPI; use STM32.SPI; with HAL.SPI; use HAL.SPI; with cc3df4revo.Board; package body spi_accel is package GPIO renames STM32.GPIO; -- -- SPI connection initialization -- procedure init is procedure init_gpio; procedure reinit_spi; procedure configure_accel; -- all i/o lines initializations procedure init_gpio is begin -- activate spi lines STM32.Device.Enable_Clock (SCLK & MOSI & MISO); GPIO.Configure_IO (Points => (MOSI, MISO, SCLK), Config => (Mode => Mode_AF, AF => STM32.Device.GPIO_AF_SPI1_5, AF_Output_Type => Push_Pull, AF_Speed => Speed_Very_High, Resistors => Floating )); -- activate chip_select line STM32.Device.Enable_Clock (CS_ACCEL); GPIO.Configure_IO (This => CS_ACCEL, Config => (Mode => Mode_Out, Output_Type => Push_Pull, Speed => Speed_Very_High, Resistors => Floating )); GPIO.Set (CS_ACCEL); -- CS_ACCEL line is inverted end init_gpio; -- spi device initialization procedure reinit_spi is cfg : constant SPI_Configuration := SPI_Configuration' (Direction => D2Lines_FullDuplex, Data_Size => Data_Size_8b, Mode => Master, Clock_Polarity => Low, Clock_Phase => P1Edge, Slave_Management => Software_Managed, Baud_Rate_Prescaler => BRP_256, First_Bit => MSB, CRC_Poly => 7 ); begin SPI_Accel_Port.Disable; STM32.Device.Enable_Clock (SPI_Accel_Port); SPI_Accel_Port.Configure (Conf => cfg); SPI_Accel_Port.Enable; end reinit_spi; -- -- accel init -- procedure configure_accel is begin mpu6000_spi.Configure (gyro); end configure_accel; -- BODY begin reinit_spi; init_gpio; cc3df4revo.Board.usb_transmit ("spi ok; gpio ok;" & ASCII.CR & ASCII.LF); configure_accel; cc3df4revo.Board.usb_transmit ("gyro ok;" & ASCII.CR & ASCII.LF); end init; -- -- Reading data from accellerometer on board -- function read return accel_data is d : constant mpu6000_spi.Acc_Data := mpu6000_spi.Read (gyro); begin return accel_data'(X => d.Xacc, Y => d.Yacc, Z => d.Zacc, GX => d.Xang, GY => d.Yang, GZ => d.Zang); end read; function id (product : out Unsigned_8) return Unsigned_8 is begin return mpu6000_spi.Id (gyro, product); end id; end spi_accel;
-- -- Copyright (C) 2017 Nico Huber <nico.h@gmx.de> -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- with Interfaces.C; with Interfaces.C.Strings; with Ada.Directories; with HW.Debug; use Interfaces.C; use Interfaces.C.Strings; package body HW.File is READ : constant := 16#01#; WRITE : constant := 16#02#; function c_map (addr : out Word64; path : chars_ptr; len : Word32; off : Word32; mode : Word32; copy : int) return int; pragma Import (C, c_map, "hw_file_map"); procedure Map (Addr : out Word64; Path : in String; Len : in Natural := 0; Offset : in Natural := 0; Readable : in Boolean := False; Writable : in Boolean := False; Map_Copy : in Boolean := False; Success : out Boolean) is use type HW.Word32; cpath : chars_ptr := New_String (Path); ret : constant int := c_map (addr => Addr, path => cpath, len => Word32 (Len), off => Word32 (Offset), mode => (if Readable then READ else 0) or (if Writable then WRITE else 0), copy => (if Map_Copy then 1 else 0)); begin pragma Warnings(GNAT, Off, """cpath"" modified*, but* referenced", Reason => "Free() demands to set it to null_ptr"); Free (cpath); pragma Warnings(GNAT, On, """cpath"" modified*, but* referenced"); Success := ret = 0; pragma Debug (not Success, Debug.Put ("Mapping failed: ")); pragma Debug (not Success, Debug.Put_Int32 (Int32 (ret))); pragma Debug (not Success, Debug.New_Line); end Map; procedure Size (Length : out Natural; Path : String) with SPARK_Mode => Off is use type Ada.Directories.File_Size; Res_Size : Ada.Directories.File_Size; begin Res_Size := Ada.Directories.Size (Path); Length := Natural (Res_Size); exception when others => Length := 0; end Size; end HW.File;
-- { dg-do compile } procedure Slice_Enum is Pos : array (Boolean) of Integer; begin Pos (Boolean) := (others => 0); end;
-------------------------------------------------------------------------------------------------------------------- -- Copyright (c) 2013-2018 Luke A. Guest -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely, subject to the following restrictions: -- -- 1. The origin of this software must not be misrepresented; you must not -- claim that you wrote the original software. If you use this software -- in a product, an acknowledgment in the product documentation would be -- appreciated but is not required. -- -- 2. Altered source versions must be plainly marked as such, and must not be -- misrepresented as being the original software. -- -- 3. This notice may not be removed or altered from any source -- distribution. -------------------------------------------------------------------------------------------------------------------- -- SDL.Inputs.Mice -------------------------------------------------------------------------------------------------------------------- with SDL.Events.Mice; with SDL.Video.Windows; package SDL.Inputs.Mice is Mice_Error : exception; type Cursor_Toggles is (Off, On); for Cursor_Toggles use (Off => 0, On => 1); type Supported is (Yes, No); -- TODO: Re-enable this when the library links against 2.0.4! -- function Capture (Enabled : in Boolean) return Supported; -- SDL_CreateColorCursor -- SDL_CreateCursor -- SDL_CreateSystemCursor -- SDL_FreeCursor -- SDL_GetCursor -- SDL_GetDefaultCursor -- TODO: Re-enable this when the library links against 2.0.4! -- function Get_Global_State (X_Relative, Y_Relative : out SDL.Events.Mice.Movement_Values) return -- SDL.Events.Mice.Button_Masks; -- SDL_GetMouseFocus function Get_State (X_Relative, Y_Relative : out SDL.Events.Mice.Movement_Values) return SDL.Events.Mice.Button_Masks; function In_Relative_Mode return Boolean; function Get_Relative_State (X_Relative, Y_Relative : out SDL.Events.Mice.Movement_Values) return SDL.Events.Mice.Button_Masks; -- SDL_SetCursor procedure Set_Relative_Mode (Enable : in Boolean); -- SDL_ShowCursor -- TODO: Re-enable this when the library links against 2.0.4! -- Move the mouse to (x, y) on the screen. -- procedure Warp (X, Y : in SDL.Events.Mice.Screen_Coordinates); -- -- Move the mouse to (x, y) in the specified window. -- procedure Warp (Window : in SDL.Video.Windows.Window; X, Y : in SDL.Events.Mice.Window_Coordinates); end SDL.Inputs.Mice;
with Ada.Strings.Unbounded; package body Test_Utils is function Shift_Right (Value : Storage_Element; Amount : Natural) return Storage_Element with Import, Convention => Intrinsic; type UInt4 is mod 2 ** 4 with Size => 4; UInt4_To_Char : constant array (UInt4) of Character := (0 => '0', 1 => '1', 2 => '2', 3 => '3', 4 => '4', 5 => '5', 6 => '6', 7 => '7', 8 => '8', 9 => '9', 10 => 'A', 11 => 'B', 12 => 'C', 13 => 'D', 14 => 'E', 15 => 'F'); ---------------- -- From_Array -- ---------------- function From_Array (Data : Storage_Array) return Data_Frame is Result : Data_Frame; begin for Elt of Data loop Result.Append (Elt); end loop; return Result; end From_Array; --------------------- -- To_Array_Access -- --------------------- function To_Array_Access (Data : Data_Frame'Class) return Storage_Array_Access is Result : constant Storage_Array_Access := new Storage_Array (1 .. Storage_Count (Data.Length)); Index : Storage_Offset := Result'First; begin for Elt of Data loop Result (Index) := Elt; Index := Index + 1; end loop; return Result; end To_Array_Access; -------------- -- Hex_Dump -- -------------- function Hex_Dump (Data : Data_Frame'Class) return AAA.Strings.Vector is Result : AAA.Strings.Vector; Cnt : Natural := 0; begin for Elt of Data loop Result.Append_To_Last_Line (UInt4_To_Char (UInt4 (Shift_Right (Elt, 4))) & UInt4_To_Char (UInt4 (Elt and 16#0F#))); Cnt := Cnt + 1; if Cnt = 16 then Result.Append (""); Cnt := 0; else Result.Append_To_Last_Line (" "); end if; end loop; return Result; end Hex_Dump; ---------- -- Diff -- ---------- function Diff (A, B : Data_Frame'Class; A_Name : String := "Expected"; B_Name : String := "Output"; Skip_Header : Boolean := False) return AAA.Strings.Vector is begin return AAA.Strings.Diff (Hex_Dump (A), Hex_Dump (B), A_Name, B_Name, Skip_Header); end Diff; ----------- -- Image -- ----------- function Image (D : Storage_Array) return String is use Ada.Strings.Unbounded; Result : Unbounded_String; First : Boolean := True; begin Append (Result, "["); for Elt of D loop if First then First := False; else Append (Result, ", "); end if; Append (Result, UInt4_To_Char (UInt4 (Shift_Right (Elt, 4))) & UInt4_To_Char (UInt4 (Elt and 16#0F#))); end loop; Append (Result, "]"); return To_String (Result); end Image; ----------- -- Image -- ----------- function Image (D : Data_Frame) return String is use Ada.Strings.Unbounded; Result : Unbounded_String; First : Boolean := True; begin Append (Result, "["); for Elt of D loop if First then First := False; else Append (Result, ", "); end if; Append (Result, UInt4_To_Char (UInt4 (Shift_Right (Elt, 4))) & UInt4_To_Char (UInt4 (Elt and 16#0F#))); end loop; Append (Result, "]"); return To_String (Result); end Image; ---------------------- -- Number_Of_Frames -- ---------------------- function Number_Of_Frames (This : Abstract_Data_Processing) return Storage_Count is begin return Storage_Count (This.Frames.Length); end Number_Of_Frames; ----------- -- Clear -- ----------- procedure Clear (This : in out Abstract_Data_Processing) is begin This.Frames.Clear; This.Current_Frame.Clear; end Clear; --------------- -- Get_Frame -- --------------- function Get_Frame (This : Abstract_Data_Processing'Class; Index : Storage_Count) return Data_Frame is begin return This.Frames (Index); end Get_Frame; --------------------- -- Start_New_Frame -- --------------------- procedure Start_New_Frame (This : in out Abstract_Data_Processing) is begin This.Current_Frame.Clear; end Start_New_Frame; ------------------- -- Push_To_Frame -- ------------------- procedure Push_To_Frame (This : in out Abstract_Data_Processing; Data : Storage_Element) is begin This.Current_Frame.Append (Data); end Push_To_Frame; ---------------- -- Save_Frame -- ---------------- procedure Save_Frame (This : in out Abstract_Data_Processing) is begin This.Frames.Append (This.Current_Frame); end Save_Frame; end Test_Utils;
with game_types,ada.text_io ; use ada.text_io ; package game_functions is function initialize_cells return game_types.array_of_cell ; procedure render_game(cells : game_types.array_of_cell) ; function evolve_cells(cells : game_types.array_of_cell) return game_types.array_of_cell ; end game_functions ;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2017, AdaCore -- -- -- -- 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. Neither the name of the copyright holder 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 -- -- HOLDER 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. -- -- -- ------------------------------------------------------------------------------ with HAL; use HAL; with Ada.Unchecked_Conversion; package body STMPE1600 is subtype BA_2 is UInt8_Array (1 .. 2); function To_Pins is new Ada.Unchecked_Conversion (BA_2, STMPE1600_Pins); function From_Pins is new Ada.Unchecked_Conversion (STMPE1600_Pins, BA_2); ---------- -- Read -- ---------- procedure Read (This : STMPE1600_Expander; Reg : UInt8; Data : out UInt8_Array; Status : out Boolean) is S : HAL.I2C.I2C_Status; use type HAL.I2C.I2C_Status; begin This.Port.Mem_Read (This.Addr, UInt16 (Reg), HAL.I2C.Memory_Size_8b, Data, S); Status := S = HAL.I2C.Ok; end Read; ----------- -- Write -- ----------- procedure Write (This : STMPE1600_Expander; Reg : UInt8; Data : UInt8_Array; Status : out Boolean) is S : HAL.I2C.I2C_Status; use type HAL.I2C.I2C_Status; begin This.Port.Mem_Write (This.Addr, UInt16 (Reg), HAL.I2C.Memory_Size_8b, Data, S); Status := S = HAL.I2C.Ok; end Write; -------------- -- Check_Id -- -------------- procedure Check_Id (This : in out STMPE1600_Expander; Status : out Boolean) is Identifier : UInt8_Array (1 .. 2); begin Read (This, STMPE1600_REG_ChipID, Identifier, Status); if Identifier (1) /= 0 or else Identifier (2) /= 16#16# then Status := False; end if; end Check_Id; -------------------------- -- Set_Interrupt_Enable -- -------------------------- procedure Set_Interrupt_Enable (This : in out STMPE1600_Expander; Enable : Boolean; Polarity : STMPE1600_Pin_Polarity; Status : out Boolean) is Sys_Ctrl : aliased STMPE1600_SYS_CTRL; BA : aliased UInt8_Array (1 .. 1) with Address => Sys_Ctrl'Address; begin Read (This, STMPE1600_REG_System_Ctrl, BA, Status); if Status then Sys_Ctrl.INT_Enable := Enable; Sys_Ctrl.INT_Polarity := Polarity; Write (This, STMPE1600_REG_System_Ctrl, BA, Status); end if; end Set_Interrupt_Enable; ------------------------ -- Set_Interrupt_Mask -- ------------------------ procedure Set_Interrupt_Mask (This : STMPE1600_Expander; Mask : STMPE1600_Pins; Status : out Boolean) is BA : aliased UInt8_Array (1 .. 2) with Address => Mask'Address; begin Write (This, STMPE1600_REG_IEGPIOR_0, BA, Status); end Set_Interrupt_Mask; -------------------- -- Interrupt_Mask -- -------------------- function Interrupt_Mask (This : STMPE1600_Expander) return STMPE1600_Pins is BA : aliased UInt8_Array (1 .. 2); Status : Boolean; begin Read (This, STMPE1600_REG_IEGPIOR_0, BA, Status); return To_Pins (BA); end Interrupt_Mask; --------------------- -- Interrupt_State -- --------------------- function Interrupt_State (This : STMPE1600_Expander) return STMPE1600_Pins is BA : aliased UInt8_Array (1 .. 2); Status : Boolean; begin Read (This, STMPE1600_REG_ISGPIOR_0, BA, Status); return To_Pins (BA); end Interrupt_State; ---------------- -- Pins_State -- ---------------- function Pins_State (This : in out STMPE1600_Expander) return STMPE1600_Pins is BA : aliased UInt8_Array (1 .. 2); Status : Boolean; begin Read (This, STMPE1600_REG_GPMR_0, BA, Status); return To_Pins (BA); end Pins_State; --------------- -- Pin_State -- --------------- function Pin_State (This : in out STMPE1600_Expander; Pin : STMPE1600_Pin_Number) return Boolean is Pins : constant STMPE1600_Pins := Pins_State (This); begin return Pins (Pin); end Pin_State; -------------------- -- Set_Pins_State -- -------------------- procedure Set_Pins_State (This : in out STMPE1600_Expander; Pins : STMPE1600_Pins) is BA : constant UInt8_Array (1 .. 2) := From_Pins (Pins); Status : Boolean with Unreferenced; begin Write (This, STMPE1600_REG_GPSR_0, BA, Status); end Set_Pins_State; ------------------- -- Set_Pin_State -- ------------------- procedure Set_Pin_State (This : in out STMPE1600_Expander; Pin : STMPE1600_Pin_Number; State : Boolean) is Pins : STMPE1600_Pins := Pins_State (This); begin Pins (Pin) := State; Set_Pins_State (This, Pins); end Set_Pin_State; ------------------------ -- Set_Pins_Direction -- ------------------------ procedure Set_Pins_Direction (This : STMPE1600_Expander; Pins : STMPE1600_Pins_Direction) is BA : aliased UInt8_Array (1 .. 2) with Address => Pins'Address; Status : Boolean with Unreferenced; begin Write (This, STMPE1600_REG_GPDR_0, BA, Status); end Set_Pins_Direction; ----------------------- -- Set_Pin_Direction -- ----------------------- procedure Set_Pin_Direction (This : STMPE1600_Expander; Pin : STMPE1600_Pin_Number; Direction : STMPE1600_Pin_Direction) is Pins : aliased STMPE1600_Pins; BA : aliased UInt8_Array (1 .. 2) with Address => Pins'Address; Status : Boolean with Unreferenced; New_State : constant Boolean := Direction = Output; begin Read (This, STMPE1600_REG_GPDR_0, BA, Status); if Pins (Pin) = New_State then -- Nothing to do return; end if; Pins (Pin) := New_State; Write (This, STMPE1600_REG_GPDR_0, BA, Status); end Set_Pin_Direction; ------------------- -- Pin_Direction -- ------------------- function Pin_Direction (This : STMPE1600_Expander; Pin : STMPE1600_Pin_Number) return STMPE1600_Pin_Direction is Pins : aliased STMPE1600_Pins; BA : aliased UInt8_Array (1 .. 2) with Address => Pins'Address; Status : Boolean with Unreferenced; begin Read (This, STMPE1600_REG_GPDR_0, BA, Status); return (if Pins (Pin) then Output else Input); end Pin_Direction; -------------------------------- -- Set_Pin_Polarity_Inversion -- -------------------------------- procedure Set_Pin_Polarity_Inversion (This : STMPE1600_Expander; Pin : STMPE1600_Pin_Number; Inversion_State : Boolean) is Pins : aliased STMPE1600_Pins; BA : aliased UInt8_Array (1 .. 2) with Address => Pins'Address; Status : Boolean with Unreferenced; begin Read (This, STMPE1600_REG_GPPIR_0, BA, Status); if Pins (Pin) = Inversion_State then -- Nothing to do return; end if; Pins (Pin) := Inversion_State; Write (This, STMPE1600_REG_GPPIR_0, BA, Status); end Set_Pin_Polarity_Inversion; ------------------- -- As_GPIO_Point -- ------------------- function As_GPIO_Point (This : in out STMPE1600_Expander; Pin : STMPE1600_Pin_Number) return HAL.GPIO.Any_GPIO_Point is begin This.Points (Pin) := (This'Unrestricted_Access, Pin); return This.Points (Pin)'Unchecked_Access; end As_GPIO_Point; ---------- -- Mode -- ---------- overriding function Mode (This : STMPE1600_Pin) return HAL.GPIO.GPIO_Mode is begin return (case Pin_Direction (This.Port.all, This.Pin) is when Input => HAL.GPIO.Input, when Output => HAL.GPIO.Output); end Mode; -------------- -- Set_Mode -- -------------- overriding function Set_Mode (This : in out STMPE1600_Pin; Mode : HAL.GPIO.GPIO_Config_Mode) return Boolean is begin Set_Pin_Direction (This.Port.all, This.Pin, (case Mode is when HAL.GPIO.Input => Input, when HAL.GPIO.Output => Output)); return True; end Set_Mode; --------- -- Set -- --------- overriding function Set (This : STMPE1600_Pin) return Boolean is begin return Pin_State (This.Port.all, This.Pin); end Set; --------- -- Set -- --------- overriding procedure Set (This : in out STMPE1600_Pin) is begin Set_Pin_State (This.Port.all, This.Pin, True); end Set; ----------- -- Clear -- ----------- overriding procedure Clear (This : in out STMPE1600_Pin) is begin Set_Pin_State (This.Port.all, This.Pin, False); end Clear; ------------ -- Toggle -- ------------ overriding procedure Toggle (This : in out STMPE1600_Pin) is begin if This.Set then This.Clear; else This.Set; end if; end Toggle; end STMPE1600;
package Crawler is end Crawler;
--:::::::::: --random_generic.ads --:::::::::: generic type Result_Subtype is (<>); package Random_Generic is -- Simple integer pseudo-random number generator package. -- Michael B. Feldman, The George Washington University, -- June 1995. function Random_Value return Result_Subtype; end Random_Generic; --:::::::::: --screen.ads --:::::::::: package Screen is -- simple ANSI terminal emulator -- Michael Feldman, The George Washington University -- July, 1995 ScreenHeight : constant Integer := 24; ScreenWidth : constant Integer := 80; subtype Height is Integer range 1 .. ScreenHeight; subtype Width is Integer range 1 .. ScreenWidth; type Position is record Row : Height := 1; Column : Width := 1; end record; procedure Beep; -- Pre: none -- Post: the terminal beeps once procedure ClearScreen; -- Pre: none -- Post: the terminal screen is cleared procedure MoveCursor (To : in Position); -- Pre: To is defined -- Post: the terminal cursor is moved to the given position end Screen; --:::::::::: --windows.ads --:::::::::: with Screen; package Windows is -- manager for simple, nonoverlapping screen windows -- Michael Feldman, The George Washington University -- July, 1995 type Window is private; function Open (UpperLeft : Screen.Position; Height : Screen.Height; Width : Screen.Width) return Window; -- Pre: W, Height, and Width are defined -- Post: returns a Window with the given upper-left corner, -- height, and width procedure Title (W : in out Window; Name : in String; Under : in Character); -- Pre: W, Name, and Under are defined -- Post: Name is displayed at the top of the window W, underlined -- with the character Under. procedure Borders (W : in out Window; Corner : in Character; Down : in Character; Across : in Character); -- Pre: All parameters are defined -- Post: Draw border around current writable area in window with -- characters specified. Call this BEFORE Title. procedure MoveCursor (W : in out Window; P : in Screen.Position); -- Pre: W and P are defined, and P lies within the area of W -- Post: Cursor is moved to the specified position. -- Coordinates are relative to the -- upper left corner of W, which is (1, 1) procedure Put (W : in out Window; Ch : in Character); -- Pre: W and Ch are defined. -- Post: Ch is displayed in the window at -- the next available position. -- If end of column, go to the next row. -- If end of window, go to the top of the window. procedure Put (W : in out Window; S : in String); -- Pre: W and S are defined -- Post: S is displayed in the window, "line-wrapped" if necessary procedure New_Line (W : in out Window); -- Pre: W is defined -- Post: Cursor moves to beginning of next line of W; -- line is not blanked until next character is written private type Window is record First : Screen.Position; -- coordinates of upper left Last : Screen.Position; -- coordinates of lower right Current : Screen.Position; -- current cursor position end record; end Windows; --:::::::::: --Picture.ads --:::::::::: with Windows; with Screen; package Picture is -- Manager for semigraphical presentation of the philosophers -- i.e. more application oriented windows, build on top of -- the windows package. -- Each picture has an orientation, which defines which borders -- top-bottom, bottom-top, left-right, or right-left correspond -- to the left and right hand of the philosopher. -- -- Bjorn Kallberg, CelsiusTech Systems, Sweden -- July, 1995 type Root is abstract tagged private; type Root_Ptr is access Root'Class; procedure Open (W : in out Root; UpperLeft : in Screen.Position; Height : in Screen.Height; Width : in Screen.Width); -- Pre: Not opened -- Post: An empty window exists procedure Title (W : in out Root; Name : in String); -- Pre: An empty window -- Post: Name and a border is drawn. procedure Put_Line (W : in out Root; S : in String); procedure Left_Fork (W : in out Root; Pick : in Boolean) is abstract; procedure Right_Fork (W : in out Root; Pick : in Boolean) is abstract; -- left and right relates to philosopher position around table type North is new Root with private; type South is new Root with private; type East is new Root with private; type West is new Root with private; private type Root is abstract tagged record W : Windows.Window; end record; type North is new Root with null record; type South is new Root with null record; type East is new Root with null record; type West is new Root with null record; procedure Left_Fork (W : in out North; Pick : in Boolean); procedure Right_Fork (W : in out North; Pick : in Boolean); procedure Left_Fork (W : in out South; Pick : in Boolean); procedure Right_Fork (W : in out South; Pick : in Boolean); procedure Left_Fork (W : in out East; Pick : in Boolean); procedure Right_Fork (W : in out East; Pick : in Boolean); procedure Left_Fork (W : in out West; Pick : in Boolean); procedure Right_Fork (W : in out West; Pick : in Boolean); end Picture; --:::::::::: --chop.ads --:::::::::: package Chop is -- Dining Philosophers - Ada 95 edition -- Chopstick is an Ada 95 protected type -- Michael B. Feldman, The George Washington University, -- July, 1995. protected type Stick is entry Pick_Up; procedure Put_Down; private In_Use: Boolean := False; end Stick; end Chop; --:::::::::: --society.ads --:::::::::: package Society is -- Dining Philosophers - Ada 95 edition -- Society gives unique ID's to people, and registers their names -- Michael B. Feldman, The George Washington University, -- July, 1995. subtype Unique_DNA_Codes is Positive range 1 .. 5; Name_Register : array (Unique_DNA_Codes) of String (1 .. 18) := ("Edsger Dijkstra ", "Bjarne Stroustrup ", "Chris Anderson ", "Tucker Taft ", "Jean Ichbiah "); end Society; --:::::::::: --phil.ads --:::::::::: with Society; package Phil is -- Dining Philosophers - Ada 95 edition -- Philosopher is an Ada 95 task type with discriminant -- Michael B. Feldman, The George Washington University, -- July 1995 -- -- Revisions: -- July 1995. Bjorn Kallberg, CelsiusTech -- Reporting left or right instead of first stick task type Philosopher (My_ID : Society.Unique_DNA_Codes) is entry Start_Eating (Chopstick1 : in Positive; Chopstick2 : in Positive); end Philosopher; type States is (Breathing, Thinking, Eating, Done_Eating, Got_Left_Stick, Got_Right_Stick, Got_Other_Stick, Dying); end Phil; --:::::::::: --room.ads --:::::::::: with Chop; with Phil; with Society; package Room is -- Dining Philosophers - Ada 95 edition -- Room.Maitre_D is responsible for assigning seats at the -- table, "left" and "right" chopsticks, and for reporting -- interesting events to the outside world. -- Michael B. Feldman, The George Washington University, -- July, 1995. Table_Size : constant := 5; subtype Table_Type is Positive range 1 .. Table_Size; Sticks : array (Table_Type) of Chop.Stick; task Maitre_D is entry Start_Serving; entry Report_State (Which_Phil : in Society.Unique_DNA_Codes; State : in Phil.States; How_Long : in Natural := 0; Which_Meal : in Natural := 0); end Maitre_D; end Room; --:::::::::: --random_generic.adb --:::::::::: with Ada.Numerics.Discrete_Random; package body Random_Generic is -- Body of random number generator package. -- Uses Ada 95 random number generator; hides generator parameters -- Michael B. Feldman, The George Washington University, -- June 1995. package Ada95_Random is new Ada.Numerics.Discrete_Random (Result_Subtype => Result_Subtype); G : Ada95_Random.Generator; function Random_Value return Result_Subtype is begin return Ada95_Random.Random (Gen => G); end Random_Value; begin -- Random_Generic Ada95_Random.Reset (Gen => G); -- time-dependent initialization end Random_Generic; --:::::::::: --screen.adb --:::::::::: with Text_IO; package body Screen is -- simple ANSI terminal emulator -- Michael Feldman, The George Washington University -- July, 1995 -- These procedures will work correctly only if the actual -- terminal is ANSI compatible. ANSI.SYS on a DOS machine -- will suffice. package Int_IO is new Text_IO.Integer_IO (Num => Integer); procedure Beep is begin Text_IO.Put (Item => ASCII.BEL); end Beep; procedure ClearScreen is begin Text_IO.Put (Item => ASCII.ESC); Text_IO.Put (Item => "[2J"); end ClearScreen; procedure MoveCursor (To : in Position) is begin Text_IO.New_Line; Text_IO.Put (Item => ASCII.ESC); Text_IO.Put ("["); Int_IO.Put (Item => To.Row, Width => 1); Text_IO.Put (Item => ';'); Int_IO.Put (Item => To.Column, Width => 1); Text_IO.Put (Item => 'f'); end MoveCursor; end Screen; --:::::::::: --windows.adb --:::::::::: with Text_IO, with Screen; package body Windows is -- manager for simple, nonoverlapping screen windows -- Michael Feldman, The George Washington University -- July, 1995 function Open (UpperLeft : Screen.Position; Height : Screen.Height; Width : Screen.Width) return Window is Result : Window; begin Result.Current := UpperLeft; Result.First := UpperLeft; Result.Last := (Row => UpperLeft.Row + Height - 1, Column => UpperLeft.Column + Width - 1); return Result; end Open; procedure EraseToEndOfLine (W : in out Window) is begin Screen.MoveCursor (W.Current); for Count in W.Current.Column .. W.Last.Column loop Text_IO.Put (' '); end loop; Screen.MoveCursor (W.Current); end EraseToEndOfLine; procedure Put (W : in out Window; Ch : in Character) is begin -- If at end of current line, move to next line if W.Current.Column > W.Last.Column then if W.Current.Row = W.Last.Row then W.Current.Row := W.First.Row; else W.Current.Row := W.Current.Row + 1; end if; W.Current.Column := W.First.Column; end if; -- If at First char, erase line if W.Current.Column = W.First.Column then EraseToEndOfLine (W); end if; Screen.MoveCursor (To => W.Current); -- here is where we actually write the character! Text_IO.Put (Ch); W.Current.Column := W.Current.Column + 1; end Put; procedure Put (W : in out Window; S : in String) is begin for Count in S'Range loop Put (W, S (Count)); end loop; end Put; procedure New_Line (W : in out Window) is begin if W.Current.Column = 1 then EraseToEndOfLine (W); end if; if W.Current.Row = W.Last.Row then W.Current.Row := W.First.Row; else W.Current.Row := W.Current.Row + 1; end if; W.Current.Column := W.First.Column; end New_Line; procedure Title (W : in out Window; Name : in String; Under : in Character) is begin -- Put name on top line W.Current := W.First; Put (W, Name); New_Line (W); -- Underline name if desired, and reduce the writable area -- of the window by one line if Under = ' ' then -- no underlining W.First.Row := W.First.Row + 1; else -- go across the row, underlining for Count in W.First.Column .. W.Last.Column loop Put (W, Under); end loop; New_Line (W); W.First.Row := W.First.Row + 2; -- reduce writable area end if; end Title; procedure Borders (W : in out Window; Corner : in Character; Down : in Character; Across : in Character) is begin -- Put top line of border Screen.MoveCursor (W.First); Text_IO.Put (Corner); for Count in W.First.Column + 1 .. W.Last.Column - 1 loop Text_IO.Put (Across); end loop; Text_IO.Put (Corner); -- Put the two side lines for Count in W.First.Row + 1 .. W.Last.Row - 1 loop Screen.MoveCursor ((Row => Count, Column => W.First.Column)); Text_IO.Put (Down); Screen.MoveCursor ((Row => Count, Column => W.Last.Column)); Text_IO.Put (Down); end loop; -- Put the bottom line of the border Screen.MoveCursor ((Row => W.Last.Row, Column => W.First.Column)); Text_IO.Put (Corner); for Count in W.First.Column + 1 .. W.Last.Column - 1 loop Text_IO.Put (Across); end loop; Text_IO.Put (Corner); -- Make the Window smaller by one character on each side W.First := (Row => W.First.Row + 1, Column => W.First.Column + 1); W.Last := (Row => W.Last.Row - 1, Column => W.Last.Column - 1); W.Current := W.First; end Borders; procedure MoveCursor (W : in out Window; P : in Screen.Position) is -- Relative to writable Window boundaries, of course begin W.Current.Row := W.First.Row + P.Row; W.Current.Column := W.First.Column + P.Column; end MoveCursor; begin -- Windows Text_IO.New_Line; Screen.ClearScreen; Text_IO.New_Line; end Windows; -------------------- package Windows.Util is -- -- Child package to change the borders of an existing window -- Bjorn Kallberg, CelsiusTech Systems, Sweden -- July, 1995. -- call these procedures after border and title procedure Draw_Left (W : in out Window; C : in Character); procedure Draw_Right (W : in out Window; C : in Character); procedure Draw_Top (W : in out Window; C : in Character); procedure Draw_Bottom (W : in out Window; C : in Character); end Windows.Util; -------------------- with Text_IO; package body Windows.Util is -- Bjorn Kallberg, CelsiusTech Systems, Sweden -- July, 1995. -- When making borders and titles, the size has shrunk, so -- we must now draw outside the First and Last points procedure Draw_Left (W : in out Window; C : in Character) is begin for R in W.First.Row - 3 .. W.Last.Row + 1 loop Screen.MoveCursor ((Row => R, Column => W.First.Column-1)); Text_IO.Put (C); end loop; end; procedure Draw_Right (W : in out Window; C : in Character) is begin for R in W.First.Row - 3 .. W.Last.Row + 1 loop Screen.MoveCursor ((Row => R, Column => W.Last.Column + 1)); Text_IO.Put (C); end loop; end; procedure Draw_Top (W : in out Window; C : in Character) is begin for I in W.First.Column - 1 .. W.Last.Column + 1 loop Screen.MoveCursor ((Row => W.First.Row - 3, Column => I)); Text_IO.Put (C); end loop; end; procedure Draw_Bottom (W : in out Window; C : in Character) is begin for I in W.First.Column - 1 .. W.Last.Column + 1 loop Screen.MoveCursor ((Row => W.Last.Row + 1, Column => I)); Text_IO.Put (C); end loop; end; end Windows.Util; --:::::::::: --Picture.adb --:::::::::: with Windows.Util; package body Picture is -- -- Bjorn Kallberg, CelsiusTech Systems, Sweden -- July, 1995 function Vertical_Char (Stick : Boolean) return Character is begin if Stick then return '#'; else return ':'; end if; end; function Horizontal_Char (Stick : Boolean) return Character is begin if Stick then return '#'; else return '-'; end if; end; procedure Open (W : in out Root; UpperLeft : in Screen.Position; Height : in Screen.Height; Width : in Screen.Width) is begin W.W := Windows.Open (UpperLeft, Height, Width); end; procedure Title (W : in out Root; Name : in String) is -- Pre: An empty window -- Post: Name and a boarder is drawn. begin Windows.Borders (W.W, '+', ':', '-'); Windows.Title (W.W, Name,'-'); end; procedure Put_Line (W : in out Root; S : in String) is begin Windows.Put (W.W, S); Windows.New_Line (W.W); end; -- North procedure Left_Fork (W : in out North; Pick : in Boolean) is begin Windows.Util.Draw_Right (W.W, Vertical_Char (Pick)); end; procedure Right_Fork (W : in out North; Pick : in Boolean) is begin Windows.Util.Draw_Left (W.W, Vertical_Char (Pick)); end; -- South procedure Left_Fork (W : in out South; Pick : in Boolean) is begin Windows.Util.Draw_Left (W.W, Vertical_Char (Pick)); end; procedure Right_Fork (W : in out South; Pick : in Boolean) is begin Windows.Util.Draw_Right (W.W, Vertical_Char (Pick)); end; -- East procedure Left_Fork (W : in out East; Pick : in Boolean) is begin Windows.Util.Draw_Bottom (W.W, Horizontal_Char (Pick)); end; procedure Right_Fork (W : in out East; Pick : in Boolean) is begin Windows.Util.Draw_Top (W.W, Horizontal_Char (Pick)); end; -- West procedure Left_Fork (W : in out West; Pick : in Boolean) is begin Windows.Util.Draw_Top (W.W, Horizontal_Char (Pick)); end; procedure Right_Fork (W : in out West; Pick : in Boolean) is begin Windows.Util.Draw_Bottom (W.W, Horizontal_Char (Pick)); end; end Picture; --:::::::::: --chop.adb --:::::::::: package body Chop is -- Dining Philosophers - Ada 95 edition -- Chopstick is an Ada 95 protected type -- Michael B. Feldman, The George Washington University, -- July, 1995. protected body Stick is entry Pick_Up when not In_Use is begin In_Use := True; end Pick_Up; procedure Put_Down is begin In_Use := False; end Put_Down; end Stick; end Chop; --:::::::::: --phil.adb --:::::::::: with Society; with Room; with Random_Generic; package body Phil is -- Dining Philosophers - Ada 95 edition -- Philosopher is an Ada 95 task type with discriminant. -- Chopsticks are assigned by a higher authority, which -- can vary the assignments to show different algorithms. -- Philosopher always grabs First_Grab, then Second_Grab. -- Philosopher is oblivious to outside world, but needs to -- communicate is life-cycle events the Maitre_D. -- Chopsticks assigned to one philosopher must be -- consecutive numbers, or the first and last chopstick. -- Michael B. Feldman, The George Washington University, -- July, 1995. -- Revisions: -- July, 1995. Bjorn Kallberg, CelsiusTech subtype Think_Times is Positive range 1 .. 8; package Think_Length is new Random_Generic (Result_Subtype => Think_Times); subtype Meal_Times is Positive range 1 .. 10; package Meal_Length is new Random_Generic (Result_Subtype => Meal_Times); task body Philosopher is -- My_ID is discriminant subtype Life_Time is Positive range 1 .. 5; Who_Am_I : Society.Unique_DNA_Codes := My_ID; -- discriminant First_Grab : Positive; Second_Grab : Positive; Meal_Time : Meal_Times; Think_Time : Think_Times; First_Stick : States; begin -- get assigned the first and second chopsticks here accept Start_Eating (Chopstick1 : in Positive; Chopstick2 : in Positive) do First_Grab := Chopstick1; Second_Grab := Chopstick2; if (First_Grab mod Room.Table_Type'Last) + 1 = Second_Grab then First_Stick := Got_Right_Stick; else First_Stick := Got_Left_Stick; end if; end Start_Eating; Room.Maitre_D.Report_State (Who_Am_I, Breathing); for Meal in Life_Time loop Room.Sticks (First_Grab).Pick_Up; Room.Maitre_D.Report_State (Who_Am_I, First_Stick, First_Grab); Room.Sticks (Second_Grab).Pick_Up; Room.Maitre_D.Report_State (Who_Am_I, Got_Other_Stick, Second_Grab); Meal_Time := Meal_Length.Random_Value; Room.Maitre_D.Report_State (Who_Am_I, Eating, Meal_Time, Meal); delay Duration (Meal_Time); Room.Maitre_D.Report_State (Who_Am_I, Done_Eating); Room.Sticks (First_Grab).Put_Down; Room.Sticks (Second_Grab).Put_Down; Think_Time := Think_Length.Random_Value; Room.Maitre_D.Report_State (Who_Am_I, Thinking, Think_Time); delay Duration (Think_Time); end loop; Room.Maitre_D.Report_State (Who_Am_I, Dying); end Philosopher; end Phil; --:::::::::: --room.adb --:::::::::: with Picture; with Chop; with Phil; with Society; with Calendar; pragma Elaborate (Phil); package body Room is -- Dining Philosophers, Ada 95 edition -- A line-oriented version of the Room package -- Michael B. Feldman, The George Washington University, -- July, 1995. -- Revisions -- July, 1995. Bjorn Kallberg, CelsiusTech Systems, Sweden. -- Pictorial display of stick in use -- philosophers sign into dining room, giving Maitre_D their DNA code Dijkstra : aliased Phil.Philosopher (My_ID => 1); Stroustrup : aliased Phil.Philosopher (My_ID => 2); Anderson : aliased Phil.Philosopher (My_ID => 3); Taft : aliased Phil.Philosopher (My_ID => 4); Ichbiah : aliased Phil.Philosopher (My_ID => 5); type Philosopher_Ptr is access all Phil.Philosopher; Phils : array (Table_Type) of Philosopher_Ptr; Phil_Pics : array (Table_Type) of Picture.Root_Ptr; Phil_Seats : array (Society.Unique_DNA_Codes) of Table_Type; task body Maitre_D is T : Natural; Start_Time : Calendar.Time; Blanks : constant String := " "; begin accept Start_Serving; Start_Time := Calendar.Clock; -- now Maitre_D assigns phils to seats at the table Phils := (Dijkstra'Access, Anderson'Access, Ichbiah'Access, Taft'Access, Stroustrup'Access); -- Which seat each phil occupies. for I in Table_Type loop Phil_Seats (Phils(I).My_Id) := I; end loop; Phil_Pics := (new Picture.North, new Picture.East, new Picture.South, new Picture.South, new Picture.West); Picture.Open (Phil_Pics(1).all,( 1, 24), 7, 30); Picture.Open (Phil_Pics(2).all,( 9, 46), 7, 30); Picture.Open (Phil_Pics(3).all,(17, 41), 7, 30); Picture.Open (Phil_Pics(4).all,(17, 7), 7, 30); Picture.Open (Phil_Pics(5).all,( 9, 2), 7, 30); -- and assigns them their chopsticks. Phils (1).Start_Eating (1, 2); Phils (3).Start_Eating (3, 4); Phils (2).Start_Eating (2, 3); Phils (5).Start_Eating (1, 5); Phils (4).Start_Eating (4, 5); loop select accept Report_State (Which_Phil : in Society.Unique_DNA_Codes; State : in Phil.States; How_Long : in Natural := 0; Which_Meal : in Natural := 0) do T := Natural (Calendar."-" (Calendar.Clock, Start_Time)); case State is when Phil.Breathing => Picture.Title (Phil_Pics (Phil_Seats (Which_Phil)).all, Society.Name_Register (Which_Phil)); Picture.Put_line (Phil_Pics (Phil_Seats (Which_Phil)).all, "T =" & Integer'Image (T) & " " & "Breathing..."); when Phil.Thinking => Picture.Put_line (Phil_Pics (Phil_Seats (Which_Phil)).all, "T =" & Integer'Image (T) & " " & "Thinking" & Integer'Image (How_Long) & " seconds."); when Phil.Eating => Picture.Put_line (Phil_Pics (Phil_Seats (Which_Phil)).all, "T =" & Integer'Image (T) & " " & "Meal" & Integer'Image (Which_Meal) & "," & Integer'Image (How_Long) & " seconds."); when Phil.Done_Eating => Picture.Put_line (Phil_Pics (Phil_Seats (Which_Phil)).all, "T =" & Integer'Image (T) & " " & "Yum-yum (burp)"); Picture.Left_Fork (Phil_Pics (Phil_Seats (Which_Phil)).all, False); Picture.Right_Fork (Phil_Pics (Phil_Seats (Which_Phil)).all, False); when Phil.Got_Left_Stick => Picture.Put_line (Phil_Pics (Phil_Seats (Which_Phil)).all, "T =" & Integer'Image (T) & " " & "First chopstick" & Integer'Image (How_Long)); Picture.Left_Fork (Phil_Pics (Phil_Seats (Which_Phil)).all, True); when Phil.Got_Right_Stick => Picture.Put_line (Phil_Pics (Phil_Seats (Which_Phil)).all, "T =" & Integer'Image (T) & " " & "First chopstick" & Integer'Image (How_Long)); Picture.Right_Fork (Phil_Pics (Phil_Seats (Which_Phil)).all, True); when Phil.Got_Other_Stick => Picture.Put_line (Phil_Pics (Phil_Seats (Which_Phil)).all, "T =" & Integer'Image (T) & " " & "Second chopstick" & Integer'Image (How_Long)); Picture.Left_Fork (Phil_Pics (Phil_Seats (Which_Phil)).all, True); Picture.Right_Fork (Phil_Pics (Phil_Seats (Which_Phil)).all, True); when Phil.Dying => Picture.Put_line (Phil_Pics (Phil_Seats (Which_Phil)).all, "T =" & Integer'Image (T) & " " & "Croak"); end case; -- State end Report_State; or terminate; end select; end loop; end Maitre_D; end Room; --:::::::::: --diners.adb --:::::::::: with Text_IO; with Room; procedure Diners is -- Dining Philosophers - Ada 95 edition -- This is the main program, responsible only for telling the -- Maitre_D to get busy. -- Michael B. Feldman, The George Washington University, -- July, 1995. begin --Text_IO.New_Line; -- artifice to flush output buffer Room.Maitre_D.Start_Serving; end Diners;
----------------------------------------------------------------------- -- AWA.Comments.Models -- AWA.Comments.Models ----------------------------------------------------------------------- -- File generated by ada-gen DO NOT MODIFY -- Template used: templates/model/package-spec.xhtml -- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 1095 ----------------------------------------------------------------------- -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- 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. ----------------------------------------------------------------------- pragma Warnings (Off); with ADO.Sessions; with ADO.Objects; with ADO.Statements; with ADO.SQL; with ADO.Schemas; with ADO.Queries; with ADO.Queries.Loaders; with Ada.Calendar; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Util.Beans.Objects; with Util.Beans.Objects.Enums; with Util.Beans.Basic.Lists; with ADO.Audits; with AWA.Users.Models; with Util.Beans.Methods; pragma Warnings (On); package AWA.Comments.Models is pragma Style_Checks ("-mr"); -- -------------------- -- The format type defines the message format type. -- -------------------- type Format_Type is (FORMAT_TEXT, FORMAT_WIKI, FORMAT_HTML); for Format_Type use (FORMAT_TEXT => 0, FORMAT_WIKI => 1, FORMAT_HTML => 2); package Format_Type_Objects is new Util.Beans.Objects.Enums (Format_Type); type Nullable_Format_Type is record Is_Null : Boolean := True; Value : Format_Type; end record; -- -------------------- -- The status type defines whether the comment is visible or not. -- The comment can be put in the COMMENT_WAITING state so that -- it is not immediately visible. It must be put in the COMMENT_PUBLISHED -- state to be visible. -- -------------------- type Status_Type is (COMMENT_PUBLISHED, COMMENT_WAITING, COMMENT_SPAM, COMMENT_BLOCKED, COMMENT_ARCHIVED); for Status_Type use (COMMENT_PUBLISHED => 0, COMMENT_WAITING => 1, COMMENT_SPAM => 2, COMMENT_BLOCKED => 3, COMMENT_ARCHIVED => 4); package Status_Type_Objects is new Util.Beans.Objects.Enums (Status_Type); type Nullable_Status_Type is record Is_Null : Boolean := True; Value : Status_Type; end record; type Comment_Ref is new ADO.Objects.Object_Ref with null record; -- -------------------- -- The Comment table records a user comment associated with a database entity. -- The comment can be associated with any other database record. -- -------------------- -- Create an object key for Comment. function Comment_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key; -- Create an object key for Comment from a string. -- Raises Constraint_Error if the string cannot be converted into the object key. function Comment_Key (Id : in String) return ADO.Objects.Object_Key; Null_Comment : constant Comment_Ref; function "=" (Left, Right : Comment_Ref'Class) return Boolean; -- Set the comment publication date procedure Set_Create_Date (Object : in out Comment_Ref; Value : in Ada.Calendar.Time); -- Get the comment publication date function Get_Create_Date (Object : in Comment_Ref) return Ada.Calendar.Time; -- Set the comment message. procedure Set_Message (Object : in out Comment_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Set_Message (Object : in out Comment_Ref; Value : in String); -- Get the comment message. function Get_Message (Object : in Comment_Ref) return Ada.Strings.Unbounded.Unbounded_String; function Get_Message (Object : in Comment_Ref) return String; -- Set the entity identifier to which this comment is associated procedure Set_Entity_Id (Object : in out Comment_Ref; Value : in ADO.Identifier); -- Get the entity identifier to which this comment is associated function Get_Entity_Id (Object : in Comment_Ref) return ADO.Identifier; -- Set the comment identifier procedure Set_Id (Object : in out Comment_Ref; Value : in ADO.Identifier); -- Get the comment identifier function Get_Id (Object : in Comment_Ref) return ADO.Identifier; -- Get the optimistic lock version. function Get_Version (Object : in Comment_Ref) return Integer; -- Set the entity type that identifies the table to which the comment is associated. procedure Set_Entity_Type (Object : in out Comment_Ref; Value : in ADO.Entity_Type); -- Get the entity type that identifies the table to which the comment is associated. function Get_Entity_Type (Object : in Comment_Ref) return ADO.Entity_Type; -- Set the comment status to decide whether the comment is visible (published) or not. procedure Set_Status (Object : in out Comment_Ref; Value : in AWA.Comments.Models.Status_Type); -- Get the comment status to decide whether the comment is visible (published) or not. function Get_Status (Object : in Comment_Ref) return AWA.Comments.Models.Status_Type; -- Set the comment format type. procedure Set_Format (Object : in out Comment_Ref; Value : in AWA.Comments.Models.Format_Type); -- Get the comment format type. function Get_Format (Object : in Comment_Ref) return AWA.Comments.Models.Format_Type; -- procedure Set_Author (Object : in out Comment_Ref; Value : in AWA.Users.Models.User_Ref'Class); -- function Get_Author (Object : in Comment_Ref) return AWA.Users.Models.User_Ref'Class; -- Load the entity identified by 'Id'. -- Raises the NOT_FOUND exception if it does not exist. procedure Load (Object : in out Comment_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier); -- Load the entity identified by 'Id'. -- Returns True in <b>Found</b> if the object was found and False if it does not exist. procedure Load (Object : in out Comment_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean); -- Find and load the entity. overriding procedure Find (Object : in out Comment_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); -- Save the entity. If the entity does not have an identifier, an identifier is allocated -- and it is inserted in the table. Otherwise, only data fields which have been changed -- are updated. overriding procedure Save (Object : in out Comment_Ref; Session : in out ADO.Sessions.Master_Session'Class); -- Delete the entity. overriding procedure Delete (Object : in out Comment_Ref; Session : in out ADO.Sessions.Master_Session'Class); overriding function Get_Value (From : in Comment_Ref; Name : in String) return Util.Beans.Objects.Object; -- Table definition COMMENT_TABLE : constant ADO.Schemas.Class_Mapping_Access; -- Internal method to allocate the Object_Record instance overriding procedure Allocate (Object : in out Comment_Ref); -- Copy of the object. procedure Copy (Object : in Comment_Ref; Into : in out Comment_Ref); -- -------------------- -- The comment information. -- -------------------- type Comment_Info is new Util.Beans.Basic.Bean with record -- the comment identifier. Id : ADO.Identifier; -- the comment author's name. Author : Ada.Strings.Unbounded.Unbounded_String; -- the comment author's email. Email : Ada.Strings.Unbounded.Unbounded_String; -- the comment date. Date : Ada.Calendar.Time; -- the comment format type. Format : AWA.Comments.Models.Format_Type; -- the comment text. Comment : Ada.Strings.Unbounded.Unbounded_String; -- the comment status. Status : AWA.Comments.Models.Status_Type; end record; -- Get the bean attribute identified by the name. overriding function Get_Value (From : in Comment_Info; Name : in String) return Util.Beans.Objects.Object; -- Set the bean attribute identified by the name. overriding procedure Set_Value (Item : in out Comment_Info; Name : in String; Value : in Util.Beans.Objects.Object); package Comment_Info_Beans is new Util.Beans.Basic.Lists (Element_Type => Comment_Info); package Comment_Info_Vectors renames Comment_Info_Beans.Vectors; subtype Comment_Info_List_Bean is Comment_Info_Beans.List_Bean; type Comment_Info_List_Bean_Access is access all Comment_Info_List_Bean; -- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>. procedure List (Object : in out Comment_Info_List_Bean'Class; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); subtype Comment_Info_Vector is Comment_Info_Vectors.Vector; -- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>. procedure List (Object : in out Comment_Info_Vector; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); Query_Comment_List : constant ADO.Queries.Query_Definition_Access; Query_All_Comment_List : constant ADO.Queries.Query_Definition_Access; type Comment_Bean is abstract new AWA.Comments.Models.Comment_Ref and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with null record; -- This bean provides some methods that can be used in a Method_Expression. overriding function Get_Method_Bindings (From : in Comment_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Set the bean attribute identified by the name. overriding procedure Set_Value (Item : in out Comment_Bean; Name : in String; Value : in Util.Beans.Objects.Object); procedure Create (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; procedure Delete (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; procedure Save (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; procedure Publish (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; private COMMENT_NAME : aliased constant String := "awa_comment"; COL_0_1_NAME : aliased constant String := "create_date"; COL_1_1_NAME : aliased constant String := "message"; COL_2_1_NAME : aliased constant String := "entity_id"; COL_3_1_NAME : aliased constant String := "id"; COL_4_1_NAME : aliased constant String := "version"; COL_5_1_NAME : aliased constant String := "entity_type"; COL_6_1_NAME : aliased constant String := "status"; COL_7_1_NAME : aliased constant String := "format"; COL_8_1_NAME : aliased constant String := "author_id"; COMMENT_DEF : aliased constant ADO.Schemas.Class_Mapping := (Count => 9, Table => COMMENT_NAME'Access, Members => ( 1 => COL_0_1_NAME'Access, 2 => COL_1_1_NAME'Access, 3 => COL_2_1_NAME'Access, 4 => COL_3_1_NAME'Access, 5 => COL_4_1_NAME'Access, 6 => COL_5_1_NAME'Access, 7 => COL_6_1_NAME'Access, 8 => COL_7_1_NAME'Access, 9 => COL_8_1_NAME'Access) ); COMMENT_TABLE : constant ADO.Schemas.Class_Mapping_Access := COMMENT_DEF'Access; COMMENT_AUDIT_DEF : aliased constant ADO.Audits.Auditable_Mapping := (Count => 3, Of_Class => COMMENT_DEF'Access, Members => ( 1 => 1, 2 => 6, 3 => 7) ); COMMENT_AUDIT_TABLE : constant ADO.Audits.Auditable_Mapping_Access := COMMENT_AUDIT_DEF'Access; Null_Comment : constant Comment_Ref := Comment_Ref'(ADO.Objects.Object_Ref with null record); type Comment_Impl is new ADO.Audits.Auditable_Object_Record (Key_Type => ADO.Objects.KEY_INTEGER, Of_Class => COMMENT_DEF'Access, With_Audit => COMMENT_AUDIT_DEF'Access) with record Create_Date : Ada.Calendar.Time; Message : Ada.Strings.Unbounded.Unbounded_String; Entity_Id : ADO.Identifier; Version : Integer; Entity_Type : ADO.Entity_Type; Status : AWA.Comments.Models.Status_Type; Format : AWA.Comments.Models.Format_Type; Author : AWA.Users.Models.User_Ref; end record; type Comment_Access is access all Comment_Impl; overriding procedure Destroy (Object : access Comment_Impl); overriding procedure Find (Object : in out Comment_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); overriding procedure Load (Object : in out Comment_Impl; Session : in out ADO.Sessions.Session'Class); procedure Load (Object : in out Comment_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class); overriding procedure Save (Object : in out Comment_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Create (Object : in out Comment_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Delete (Object : in out Comment_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Set_Field (Object : in out Comment_Ref'Class; Impl : out Comment_Access); package File_1 is new ADO.Queries.Loaders.File (Path => "comment-queries.xml", Sha1 => "80302F51E2EC9855EFAFB43954D724A697C1F8E6"); package Def_Commentinfo_Comment_List is new ADO.Queries.Loaders.Query (Name => "comment-list", File => File_1.File'Access); Query_Comment_List : constant ADO.Queries.Query_Definition_Access := Def_Commentinfo_Comment_List.Query'Access; package Def_Commentinfo_All_Comment_List is new ADO.Queries.Loaders.Query (Name => "all-comment-list", File => File_1.File'Access); Query_All_Comment_List : constant ADO.Queries.Query_Definition_Access := Def_Commentinfo_All_Comment_List.Query'Access; end AWA.Comments.Models;
------------------------------------------------------------------------------- -- Copyright (c) 2016 Daniel King -- -- Permission is hereby granted, free of charge, to any person obtaining a -- copy of this software and associated documentation files (the "Software"), -- to deal in the Software without restriction, including without limitation -- the rights to use, copy, modify, merge, publish, distribute, sublicense, -- and/or sell copies of the Software, and to permit persons to whom the -- Software is furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------- pragma Profile (Ravenscar); pragma Partition_Elaboration_Policy (Sequential); with Ada.Real_Time; with DW1000.Constants; with DW1000.BSP; with DW1000.Register_Types; use DW1000.Register_Types; with DW1000.System_Time; use DW1000.System_Time; with DW1000.Types; use DW1000.Types; with Interfaces; use Interfaces; -- This package contains high-level procedures for using the DW1000. package DW1000.Driver with SPARK_Mode => On is type Result_Type is (Success, Error); type Clocks is (Enable_All_Seq, Force_Sys_XTI, Force_Sys_PLL, Read_Acc_On, Read_Acc_Off, Force_OTP_On, Force_OTP_Off, Force_Tx_PLL); type Data_Rates is (Data_Rate_110k, -- 110 kbps Data_Rate_850k, -- 850 kbps Data_Rate_6M8); -- 6.8 Mbps for Data_Rates use (Data_Rate_110k => 2#00#, Data_Rate_850k => 2#01#, Data_Rate_6M8 => 2#10#); type Channel_Number is range 1 .. 7 with Static_Predicate => Channel_Number in 1 .. 5 | 7; -- Channels 1 .. 5 and 7 are supported by the DW1000. type PRF_Type is (PRF_16MHz, PRF_64MHz); for PRF_Type use (PRF_16MHz => 2#01#, PRF_64MHz => 2#10#); type Preamble_Lengths is (PLEN_64, PLEN_128, PLEN_256, PLEN_512, PLEN_1024, PLEN_1536, PLEN_2048, PLEN_4096); type Preamble_Acq_Chunk_Length is (PAC_8, PAC_16, PAC_32, PAC_64); type Preamble_Code_Number is new Positive range 1 .. 24; type Physical_Header_Modes is (Standard_Frames, Extended_Frames); for Physical_Header_Modes use (Standard_Frames => 2#00#, Extended_Frames => 2#11#); type SFD_Timeout_Number is new Natural range 0 .. (2**16) - 1; type SFD_Length_Number is new Natural range 8 .. 64 with Static_Predicate => SFD_Length_Number in 8 .. 16 | 64; type AON_Address_Array is array (Index range <>) of AON_ADDR_Field; -- Array of addresses within the AON address space. type Rx_Modes is (Normal, Sniff); type Tx_Power_Config_Type (Smart_Tx_Power_Enabled : Boolean := True) is record case Smart_Tx_Power_Enabled is when True => Boost_Normal : TX_POWER_Field; Boost_500us : TX_POWER_Field; Boost_250us : TX_POWER_Field; Boost_125us : TX_POWER_Field; when False => Boost_SHR : TX_POWER_Field; Boost_PHR : TX_POWER_Field; end case; end record; type Tx_Power_Config_Table is array (Positive range 1 .. 7, PRF_Type) of Tx_Power_Config_Type; function To_Positive (PAC : in Preamble_Acq_Chunk_Length) return Positive is (case PAC is when PAC_8 => 8, when PAC_16 => 16, when PAC_32 => 32, when PAC_64 => 64); function To_Positive (Preamble_Length : in Preamble_Lengths) return Positive is (case Preamble_Length is when PLEN_64 => 64, when PLEN_128 => 128, when PLEN_256 => 256, when PLEN_512 => 512, when PLEN_1024 => 1024, when PLEN_1536 => 1536, when PLEN_2048 => 2048, when PLEN_4096 => 4096); function Recommended_PAC (Preamble_Length : in Preamble_Lengths) return Preamble_Acq_Chunk_Length is (case Preamble_Length is when PLEN_64 => PAC_8, when PLEN_128 => PAC_8, when PLEN_256 => PAC_16, when PLEN_512 => PAC_16, when PLEN_1024 => PAC_32, when PLEN_1536 => PAC_64, when PLEN_2048 => PAC_64, when PLEN_4096 => PAC_64); -- Get the recommended preamble acquisition chunk (PAC) length based -- on the preamble length. -- -- These recommendations are from Section 4.1.1 of the DW1000 User Manual. function Recommended_SFD_Timeout (Preamble_Length : in Preamble_Lengths; SFD_Length : in SFD_Length_Number; PAC : in Preamble_Acq_Chunk_Length) return SFD_Timeout_Number is (SFD_Timeout_Number ((To_Positive (Preamble_Length) + Positive (SFD_Length) + 1) - To_Positive (PAC))); -- Compute the recommended SFD timeout for a given preamble length, SFD -- length, and preamble acquisition chunk length. -- -- For example, with a preable length of 1024 symbols, an SFD length of -- 64 symbols, and a PAC length of 32 symbols the recommended SFD timeout -- is 1024 + 64 + 1 - 32 = 1057 symbols. -- -- @param Preamble_Length The length of the preamble in symbols. -- -- @param SFD_Length The length of the SFD in symbols. The SFD length -- depends on whether or not a non-standard SFD is used, and the data -- rate. For a data rate of 110 kbps the SFD length is 64 symbols for -- the standard SFD and DecaWave-defined SFD. For a data rate of 850 -- kbps and above the SFD length is 8 symbols for a standard SFD, and 8 -- or 16 symbols for the DecaWave-defined SFD sequence. -- -- @param PAC The preamble acquisition chunk length. procedure Load_LDE_From_ROM with Global => (In_Out => DW1000.BSP.Device_State, Input => Ada.Real_Time.Clock_Time), Depends => (DW1000.BSP.Device_State => DW1000.BSP.Device_State, null => Ada.Real_Time.Clock_Time); -- Loads the leading edge detection (LDE) microcode from ROM. -- -- The LDE code must be loaded in order to use the LDE algorithm. If the -- LDE code is not loaded then the LDERUNE bit in the PMSC_CTRL1 register -- must be set to 0. -- -- Note: This procedure modifies the clocks setting in PMSC_CTRL0. procedure Enable_Clocks (Clock : in Clocks) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ Clock); -- Enables and configures the specified clock. -- -- This procedure configures the following registers: -- * PMSC_CTRL0 procedure Read_OTP (Address : in OTP_ADDR_Field; Word : out Bits_32) with Global => (In_Out => DW1000.BSP.Device_State), Depends => ((DW1000.BSP.Device_State, Word) => (DW1000.BSP.Device_State, Address)); -- Reads a 32-bit word from the DW1000 one-time programmable (OTP) memory. -- -- The package DW1000.Constants defines the addresses used to store the -- various data stored in the OTP memory. procedure Read_OTP_Tx_Power_Level (Channel : in Channel_Number; PRF : in PRF_Type; Power_Level : out TX_POWER_Type) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => (DW1000.BSP.Device_State, Channel, PRF), Power_Level => (DW1000.BSP.Device_State, Channel, PRF)); procedure Read_OTP_Antenna_Delay (Antenna_Delay_16_MHz : out Antenna_Delay_Time; Antenna_Delay_64_MHz : out Antenna_Delay_Time) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => DW1000.BSP.Device_State, Antenna_Delay_16_MHz => DW1000.BSP.Device_State, Antenna_Delay_64_MHz => DW1000.BSP.Device_State); procedure Configure_Tx_Power (Config : Tx_Power_Config_Type) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ Config); -- Configure the transmit power of the DW1000 transmitter. -- -- This procedure is used to configure both smart transmit power and -- manual transmit power. The @Smart_Tx_Power_Enabled@ field of the -- @Tx_Power_Config_Type@ record determines whether or not smart tx is -- enabled or disabled. -- -- Depending on whether or not smart transmit power is enabled or disabled -- the @Tx_Power_Config_Type@ record contains different fields. -- -- An example of configuring a specific smart transmit power configuration -- is demonstrated below: -- -- Configure_Tx_Power (Tx_Power_Config_Type' -- (Smart_Tx_Power_Enabled => True, -- Boost_Normal => (Coarse_Gain_Enabled => True, -- Fine_Gain => 10.5, -- Coarse_Gain => 9.0), -- Boost_500us => (Coarse_Gain_Enabled => True, -- Fine_Gain => 10.5, -- Coarse_Gain => 12.0), -- Boost_250us => (Coarse_Gain_Enabled => True, -- Fine_Gain => 10.5, -- Coarse_Gain => 15.0), -- Boost_125us => (Coarse_Gain_Enabled => True, -- Fine_Gain => 10.5, -- Coarse_Gain => 18.0))); -- -- An example manual transmit power configuration is shown below: -- -- Configure_Tx_Power (Tx_Power_Config_Type' -- (Smart_Tx_Power_Enabled => False, -- Boost_SHR => (Coarse_Gain_Enabled => True, -- Fine_Gain => 3.5, -- Coarse_Gain => 9.0), -- Boost_PHR => (Coarse_Gain_Enabled => True, -- Fine_Gain => 3.5, -- Coarse_Gain => 9.0)); -- -- @param Config Record containing the transmit power configuration. procedure Read_EUID (EUID : out Bits_64) with Global => (In_Out => DW1000.BSP.Device_State), Depends => ((DW1000.BSP.Device_State, EUID) => DW1000.BSP.Device_State); -- Read the extended unique identifier (EUID). procedure Write_EUID (EUID : in Bits_64) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ EUID); -- Write the extended unique identifier (EUID). procedure Read_PAN_ID (PAN_ID : out Bits_16) with Global => (In_Out => DW1000.BSP.Device_State), Depends => ((DW1000.BSP.Device_State, PAN_ID) => DW1000.BSP.Device_State); procedure Write_PAN_ID (PAN_ID : in Bits_16) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ PAN_ID); procedure Read_Short_Address (Short_Address : out Bits_16) with Global => (In_Out => DW1000.BSP.Device_State), Depends => ((DW1000.BSP.Device_State, Short_Address) => DW1000.BSP.Device_State); procedure Write_Short_Address (Short_Address : in Bits_16) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ Short_Address); procedure Read_PAN_ID_And_Short_Address (PAN_ID : out Bits_16; Short_Address : out Bits_16) with Global => (In_Out => DW1000.BSP.Device_State), Depends => ((DW1000.BSP.Device_State, PAN_ID, Short_Address) => DW1000.BSP.Device_State); procedure Write_PAN_ID_And_Short_Address (PAN_ID : in Bits_16; Short_Address : in Bits_16) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ (PAN_ID, Short_Address)); procedure Read_Tx_Antenna_Delay (Antenna_Delay : out Antenna_Delay_Time) with Global => (In_Out => DW1000.BSP.Device_State), Depends => ((DW1000.BSP.Device_State, Antenna_Delay) => DW1000.BSP.Device_State); -- Read the currently configured Tx antenna delay. -- -- The antenna delay is a 16-bit value using the same unit as the system -- time and time stamps, i.e. 499.2 MHz * 128, so the least significant -- bit is approximately 15.65 picoseconds. procedure Write_Tx_Antenna_Delay (Antenna_Delay : in Antenna_Delay_Time) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => (DW1000.BSP.Device_State, Antenna_Delay)), Pre => Antenna_Delay <= (2.0**16 - 1.0) * Fine_System_Time'Delta; -- Set the Tx antenna delay. -- -- The antenna delay is a 16-bit value using the same unit as the system -- time and time stamps, i.e. 499.2 MHz * 128, so the least significant -- bit is approximately 15.65 picoseconds. -- -- This procedure configures the following registers: -- * TX_ANTD -- -- @param Antenna_Delay The antenna delay. The maximum allowed value is -- 1025.625 nanoseconds. procedure Read_Rx_Antenna_Delay (Antenna_Delay : out Antenna_Delay_Time) with Global => (In_Out => DW1000.BSP.Device_State), Depends => ((DW1000.BSP.Device_State, Antenna_Delay) => DW1000.BSP.Device_State); -- Read the currently configured Rx antenna delay. -- -- The antenna delay is a 16-bit value using the same unit as the system -- time and time stamps, i.e. 499.2 MHz * 128, so the least significant -- bit is approximately 15.65 picoseconds. procedure Write_Rx_Antenna_Delay (Antenna_Delay : in Antenna_Delay_Time) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => (DW1000.BSP.Device_State, Antenna_Delay)), Pre => Antenna_Delay <= (2.0**16 - 1.0) * Fine_System_Time'Delta; -- Set the Rx antenna delay. -- -- The antenna delay is a 16-bit value using the same unit as the system -- time and time stamps, i.e. 499.2 MHz * 128, so the least significant -- bit is approximately 15.65 picoseconds. -- -- This procedure configures the following registers: -- * LDE_RXANTD -- -- @param Antenna_Delay The antenna delay. The maximum allowed value is -- 1025.625 nanoseconds. procedure Configure_LDE (PRF : in PRF_Type; Rx_Preamble_Code : in Preamble_Code_Number; Data_Rate : in Data_Rates) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => (DW1000.BSP.Device_State, PRF, Rx_Preamble_Code, Data_Rate)); -- Configures the LDE subsystem for the specified pulse repetition -- frequency (PRF), receiver preamble code, and data rate. -- -- This procedure configures the following registers: -- * LDE_CFG1 -- * LDE_CFG2 -- * LDE_REPC procedure Configure_PLL (Channel : in Channel_Number) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => (DW1000.BSP.Device_State, Channel)); -- Configures the PLL subsystem for the specified UWB channel. -- -- This procedure configures the following registers: -- * FS_PLLCFG -- * FS_PLLTUNE -- * FS_XTALT procedure Configure_RF (Channel : in Channel_Number) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => (DW1000.BSP.Device_State, Channel)); -- Configures the RF subsystem for the specified UWB channel. -- -- This procedure configures the following registers: -- * RF_RXCTRLH -- * RF_TXCTRL procedure Configure_DRX (PRF : in PRF_Type; Data_Rate : in Data_Rates; Tx_Preamble_Length : in Preamble_Lengths; PAC : in Preamble_Acq_Chunk_Length; SFD_Timeout : in SFD_Timeout_Number; Nonstandard_SFD : in Boolean) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => (DW1000.BSP.Device_State, PRF, Data_Rate, Tx_Preamble_Length, PAC, SFD_Timeout, Nonstandard_SFD)); -- Configures the DRX subsystem for the specified configuration. -- -- This procedure configures the following registers: -- * DRX_TUNE0b -- * DRX_TUNE1a -- * DRX_TUNE1b -- * DRX_TUNE4H -- * DRX_TUNE2 -- * DRX_SFDTOC procedure Configure_AGC (PRF : in PRF_Type) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ PRF); -- Configures the automatic gain control (AGC) subsystem. -- -- This procedure configures the following registers: -- * AGC_TUNE2 -- * AGC_TUNE1 procedure Configure_TC (Channel : in Channel_Number) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ Channel); -- Configure the transmit calibration (TC) block for the specified channel. procedure Configure_TX_FCTRL (Frame_Length : in Natural; Tx_Data_Rate : in Data_Rates; Tx_PRF : in PRF_Type; Ranging : in Boolean; Preamble_Length : in Preamble_Lengths; Tx_Buffer_Offset : in Natural; Inter_Frame_Spacing : in Natural) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => (DW1000.BSP.Device_State, Frame_Length, Tx_Data_Rate, Tx_PRF, Ranging, Preamble_Length, Tx_Buffer_Offset, Inter_Frame_Spacing)), Pre => (Frame_Length < Constants.TX_BUFFER_Length and then Tx_Buffer_Offset < Constants.TX_BUFFER_Length and then Frame_Length + Tx_Buffer_Offset <= Constants.TX_BUFFER_Length and then Inter_Frame_Spacing < 256); procedure Configure_CHAN_CTRL (Tx_Channel : in Channel_Number; Rx_Channel : in Channel_Number; Use_DecaWave_SFD : in Boolean; Use_Tx_User_Defined_SFD : in Boolean; Use_Rx_User_Defined_SFD : in Boolean; Rx_PRF : in PRF_Type; Tx_Preamble_Code : in Preamble_Code_Number; Rx_Preamble_Code : in Preamble_Code_Number) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => (DW1000.BSP.Device_State, Tx_Channel, Rx_Channel, Use_DecaWave_SFD, Use_Tx_User_Defined_SFD, Use_Rx_User_Defined_SFD, Rx_PRF, Tx_Preamble_Code, Rx_Preamble_Code)), Pre => ((if Use_Tx_User_Defined_SFD then not Use_DecaWave_SFD) and (if Use_Rx_User_Defined_SFD then not Use_DecaWave_SFD)); procedure Configure_Nonstandard_SFD_Length (Data_Rate : in Data_Rates) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ Data_Rate); -- Configures the length of the non-standard SFD for the specified -- data rate. -- -- This procedure configures the following registers: -- * USR_SFD procedure Configure_Non_Standard_SFD (Rx_SFD : in String; Tx_SFD : in String) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ (Rx_SFD, Tx_SFD)), Pre => (Rx_SFD'Length in 8 .. 16 | 64 and Tx_SFD'Length = Rx_SFD'Length and (for all I in Rx_SFD'Range => Rx_SFD (I) in '+' | '-' | '0') and (for all I in Tx_SFD'Range => Tx_SFD (I) in '+' | '-' | '0') ); -- Configure a non-standard SFD sequence. -- -- WARNING: Only experts should consider designing their own SFD sequence. -- Designing an SFD is a complicated task, and is outside the scope of this -- documentation. It is strongly recommended to use either the standard -- defined SFD sequence, or the DecaWave defined SFD sequence. -- -- The Rx_SFD and Tx_SFD strings must be strings containing only '+', '-', -- and '0' characters. No other characters are permitted. -- Below is an example of calling this procedure, using the -- DecaWave defined 16-symbol SFD sequence as an example SFD sequence: -- -- Configure_Non_Standard_SFD (Rx_SFD => "----+-+--++--+00", -- Tx_SFD => "----+-+--++--+00"); -- -- Note that the Tx and Rx SFD must have the same length. -- -- @param Rx_SFD The SFD sequence to use in the receiver. -- -- @param Tx_SFD The SFD sequence to use in the transmitter. procedure Set_Frame_Filtering_Enabled (Enable : in Boolean) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ Enable); -- Enable or disable frame filtering. -- -- Frame filtering allows the DW1000 to automatically reject frames -- according to certain criterea according to the IEEE 802.15.4-2011 -- MAC layer. -- -- To configure which frames are accepted or rejected by the DW1000 see the -- Configure_Frame_Filtering procedure. -- -- @param Enabled When set to True frame filtering is enabled. Otherwise, -- it is disabled. procedure Set_FCS_Check_Enabled (Enable : in Boolean) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ Enable); -- Enable or disable the automatic frame check sequence (FCS) on received -- frames. -- -- By default, the DW1000 automatically checks the 16-bit CRC FCS on each -- received frame. The last two octets in the received frame are assumed -- as the 16-bit CRC, and is compared against the actual FCS computed -- against all but the last two octets in the received frame. -- -- If the DW1000 detects that the actual FCS does not match the FCS in the -- received frame, then it generates an FCS error. If double-buffered mode -- is enabled then the received frame is discarded and the buffer re-used -- for the next received frame. -- -- This procedure enables or disables the FCS check. -- -- @param Enabled When True (default after DW1000 reset) the DW1000 will -- check the FCS of each received frame. Set this to false to disable -- the FCS check for each packet. procedure Configure_Frame_Filtering (Behave_As_Coordinator : in Boolean; Allow_Beacon_Frame : in Boolean; Allow_Data_Frame : in Boolean; Allow_Ack_Frame : in Boolean; Allow_MAC_Cmd_Frame : in Boolean; Allow_Reserved_Frame : in Boolean; Allow_Frame_Type_4 : in Boolean; Allow_Frame_Type_5 : in Boolean) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => (DW1000.BSP.Device_State, Behave_As_Coordinator, Allow_Beacon_Frame, Allow_Data_Frame, Allow_Ack_Frame, Allow_MAC_Cmd_Frame, Allow_Reserved_Frame, Allow_Frame_Type_4, Allow_Frame_Type_5)); -- Configure which MAC frame types are automatically filtered by the -- DW1000. -- -- Note that the frame filtering configuration only takes effect when -- frame filtering is enabled (see Set_Frame_Filtering_Enabled). -- -- @param Behave_As_Coordinator When set to True the DW1000 will accept -- a frame without a destination address if the source address has -- the PAN ID matching the coordinator's PAN ID. When set to False -- and when filtering is enabled the DW1000 will reject these frames. -- -- @param Allow_Beacon_Frame When set to True the DW1000 will accept -- frames whose frame type is a beacon frame. When set to False -- and when filtering is enabled the DW1000 will reject these frames. -- -- @param Allow_Data_Frame When set to True the DW1000 will accept -- frames whose frame type is a data frame. When set to False -- and when filtering is enabled the DW1000 will reject these frames. -- -- @param Allow_Ack_Frame When set to True the DW1000 will accept frames -- whose frame type is an acknowledgement frame. When set to False -- and when filtering is enabled the DW1000 will reject these frames. -- -- @param Allow_MAC_Cmd_Frame When set to True the DW1000 will accept -- frames whose frame type is a MAC command frame. When set to False -- and when filtering is enabled the DW1000 will reject these frames. -- -- @param Allow_Reserved_Frame When set to True the DW1000 will accept -- frames whose frame type is set to a reserved value (values 2#100# -- to 2#111#) as defined by IEEE 802.15.4-2011. When set to False -- and when filtering is enabled the DW1000 will reject these frames. -- -- @param Allow_Frame_Type_4 When set to True the DW1000 will accept -- frames whose frame type is set to the value 2#100#, i.e. 4. -- When set to False and when frame filtering is enabled the DW1000 -- will reject these frames. -- -- @param Allow_Frame_Type_5 When set to True the DW1000 will accept -- frames whose frame type is set to the value 2#101#, i.e. 5. -- When set to False and when frame filtering is enabled the DW1000 -- will reject these frames. procedure Set_Smart_Tx_Power (Enable : in Boolean) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ Enable); -- Enables or disables smart Tx power control. -- -- Regulations for UWB typically specify a maximum transmit power limit of -- -41.3 dBm / MHz, typically measured with a dwell time of 1 ms. Short -- frames transmitted at a data rate of 6.8 Mbps and a short preamble -- length are transmitted in a fraction of a millisecond. If only a single -- short frame is transmitted with in 1 ms then the frame can be -- transmitted at a higher power than the -41.3 dBm / MHz regulatory limit. -- -- When the smart tx power control is enabled then the DW1000 will -- boost the power for short transmissions. It is the user's responsibility -- to avoid sending multiple short frames within the same millisecond to -- remain within the regulatory limits. -- -- This procedure configures the following registers: -- * SYS_CFG procedure Set_Tx_Data (Data : in Types.Byte_Array; Offset : in Natural) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => (DW1000.BSP.Device_State, Data, Offset)), Pre => (Data'Length <= DW1000.Constants.TX_BUFFER_Length and then Offset < DW1000.Constants.TX_BUFFER_Length and then Data'Length + Offset <= DW1000.Constants.TX_BUFFER_Length); -- Write data to the DW1000 TX buffer. -- -- Before starting the transmission, the frame length and offset must be -- programmed into the DW1000 separately using the Set_Tx_Frame_Length -- procedure. -- -- The frame is not transmitted until the Start_Tx procedure is called. -- -- This procedure configures the following registers: -- * TX_BUFFER procedure Set_Tx_Frame_Length (Length : in Natural; Offset : in Natural) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ (Length, Offset)), Pre => (Length < DW1000.Constants.TX_BUFFER_Length and then Offset < DW1000.Constants.TX_BUFFER_Length and then Length + Offset <= DW1000.Constants.TX_BUFFER_Length); -- Configures the frame length and offset within the transmit buffer -- (TX_BUFFER) to use when transmitting the next packet. -- -- This procedure configures the following registers: -- * TX_FCTRL procedure Read_Rx_Data (Data : out Types.Byte_Array; Offset : in Natural) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ (Offset, Data), Data => (DW1000.BSP.Device_State, Offset)), Pre => (Data'Length > 0 and then Data'Length <= DW1000.Constants.RX_BUFFER_Length and then Offset < DW1000.Constants.RX_BUFFER_Length and then Data'Length + Offset <= DW1000.Constants.RX_BUFFER_Length); -- Read the received frame from the Rx buffer. procedure Start_Tx_Immediate (Rx_After_Tx : in Boolean; Auto_Append_FCS : in Boolean) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ (Rx_After_Tx, Auto_Append_FCS)); procedure Start_Tx_Delayed (Rx_After_Tx : in Boolean; Result : out Result_Type) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ Rx_After_Tx, Result => (DW1000.BSP.Device_State, Rx_After_Tx)); -- Transmit the contents of the TX buffer with a delay. -- -- The time at which the packet is to be transmitted must be set before -- calling this procedure by using the Set_Delayed_Tx_Rx_Time procedure. -- -- When Rx_After_Tx is True then the receiver is automatically enabled -- after the transmission is completed. -- -- This procedure configures the following registers: -- * SYS_CTRL procedure Set_Delayed_Tx_Rx_Time (Delay_Time : in Coarse_System_Time) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ Delay_Time); -- Set the receive and transmit delay. -- -- Both Rx and Tx share the same delay. It is not possible for the receiver -- and transmitter to use different delays simultaneously. -- -- The delay time is measured in units of 499.2 MHz * 128, i.e. the least -- significant bit of the delay time is approximately 15.65 ps. -- -- Note that the 9 low order bits of the input value are ignored by the -- DW1000, as described in Section 7.2.12 of the DW1000 User Manual -- (DX_TIME register). -- -- This procedure configures the following registers: -- * DX_TIME procedure Set_Sleep_After_Tx (Enable : in Boolean) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ Enable); -- Configures the DW1000 to enter sleep more (or not) after transmitting a -- frame. -- -- When Enable is True, the DW1000 will automatically enter sleep mode -- after each frame is sent. Otherwise, when Enable is False the DW1000 -- will not enter sleep mode after each frame is sent. -- -- This procedure configures the following registers: -- * PMSC_CTRL1 procedure Read_Rx_Adjusted_Timestamp (Timestamp : out Fine_System_Time) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => DW1000.BSP.Device_State, Timestamp => DW1000.BSP.Device_State); -- Read the corrected timestamp associated with the last received packet. -- -- This timestamp is the timestamp that has been fully corrected for the -- time of packet reception. The timestamp is in units of approximately -- 15.65 picoseconds. procedure Read_Rx_Raw_Timestamp (Timestamp : out Coarse_System_Time) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => DW1000.BSP.Device_State, Timestamp => DW1000.BSP.Device_State); -- Read the raw timestamp associated with the last received packet. -- -- This timestamp is the timestamp before the various corrections for the -- time of reception have been applied. The timestamp is in units of -- approximately 8.013 nanoseconds. procedure Read_Rx_Timestamps (Adjusted : out Fine_System_Time; Raw : out Coarse_System_Time) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => DW1000.BSP.Device_State, (Adjusted, Raw) => DW1000.BSP.Device_State); -- Read both the raw and adjusted timestamps for the last received packet. procedure Read_Tx_Adjusted_Timestamp (Timestamp : out Fine_System_Time) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => DW1000.BSP.Device_State, Timestamp => DW1000.BSP.Device_State); -- Read the corrected timestamp associated with the last transmitted -- packet. -- -- This timestamp is the timestamp that has been fully corrected for the -- time of packet transmission. The timestamp is in units of approximately -- 15.65 picoseconds. procedure Read_Tx_Raw_Timestamp (Timestamp : out Coarse_System_Time) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => DW1000.BSP.Device_State, Timestamp => DW1000.BSP.Device_State); -- Read the raw timestamp associated with the last transmitted packet. -- -- This timestamp is the timestamp before the various corrections for the -- time of transmission have been applied. The timestamp is in units of -- approximately 8.013 nanoseconds. procedure Read_Tx_Timestamps (Adjusted : out Fine_System_Time; Raw : out Coarse_System_Time) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => DW1000.BSP.Device_State, (Adjusted, Raw) => DW1000.BSP.Device_State); procedure Read_System_Timestamp (Timestamp : out Coarse_System_Time) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => DW1000.BSP.Device_State, Timestamp => DW1000.BSP.Device_State); -- Read the current value of the DW1000's system timestamp. -- -- The timestamp is measured in units of 499.2 MHz * 128, i.e. the least -- significant bit of the timestamp is approximately 15.65 ps. procedure Check_Overrun (Overrun : out Boolean) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => DW1000.BSP.Device_State, Overrun => DW1000.BSP.Device_State); -- Check if an overrun condition has occurred. -- -- An overrun condition occurs if the DW1000 receives a new packet before -- the host processor has been able to read the previously received packet. -- -- See Section 4.3.5 of the DW1000 User Manual for more information of the -- overrun condition. procedure Force_Tx_Rx_Off with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => DW1000.BSP.Device_State); -- Force off the tranceiver. -- -- This also clears the status registers. -- -- Turning off the tranceiver will cancel any pending receive or -- transmit operation. procedure Reset_Rx with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => DW1000.BSP.Device_State); -- Perform a soft reset of the receiver only. procedure Toggle_Host_Side_Rx_Buffer_Pointer with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => DW1000.BSP.Device_State); -- Toggle the host side receive buffer pointer (HSRBP). -- -- This procedure is only relevant when double-buffer mode is enabled. -- Calling this procedure signals to the DW1000 that the host IC is -- finished with the contents of the current double-buffered set. -- -- It should be called after the host IC has finished reading the receive -- registers after a packet has been received. procedure Sync_Rx_Buffer_Pointers with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => DW1000.BSP.Device_State); -- Synchronize the Rx buffer pointers for double-buffer operation. -- -- This procedure synchronizes the ICRBP and HSRBP bits in the SYS_CTRL -- register so that they are the same. This is only relevant when the -- DW1000 is operating in double-buffer mode. -- -- This procedure configures the following registers: -- * SYS_CTRL procedure Start_Rx_Immediate with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => DW1000.BSP.Device_State); -- Enable the receiver immediately (without a delay). -- -- This procedure configures the following registers: -- * SYS_CTRL procedure Start_Rx_Delayed (Result : out Result_Type) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => DW1000.BSP.Device_State, Result => DW1000.BSP.Device_State); -- Enable the receiver after a delay. -- -- The receiver is enabled only at the time configured by calling the -- Set_Tx_Rx_Delay_Time procedure, which must be set before calling this -- procedure. -- -- This procedure configures the following registers: -- * SYS_CTRL procedure Set_Rx_Mode (Mode : in Rx_Modes; Rx_On_Time : in RX_SNIFF_SNIFF_ONT_Field; Rx_Off_Time : in Sniff_Off_Time) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ (Mode, Rx_On_Time, Rx_Off_Time)), Pre => (if Mode = Sniff then Rx_Off_Time > 0.0); -- Enables or disables the receiver sniff mode. -- -- When Mode is set to Normal then when the receiver is turned on (see -- the Enable_Rx procedure) then it will operate until either a frame is -- received, or until the receiver timeout time is reached. In the Normal -- mode the Rx_On_Time and Rx_Off_Time parameters are not used. -- -- When Mode is set to Sniff then the receiver will be activated for the -- duration of the Rx_On_Time, searching for a preamble. If a preamble is -- detected within this duration then the receiver continues operation to -- try to receive the packet. Otherwise, if no preamble is detected then -- the receiver is then disabled for the Rx_Off_Time, after which it is -- re-enabled to repeat the process. -- -- The Rx_On_Time is measured in units of the preamble acquisition count -- (PAC) see Section 4.1.1 of the DW100 User Manual for more information. -- -- The Rx_Off_Time is measured in units of the 128 system clock cycles, or -- approximately 1 us. If the Mode is set to Sniff then the Rx_Off_Time -- must be non-zero (a value of 0 would disable the sniff mode on the -- DW1000). -- -- The Rx_Off_Time must be less than 15.385 microseconds. -- -- This procedure configures the following registers: -- * RX_SNIFF procedure Set_Auto_Rx_Reenable (Enable : in Boolean) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ Enable); -- Enable or disable the Rx auto re-enable feature. -- -- This feature has different behaviour depending on whether or not the -- receiver is operating in double-buffer mode. -- -- When Rx auto re-enable is disabled the receiver will stop receiving -- when any receive event happens (e.g. an error occurred, or a frame -- was received OK). -- -- When Rx auto re-enable is enabled then the receiver behaviour -- depends on the double-buffer configuration: -- * In single-buffer mode the receiver is automatically re-enabled -- after a receive error occurs (e.g. physical header error), -- EXCEPT a frame wait timeout error. -- * In double-buffer mode the receiver is automatically re-enabled -- when a frame is received, or when an error occurs (e.g. physical -- header error), EXCEPT a frame wait timeout error. -- -- This procedure configures the following registers: -- * SYS_CFG procedure Set_Rx_Double_Buffer (Enable : in Boolean) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ Enable); -- Configures double-buffer mode. -- -- By default the DW1000 operates in single-buffer mode. Double-buffer -- mode can be enabled to allow the host application to read the previously -- received frame at the same time as the DW1000 is receiving the next -- frame. -- -- Also see the Sync_Rx_Buffer_Pointers procedure. -- -- This procedure configures the following registers: -- * SYS_CFG procedure Set_Rx_Frame_Wait_Timeout (Timeout : in Frame_Wait_Timeout_Time) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ Timeout); -- Configure the receive timeout. -- -- When the receiver is enabled the receive timeout is started. -- If no complete frame is received within the configured Rx timeout -- then the receiver is automatically disabled. -- -- The Rx timeout can be disabled by setting the Timeout to 0.0. -- -- The Rx timeout is measured in units of 499.2 MHz / 512, i.e. in units -- of approximately 1.026 us. The maximum timeout is approximately -- 67.215385 ms. -- -- This procedure configures the following registers: -- * SYS_CFG -- -- @param Timeout The maximum time (in seconds) to wait for a frame. -- E.g. a value of 0.001 is 1 millisecond. The maximum permitted value -- is 0.067_215_385, i.e. a little over 67 milliseconds. procedure Set_Preamble_Detect_Timeout (Timeout : in DRX_PRETOC_Field) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ Timeout); -- Configure the preamble detection timeout. -- -- When the receiver is enabled the preamble timeout is started. -- If no preamble is detected within the configured preamble detection -- timeout then the receiver is automatically disabled. -- -- The preamble detect timeout can be disabled by setting the Timeout to 0. -- -- The preamble detect timeout is measured in units of preamble acquisition -- chunk (PAC) size, which can be 8, 16, 32, or 64. See Section 7.2.40.9 of -- the DW1000 User Manual for more information. -- -- This procedure configures the following registers: -- * DRX_PRETOC procedure Calibrate_Sleep_Count (Half_XTAL_Cycles_Per_LP_Osc_Cycle : out Types.Bits_16) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => DW1000.BSP.Device_State, Half_XTAL_Cycles_Per_LP_Osc_Cycle => DW1000.BSP.Device_State); procedure Upload_AON_Config with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => DW1000.BSP.Device_State); -- Upload the AON block configurations to the AON. -- -- This uploads the configuration from the AON_CFG0 and AON_CFG1 registers -- into the AON block. procedure Save_Registers_To_AON with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => DW1000.BSP.Device_State); -- Copy the user configurations from the host interface register set into -- the AON memory. -- -- If enabled to do so, after exiting sleep mode the DW1000 will reload the -- user configuration from the AON memory into the host interface register -- set. -- -- The behaviour of the AON subsystem when exiting sleep or deep-sleep -- states can be configured via the AON_WCFG register. procedure Restore_Registers_From_AON with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => DW1000.BSP.Device_State); -- Load the user configuration from the AON memory into the host interface -- register set. procedure AON_Read_Byte (Address : in AON_ADDR_Field; Data : out Types.Bits_8) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => (DW1000.BSP.Device_State, Address), Data => (DW1000.BSP.Device_State, Address)); -- Reads a single byte from the Always-On block. procedure AON_Contiguous_Read (Start_Address : in AON_ADDR_Field; Data : out Types.Byte_Array) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => (DW1000.BSP.Device_State, Start_Address, Data), Data =>+ (DW1000.BSP.Device_State, Start_Address)), Pre => (Data'Length <= 256 and then Natural (Start_Address) + Data'Length <= 256); -- Reads a contiguous sequence of bytes from the Always-On block. procedure AON_Scatter_Read (Addresses : in AON_Address_Array; Data : out Types.Byte_Array) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => (DW1000.BSP.Device_State, Addresses, Data), Data =>+ (DW1000.BSP.Device_State, Addresses)), Pre => Addresses'Length = Data'Length; -- Reads a non-contiguous set of bytes from the Always-on block. -- -- This procedure reads bytes from the sequence of addresses in the -- Addresses array, and stores the byte that was read in the corresponding -- position in the Data array. procedure Configure_Sleep_Count (Sleep_Count : in AON_CFG0_SLEEP_TIM_Field) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ Sleep_Count); procedure Set_XTAL_Trim (Trim : in FS_XTALT_Field) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State =>+ Trim); procedure Configure_LEDs (Tx_LED_Enable : in Boolean; Rx_LED_Enable : in Boolean; Rx_OK_LED_Enable : in Boolean; SFD_LED_Enable : in Boolean; Test_Flash : in Boolean) with Global => (In_Out => DW1000.BSP.Device_State), Depends => (DW1000.BSP.Device_State => (DW1000.BSP.Device_State, Tx_LED_Enable, Rx_LED_Enable, Rx_OK_LED_Enable, SFD_LED_Enable, Test_Flash)); -- Configure the behaviour of the LEDs. -- -- @param Tx_LED_Enable When set to True the DW1000 will flash the Tx LED -- while the transmitter is on. -- -- @param Rx_LED_Enable When set to True the DW1000 will flash the Rx LED -- while the receiver is on. -- -- @param Rx_OK_LED_Enable When set to True the DW1000 will flash the LED -- when a packet is received without errors. -- -- @param SFD_LED_Enable When set to True the DW1000 will flash the LED -- when an SFD is detected. -- -- @param Test_Flash When set to True the DW1000 will flash the configured -- LEDs once, immediately after the LEDs are configured. end DW1000.Driver;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2021 The progress_indicators authors -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. package body Progress_Indicators.Work_Trackers is protected body Work_Tracker is procedure Start_Work (Amount : Natural) is begin Current.Total := Current.Total + Amount; end Start_Work; procedure Finish_Work (Amount : Natural) is begin Current.Completed := Current.Completed + Amount; end Finish_Work; function Report return Status_Report is (Current); end Work_Tracker; end Progress_Indicators.Work_Trackers;
with Ada.Text_IO; use Ada.Text_IO; with Integer_IO; use Integer_IO; -- utiliser les opérations de Integer_IO. procedure Exemple_Integer_IO is Nombre: Integer; begin Put ("10 = "); Afficher (10); New_Line; Put ("0 = "); Afficher (0); New_Line; Put ("Integer'Last = "); Afficher (Integer'Last); New_Line; loop Put ("Nombre (0 pour quitter) : "); Saisir (Nombre); if Nombre /= -1 then Put ("Vous avez saisi : "); Afficher (Nombre); New_Line; else Put_Line ("Ce n'est pas un entier naturel !"); Skip_Line; -- vider le buffer d'entrée (jusqu'à EOL) end if; exit when Nombre = 0; end loop; end Exemple_Integer_IO;
with STM32.GPIO; use STM32.GPIO; with STM32.Timers; use STM32.Timers; with STM32.PWM; use STM32.PWM; with STM_Board; use STM_Board; with Inverter_ADC; use Inverter_ADC; package Inverter_PWM is ----------------- -- Definitions -- ----------------- type PWM_Phase is (A, B); -- Each phase of a full bridge circuit. type PWM_Alignment is (Edge, -- Positive edge Center -- Center of positive part ); -- Describes where on the PWM waveform the signals shall be aligned. -- The final maximum amplitude for the sine voltage is defined by the -- maximum sine table value, that is 10_000. -- Considering that the battery nominal voltage is 12 Volts, this will -- be the peak AC value, which corresponds to a primary AC RMS voltage -- of 12 V / sqrt(2) = 8.485 V. -- With a minimum battery voltage of 10 V, the minimum AC RMS voltage -- will be 10 V / sqrt(2) = 7.07 V. -- The transformer voltage ratio between the primary and secondary, for -- a maximum output voltage of 230 V RMS, will be 230 V / 7.07 V = 32.5, -- so the turns ratio of the transformer will be (Ns / Np) = 33. subtype Table_Amplitude is Integer range 0 .. 10_000; -- Values inside 14 bits (0 - 16_384). subtype Duty_Cycle is Float range 0.0 .. 100.0; -- The upload frequency of the duty cycle is defined by the number of points -- for each semi-sinusoid. -- For 50 Hz we have 2 half senoids * 50 Hz * 250 points = 25000 Hz. -- For 60 Hz we have 2 half senoids * 60 Hz * 250 points = 30000 Hz. -- For 400 Hz we have 2 half senoids * 400 Hz * 250 points = 200000 Hz. PWM_Frequency_Hz : Frequency_Hz := 30_000.0; -- for 60 Hz -- STM32H743 operates at 400 MHz with 200 MHz into Prescaler. -- With 200 MHz and (20 - 1) for prescaler we have 10 MHz for counter -- period, that have values of 400, 333 and 50 for 25, 30 and 200 KHz. -- For 50 Hz we have 200 MHz / 25 kHz = 8000 ticks by each 25 kHz period, -- so the minimum duty cycle is 100 / 8000 = 0.0125 %. -- For 60 Hz we have 200 MHz / 30 kHz = 6667 ticks by each 30 kHz period, -- so the minimum duty cycle is 100 / 6667 = 0.0150 %. -- For 400 Hz we have 200 MHz / 200 kHz = 1000 ticks by each 200 kHz period, -- so the minimum duty cycle is 100 / 1000 = 0.1000 %. subtype Deadtime_Range is Float range 0.0 .. 400.0e-9; -- Maximum deadtime permissible is 126 us. -- Maximum deadtime chosen is 1% of the PWM_Frequency_Hz = 0.01/25_000. PWM_Deadtime : constant Deadtime_Range := 166.7e-9; -- The delay exists in the rising edges. -- It depends on the electronic circuit rise and fall times. -- 166.7e-9 * 30 kHz * 100 = 0.5% of the total period, -- 0.5% of 8000 ticks = 40 ticks. ----------------------------- -- Procedures and function -- ----------------------------- procedure Initialize_PWM (Frequency : Frequency_Hz; Deadtime : Deadtime_Range; Alignment : PWM_Alignment); -- Initialize the timer peripheral for PWM. -- Each phase needs to be enabled manually after this. procedure Enable_Phase (This : PWM_Phase) with inline; -- Enable PWM generation for the specified phase. procedure Disable_Phase (This : PWM_Phase) with inline; -- Disable PWM generation for the specified phase. procedure Start_PWM with Pre => Is_Initialized; -- Start the generation of sinusoid wave by enabling interrupt. procedure Stop_PWM with Pre => Is_Initialized; -- Stop the generation of sinusoid wave by disabling interrupt. function Get_Duty_Resolution return Duty_Cycle; -- Return the minimum step that the duty can be changed, in percent. procedure Set_Duty_Cycle (This : PWM_Phase; Value : Duty_Cycle); -- Sets the duty cycle in percent for the specified phase. procedure Set_Duty_Cycle (This : PWM_Phase; Amplitude : Table_Amplitude; Gain : Gain_Range); -- Sets the duty cycle for the specified phase. procedure Set_PWM_Gate_Power (Enabled : in Boolean) with Pre => (if Enabled = False then STM_Board.Is_Initialized else Is_Initialized and STM_Board.Is_Initialized); -- Enable or disable the output of the gate drivers. procedure Reset_Sine_Step; -- Set the sine table step counter to the last position of the -- table, or 250, whose amplitude value is 0. procedure Safe_State; -- Forces the inverter into a state that is considered safe. -- Typically this disables the PWM generation (all switches off), and -- turns off the power to the gate drivers. function Is_Initialized return Boolean; -- Returns True if the board specifics are initialized. private Initialized : Boolean := False; subtype Sine_Step_Range is Natural range 1 .. 250; -- Number of steps for the half sine table. Sine_Step : Sine_Step_Range := 250; -- The table last step value is 0. -- The table for sine generation is produced knowing the number of points -- to complete 1/4 sine period. The semi-sinusoid, or 1/2 sine period is -- completed with these same points in reverse order. -- The equation which defines each point is: -- -- D = A * sin(pi/2 * x/N) -- D = Duty cycle at a given discrete point; -- A = Signal amplitude of the maximum duty cycle. We adopt 10_000. -- pi/2 = 1/4 of the sine period -- x = Step number -- N = Number of points = 125 -- Sine table with 125 points from 0 to 10000, in direct and reverse order -- to create a semi-sinusoid with 250 points. Sine_Table : constant array (Sine_Step_Range) of Table_Amplitude := (126, 251, 377, 502, 628, 753, 879, 1004, 1129, 1253, 1378, 1502, 1626, 1750, 1874, 1997, 2120, 2243, 2365, 2487, 2608, 2730, 2850, 2970, 3090, 3209, 3328, 3446, 3564, 3681, 3798, 3914, 4029, 4144, 4258, 4371, 4484, 4596, 4707, 4818, 4927, 5036, 5144, 5252, 5358, 5464, 5569, 5673, 5776, 5878, 5979, 6079, 6179, 6277, 6374, 6471, 6566, 6660, 6753, 6845, 6937, 7026, 7115, 7203, 7290, 7375, 7459, 7543, 7624, 7705, 7785, 7863, 7940, 8016, 8090, 8163, 8235, 8306, 8375, 8443, 8510, 8575, 8639, 8702, 8763, 8823, 8881, 8938, 8994, 9048, 9101, 9152, 9202, 9251, 9298, 9343, 9387, 9430, 9471, 9511, 9549, 9585, 9620, 9654, 9686, 9716, 9745, 9773, 9799, 9823, 9846, 9867, 9887, 9905, 9921, 9936, 9950, 9961, 9972, 9980, 9987, 9993, 9997, 9999, 10000, 9999, 9997, 9993, 9987, 9980, 9972, 9961, 9950, 9936, 9921, 9905, 9887, 9867, 9846, 9823, 9799, 9773, 9745, 9716, 9686, 9654, 9620, 9585, 9549, 9511, 9471, 9430, 9387, 9343, 9298, 9251, 9202, 9152, 9101, 9048, 8994, 8938, 8881, 8823, 8763, 8702, 8639, 8575, 8510, 8443, 8375, 8306, 8235, 8163, 8090, 8016, 7940, 7863, 7785, 7705, 7624, 7543, 7459, 7375, 7290, 7203, 7115, 7026, 6937, 6845, 6753, 6660, 6566, 6471, 6374, 6277, 6179, 6079, 5979, 5878, 5776, 5673, 5569, 5464, 5358, 5252, 5144, 5036, 4927, 4818, 4707, 4596, 4484, 4371, 4258, 4144, 4029, 3914, 3798, 3681, 3564, 3446, 3328, 3209, 3090, 2970, 2850, 2730, 2608, 2487, 2365, 2243, 2120, 1997, 1874, 1750, 1626, 1502, 1378, 1253, 1129, 1004, 879, 753, 628, 502, 377, 251, 126, 0); PWM_Timer_Ref : access Timer := PWM_Timer'Access; Modulators : array (PWM_Phase'Range) of PWM_Modulator; type Gate_Setting is record Channel : Timer_Channel; Pin_H : GPIO_Point; Pin_L : GPIO_Point; Pin_AF : STM32.GPIO_Alternate_Function; end record; type Gate_Settings is array (PWM_Phase'Range) of Gate_Setting; Gate_Phase_Settings : constant Gate_Settings := ((A) => Gate_Setting'(Channel => PWM_A_Channel, Pin_H => PWM_A_H_Pin, Pin_L => PWM_A_L_Pin, Pin_AF => PWM_A_GPIO_AF), (B) => Gate_Setting'(Channel => PWM_B_Channel, Pin_H => PWM_B_H_Pin, Pin_L => PWM_B_L_Pin, Pin_AF => PWM_B_GPIO_AF)); protected PWM_Handler is pragma Interrupt_Priority (PWM_ISR_Priority); private Counter : Integer := 0; -- For testing the output. Semi_Senoid : Boolean := False; -- Defines False = 1'st half sinusoid, True = 2'nd half sinusoid. procedure PWM_ISR_Handler with Attach_Handler => PWM_Interrupt; end PWM_Handler; end Inverter_PWM;
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with SDA_Exceptions; use SDA_Exceptions; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; --! Les Unbounded_String ont une capacité variable, contrairement au String --! pour lesquelles une capacité doit être fixée. with TH; procedure Test_TH is package TH_String_Integer is new TH (Capacite => 11, T_Cle => Unbounded_String, T_Donnee => Integer, Hachage => Length); use TH_String_Integer; -- Retourner une chaîne avec des guillemets autour de S function Avec_Guillemets (S: Unbounded_String) return String is begin return '"' & To_String (S) & '"'; end; -- Utiliser & entre String à gauche et Unbounded_String à droite. Des -- guillemets sont ajoutées autour de la Unbounded_String -- Il s'agit d'un masquage de l'opérteur & défini dans Strings.Unbounded function "&" (Left: String; Right: Unbounded_String) return String is begin return Left & Avec_Guillemets (Right); end; -- Surcharge l'opérateur unaire "+" pour convertir une String -- en Unbounded_String. -- Cette astuce permet de simplifier l'initialisation -- de cles un peu plus loin. function "+" (Item : in String) return Unbounded_String renames To_Unbounded_String; -- Afficher une Unbounded_String et un entier. procedure Afficher (S : in Unbounded_String; N: in Integer) is begin Put (Avec_Guillemets (S)); Put (" : "); Put (N, 1); New_Line; end Afficher; -- Afficher la Sda. procedure Afficher is new Pour_Chaque (Afficher); Nb_Cles : constant Integer := 7; Cles : constant array (1..Nb_Cles) of Unbounded_String := (+"un", +"deux", +"trois", +"quatre", +"cinq", +"quatre-vingt-dix-neuf", +"vingt-et-un"); Inconnu : constant Unbounded_String := To_Unbounded_String ("Inconnu"); Donnees : constant array (1..Nb_Cles) of Integer := (1, 2, 3, 4, 5, 99, 21); Somme_Donnees : constant Integer := 135; Somme_Donnees_Len4 : constant Integer := 7; -- somme si Length (Cle) = 4 Somme_Donnees_Q: constant Integer := 103; -- somme si initiale de Cle = 'q' -- Initialiser l'annuaire avec les Donnees et Cles ci-dessus. -- Attention, c'est à l'appelant de libérer la mémoire associée en -- utilisant Vider. -- Si Bavard est vrai, les insertions sont tracées (affichées). procedure Construire_Exemple_Sujet (Annuaire : out T_TH; Bavard: Boolean := False) is begin Initialiser (Annuaire); pragma Assert (Est_Vide (Annuaire)); pragma Assert (Taille (Annuaire) = 0); for I in 1..Nb_Cles loop Enregistrer (Annuaire, Cles (I), Donnees (I)); if Bavard then Put_Line ("Après insertion de la clé " & Cles (I)); Afficher (Annuaire); New_Line; else null; end if; pragma Assert (not Est_Vide (Annuaire)); pragma Assert (Taille (Annuaire) = I); for J in 1..I loop pragma Assert (La_Donnee (Annuaire, Cles (J)) = Donnees (J)); end loop; for J in I+1..Nb_Cles loop pragma Assert (not Cle_Presente (Annuaire, Cles (J))); end loop; end loop; end Construire_Exemple_Sujet; procedure Tester_Exemple_Sujet is Annuaire : T_TH; begin Construire_Exemple_Sujet (Annuaire, True); Vider (Annuaire); end Tester_Exemple_Sujet; -- Tester suppression en commençant par les derniers éléments ajoutés procedure Tester_Supprimer_Inverse is Annuaire : T_TH; begin Put_Line ("=== Tester_Supprimer_Inverse..."); New_Line; Construire_Exemple_Sujet (Annuaire); for I in reverse 1..Nb_Cles loop Supprimer (Annuaire, Cles (I)); Put_Line ("Après suppression de " & Cles (I) & " :"); Afficher (Annuaire); New_Line; for J in 1..I-1 loop pragma Assert (Cle_Presente (Annuaire, Cles (J))); pragma Assert (La_Donnee (Annuaire, Cles (J)) = Donnees (J)); end loop; for J in I..Nb_Cles loop pragma Assert (not Cle_Presente (Annuaire, Cles (J))); end loop; end loop; Vider (Annuaire); end Tester_Supprimer_Inverse; -- Tester suppression en commençant les les premiers éléments ajoutés procedure Tester_Supprimer is Annuaire : T_TH; begin Put_Line ("=== Tester_Supprimer..."); New_Line; Construire_Exemple_Sujet (Annuaire); for I in 1..Nb_Cles loop Put_Line ("Suppression de " & Cles (I) & " :"); Supprimer (Annuaire, Cles (I)); Afficher (Annuaire); New_Line; for J in 1..I loop pragma Assert (not Cle_Presente (Annuaire, Cles (J))); end loop; for J in I+1..Nb_Cles loop pragma Assert (Cle_Presente (Annuaire, Cles (J))); pragma Assert (La_Donnee (Annuaire, Cles (J)) = Donnees (J)); end loop; end loop; Vider (Annuaire); end Tester_Supprimer; procedure Tester_Supprimer_Un_Element is -- Tester supprimer sur un élément, celui à Indice dans Cles. procedure Tester_Supprimer_Un_Element (Indice: in Integer) is Annuaire : T_TH; begin Construire_Exemple_Sujet (Annuaire); Put_Line ("Suppression de " & Cles (Indice) & " :"); Supprimer (Annuaire, Cles (Indice)); Afficher (Annuaire); New_Line; for J in 1..Nb_Cles loop if J = Indice then pragma Assert (not Cle_Presente (Annuaire, Cles (J))); else pragma Assert (Cle_Presente (Annuaire, Cles (J))); end if; end loop; Vider (Annuaire); end Tester_Supprimer_Un_Element; begin Put_Line ("=== Tester_Supprimer_Un_Element..."); New_Line; for I in 1..Nb_Cles loop Tester_Supprimer_Un_Element (I); end loop; end Tester_Supprimer_Un_Element; procedure Tester_Remplacer_Un_Element is -- Tester enregistrer sur un élément présent, celui à Indice dans Cles. procedure Tester_Remplacer_Un_Element (Indice: in Integer; Nouveau: in Integer) is Annuaire : T_TH; begin Construire_Exemple_Sujet (Annuaire); Put_Line ("Remplacement de " & Cles (Indice) & " par " & Integer'Image(Nouveau) & " :"); enregistrer (Annuaire, Cles (Indice), Nouveau); Afficher (Annuaire); New_Line; for J in 1..Nb_Cles loop pragma Assert (Cle_Presente (Annuaire, Cles (J))); if J = Indice then pragma Assert (La_Donnee (Annuaire, Cles (J)) = Nouveau); else pragma Assert (La_Donnee (Annuaire, Cles (J)) = Donnees (J)); end if; end loop; Vider (Annuaire); end Tester_Remplacer_Un_Element; begin Put_Line ("=== Tester_Remplacer_Un_Element..."); New_Line; for I in 1..Nb_Cles loop Tester_Remplacer_Un_Element (I, 0); null; end loop; end Tester_Remplacer_Un_Element; procedure Tester_Supprimer_Erreur is Annuaire : T_TH; begin begin Put_Line ("=== Tester_Supprimer_Erreur..."); New_Line; Construire_Exemple_Sujet (Annuaire); Supprimer (Annuaire, Inconnu); exception when Cle_Absente_Exception => null; when others => pragma Assert (False); end; Vider (Annuaire); end Tester_Supprimer_Erreur; procedure Tester_La_Donnee_Erreur is Annuaire : T_TH; Inutile: Integer; begin begin Put_Line ("=== Tester_Supprimer_Erreur..."); New_Line; Construire_Exemple_Sujet (Annuaire); Inutile := La_Donnee (Annuaire, Inconnu); exception when Cle_Absente_Exception => null; when others => pragma Assert (False); end; Vider (Annuaire); end Tester_La_Donnee_Erreur; procedure Tester_Pour_chaque is Annuaire : T_TH; Somme: Integer; procedure Sommer (Cle: Unbounded_String; Donnee: Integer) is begin Put (" + "); Put (Donnee, 2); New_Line; Somme := Somme + Donnee; end; procedure Sommer is new Pour_Chaque (Sommer); begin Put_Line ("=== Tester_Pour_Chaque..."); New_Line; Construire_Exemple_Sujet(Annuaire); Somme := 0; Sommer (Annuaire); pragma Assert (Somme = Somme_Donnees); Vider(Annuaire); New_Line; end Tester_Pour_chaque; procedure Tester_Pour_chaque_Somme_Si_Cle_Commence_Par_Q is Annuaire : T_TH; Somme: Integer; procedure Sommer_Cle_Commence_Par_Q (Cle: Unbounded_String; Donnee: Integer) is begin if To_String (Cle) (1) = 'q' then Put (" + "); Put (Donnee, 2); New_Line; Somme := Somme + Donnee; else null; end if; end; procedure Sommer is new Pour_Chaque (Sommer_Cle_Commence_Par_Q); begin Put_Line ("=== Tester_Pour_Chaque_Somme_Si_Cle_Commence_Par_Q..."); New_Line; Construire_Exemple_Sujet(Annuaire); Somme := 0; Sommer (Annuaire); pragma Assert (Somme = Somme_Donnees_Q); Vider(Annuaire); New_Line; end Tester_Pour_chaque_Somme_Si_Cle_Commence_Par_Q; procedure Tester_Pour_chaque_Somme_Len4_Erreur is Annuaire : T_TH; Somme: Integer; procedure Sommer_Len4_Erreur (Cle: Unbounded_String; Donnee: Integer) is Nouvelle_Exception: Exception; begin if Length (Cle) = 4 then Put (" + "); Put (Donnee, 2); New_Line; Somme := Somme + Donnee; else raise Nouvelle_Exception; end if; end; procedure Sommer is new Pour_Chaque (Sommer_Len4_Erreur); begin Put_Line ("=== Tester_Pour_Chaque_Somme_Len4_Erreur..."); New_Line; Construire_Exemple_Sujet(Annuaire); Somme := 0; Sommer (Annuaire); pragma Assert (Somme = Somme_Donnees_Len4); Vider(Annuaire); New_Line; end Tester_Pour_chaque_Somme_Len4_Erreur; begin Tester_Exemple_Sujet; Tester_Supprimer_Inverse; Tester_Supprimer; Tester_Supprimer_Un_Element; Tester_Remplacer_Un_Element; Tester_Supprimer_Erreur; Tester_La_Donnee_Erreur; Tester_Pour_chaque; Tester_Pour_chaque_Somme_Si_Cle_Commence_Par_Q; Tester_Pour_chaque_Somme_Len4_Erreur; Put_Line ("Fin des tests : OK."); end Test_TH;
-- -- Jan & Uwe R. Zimmer, Australia, July 2011 -- generic No_Of_CPU_Cores : Positive; package Swarm_Control_Concurrent_Generic is type Job_Type is (Set_Accelerations, Forward_Messages, Move_Elements, Update_Rotations, No_Job); procedure Distribute_Jobs (Job : Job_Type); end Swarm_Control_Concurrent_Generic;
package Noreturn3 is Exc1 : Exception; Exc2 : Exception; Exc3 : Exception; type Enum is (One, Two, Three); procedure Raise_Error (E : Enum; ErrorMessage : String); pragma No_Return (Raise_Error); end Noreturn3;
with STM32GD.Board; with Drivers.Si7006; with Drivers.Text_IO; package Peripherals is subtype Millivolts is Natural range 0..4095; package Si7006 is new Drivers.Si7006 (I2C => STM32GD.Board.I2C); procedure Init; procedure Power_Down; procedure Power_Up; procedure Enable_Stop_Mode (Low_Power : Boolean); procedure Enter_Stop_Mode; procedure Disable_Stop_Mode; function Supply_Voltage return Millivolts; end Peripherals;
-- -- Copyright (c) 2008-2009 Tero Koskinen <tero.koskinen@iki.fi> -- -- Permission to use, copy, modify, and distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- with Ahven.Framework; with Ahven.Listeners; with Ahven.Temporary_Output; package Ahven.Tap_Runner is use Ahven.Listeners; procedure Run (Suite : in out Framework.Test'Class); -- Run the suite and print the results. private type Tap_Result_Type is (OK_RESULT, NOT_OK_RESULT); type Tap_Listener is new Ahven.Listeners.Result_Listener with record Result : Tap_Result_Type := NOT_OK_RESULT; Current_Test : Framework.Test_Count_Type := 0; Verbose : Boolean := True; Output_File : Temporary_Output.Temporary_File; Capture_Output : Boolean := False; end record; procedure Add_Pass (Listener : in out Tap_Listener; Info : Context); procedure Add_Failure (Listener : in out Tap_Listener; Info : Context); procedure Add_Error (Listener : in out Tap_Listener; Info : Context); procedure Add_Skipped (Listener : in out Tap_Listener; Info : Context); procedure Start_Test (Listener : in out Tap_Listener; Info : Context); procedure End_Test (Listener : in out Tap_Listener; Info : Context); end Ahven.Tap_Runner;
with Ada.Text_IO; use Ada.Text_IO; with Ada.Command_Line; use Ada.Command_Line; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with System.Assertions; use System.Assertions; with Ada.Containers.Hashed_Maps; use Ada.Containers; with Ada.Characters.Handling; use Ada.Characters.Handling; procedure Day24 is type Tile is record X : Integer; Y : Integer; Z : Integer; end record; function "+"(T1: Tile; T2: Tile) return Tile is begin return (T1.X + T2.X, T1.Y + T2.Y, T1.Z + T2.Z); end; type Dir_Kind is (E, SE, SW, W, NW, NE); Dir_To_Delta : constant array (Dir_Kind) of Tile := ( E => (X => 1, Y => -1, Z => 0), SE => (X => 0, Y => -1, Z => 1), SW => (X => -1, Y => 0, Z => 1), W => (X => -1, Y => 1, Z => 0), NW => (X => 0, Y => 1, Z => -1), NE => (X => 1, Y => 0, Z => -1) ); function Tile_Hash(T: Tile) return Hash_Type is Result : Long_Integer := Long_Integer(T.X); begin Result := Result * 31 + Long_Integer(T.Y); Result := Result * 97 + Long_Integer(T.Z); return Hash_Type(Result mod 1_000_000_000); end; package Floor is new Ada.Containers.Hashed_Maps (Key_Type => Tile, Element_Type => Boolean, Hash => Tile_Hash, Equivalent_Keys => "="); procedure Flip_Tile(F: in out Floor.Map; T: Tile) is D: Floor.Cursor := Floor.Find(F, T); begin if not Floor.Has_Element(D) then Floor.Insert(F, T, True); else Floor.Replace_Element(F, D, not Floor.Element(D)); end if; end; function Is_Black(F: in Floor.Map; T: Tile) return Boolean is C: Floor.Cursor := Floor.Find(F, T); begin return Floor.Has_Element(C) and then Floor.Element(C); end; function Count_Neighbours(F: in Floor.Map; T: Tile) return Integer is Result: Integer := 0; begin for Dir of Dir_To_Delta loop if Is_Black(F, T + Dir) then Result := Result + 1; end if; end loop; return Result; end; procedure Set_Tile(F: in out Floor.Map; T: Tile; Value: Boolean) is C: Floor.Cursor := Floor.Find(F, T); begin if Floor.Has_Element(C) then Floor.Replace_Element(F, C, Value); else Floor.Insert(F, T, Value); end if; end; procedure Next_Floor(F1: in Floor.Map; F2: out Floor.Map) is T : Tile; Neighbours : Integer; begin Floor.Clear(F2); for C in Floor.Iterate(F1) loop for Dir of Dir_To_Delta loop T := Floor.Key(C) + Dir; Neighbours := Count_Neighbours(F1, T); if Is_Black(F1, T) then Set_Tile(F2, T, not (Neighbours = 0 or Neighbours > 2)); else Set_Tile(F2, T, Neighbours = 2); end if; end loop; end loop; end; function Count_Black(F: in Floor.Map) return Integer is C: Floor.Cursor := Floor.First(F); Result: Integer := 0; begin while Floor.Has_Element(C) loop if Floor.Element(C) then Result := Result + 1; end if; C := Floor.Next(C); end loop; return Result; end; function Tile_Image(T: Tile) return String is begin return "(" & Integer'Image(T.X) & ", " & Integer'Image(T.Y) & ", " & Integer'Image(T.Z) & ")"; end; function Next_Dir(Desc: String) return Dir_Kind is begin for Dir in Dir_Kind loop declare Dir_Str : constant String := To_Lower (Dir'Img); begin if Dir_Str'Length <= Desc'Length then if Desc (Desc'First .. Desc'First + Dir_Str'Length - 1) = Dir_Str then return Dir; end if; end if; end; end loop; Raise_Assert_Failure("Unreachable. Could not get the next direction"); end Next_Dir; function Parse_Tile(Desc: Unbounded_String) return Tile is Result : Tile := (X => 0, Y => 0, Z => 0); Dir: Dir_Kind; Input: Unbounded_String := Desc; begin while Length(Input) > 0 loop Dir := Next_Dir(To_String (Input)); Input := Unbounded_Slice(Input, Dir'Img'Length + 1, Length(Input)); Result := Result + Dir_To_Delta (Dir); end loop; return Result; end Parse_Tile; procedure Floor_From_File(File_Path: String; F: out Floor.Map) is File : File_Type; T : Tile; begin Open(File => File, Mode => In_File, Name => File_Path); while not End_Of_File(File) loop T := Parse_Tile(To_Unbounded_String(Get_Line(File))); Flip_Tile(F, T); end loop; Close(File); end; function Part1(File_Path: String) return Integer is F : Floor.Map; begin Floor_From_File(File_Path, F); return Count_Black(F); end; function Part2(File_Path: String) return Integer is F : array (0..1) of Floor.Map; Current : Integer := 0; begin Floor_From_File(File_Path, F(Current)); for i in 1..100 loop Next_Floor(F(Current), F(1 - Current)); Current := 1 - Current; end loop; return Count_Black(F(Current)); end; procedure Solve_File(File_Path: String) is begin Put_Line("Input file: " & File_Path); Put_Line(" Part 1:" & Integer'Image(Part1(File_Path))); Put_Line(" Part 2:" & Integer'Image(Part2(File_Path))); end Solve_File; begin Put_Line("Amount of args: " & Integer'Image(Argument_Count)); for Arg in 1..Argument_Count loop Solve_File(Argument(Arg)); end loop; end Day24;
with glx.Pointers; package glx.Context is subtype Item is Pointers.ContextRec_Pointer; type Pointer is access all Item; type Pointer_Pointer is access all Pointer; type Items is array (C.size_t range <>) of aliased Item; type Pointers is array (C.size_t range <>) of aliased Pointer; end glx.Context;
----------------------------------------------------------------------- -- util-http-clients -- HTTP Clients -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- 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. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Http.Cookies; -- == Client == -- The <tt>Util.Http.Clients</tt> package defines a set of API for an HTTP client to send -- requests to an HTTP server. -- -- === GET request === -- To retrieve a content using the HTTP GET operation, a client instance must be created. -- The response is returned in a specific object that must therefore be declared: -- -- Http : Util.Http.Clients.Client; -- Response : Util.Http.Clients.Response; -- -- Before invoking the GET operation, the client can setup a number of HTTP headers. -- -- Http.Add_Header ("X-Requested-By", "wget"); -- -- The GET operation is performed when the <tt>Get</tt> procedure is called: -- -- Http.Get ("http://www.google.com", Response); -- -- Once the response is received, the <tt>Response</tt> object contains the status of the -- HTTP response, the HTTP reply headers and the body. A response header can be obtained -- by using the <tt>Get_Header</tt> function and the body using <tt>Get_Body</tt>: -- -- Body : constant String := Response.Get_Body; -- package Util.Http.Clients is Connection_Error : exception; -- ------------------------------ -- Http response -- ------------------------------ -- The <b>Response</b> type represents a response returned by an HTTP request. type Response is limited new Abstract_Response with private; -- Returns a boolean indicating whether the named response header has already -- been set. overriding function Contains_Header (Reply : in Response; Name : in String) return Boolean; -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. overriding function Get_Header (Reply : in Response; Name : in String) return String; -- Sets a message header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. overriding procedure Set_Header (Reply : in out Response; Name : in String; Value : in String); -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. overriding procedure Add_Header (Reply : in out Response; Name : in String; Value : in String); -- Iterate over the response headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Reply : in Response; Process : not null access procedure (Name : in String; Value : in String)); -- Get the response body as a string. overriding function Get_Body (Reply : in Response) return String; -- Get the response status code. overriding function Get_Status (Reply : in Response) return Natural; -- ------------------------------ -- Http client -- ------------------------------ -- The <b>Client</b> type allows to execute HTTP GET/POST requests. type Client is limited new Abstract_Request with private; type Client_Access is access all Client; -- Returns a boolean indicating whether the named response header has already -- been set. overriding function Contains_Header (Request : in Client; Name : in String) return Boolean; -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. overriding function Get_Header (Request : in Client; Name : in String) return String; -- Sets a header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. overriding procedure Set_Header (Request : in out Client; Name : in String; Value : in String); -- Adds a header with the given name and value. -- This method allows headers to have multiple values. overriding procedure Add_Header (Request : in out Client; Name : in String; Value : in String); -- Iterate over the request headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Request : in Client; Process : not null access procedure (Name : in String; Value : in String)); -- Removes all headers with the given name. procedure Remove_Header (Request : in out Client; Name : in String); -- Adds the specified cookie to the request. This method can be called multiple -- times to set more than one cookie. procedure Add_Cookie (Http : in out Client; Cookie : in Util.Http.Cookies.Cookie); -- Execute an http GET request on the given URL. Additional request parameters, -- cookies and headers should have been set on the client object. procedure Get (Request : in out Client; URL : in String; Reply : out Response'Class); -- Execute an http POST request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. procedure Post (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class); private subtype Http_Request is Abstract_Request; subtype Http_Request_Access is Abstract_Request_Access; subtype Http_Response is Abstract_Response; subtype Http_Response_Access is Abstract_Response_Access; type Http_Manager is interface; type Http_Manager_Access is access all Http_Manager'Class; procedure Create (Manager : in Http_Manager; Http : in out Client'Class) is abstract; procedure Do_Get (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is abstract; procedure Do_Post (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is abstract; Default_Http_Manager : Http_Manager_Access; type Response is new Ada.Finalization.Limited_Controlled and Abstract_Response with record Delegate : Abstract_Response_Access; end record; -- Free the resource used by the response. overriding procedure Finalize (Reply : in out Response); type Client is new Ada.Finalization.Limited_Controlled and Abstract_Request with record Manager : Http_Manager_Access; Delegate : Http_Request_Access; end record; -- Initialize the client overriding procedure Initialize (Http : in out Client); overriding procedure Finalize (Http : in out Client); end Util.Http.Clients;
-- C38102A.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- CHECK THAT AN INCOMPLETE TYPE DECLARATION CAN BE GIVEN FOR ANY TYPE. -- FULL DECLARATIONS FOR INTEGER, ENUMERATION, CONSTRAINED AND -- UNCONSTRAINED ARRAYS, RECORDS WITHOUT DISCRIMINANTS, -- AN ACCESS TYPE, OR TYPES DERIVED FROM ANY OF THE ABOVE. -- (FLOAT, FIXED, TASKS AND RECORDS WITH DISCRIMINANTS ARE CHECKED -- IN OTHER TESTS). -- DAT 3/24/81 -- SPS 10/25/82 -- SPS 2/17/82 WITH REPORT; USE REPORT; PROCEDURE C38102A IS BEGIN TEST ("C38102A", "ANY TYPE MAY BE INCOMPLETE"); DECLARE TYPE X1; TYPE X2; TYPE X3; TYPE X4; TYPE X5; TYPE X6; TYPE X7; TYPE X8; TYPE D1; TYPE D2; TYPE D3; TYPE D4; TYPE D5; TYPE D6; TYPE X1 IS RANGE 1 .. 10; TYPE X2 IS (TRUE, FALSE, MAYBE, GREEN); TYPE X3 IS ARRAY (1 .. 3) OF STRING (1..10); TYPE X4 IS ARRAY (NATURAL RANGE <> ) OF X3; TYPE AR1 IS ARRAY (X2) OF X3; TYPE X5 IS RECORD C1 : X4 (1..3); C2 : AR1; END RECORD; TYPE X6 IS ACCESS X8; TYPE X7 IS ACCESS X6; TYPE X8 IS ACCESS X6; TYPE D1 IS NEW X1; TYPE D2 IS NEW X2; TYPE D3 IS NEW X3; TYPE D4 IS NEW X4; TYPE D5 IS NEW X5; SUBTYPE D7 IS X7; SUBTYPE D8 IS X8; TYPE D6 IS ACCESS D8; PACKAGE P IS TYPE X1; TYPE X2; TYPE X3; TYPE X4; TYPE X5; TYPE X6; TYPE X7 IS PRIVATE; TYPE X8 IS LIMITED PRIVATE; TYPE D1; TYPE D2; TYPE D3; TYPE D4; TYPE D5; TYPE D6; TYPE X1 IS RANGE 1 .. 10; TYPE X2 IS (TRUE, FALSE, MAYBE, GREEN); TYPE X3 IS ARRAY (1 .. 3) OF STRING (1..10); TYPE X4 IS ARRAY (NATURAL RANGE <> ) OF X3; TYPE AR1 IS ARRAY (X2) OF X3; TYPE X5 IS RECORD C1 : X4 (1..3); C2 : AR1; END RECORD; TYPE X6 IS ACCESS X8; TYPE D1 IS RANGE 1 .. 10; TYPE D2 IS NEW X2; TYPE D3 IS NEW X3; TYPE D4 IS NEW X4; TYPE D5 IS NEW X5; TYPE D6 IS NEW X6; SUBTYPE D7 IS X7; SUBTYPE D8 IS X8; TYPE D9 IS ACCESS D8; VX7 : CONSTANT X7; PRIVATE TYPE X7 IS RECORD C1 : X1; C3 : X3; C5 : X5; C6 : X6; C8 : D9; END RECORD; V3 : X3 := (X3'RANGE => "ABCDEFGHIJ"); TYPE A7 IS ACCESS X7; TYPE X8 IS ARRAY (V3'RANGE) OF A7; VX7 : CONSTANT X7 := (3, V3, ((1..3=>V3), (TRUE..GREEN=>V3)), NULL, NEW D8); END P; USE P; VD7: P.D7; PACKAGE BODY P IS BEGIN VD7 := D7(VX7); END P; BEGIN IF VX7 /= P.X7(VD7) THEN FAILED ("WRONG VALUE SOMEWHERE"); END IF; END; RESULT; END C38102A;
pragma License (Unrestricted); -- overridable runtime unit specialized for Windows (x86_64) with System.Unwind.Representation; with C.winnt; package System.Unwind.Mapping is pragma Preelaborate; -- signal alt stack type Signal_Stack_Type is private; -- register signal handler (init.c/seh_init.c) procedure Install_Exception_Handler (SEH : Address) is null with Export, -- for weak linking Convention => Ada, External_Name => "__drake_install_exception_handler"; procedure Install_Task_Exception_Handler ( SEH : Address; Signal_Stack : not null access Signal_Stack_Type) is null with Export, Convention => Ada, External_Name => "__drake_install_task_exception_handler"; procedure Reinstall_Exception_Handler is null with Export, Convention => Ada, External_Name => "__drake_reinstall_exception_handler"; -- equivalent to __gnat_map_SEH (seh_init.c) -- and Create_Machine_Occurrence_From_Signal_Handler (a-except-2005.adb) function New_Machine_Occurrence_From_SEH ( Exception_Record : C.winnt.struct_EXCEPTION_RECORD_ptr) return Representation.Machine_Occurrence_Access with Export, Convention => Ada, External_Name => "__drake_new_machine_occurrence_from_seh"; pragma No_Inline (New_Machine_Occurrence_From_SEH); private type Signal_Stack_Type is null record; pragma Suppress_Initialization (Signal_Stack_Type); end System.Unwind.Mapping;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../../License.txt with Ada.Characters.Latin_1; package body Spatial_Data is package LAT renames Ada.Characters.Latin_1; --------------------------- -- initialize_as_point -- --------------------------- function initialize_as_point (point : Geometric_Point) return Geometry is metadata : Ring_Structure := (Item_Type => single_point, Item_ID => 1, Ring_ID => 1, Ring_Size => 1, Ring_Count => 1, Point_Index => 1, Level_Flags => 0, Group_ID => 1); begin return (contents => single_point, units => 1, subunits => 1, points => 1, structures => (1 => metadata), points_set => (1 => point)); end initialize_as_point; --------------------------------- -- initialize_as_multi_point -- --------------------------------- function initialize_as_multi_point (point : Geometric_Point) return Geometry is metadata : Ring_Structure := (Item_Type => multi_point, Item_ID => 1, Ring_ID => 1, Ring_Size => 1, Ring_Count => 1, Point_Index => 1, Level_Flags => 0, Group_ID => 1); begin return (contents => multi_point, units => 1, subunits => 1, points => 1, structures => (1 => metadata), points_set => (1 => point)); end initialize_as_multi_point; -------------------------- -- initialize_as_line -- -------------------------- function initialize_as_line (line_string : Geometric_Line_String) return Geometry is metadata : Ring_Structure := (Item_Type => single_line_string, Item_ID => 1, Ring_ID => 1, Ring_Size => line_string'Length, Ring_Count => 1, Point_Index => 1, Level_Flags => 0, Group_ID => 1); begin return (contents => single_line_string, units => 1, subunits => 1, points => line_string'Length, structures => (1 => metadata), points_set => line_string); end initialize_as_line; -------------------------------- -- initialize_as_multi_line -- -------------------------------- function initialize_as_multi_line (line_string : Geometric_Line_String) return Geometry is metadata : Ring_Structure := (Item_Type => multi_line_string, Item_ID => 1, Ring_ID => 1, Ring_Size => line_string'Length, Ring_Count => 1, Point_Index => 1, Level_Flags => 0, Group_ID => 1); begin return (contents => multi_line_string, units => 1, subunits => 1, points => line_string'Length, structures => (1 => metadata), points_set => line_string); end initialize_as_multi_line; --------------------- -- start_polygon -- --------------------- function start_polygon (outer_ring : Geometric_Ring) return Geometric_Polygon is num_points : constant Natural := outer_ring'Length; PG : Geometric_Polygon (rings => 1, points => num_points); metadata : Ring_Structure := (Item_Type => single_polygon, Item_ID => 1, Ring_ID => 1, Ring_Size => num_points, Ring_Count => 1, Point_Index => 1, Level_Flags => 0, Group_ID => 1); begin if num_points < 4 then raise LACKING_POINTS with "polygon rings must have at least 4 points (found only" & num_points'Img & ")"; end if; PG.structures := (1 => metadata); PG.points_set := outer_ring; return PG; end start_polygon; ------------------------- -- append_inner_ring -- ------------------------- procedure append_inner_ring (polygon : in out Geometric_Polygon; inner_ring : Geometric_Ring) is num_points : constant Natural := inner_ring'Length; last_ring : constant Positive := polygon.rings + 1; total_points : constant Natural := polygon.points + num_points; PG : Geometric_Polygon (rings => last_ring, points => total_points); metadata : Ring_Structure := (Item_Type => single_polygon, Item_ID => 1, Ring_ID => last_ring, Ring_Size => num_points, Ring_Count => last_ring, Point_Index => polygon.points + 1, Level_Flags => 0, Group_ID => 1); begin if num_points < 4 then raise LACKING_POINTS with "polygon rings must have at least 4 points (found only" & num_points'Img & ")"; end if; for ring in 1 .. polygon.rings loop PG.structures (ring) := polygon.structures (ring); PG.structures (ring).Ring_Count := last_ring; end loop; PG.structures (last_ring) := metadata; for pt in 1 .. polygon.points loop PG.points_set (pt) := polygon.points_set (pt); end loop; for pt in 1 .. num_points loop PG.points_set (polygon.points + pt) := inner_ring (pt); end loop; polygon := PG; end append_inner_ring; ----------------------- -- number_of_rings -- ----------------------- function number_of_rings (polygon : Geometric_Polygon) return Natural is begin return Natural (polygon.rings); end number_of_rings; --------------------- -- retrieve_ring -- --------------------- function retrieve_ring (polygon : Geometric_Polygon; ring_index : Positive) return Geometric_Ring is begin if ring_index > polygon.rings then raise OUT_OF_COLLECTION_RANGE with "Requested ring" & ring_index'Img & ", but there are only" & polygon.rings'Img & " available"; end if; declare num_points : Positive := polygon.structures (ring_index).Ring_Size; start_here : Positive := polygon.structures (ring_index).Point_Index; finish : Positive := start_here + num_points - 1; GR : Geometric_Ring (1 .. num_points); begin GR := polygon.points_set (start_here .. finish); return GR; end; end retrieve_ring; ----------------------------- -- initialize_as_polygon -- ----------------------------- function initialize_as_polygon (polygon : Geometric_Polygon) return Geometry is GM : Geometry (contents => single_polygon, units => 1, subunits => polygon.rings, points => polygon.points); begin for ring in 1 .. polygon.rings loop GM.structures (ring) := polygon.structures (ring); end loop; for pt in 1 .. polygon.points loop GM.points_set (pt) := polygon.points_set (pt); end loop; return GM; end initialize_as_polygon; ----------------------------------- -- initialize_as_multi_polygon -- ----------------------------------- function initialize_as_multi_polygon (polygon : Geometric_Polygon) return Geometry is GM : Geometry (contents => multi_polygon, units => 1, subunits => polygon.rings, points => polygon.points); begin for ring in 1 .. polygon.rings loop GM.structures (ring) := polygon.structures (ring); GM.structures (ring).Item_Type := multi_polygon; end loop; for pt in 1 .. polygon.points loop GM.points_set (pt) := polygon.points_set (pt); end loop; return GM; end initialize_as_multi_polygon; -------------------------------- -- initialize_as_collection -- -------------------------------- function initialize_as_collection (anything : Geometry) return Geometry is classification : Collection_Type := anything.contents; GM : Geometry (contents => heterogeneous, units => anything.units, subunits => anything.subunits, points => anything.points); begin GM.structures := anything.structures; GM.points_set := anything.points_set; for ring in 1 .. anything.subunits loop -- Shift any existing flags over one place before setting level GM.structures (ring).Level_Flags := 1 + (anything.structures (ring).Level_Flags * 2); end loop; return GM; end initialize_as_collection; -------------------------- -- size_of_collection -- -------------------------- function size_of_collection (collection : Geometry) return Positive is begin if collection.contents = heterogeneous then -- For colletions, return the number of groups, not units return collection.structures (collection.structures'Last).Group_ID; else return collection.units; end if; end size_of_collection; -------------------------- -- type_of_collection -- -------------------------- function type_of_collection (collection : Geometry) return Collection_Type is begin return collection.contents; end type_of_collection; --------------------------- -- augment_multi_point -- --------------------------- procedure augment_multi_point (collection : in out Geometry; point : Geometric_Point) is begin case collection.contents is when multi_point => declare last_point : Geo_Points := collection.points + 1; last_unit : Geo_Units := collection.units + 1; GM : Geometry (contents => multi_point, units => last_unit, subunits => last_unit, points => last_point); begin for ring in 1 .. collection.subunits loop GM.structures (ring) := collection.structures (ring); GM.structures (ring).Ring_Count := last_unit; end loop; GM.points_set (1 .. collection.points) := collection.points_set; GM.structures (last_unit) := (Item_Type => multi_point, Item_ID => last_unit, Ring_ID => 1, Ring_Size => 1, Ring_Count => last_unit, Point_Index => last_point, Level_Flags => 0, Group_ID => 1); GM.points_set (last_point) := point; collection := GM; end; when others => raise ILLEGAL_SHAPE with "The collection must already be a multi_point type"; end case; end augment_multi_point; -------------------------- -- augment_multi_line -- -------------------------- procedure augment_multi_line (collection : in out Geometry; line : Geometric_Line_String) is begin case collection.contents is when multi_line_string => declare LL : Natural := line'Length; first_point : Geo_Points := collection.points + 1; last_point : Geo_Points := collection.points + LL; last_unit : Geo_Units := collection.units + 1; marker : Positive := line'First; GM : Geometry (contents => multi_line_string, units => last_unit, subunits => last_unit, points => last_point); begin for ring in 1 .. collection.subunits loop GM.structures (ring) := collection.structures (ring); GM.structures (ring).Ring_Count := last_unit; end loop; GM.points_set (1 .. collection.points) := collection.points_set; GM.structures (last_unit) := (Item_Type => multi_line_string, Item_ID => last_unit, Ring_ID => 1, Ring_Size => LL, Ring_Count => last_unit, Point_Index => first_point, Level_Flags => 0, Group_ID => 1); for pt in first_point .. last_point loop GM.points_set (pt) := line (marker); marker := marker + 1; end loop; collection := GM; end; when others => raise ILLEGAL_SHAPE with "The collection must already be a multi_line_string type"; end case; end augment_multi_line; ----------------------------- -- augment_multi_polygon -- ----------------------------- procedure augment_multi_polygon (collection : in out Geometry; polygon : Geometric_Polygon) is begin case collection.contents is when multi_polygon => declare num_points : Geo_Points := polygon.points; first_point : Geo_Points := collection.points + 1; last_point : Geo_Points := collection.points + num_points; last_unit : Geo_Units := collection.units + 1; first_subunit : Geo_Units := collection.subunits + 1; last_subunit : Geo_Units := collection.subunits + polygon.rings; marker : Positive := polygon.structures'First; ptmr : Geo_Points := first_point; ppsm : Geo_Points := polygon.points_set'First; GM : Geometry (contents => multi_polygon, units => last_unit, subunits => last_subunit, points => last_point); begin for ring in 1 .. collection.subunits loop GM.structures (ring) := collection.structures (ring); GM.structures (ring).Ring_Count := last_subunit; end loop; GM.points_set (1 .. collection.points) := collection.points_set; for ring in first_subunit .. last_subunit loop GM.structures (ring) := (Item_Type => multi_polygon, Item_ID => last_unit, Ring_ID => polygon.structures (marker).Ring_ID, Ring_Size => polygon.structures (marker).Ring_Size, Ring_Count => last_subunit, Point_Index => ptmr, Level_Flags => 0, Group_ID => 1); ptmr := ptmr + polygon.structures (marker).Ring_Size; marker := marker + 1; end loop; for pt in first_point .. last_point loop GM.points_set (pt) := polygon.points_set (ppsm); ppsm := ppsm + 1; end loop; collection := GM; end; when others => raise ILLEGAL_SHAPE with "The collection must already be a multi_polygon type"; end case; end augment_multi_polygon; -------------------------- -- augment_collection -- -------------------------- procedure augment_collection (collection : in out Geometry; anything : Geometry) is begin case collection.contents is when heterogeneous => declare num_points : Geo_Points := anything.points; first_point : Geo_Points := collection.points + 1; last_point : Geo_Points := collection.points + num_points; last_unit : Geo_Units := collection.units + 1; first_subunit : Geo_Units := collection.subunits + 1; last_subunit : Geo_Units := collection.subunits + anything.subunits; marker : Positive := anything.structures'First; ptmr : Geo_Points := first_point; ppsm : Geo_Points := anything.points_set'First; multiplier : constant collection_flags := highest_level (collection) * 2; last_id : Positive := collection.structures (collection.subunits).Item_ID; next_group : Positive := collection.structures (collection.subunits).Group_ID + 1; GM : Geometry (contents => heterogeneous, units => last_unit, subunits => last_subunit, points => last_point); begin GM.structures (1 .. collection.subunits) := collection.structures; GM.points_set (1 .. collection.points) := collection.points_set; for ring in first_subunit .. last_subunit loop GM.structures (ring) := (Item_Type => anything.structures (marker).Item_Type, Item_ID => anything.structures (marker).Item_ID + last_id, Ring_ID => anything.structures (marker).Ring_ID, Ring_Size => anything.structures (marker).Ring_Size, Ring_Count => anything.structures (marker).Ring_Count, Point_Index => ptmr, Level_Flags => (anything.structures (marker).Level_Flags * multiplier) + 1, Group_ID => next_group); ptmr := ptmr + anything.structures (marker).Ring_Size; marker := marker + 1; end loop; for pt in first_point .. last_point loop GM.points_set (pt) := anything.points_set (ppsm); ppsm := ppsm + 1; end loop; collection := GM; end; when others => raise ILLEGAL_SHAPE with "The collection must already be a hetegeneous type"; end case; end augment_collection; ------------------------------ -- check_collection_index -- ------------------------------ procedure check_collection_index (collection : Geometry; index : Positive) is begin if index > collection.units then raise OUT_OF_COLLECTION_RANGE with "Only" & collection.units'Img & " items in collection " & "(attempted index of" & index'Img & ")"; end if; end check_collection_index; ---------------------- -- retrieve_point -- ---------------------- function retrieve_point (collection : Geometry; index : Positive := 1) return Geometric_Point is begin check_collection_index (collection, index); case collection.contents is when single_point | multi_point => return collection.points_set (index); when heterogeneous => raise CONVERSION_FAILED with "Requested polygon from mixed collection. " & "(Extract using retrieve_subcollection instead)"; when others => raise CONVERSION_FAILED with "Requested point, but shape is " & collection_item_shape (collection, index)'Img; end case; end retrieve_point; --------------------- -- retrieve_line -- --------------------- function retrieve_line (collection : Geometry; index : Positive := 1) return Geometric_Line_String is begin check_collection_index (collection, index); case collection.contents is when single_line_string | multi_line_string => declare CS : Ring_Structure renames collection.structures (index); data_size : Positive := CS.Ring_Size; first_point : Geo_Points := CS.Point_Index; last_point : Geo_Points := first_point + data_size - 1; LNS : Geometric_Line_String (1 .. data_size); begin LNS := collection.points_set (first_point .. last_point); return LNS; end; when heterogeneous => raise CONVERSION_FAILED with "Requested line_string from mixed collection. " & "(Extract using retrieve_subcollection instead)"; when others => raise CONVERSION_FAILED with "Requested line_string, but shape is " & collection_item_shape (collection, index)'Img; end case; end retrieve_line; ------------------------ -- retrieve_polygon -- ------------------------ function retrieve_polygon (collection : Geometry; index : Positive := 1) return Geometric_Polygon is found : Boolean := False; F_subunit : Geo_Units; L_subunit : Geo_Units; product : Geometric_Polygon; begin check_collection_index (collection, index); case collection.contents is when single_polygon | multi_polygon => for subunit in 1 .. collection.subunits loop if collection.structures (subunit).Item_ID = index then if not found then F_subunit := subunit; end if; L_subunit := subunit; found := True; end if; end loop; if not found then raise OUT_OF_COLLECTION_RANGE with "Failed to locate polygon" & index'Img; end if; declare CS : Ring_Structure renames collection.structures (F_subunit); data_size : Positive := CS.Ring_Size; first_point : Geo_Points := CS.Point_Index; last_point : Geo_Points := first_point + data_size - 1; outer_ring : Geometric_Ring (1 .. data_size); begin outer_ring := collection.points_set (first_point .. last_point); product := start_polygon (outer_ring); end; for subunit in F_subunit + 1 .. L_subunit loop declare CS : Ring_Structure renames collection.structures (subunit); data_size : Positive := CS.Ring_Size; first_point : Geo_Points := CS.Point_Index; last_point : Geo_Points := first_point + data_size - 1; hole : Geometric_Ring (1 .. data_size); begin hole := collection.points_set (first_point .. last_point); append_inner_ring (product, hole); end; end loop; return product; when heterogeneous => raise CONVERSION_FAILED with "Requested polygon from mixed collection. " & "(Extract using retrieve_subcollection instead)"; when others => raise CONVERSION_FAILED with "Requested polygon, but shape is " & collection_item_shape (collection, index)'Img; end case; end retrieve_polygon; --------------------- -- single_canvas -- --------------------- function single_canvas (gm_type : Collection_Type; items : Item_ID_type; subunits : Geo_Units; points : Geo_Points) return Geometry is p_set : Geometric_Point_Collection (1 .. points) := (others => Origin_Point); s_set : Ring_Structures (1 .. subunits) := (others => (Item_Type => single_point, Item_ID => 1, Ring_ID => 1, Ring_Size => 1, Ring_Count => 1, Point_Index => 1, Level_Flags => 0, Group_ID => 1)); begin case gm_type is when unset => return (unset, 1, 1, 1); when single_point => return (single_point, items, 1, 1, s_set, p_set); when single_line_string => return (single_line_string, items, 1, points, s_set, p_set); when single_polygon => return (single_polygon, items, subunits, points, s_set, p_set); when multi_point => return (multi_point, items, subunits, points, s_set, p_set); when multi_line_string => return (multi_line_string, items, subunits, points, s_set, p_set); when multi_polygon => return (multi_polygon, items, subunits, points, s_set, p_set); when heterogeneous => return (contents => heterogeneous, units => items, subunits => subunits, points => points, structures => s_set, points_set => p_set); end case; end single_canvas; ------------------------------ -- retrieve_subcollection -- ------------------------------ function retrieve_subcollection (collection : Geometry; index : Positive := 1) return Geometry is function cut (flags : collection_flags) return collection_flags; found : Boolean := False; num_points : Natural := 0; num_sunits : Geo_Units := 0; num_items : Natural := 0; prev_unit : Natural := 0; first_unit : Natural := 0; prev_flags : collection_flags; F_subunit : Geo_Units; L_subunit : Geo_Units; coltype : Collection_Type; function cut (flags : collection_flags) return collection_flags is begin return flags / 2; end cut; begin case collection.contents is when unset | single_point | single_polygon | single_line_string => raise OUT_OF_COLLECTION_RANGE with "Applies only to multi- and mixed geometric collections"; when multi_point => declare pt : Geometric_Point := retrieve_point (collection, index); begin return initialize_as_point (pt); end; when multi_line_string => declare LS : Geometric_Line_String := retrieve_line (collection, index); begin return initialize_as_line (LS); end; when multi_polygon => declare PG : Geometric_Polygon := retrieve_polygon (collection, index); begin return initialize_as_polygon (PG); end; when heterogeneous => for subunit in 1 .. collection.subunits loop declare CSU : Ring_Structure renames collection.structures (subunit); lvl : collection_flags := cut (cut (CSU.Level_Flags)); begin if CSU.Group_ID = index then if not found then found := True; F_subunit := subunit; coltype := CSU.Item_Type; prev_unit := CSU.Item_ID; first_unit := CSU.Item_ID; prev_flags := lvl; num_items := 1; if cut (CSU.Level_Flags) > 0 then coltype := heterogeneous; end if; end if; L_subunit := subunit; num_sunits := num_sunits + 1; num_points := num_points + CSU.Ring_Size; if coltype = heterogeneous then if lvl = 0 then -- If lvl = 0 then we're in a geometry -- collection that does not contain other -- collections. Thus the active group ID points -- to a single* or multi* type, and all Item_IDs -- are counted as retrievable items. -- If we find a ring count > 1 then we have a -- multi* type that was added to a collection -- so keep these together (group ID gets mangled) if CSU.Item_ID /= prev_unit then num_items := num_items + 1; end if; else -- Within this collection is another geometry -- collection. Items with the same baseflags are -- considered a single unit. Only count changes -- to and from level 0. Item IDs always change -- at those borders; no need to check if prev_flags = 0 then num_items := num_items + 1; end if; end if; else -- single* types only have one unit, 1 group -- multi* types have 1+ units, but only 1 group num_items := CSU.Item_ID - first_unit + 1; end if; prev_flags := lvl; prev_unit := CSU.Item_ID; end if; end; end loop; if not found then raise OUT_OF_COLLECTION_RANGE with "Failed to locate subcollection" & index'Img; end if; case coltype is when unset => raise CONVERSION_FAILED with "Illegal heterogenous type (unset)"; when others => declare RS : Ring_Structures renames collection.structures; CS : Ring_Structure renames RS (F_subunit); FP : Geo_Points := CS.Point_Index; LP : Geo_Points := FP + num_points - 1; GM : Geometry := single_canvas (coltype, num_items, num_sunits, num_points); marker : Geo_Units := 1; diff : Natural := CS.Item_ID - 1; ptdiff : Natural := CS.Point_Index - 1; group : Positive := 1; lvl : collection_flags; rseek : Natural := 0; rtrack : Natural := 0; begin prev_unit := CS.Item_ID; prev_flags := cut (cut (CS.Level_Flags)); GM.points_set (1 .. num_points) := collection.points_set (FP .. LP); for S in F_subunit .. L_subunit loop if coltype = heterogeneous then lvl := cut (cut (RS (S).Level_Flags)); if lvl = 0 then rtrack := rtrack + 1; if rtrack > rseek then if RS (S).Item_ID /= prev_unit then group := group + 1; end if; rseek := RS (S).Ring_Count; rtrack := 1; end if; else if prev_flags = 0 then group := group + 1; end if; end if; prev_unit := RS (S).Item_ID; prev_flags := lvl; end if; GM.structures (marker) := (Item_Type => RS (S).Item_Type, Item_ID => RS (S).Item_ID - diff, Ring_ID => RS (S).Ring_ID, Ring_Size => RS (S).Ring_Size, Ring_Count => RS (S).Ring_Count, Point_Index => RS (S).Point_Index - ptdiff, Level_Flags => cut (RS (S).Level_Flags), Group_ID => group); marker := marker + 1; end loop; return GM; end; end case; end case; end retrieve_subcollection; ----------------------------- -- collection_item_shape -- ----------------------------- function collection_item_shape (collection : Geometry; index : Positive := 1) return Geometric_Shape is begin check_collection_index (collection, index); case collection.contents is when single_point => return point_shape; when single_line_string => return line_string_shape; when single_polygon => return polygon_shape; when multi_point => return point_shape; when multi_line_string => return line_string_shape; when multi_polygon => return polygon_shape; when heterogeneous => return mixture; when unset => raise CONVERSION_FAILED with "Geometry is unset - it contains zero shapes"; end case; end collection_item_shape; ---------------------------- -- collection_item_type -- ---------------------------- function collection_item_type (collection : Geometry; index : Positive := 1) return Collection_Type is begin check_collection_index (collection, index); case collection.contents is when unset => raise CONVERSION_FAILED with "geometry is unset (typeless)"; when single_point | single_polygon | single_line_string => return collection.contents; when multi_point => return single_point; when multi_line_string => return single_line_string; when multi_polygon => return single_polygon; when heterogeneous => for subunit in 1 .. collection.subunits loop if collection.structures (subunit).Group_ID = index then return collection.structures (subunit).Item_Type; end if; end loop; raise OUT_OF_COLLECTION_RANGE with "collection_item_type out of range: " & index'Img; end case; end collection_item_type; -------------------------------- -- convert_infinite_line #1 -- -------------------------------- function convert_infinite_line (line : Geometric_Line) return Slope_Intercept is diff_x : constant Geometric_Real := line (2).X - line (1).X; diff_y : constant Geometric_Real := line (2).Y - line (1).Y; slope : Geometric_Real; intercept : Geometric_Real; begin if diff_x = 0.0 then return (slope => 0.0, y_intercept => 0.0, vertical => True); end if; slope := diff_y / diff_x; intercept := line (1).Y - (slope * line (1).X); return (slope, intercept, False); end convert_infinite_line; -------------------------------- -- convert_infinite_line #2 -- -------------------------------- function convert_infinite_line (line : Geometric_Line) return Standard_Form is -- If vertical slope ("run" = 0, "rise" /= 0) the result is -- A=1 B=0 C=x-coordinate -- For the non-vertical case -- A is equivalent to negative slope -- B is equivalent to 1.0 -- C is equivalent to y-intercept SLINT : Slope_Intercept := convert_infinite_line (line); begin if SLINT.vertical then return (A => 1.0, B => 0.0, C => line (1).X); end if; return (A => -1.0 * SLINT.slope, B => 1.0, C => SLINT.y_intercept); end convert_infinite_line; ----------------------------------- -- convert_to_infinite_line #1 -- ----------------------------------- function convert_to_infinite_line (std_form : Standard_Form) return Geometric_Line is XX : Geometric_Real; YY : Geometric_Real; begin if std_form.B = 0.0 then if std_form.A = 0.0 then raise CONVERSION_FAILED with "Illegal standard form: A and B are both zero"; end if; -- Vertical line XX := std_form.C / std_form.A; return ((XX, 0.0), (XX, 1.0)); end if; if std_form.A = 0.0 then -- Horizontal line YY := std_form.C / std_form.B; return ((0.0, YY), (1.0, YY)); end if; -- Sloped (non-inclusively been +/- 0 and infinity) -- In other words, neither A nor B is zero; both axes are crossed XX := std_form.C / std_form.A; YY := std_form.C / std_form.B; return ((0.0, YY), (XX, 0.0)); end convert_to_infinite_line; ----------------------------------- -- convert_to_infinite_line #2 -- ----------------------------------- function convert_to_infinite_line (intercept_form : Slope_Intercept) return Geometric_Line is XX : Geometric_Real; YY : Geometric_Real; begin if intercept_form.vertical then raise CONVERSION_FAILED with "Cannot convert vertical lines using the intercept form"; end if; YY := intercept_form.y_intercept; -- Handle horizontal case if intercept_form.slope = 0.0 then return ((0.0, YY), (1.0, YY)); end if; -- Remaining cases cross both axes XX := -1.0 * intercept_form.y_intercept / intercept_form.slope; return ((0.0, YY), (XX, 0.0)); end convert_to_infinite_line; ------------------- -- format_real -- ------------------- function format_real (value : Geometric_Real) return String is function trim_sides (S : String) return String; raw : constant String := CT.trim (Geometric_Real'Image (abs (value))); last3 : constant String := raw (raw'Last - 2 .. raw'Last); posend : constant Natural := raw'Last - 4; shift : constant Integer := Integer'Value (last3); is_neg : constant Boolean := value < 0.0; canvas : String (1 .. 26) := (others => '0'); dot : Natural; function trim_sides (S : String) return String is left : Natural := S'First; right : Natural := S'Last; keep : Boolean; begin for x in S'Range loop keep := (S (x) /= '0' and then S (x) /= ' '); exit when keep; left := left + 1; end loop; for x in reverse S'Range loop keep := (S (x) /= '0' and then S (x) /= ' '); exit when keep; right := right - 1; end loop; if S (left) = '.' then left := left - 1; end if; if S (right) = '.' then right := right - 1; end if; if is_neg then return "-" & S (left .. right); else return S (left .. right); end if; end trim_sides; begin if shift = 0 then canvas (1 .. posend) := raw (1 .. posend); return trim_sides (canvas (1 .. posend)); elsif shift > 18 or else shift < -18 then return CT.trim (raw); elsif shift > 0 then canvas (1 .. posend) := raw (1 .. posend); dot := CT.pinpoint (canvas, "."); for bubble in Positive range dot + 1 .. dot + shift loop -- Left side is always the dot canvas (bubble - 1) := canvas (bubble); canvas (bubble) := '.'; end loop; return trim_sides (canvas); else canvas (canvas'Last - posend + 1 .. canvas'Last) := raw (1 .. posend); dot := CT.pinpoint (canvas, "."); for bubble in reverse dot + shift .. dot - 1 loop -- Right side is always the dot canvas (bubble + 1) := canvas (bubble); canvas (bubble) := '.'; end loop; return trim_sides (canvas); end if; end format_real; --------------------- -- highest_level -- --------------------- function highest_level (collection : Geometry) return collection_flags is res : collection_flags := 0; begin for csu in 1 .. collection.subunits loop if collection.structures (csu).Level_Flags > res then res := collection.structures (csu).Level_Flags; end if; end loop; return res; end highest_level; ------------ -- dump -- ------------ function dump (collection : Geometry) return String is function bin (level : collection_flags) return String; res : CT.Text; most : collection_flags := highest_level (collection); function bin (level : collection_flags) return String is mask : collection_flags; res : String (1 .. 24) := (others => '0'); begin if most = 0 then return "0"; end if; for bit in 0 .. 23 loop mask := 2 ** bit; if mask > most then return res (1 .. bit); end if; if (level and mask) > 0 then res (bit + 1) := '1'; end if; end loop; return res; end bin; begin CT.SU.Append (res, "contents : " & collection.contents'Img & LAT.LF & "units : " & CT.int2str (collection.units) & LAT.LF & "subunits : " & CT.int2str (collection.subunits) & LAT.LF & "points : " & CT.int2str (collection.points) & LAT.LF); for R in 1 .. collection.subunits loop CT.SU.Append (res, LAT.LF & "Ring #" & CT.int2str (R) & LAT.LF); declare CS : Ring_Structure renames collection.structures (R); begin CT.SU.Append (res, " Type : " & CS.Item_Type'Img & LAT.LF & " Item_ID : " & CT.int2str (CS.Item_ID) & LAT.LF & " Ring_ID : " & CT.int2str (CS.Ring_ID) & LAT.LF & " Set Size : " & CT.int2str (CS.Ring_Count) & LAT.LF & " Size : " & CT.int2str (CS.Ring_Size) & LAT.LF & " Pt Index : " & CT.int2str (CS.Point_Index) & LAT.LF & " Level : " & bin (CS.Level_Flags) & LAT.LF & " Group ID : " & CT.int2str (CS.Group_ID) & LAT.LF); end; end loop; CT.SU.Append (res, LAT.LF & "Serialized Points" & LAT.LF); for PI in 1 .. collection.points loop declare coord : Geometric_Point renames collection.points_set (PI); line : String := CT.zeropad (PI, 2) & ": " & format_real (coord.X) & ", " & format_real (coord.Y); begin CT.SU.Append (res, line & LAT.LF); end; end loop; return CT.USS (res); end dump; ------------------ -- mysql_text -- ------------------ function mysql_text (collection : Geometry; top_first : Boolean := True) return String is function initialize_title (title : String) return CT.Text; function format_point (pt : Geometric_Point; first : Boolean := False) return String; function format_polygon (poly : Geometric_Polygon; first : Boolean := False) return String; function format_line_string (LNS : Geometric_Line_String; first : Boolean := False) return String; sep : constant String := ", "; pclose : constant String := ")"; function format_point (pt : Geometric_Point; first : Boolean := False) return String is ptx : constant String := format_real (pt.X); pty : constant String := format_real (pt.Y); core : constant String := "Point(" & ptx & sep & pty & pclose; begin if first then return core; else return sep & core; end if; end format_point; function format_polygon (poly : Geometric_Polygon; first : Boolean := False) return String is lead : constant String := "Polygon("; work : CT.Text; lastsc : Natural := 0; inner1 : Boolean; nrings : Natural := number_of_rings (poly); begin if first then CT.SU.Append (work, lead); else CT.SU.Append (work, sep & lead); end if; for ring in 1 .. nrings loop if ring > 1 then CT.SU.Append (work, sep); end if; CT.SU.Append (work, "Linestring("); declare GR : Geometric_Ring := retrieve_ring (poly, ring); begin for pt in GR'Range loop inner1 := (pt = GR'First); CT.SU.Append (work, format_point (GR (pt), inner1)); end loop; end; CT.SU.Append (work, pclose); end loop; CT.SU.Append (work, pclose); return CT.USS (work); end format_polygon; function format_line_string (LNS : Geometric_Line_String; first : Boolean := False) return String is lead : constant String := "LineString("; work : CT.Text := CT.SUS (lead); inn1 : Boolean; begin for x in LNS'Range loop inn1 := (x = LNS'First); CT.SU.Append (work, format_point (LNS (x), inn1)); end loop; if first then return CT.USS (work) & pclose; else return sep & CT.USS (work) & pclose; end if; end format_line_string; function initialize_title (title : String) return CT.Text is begin if top_first then return CT.SUS (title); else return CT.SUS (sep & title); end if; end initialize_title; classification : Collection_Type := collection.contents; begin case classification is when unset => return ""; when single_point => return format_point (retrieve_point (collection), top_first); when single_line_string => return format_line_string (retrieve_line (collection), top_first); when single_polygon => return format_polygon (retrieve_polygon (collection), top_first); when multi_point => declare lead : constant String := "MultiPoint("; first : Boolean := True; product : CT.Text; begin if top_first then CT.SU.Append (product, lead); else CT.SU.Append (product, sep & lead); end if; for x in collection.points_set'Range loop CT.SU.Append (product, format_point (collection.points_set (x), first)); first := False; end loop; return CT.USS (product) & pclose; end; when multi_line_string => declare product : CT.Text := initialize_title ("MultiLineString("); first : Boolean := True; begin for ls in 1 .. collection.units loop CT.SU.Append (product, format_line_string (retrieve_line (collection, ls), first)); first := False; end loop; return CT.USS (product) & pclose; end; when multi_polygon => declare lead : constant String := "MultiPolygon("; first : Boolean := True; product : CT.Text; begin if top_first then if collection.units > 1 then CT.SU.Append (product, lead); end if; else if collection.units > 1 then CT.SU.Append (product, sep & lead); else CT.SU.Append (product, sep); end if; end if; for ls in 1 .. collection.units loop CT.SU.Append (product, format_polygon (retrieve_polygon (collection, ls), first)); first := False; end loop; if collection.units > 1 then CT.SU.Append (product, pclose); end if; return CT.USS (product); end; when heterogeneous => declare product : CT.Text := initialize_title ("GeometryCollection("); first : Boolean := True; GM : Geometry; begin for ls in 1 .. size_of_collection (collection) loop GM := retrieve_subcollection (collection, ls); CT.SU.Append (product, mysql_text (GM, first)); first := False; end loop; return CT.USS (product) & pclose; end; end case; end mysql_text; ----------------------- -- Well_Known_Text -- ----------------------- function Well_Known_Text (collection : Geometry; top_first : Boolean := True) return String is function initialize_title (title : String) return CT.Text; function format_point (pt : Geometric_Point; first : Boolean := False; label : Boolean := False) return String; function format_polygon (poly : Geometric_Polygon; first : Boolean := False; label : Boolean := False) return String; function format_line_string (LNS : Geometric_Line_String; first : Boolean := False; label : Boolean := False) return String; sep : constant String := ","; popen : constant String := "("; pclose : constant String := ")"; function initialize_title (title : String) return CT.Text is begin if top_first then return CT.SUS (title); else return CT.SUS (sep & title); end if; end initialize_title; function format_point (pt : Geometric_Point; first : Boolean := False; label : Boolean := False) return String is ptx : constant String := format_real (pt.X); pty : constant String := format_real (pt.Y); lead : constant String := "POINT"; core : constant String := ptx & " " & pty; begin if label then if first then return lead & popen & core & pclose; else return sep & lead & popen & core & pclose; end if; else if first then return core; else return sep & core; end if; end if; end format_point; function format_polygon (poly : Geometric_Polygon; first : Boolean := False; label : Boolean := False) return String is lead : constant String := "POLYGON"; work : CT.Text; inner1 : Boolean; lastsc : Natural := 0; nrings : Natural := number_of_rings (poly); begin if label then if first then CT.SU.Append (work, lead & popen); else CT.SU.Append (work, sep & lead & popen); end if; else if first then CT.SU.Append (work, popen); else CT.SU.Append (work, sep & popen); end if; end if; for ring in 1 .. nrings loop if ring > 1 then CT.SU.Append (work, sep); end if; CT.SU.Append (work, popen); declare GR : Geometric_Ring := retrieve_ring (poly, ring); begin for pt in GR'Range loop inner1 := (pt = GR'First); CT.SU.Append (work, format_point (GR (pt), inner1)); end loop; end; CT.SU.Append (work, pclose); end loop; CT.SU.Append (work, pclose); return CT.USS (work); end format_polygon; function format_line_string (LNS : Geometric_Line_String; first : Boolean := False; label : Boolean := False) return String is lead : constant String := "LINESTRING"; work : CT.Text := CT.blank; inner1 : Boolean; begin if label then if first then CT.SU.Append (work, lead & popen); else CT.SU.Append (work, sep & lead & popen); end if; else if first then CT.SU.Append (work, popen); else CT.SU.Append (work, sep & popen); end if; end if; for x in LNS'Range loop inner1 := (x = LNS'First); CT.SU.Append (work, format_point (LNS (x), inner1)); end loop; CT.SU.Append (work, pclose); return CT.USS (work); end format_line_string; classification : Collection_Type := collection.contents; begin case classification is when unset => return ""; when single_point => return format_point (retrieve_point (collection), top_first, True); when single_line_string => return format_line_string (retrieve_line (collection), top_first, True); when single_polygon => return format_polygon (retrieve_polygon (collection, 1), top_first, True); when multi_point => declare product : CT.Text := initialize_title ("MULTIPOINT("); first : Boolean := True; begin for x in collection.points_set'Range loop CT.SU.Append (product, format_point (collection.points_set (x), first)); first := False; end loop; return CT.USS (product) & pclose; end; when multi_line_string => declare product : CT.Text := initialize_title ("MULTILINESTRING("); first : Boolean := True; begin for ls in 1 .. collection.units loop CT.SU.Append (product, format_line_string (retrieve_line (collection, ls), first)); first := False; end loop; return CT.USS (product) & pclose; end; when multi_polygon => declare product : CT.Text := initialize_title ("MULTIPOLYGON("); first : Boolean := True; begin for ls in 1 .. collection.units loop CT.SU.Append (product, format_polygon (retrieve_polygon (collection, ls), first)); first := False; end loop; CT.SU.Append (product, pclose); return CT.USS (product); end; when heterogeneous => declare product : CT.Text := initialize_title ("GEOMETRYCOLLECTION("); first : Boolean := True; GM : Geometry; begin for ls in 1 .. size_of_collection (collection) loop GM := retrieve_subcollection (collection, ls); CT.SU.Append (product, Well_Known_Text (GM, first)); first := False; end loop; return CT.USS (product) & pclose; end; end case; end Well_Known_Text; end Spatial_Data;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <denkpadje@gmail.com> -- -- 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. with AUnit.Assertions; with AUnit.Test_Caller; with Orka.SIMD.SSE.Singles.Swizzle; package body Test_SIMD_SSE_Swizzle is use Orka; use Orka.SIMD; use Orka.SIMD.SSE.Singles; use Orka.SIMD.SSE.Singles.Swizzle; use AUnit.Assertions; package Caller is new AUnit.Test_Caller (Test); Test_Suite : aliased AUnit.Test_Suites.Test_Suite; function Suite return AUnit.Test_Suites.Access_Test_Suite is Name : constant String := "(SIMD - SSE - Swizzle) "; begin Test_Suite.Add_Test (Caller.Create (Name & "Test Shuffle function", Test_Shuffle'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Transpose function", Test_Transpose_Function'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Transpose procedure", Test_Transpose_Procedure'Access)); return Test_Suite'Access; end Suite; procedure Test_Shuffle (Object : in out Test) is Elements : constant m128 := (1.0, 2.0, 3.0, 4.0); Mask_0_0_0_0 : constant Unsigned_32 := 0 or 0 * 4 or 0 * 16 or 0 * 64; Mask_2_2_2_2 : constant Unsigned_32 := 2 or 2 * 4 or 2 * 16 or 2 * 64; Mask_1_0_3_2 : constant Unsigned_32 := 1 or 0 * 4 or 3 * 16 or 2 * 64; Mask_2_3_0_1 : constant Unsigned_32 := 2 or 3 * 4 or 0 * 16 or 1 * 64; Expected : constant array (Positive range <>) of m128 := ((1.0, 1.0, 1.0, 1.0), (3.0, 3.0, 3.0, 3.0), (2.0, 1.0, 4.0, 3.0), (3.0, 4.0, 1.0, 2.0)); Results : array (Positive range Expected'Range) of m128; begin Results (1) := Shuffle (Elements, Elements, Mask_0_0_0_0); Results (2) := Shuffle (Elements, Elements, Mask_2_2_2_2); Results (3) := Shuffle (Elements, Elements, Mask_1_0_3_2); Results (4) := Shuffle (Elements, Elements, Mask_2_3_0_1); for I in Expected'Range loop for J in Index_Homogeneous loop declare Message : constant String := "Unexpected Single at " & Index_Homogeneous'Image (J); begin Assert (Expected (I) (J) = Results (I) (J), Message); end; end loop; end loop; end Test_Shuffle; procedure Test_Transpose_Function (Object : in out Test) is subtype IH is Index_Homogeneous; Elements : constant m128_Array := ((1.0, 2.0, 3.0, 4.0), (5.0, 6.0, 7.0, 8.0), (9.0, 10.0, 11.0, 12.0), (13.0, 14.0, 15.0, 16.0)); Expected : constant m128_Array := ((1.0, 5.0, 9.0, 13.0), (2.0, 6.0, 10.0, 14.0), (3.0, 7.0, 11.0, 15.0), (4.0, 8.0, 12.0, 16.0)); Result : constant m128_Array := Transpose (Elements); begin for I in Result'Range loop for J in Index_Homogeneous loop Assert (Expected (I) (J) = Result (I) (J), "Unexpected Single at " & I'Image & ", " & J'Image); end loop; end loop; end Test_Transpose_Function; procedure Test_Transpose_Procedure (Object : in out Test) is subtype IH is Index_Homogeneous; Elements : m128_Array := ((1.0, 2.0, 3.0, 4.0), (5.0, 6.0, 7.0, 8.0), (9.0, 10.0, 11.0, 12.0), (13.0, 14.0, 15.0, 16.0)); Expected : constant m128_Array := ((1.0, 5.0, 9.0, 13.0), (2.0, 6.0, 10.0, 14.0), (3.0, 7.0, 11.0, 15.0), (4.0, 8.0, 12.0, 16.0)); begin Transpose (Elements); for I in Elements'Range loop for J in Index_Homogeneous loop Assert (Expected (I) (J) = Elements (I) (J), "Unexpected Single at " & I'Image & ", " & J'Image); end loop; end loop; end Test_Transpose_Procedure; end Test_SIMD_SSE_Swizzle;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- ADA.WIDE_WIDE_TEXT_IO.WIDE_WIDE_BOUNDED_IO -- -- -- -- S p e c -- -- -- -- This specification is derived from the Ada Reference Manual for use with -- -- GNAT. In accordance with the copyright of that document, you can freely -- -- copy and modify this specification, provided that if you redistribute a -- -- modified version, any changes that you have made are clearly indicated. -- -- -- ------------------------------------------------------------------------------ with Ada.Strings.Wide_Wide_Bounded; generic with package Wide_Wide_Bounded is new Ada.Strings.Wide_Wide_Bounded.Generic_Bounded_Length (<>); package Ada.Wide_Wide_Text_IO.Wide_Wide_Bounded_IO is function Get_Line return Wide_Wide_Bounded.Bounded_Wide_Wide_String; function Get_Line (File : File_Type) return Wide_Wide_Bounded.Bounded_Wide_Wide_String; procedure Get_Line (Item : out Wide_Wide_Bounded.Bounded_Wide_Wide_String); procedure Get_Line (File : File_Type; Item : out Wide_Wide_Bounded.Bounded_Wide_Wide_String); procedure Put (Item : Wide_Wide_Bounded.Bounded_Wide_Wide_String); procedure Put (File : File_Type; Item : Wide_Wide_Bounded.Bounded_Wide_Wide_String); procedure Put_Line (Item : Wide_Wide_Bounded.Bounded_Wide_Wide_String); procedure Put_Line (File : File_Type; Item : Wide_Wide_Bounded.Bounded_Wide_Wide_String); end Ada.Wide_Wide_Text_IO.Wide_Wide_Bounded_IO;
-- -- Copyright 2022 (C) Nicolas Pinault (aka DrPi) -- -- SPDX-License-Identifier: BSD-3-Clause -- with Interfaces; use Interfaces; package Elf is ELF_MAGIC : constant := 16#464c457f#; EM_ARM : constant := 16#28#; PT_LOAD : constant := 16#00000001#; type Elf_Header_Pad_Array is array (1 .. 7) of Unsigned_8 with Size => 7*8; type Elf_Header is record Magic : Unsigned_32; Arch_Class : Unsigned_8; Endianness : Unsigned_8; Version : Unsigned_8; Abi : Unsigned_8; Abi_Version : Unsigned_8; Pad : Elf_Header_Pad_Array; Header_Type : Unsigned_16; Machine : Unsigned_16; Version2 : Unsigned_32; end record with Size => (1*4 + 5 + 7 + 2*2 + 1*4)*8; for Elf_Header use record Magic at 0 range 0 .. 31; Arch_Class at 4 range 0 .. 7; Endianness at 5 range 0 .. 7; Version at 6 range 0 .. 7; Abi at 7 range 0 .. 7; Abi_Version at 8 range 0 .. 7; Pad at 9 range 0 .. 55; Header_Type at 16 range 0 .. 15; Machine at 18 range 0 .. 15; Version2 at 20 range 0 .. 31; end record; EF_ARM_ABI_FLOAT_HARD : constant := 16#00000400#; type Elf32_Header is record Common : Elf_Header; Prog_Entry : Unsigned_32; Ph_Offset : Unsigned_32; Sh_Offset : Unsigned_32; Flags : Unsigned_32; Eh_Size : Unsigned_16; Ph_Entry_Size : Unsigned_16; Ph_Num : Unsigned_16; Sh_Entry_Size : Unsigned_16; Sh_Num : Unsigned_16; Sh_Str_Index : Unsigned_16; end record with Size => (24 + 4*4 + 6*2)*8; for Elf32_Header use record Common at 0 range 0 .. 24*8-1; Prog_Entry at 24 range 0 .. 31; Ph_Offset at 28 range 0 .. 31; Sh_Offset at 32 range 0 .. 31; Flags at 36 range 0 .. 31; Eh_Size at 40 range 0 .. 15; Ph_Entry_Size at 42 range 0 .. 15; Ph_Num at 44 range 0 .. 15; Sh_Entry_Size at 46 range 0 .. 15; Sh_Num at 48 range 0 .. 15; Sh_Str_Index at 50 range 0 .. 15; end record; type Elf32_Header_Access is access Elf32_Header; type Elf32_Ph_Entry is record Entry_Type : Unsigned_32; Offset : Unsigned_32; Vaddr : Unsigned_32; Paddr : Unsigned_32; Filez : Unsigned_32; Memsz : Unsigned_32; Flags : Unsigned_32; Align : Unsigned_32; end record with Size => 8*4*8; for Elf32_Ph_Entry use record Entry_Type at 0 range 0 .. 31; Offset at 4 range 0 .. 31; Vaddr at 8 range 0 .. 31; Paddr at 12 range 0 .. 31; Filez at 16 range 0 .. 31; Memsz at 20 range 0 .. 31; Flags at 24 range 0 .. 31; Align at 28 range 0 .. 31; end record; type Elf32_Ph_Entry_Array is array (Natural range <>) of Elf32_Ph_Entry; end Elf;
------------------------------------------------------------------------------ -- Copyright (c) 2006-2013, Maxim Reznik -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the Maxim Reznik, IE 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. ------------------------------------------------------------------------------ package body Asis.Gela.Elements.Def_Names is function New_Defining_Identifier_Node (The_Context : ASIS.Context) return Defining_Identifier_Ptr is Result : Defining_Identifier_Ptr := new Defining_Identifier_Node; begin Set_Enclosing_Compilation_Unit (Result.all, Current_Unit (The_Context.all)); return Result; end New_Defining_Identifier_Node; function Defining_Name_Kind (Element : Defining_Identifier_Node) return Asis.Defining_Name_Kinds is begin return A_Defining_Identifier; end; function Clone (Element : Defining_Identifier_Node; Parent : Asis.Element) return Asis.Element is Result : constant Defining_Identifier_Ptr := new Defining_Identifier_Node; begin Result.Enclosing_Element := Parent; Result.Is_Part_Of_Implicit := Element.Is_Part_Of_Implicit; Result.Is_Part_Of_Inherited := Element.Is_Part_Of_Inherited; Result.Is_Part_Of_Instance := Element.Is_Part_Of_Instance; Result.Start_Position := Element.Start_Position; Result.End_Position := Element.End_Position; Result.Enclosing_Compilation_Unit := Enclosing_Compilation_Unit (Parent.all); Result.Hash := Element.Hash; Result.Defining_Name_Image := Element.Defining_Name_Image; Result.Corresponding_Constant_Declaration := Element.Corresponding_Constant_Declaration; null; Result.Corresponding_Generic_Element := Element.Corresponding_Generic_Element; Result.Override := Element.Override; Result.Place := Element.Place; return Asis.Element (Result); end Clone; function Position_Number_Image (Element : Defining_Enumeration_Literal_Node) return Wide_String is begin return W.To_Wide_String (Element.Position_Number_Image); end Position_Number_Image; procedure Set_Position_Number_Image (Element : in out Defining_Enumeration_Literal_Node; Value : in Wide_String) is begin Element.Position_Number_Image := W.To_Unbounded_Wide_String (Value); end Set_Position_Number_Image; function Representation_Value_Image (Element : Defining_Enumeration_Literal_Node) return Wide_String is begin return W.To_Wide_String (Element.Representation_Value_Image); end Representation_Value_Image; procedure Set_Representation_Value_Image (Element : in out Defining_Enumeration_Literal_Node; Value : in Wide_String) is begin Element.Representation_Value_Image := W.To_Unbounded_Wide_String (Value); end Set_Representation_Value_Image; function New_Defining_Enumeration_Literal_Node (The_Context : ASIS.Context) return Defining_Enumeration_Literal_Ptr is Result : Defining_Enumeration_Literal_Ptr := new Defining_Enumeration_Literal_Node; begin Set_Enclosing_Compilation_Unit (Result.all, Current_Unit (The_Context.all)); return Result; end New_Defining_Enumeration_Literal_Node; function Defining_Name_Kind (Element : Defining_Enumeration_Literal_Node) return Asis.Defining_Name_Kinds is begin return A_Defining_Enumeration_Literal; end; function Clone (Element : Defining_Enumeration_Literal_Node; Parent : Asis.Element) return Asis.Element is Result : constant Defining_Enumeration_Literal_Ptr := new Defining_Enumeration_Literal_Node; begin Result.Enclosing_Element := Parent; Result.Is_Part_Of_Implicit := Element.Is_Part_Of_Implicit; Result.Is_Part_Of_Inherited := Element.Is_Part_Of_Inherited; Result.Is_Part_Of_Instance := Element.Is_Part_Of_Instance; Result.Start_Position := Element.Start_Position; Result.End_Position := Element.End_Position; Result.Enclosing_Compilation_Unit := Enclosing_Compilation_Unit (Parent.all); Result.Hash := Element.Hash; Result.Defining_Name_Image := Element.Defining_Name_Image; Result.Corresponding_Constant_Declaration := Element.Corresponding_Constant_Declaration; null; Result.Corresponding_Generic_Element := Element.Corresponding_Generic_Element; Result.Override := Element.Override; Result.Place := Element.Place; Result.Position_Number_Image := Element.Position_Number_Image; Result.Representation_Value_Image := Element.Representation_Value_Image; return Asis.Element (Result); end Clone; function New_Defining_Character_Literal_Node (The_Context : ASIS.Context) return Defining_Character_Literal_Ptr is Result : Defining_Character_Literal_Ptr := new Defining_Character_Literal_Node; begin Set_Enclosing_Compilation_Unit (Result.all, Current_Unit (The_Context.all)); return Result; end New_Defining_Character_Literal_Node; function Defining_Name_Kind (Element : Defining_Character_Literal_Node) return Asis.Defining_Name_Kinds is begin return A_Defining_Character_Literal; end; function Clone (Element : Defining_Character_Literal_Node; Parent : Asis.Element) return Asis.Element is Result : constant Defining_Character_Literal_Ptr := new Defining_Character_Literal_Node; begin Result.Enclosing_Element := Parent; Result.Is_Part_Of_Implicit := Element.Is_Part_Of_Implicit; Result.Is_Part_Of_Inherited := Element.Is_Part_Of_Inherited; Result.Is_Part_Of_Instance := Element.Is_Part_Of_Instance; Result.Start_Position := Element.Start_Position; Result.End_Position := Element.End_Position; Result.Enclosing_Compilation_Unit := Enclosing_Compilation_Unit (Parent.all); Result.Hash := Element.Hash; Result.Defining_Name_Image := Element.Defining_Name_Image; Result.Corresponding_Constant_Declaration := Element.Corresponding_Constant_Declaration; null; Result.Corresponding_Generic_Element := Element.Corresponding_Generic_Element; Result.Override := Element.Override; Result.Place := Element.Place; Result.Position_Number_Image := Element.Position_Number_Image; Result.Representation_Value_Image := Element.Representation_Value_Image; return Asis.Element (Result); end Clone; function Operator_Kind (Element : Defining_Operator_Symbol_Node) return Asis.Operator_Kinds is begin return Element.Operator_Kind; end Operator_Kind; procedure Set_Operator_Kind (Element : in out Defining_Operator_Symbol_Node; Value : in Asis.Operator_Kinds) is begin Element.Operator_Kind := Value; end Set_Operator_Kind; function New_Defining_Operator_Symbol_Node (The_Context : ASIS.Context) return Defining_Operator_Symbol_Ptr is Result : Defining_Operator_Symbol_Ptr := new Defining_Operator_Symbol_Node; begin Set_Enclosing_Compilation_Unit (Result.all, Current_Unit (The_Context.all)); return Result; end New_Defining_Operator_Symbol_Node; function Defining_Name_Kind (Element : Defining_Operator_Symbol_Node) return Asis.Defining_Name_Kinds is begin return A_Defining_Operator_Symbol; end; function Clone (Element : Defining_Operator_Symbol_Node; Parent : Asis.Element) return Asis.Element is Result : constant Defining_Operator_Symbol_Ptr := new Defining_Operator_Symbol_Node; begin Result.Enclosing_Element := Parent; Result.Is_Part_Of_Implicit := Element.Is_Part_Of_Implicit; Result.Is_Part_Of_Inherited := Element.Is_Part_Of_Inherited; Result.Is_Part_Of_Instance := Element.Is_Part_Of_Instance; Result.Start_Position := Element.Start_Position; Result.End_Position := Element.End_Position; Result.Enclosing_Compilation_Unit := Enclosing_Compilation_Unit (Parent.all); Result.Hash := Element.Hash; Result.Defining_Name_Image := Element.Defining_Name_Image; Result.Corresponding_Constant_Declaration := Element.Corresponding_Constant_Declaration; null; Result.Corresponding_Generic_Element := Element.Corresponding_Generic_Element; Result.Override := Element.Override; Result.Place := Element.Place; Result.Operator_Kind := Element.Operator_Kind; return Asis.Element (Result); end Clone; function Defining_Prefix (Element : Defining_Expanded_Name_Node) return Asis.Name is begin return Element.Defining_Prefix; end Defining_Prefix; procedure Set_Defining_Prefix (Element : in out Defining_Expanded_Name_Node; Value : in Asis.Name) is begin Element.Defining_Prefix := Value; end Set_Defining_Prefix; function Defining_Selector (Element : Defining_Expanded_Name_Node) return Asis.Defining_Name is begin return Element.Defining_Selector; end Defining_Selector; procedure Set_Defining_Selector (Element : in out Defining_Expanded_Name_Node; Value : in Asis.Defining_Name) is begin Element.Defining_Selector := Value; end Set_Defining_Selector; function New_Defining_Expanded_Name_Node (The_Context : ASIS.Context) return Defining_Expanded_Name_Ptr is Result : Defining_Expanded_Name_Ptr := new Defining_Expanded_Name_Node; begin Set_Enclosing_Compilation_Unit (Result.all, Current_Unit (The_Context.all)); return Result; end New_Defining_Expanded_Name_Node; function Defining_Name_Kind (Element : Defining_Expanded_Name_Node) return Asis.Defining_Name_Kinds is begin return A_Defining_Expanded_Name; end; function Children (Element : access Defining_Expanded_Name_Node) return Traverse_List is begin return ((False, Element.Defining_Prefix'Access), (False, Element.Defining_Selector'Access)); end Children; function Clone (Element : Defining_Expanded_Name_Node; Parent : Asis.Element) return Asis.Element is Result : constant Defining_Expanded_Name_Ptr := new Defining_Expanded_Name_Node; begin Result.Enclosing_Element := Parent; Result.Is_Part_Of_Implicit := Element.Is_Part_Of_Implicit; Result.Is_Part_Of_Inherited := Element.Is_Part_Of_Inherited; Result.Is_Part_Of_Instance := Element.Is_Part_Of_Instance; Result.Start_Position := Element.Start_Position; Result.End_Position := Element.End_Position; Result.Enclosing_Compilation_Unit := Enclosing_Compilation_Unit (Parent.all); Result.Hash := Element.Hash; Result.Defining_Name_Image := Element.Defining_Name_Image; Result.Corresponding_Constant_Declaration := Element.Corresponding_Constant_Declaration; null; Result.Corresponding_Generic_Element := Element.Corresponding_Generic_Element; Result.Override := Element.Override; Result.Place := Element.Place; return Asis.Element (Result); end Clone; procedure Copy (Source : in Asis.Element; Target : access Defining_Expanded_Name_Node; Cloner : in Cloner_Class; Parent : in Asis.Element) is begin Target.Defining_Prefix := Copy (Cloner, Defining_Prefix (Source.all), Asis.Element (Target)); Target.Defining_Selector := Copy (Cloner, Defining_Selector (Source.all), Asis.Element (Target)); end Copy; end Asis.Gela.Elements.Def_Names;
package body Flags is procedure Add (Map : in out Map_T; Key : Key_T; Description : Colors.Color_Set_T; Success : out Boolean) is begin Success := False; -- If the key is not already in the map then -- Create a map element and add it to the map end Add; procedure Remove (Map : in out Map_T; Key : Key_T; Success : out Boolean) is begin Success := False; -- Remove the element specified by the key from the map end Remove; procedure Modify (Map : in out Map_T; Key : Key_T; Description : Colors.Color_Set_T; Success : out Boolean) is begin Success := False; -- Update the element at the key location with the new data end Modify; function Exists (Map : Map_T; Key : Key_T) return Boolean is begin -- Return True if the key is in the map return False; end Exists; function Get (Map : Map_T; Key : Key_T) return Map_Element_T is Ret_Val : Map_Element_T; begin -- Return the map element specified by key return Ret_Val; end Get; function Image (Item : Map_Element_T) return String is begin -- return a string representation of the element return ""; end Image; function Image (Flag : Map_T) return String is begin -- return a string representation of the map return ""; end Image; end Flags;
-- ----------------------------------------------------------------- -- -- AdaSDL -- -- Binding to Simple Direct Media Layer -- -- Copyright (C) 2001 A.M.F.Vargas -- -- Antonio M. F. Vargas -- -- Ponta Delgada - Azores - Portugal -- -- http://www.adapower.net/~avargas -- -- E-mail: avargas@adapower.net -- -- ----------------------------------------------------------------- -- -- -- -- This library 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 2 of the License, or (at your option) any later version. -- -- -- -- This library is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- -- General Public License for more details. -- -- -- -- You should have received a copy of the GNU General Public -- -- License along with this library; if not, write to the -- -- Free Software Foundation, Inc., 59 Temple Place - Suite 330, -- -- Boston, MA 02111-1307, USA. -- -- -- -- As a special exception, if other files instantiate generics from -- -- this unit, or you link this unit with other files to produce an -- -- executable, this unit does not by itself cause the resulting -- -- executable to be covered by the GNU General Public License. This -- -- exception does not however invalidate any other reasons why the -- -- executable file might be covered by the GNU Public License. -- -- ----------------------------------------------------------------- -- -- **************************************************************** -- -- This is an Ada binding to SDL ( Simple DirectMedia Layer from -- -- Sam Lantinga - www.libsld.org ) -- -- **************************************************************** -- -- In order to help the Ada programmer, the comments in this file -- -- are, in great extent, a direct copy of the original text in the -- -- SDL header files. -- -- **************************************************************** -- with SDL.Types; use SDL.Types; package SDL.Version is -- Printable format: "%d.%d.%d", MAJOR, MINOR, PATCHLEVEL SDL_MAJOR_VERSION : constant := 1; SDL_MINOR_VERSION : constant := 1; SDL_PATCHLEVEL : constant := 8; type version is record major : Uint8; minor : Uint8; patch : Uint8; end record; pragma Convention (C, version); type version_ptr is access all version; pragma Convention (C, version_ptr); -- This macro can be used to fill a version structure with the compile-time -- version of the SDL library. -- procedure SDL_VERSION (X : version_ptr); -- pragma Inline (SDL_VERSION); procedure SDL_VERSION (X : in out version); pragma Inline (SDL_VERSION); -- This original 'C" macro turns the version numbers into a numeric value: -- (1,2,3) -> (1203) -- This assumes that there will never be more than 100 patchlevels function SDL_VERSIONNUM ( X : Uint8; Y : Uint8; Z : Uint8) return C.int; pragma Inline (SDL_VERSIONNUM); -- This is the version number macro for the current SDL version function SDL_COMPILEDVERSION return C.int; pragma Inline (SDL_COMPILEDVERSION); -- This macro will evaluate to True if compiled with SDL at least X.Y.Z function SDL_VERSION_ATLEAST (X : Uint8; Y : Uint8; Z : Uint8) return Boolean; pragma Inline (SDL_VERSION_ATLEAST); -- This function gets the version of the dynamically linked SDL library. -- it should NOT be used to fill a version structure, instead you should -- use the Version inlined function. function Linked_Version return version_ptr; pragma Import (C, Linked_Version, "SDL_Linked_Version"); end SDL.Version;
----------------------------------------------------------------------- -- tool-data -- Perf data representation -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- 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. ----------------------------------------------------------------------- with Ada.Containers.Vectors; with Ada.Containers.Ordered_Maps; with Ada.Containers.Indefinite_Ordered_Maps; private with Ada.Containers.Indefinite_Vectors; private with Util.Beans.Objects; private with Util.Serialize.Mappers.Record_Mapper; pragma No_Recursion; package Tool.Data is -- Type representing a number of times a benchmark test is executed. type Count_Type is new Natural; -- Type representing the number of rows associated with the benchmark. type Row_Count_Type is new Natural; -- Type representing a driver index. type Driver_Type is new Positive; -- Type representing a language index. type Language_Type is new Positive; -- Type representing a database index. type Database_Type is new Positive; type Driver_Result is record Index : Driver_Type := Driver_Type'First; Language : Language_Type := Language_Type'First; Database : Database_Type := Database_Type'First; Count : Count_Type := 0; Thread_Count : Natural := 0; Rss_Size : Natural := 0; Peek_Rss : Natural := 0; User_Time : Natural := 0; Sys_Time : Natural := 0; end record; type Result_Type is record Count : Count_Type; Time : Duration; end record; package Result_Vectors is new Ada.Containers.Vectors (Index_Type => Driver_Type, Element_Type => Result_Type, "=" => "="); type Perf_Result is record Value : Row_Count_Type := 0; Results : Result_Vectors.Vector; end record; package Perf_Result_Maps is new Ada.Containers.Ordered_Maps (Key_Type => Row_Count_Type, Element_Type => Perf_Result, "<" => "<", "=" => "="); subtype Perf_Map is Perf_Result_Maps.Map; subtype Perf_Cursor is Perf_Result_Maps.Cursor; package Benchmark_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => String, Element_Type => Perf_Map, "<" => "<", "=" => Perf_Result_Maps."="); subtype Benchmark_Map is Benchmark_Maps.Map; subtype Benchmark_Cursor is Benchmark_Maps.Cursor; procedure Read (Path : in String); procedure Save (Path : in String; Databases : in String; Languages : in String) with Pre => Databases'Length > 0 and Languages'Length > 0; procedure Save_Memory (Path : in String; Languages : in String) with Pre => Languages'Length > 0; procedure Save_Excel (Path : in String); private package UBO renames Util.Beans.Objects; package Driver_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => String, Element_Type => Driver_Result, "<" => "<"); subtype Driver_Map is Driver_Maps.Map; subtype Driver_Cursor is Driver_Maps.Cursor; package Language_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Language_Type, Element_Type => String); subtype Language_Vector is Language_Vectors.Vector; subtype Language_Cursor is Language_Vectors.Cursor; package Database_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Database_Type, Element_Type => String); subtype Database_Vector is Database_Vectors.Vector; subtype Database_Cursor is Database_Vectors.Cursor; -- Array of database index. type Database_Array_Index is array (Positive range <>) of Database_Type; -- Array of language index. type Language_Array_Index is array (Positive range <>) of Language_Type; type Benchmark_Fields is (FIELD_DRIVER, FIELD_LANGUAGE, FIELD_THREADS, FIELD_RSS_SIZE, FIELD_PEEK_RSS_SIZE, FIELD_USER_TIME, FIELD_SYS_TIME, FIELD_COUNT, FIELD_TIME, FIELD_TITLE, FIELD_MEASURES, FIELD_TOTAL); type Benchmark_Info is record Drivers : Driver_Map; Databases : Database_Vector; Languages : Language_Vector; Benchmarks : Benchmark_Map; Thread_Count : Natural := 0; Rss_Size : Natural := 0; Peek_Rss_Size : Natural := 0; User_Time : Natural := 0; Sys_Time : Natural := 0; Count : Count_Type := 0; Driver : UBO.Object; Language : UBO.Object; Title : UBO.Object; Time : Duration := 0.0; Driver_Index : Driver_Type := Driver_Type'First; Language_Index : Language_Type; Database_Index : Database_Type; end record; type Benchmark_Info_Access is access all Benchmark_Info; procedure Set_Member (Benchmark : in out Benchmark_Info; Field : in Benchmark_Fields; Value : in UBO.Object); package Benchmark_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Benchmark_Info, Element_Type_Access => Benchmark_Info_Access, Fields => Benchmark_Fields, Set_Member => Set_Member); end Tool.Data;
-- Generated at 2015-02-03 21:39:53 +0000 by Natools.Static_Hash_Maps -- from src/natools-web-error_pages-maps.sx package Natools.Static_Maps.Web.Error_Pages is pragma Pure; type Command is (Unknown_Command, Location, Message, Path, Status_Code); function To_Command (Key : String) return Command; function To_Message (Key : String) return String; private Map_1_Key_0 : aliased constant String := "location"; Map_1_Key_1 : aliased constant String := "message"; Map_1_Key_2 : aliased constant String := "path"; Map_1_Key_3 : aliased constant String := "code"; Map_1_Key_4 : aliased constant String := "status"; Map_1_Key_5 : aliased constant String := "status-code"; Map_1_Keys : constant array (0 .. 5) of access constant String := (Map_1_Key_0'Access, Map_1_Key_1'Access, Map_1_Key_2'Access, Map_1_Key_3'Access, Map_1_Key_4'Access, Map_1_Key_5'Access); Map_1_Elements : constant array (0 .. 5) of Command := (Location, Message, Path, Status_Code, Status_Code, Status_Code); Map_2_Key_0 : aliased constant String := "301"; Map_2_Key_1 : aliased constant String := "303"; Map_2_Key_2 : aliased constant String := "404"; Map_2_Key_3 : aliased constant String := "405"; Map_2_Key_4 : aliased constant String := "410"; Map_2_Keys : constant array (0 .. 4) of access constant String := (Map_2_Key_0'Access, Map_2_Key_1'Access, Map_2_Key_2'Access, Map_2_Key_3'Access, Map_2_Key_4'Access); subtype Map_2_Hash is Natural range 0 .. 4; function Map_2_Elements (Hash : Map_2_Hash) return String; end Natools.Static_Maps.Web.Error_Pages;
-- Copyright (c) 2021 Bartek thindil Jasicki <thindil@laeran.pl> -- -- 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. with Ada.Text_IO; with System; with Tcl.Commands; use Tcl.Commands; package body CalculatorCommands.Unproved with SPARK_Mode => Off is -- ****o* Unproved/Unproved.On_Click -- FUNCTION -- Update display with the pressed button text or count its expression if -- button equal was pressed -- PARAMETERS -- Unused_Client_Data - Optional data passed to the function. -- Interpreter - Tcl interpreter on which the command was invoked. -- Unused_Argc - The amount of arguments passed to the command. -- Argv - The array of arguments passed to the command -- RESULT -- This function always return TCL_OK -- COMMANDS -- OnClick buttonpath displaypath -- Buttonpath is Tk path name for the button which was clicked, displaypath -- is the Tk path name for the calculator display widget -- SOURCE function On_Click (Unused_Client_Data: System.Address; Interpreter: Tcl_Interpreter; Unused_Argc: Positive; Argv: Argv_Pointer.Pointer) return Tcl_Results with Convention => C; -- **** function On_Click (Unused_Client_Data: System.Address; Interpreter: Tcl_Interpreter; Unused_Argc: Positive; Argv: Argv_Pointer.Pointer) return Tcl_Results is begin return Click_Action (Get_Argument(Argv, 1), Get_Argument(Argv, 2), Interpreter); end On_Click; -- ****o* Unproved/Unproved.Clear_Display -- FUNCTION -- Reset the calculator's display to it inital state. Show just zero -- number -- Client_Data - Optional data passed to the function. Unused -- Interpreter - Tcl interpreter on which the command was invoked. -- Argc - The amount of arguments passed to the command. Unused -- Argv - The array of arguments passed to the command -- RESULT -- This function always return TCL_OK -- COMMANDS -- ClearDisplay displaypath -- Displaypath is the Tk path name for the calculator's display widget -- SOURCE function Clear_Display (Client_Data: System.Address; Interpreter: Tcl_Interpreter; Argc: Positive; Argv: Argv_Pointer.Pointer) return Tcl_Results with Convention => C; -- **** function Clear_Display (Client_Data: System.Address; Interpreter: Tcl_Interpreter; Argc: Positive; Argv: Argv_Pointer.Pointer) return Tcl_Results is pragma Unreferenced(Client_Data, Argc); begin return Clear_Action (Get_Argument(Arguments_Pointer => Argv, Index => 1), Interpreter); end Clear_Display; function Add_Commands return Boolean is begin if Tcl_Create_Command("OnClick", On_Click'Access) = Null_Tcl_Command then Ada.Text_IO.Put_Line(Item => "Failed to add OnClick command"); return False; end if; if Tcl_Create_Command("ClearDisplay", Clear_Display'Access) = Null_Tcl_Command then Ada.Text_IO.Put_Line(Item => "Failed to add ClearDisplay command"); return False; end if; return True; end Add_Commands; end CalculatorCommands.Unproved;
-- MIT License -- -- Copyright (c) 2020 Max Reznik -- -- Permission is hereby granted, free of charge, to any person obtaining a -- copy of this software and associated documentation files (the "Software"), -- to deal in the Software without restriction, including without limitation -- the rights to use, copy, modify, merge, publish, distribute, sublicense, -- and/or sell copies of the Software, and to permit persons to whom the -- Software is furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL -- THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. with Ada.Finalization; generic type Element_Type is private; package PB_Support.Vectors is pragma Preelaborate; type Vector is tagged private; pragma Preelaborable_Initialization (Vector); function Length (Self : Vector) return Natural with Inline; function Get (Self : Vector; Index : Positive) return Element_Type with Inline; procedure Clear (Self : in out Vector) with Inline; procedure Append (Self : in out Vector; Value : Element_Type); type Option (Is_Set : Boolean := False) is record case Is_Set is when True => Value : Element_Type; when False => null; end case; end record; private type Element_Array is array (Positive range <>) of Element_Type; type Element_Array_Access is access Element_Array; type Vector is new Ada.Finalization.Controlled with record Data : Element_Array_Access; Length : Natural := 0; end record; overriding procedure Adjust (Self : in out Vector); overriding procedure Finalize (Self : in out Vector); end PB_Support.Vectors;
------------------------------------------------------------------------------ -- Copyright (c) 2016, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ package body Natools.Smaz_Generic.Tools is function Image (B : Boolean) return String; -- Return correctly-cased image of B ------------------------------ -- Local Helper Subprograms -- ------------------------------ function Image (B : Boolean) return String is begin if B then return "True"; else return "False"; end if; end Image; ---------------------- -- Public Interface -- ---------------------- function Append_String (Dict : in Dictionary; Value : in String) return Dictionary is begin return Dictionary' (Last_Code => Dictionary_Code'Succ (Dict.Last_Code), Values_Last => Dict.Values_Last + Value'Length, Variable_Length_Verbatim => Dict.Variable_Length_Verbatim, Max_Word_Length => Positive'Max (Dict.Max_Word_Length, Value'Length), Offsets => Dict.Offsets & (Dictionary_Code'First => Dict.Values_Last + 1), Values => Dict.Values & Value, Hash => Smaz_Tools.Dummy_Hash'Access); end Append_String; procedure Print_Dictionary_In_Ada (Dict : in Dictionary; Hash_Image : in String := "TODO"; Max_Width : in Positive := 70; First_Prefix : in String := " := ("; Prefix : in String := " "; Half_Indent : in String := " ") is procedure Append_Entity (Buffer : in out String; Last : in out Natural; Entity : in String); function Double_Quote (S : String; Count : Natural) return String; function Offsets_Suffix (I : Dictionary_Code) return String; function Strip_Image (S : String) return String; function Values_Separator (I : Positive) return String; procedure Append_Entity (Buffer : in out String; Last : in out Natural; Entity : in String) is begin if Last + 1 + Entity'Length <= Buffer'Last then Buffer (Last + 1) := ' '; Buffer (Last + 2 .. Last + 1 + Entity'Length) := Entity; Last := Last + 1 + Entity'Length; else Put_Line (Buffer (Buffer'First .. Last)); Last := Buffer'First + Prefix'Length - 1; Buffer (Last + 1 .. Last + Half_Indent'Length) := Half_Indent; Last := Last + Half_Indent'Length; Buffer (Last + 1 .. Last + Entity'Length) := Entity; Last := Last + Entity'Length; end if; end Append_Entity; function Double_Quote (S : String; Count : Natural) return String is begin if Count = 0 then return S; else return Quoted : String (1 .. S'Length + Count) do declare O : Positive := Quoted'First; begin for I in S'Range loop Quoted (O) := S (I); O := O + 1; if S (I) = '"' then Quoted (O) := S (I); O := O + 1; end if; end loop; end; end return; end if; end Double_Quote; function Offsets_Suffix (I : Dictionary_Code) return String is begin if I < Dict.Offsets'Last then return ","; else return "),"; end if; end Offsets_Suffix; function Strip_Image (S : String) return String is begin if S'Length > 0 and then S (S'First) = ' ' then return S (S'First + 1 .. S'Last); else return S; end if; end Strip_Image; function Values_Separator (I : Positive) return String is begin if I > Dict.Values'First then return "& "; else return ""; end if; end Values_Separator; Line_Buffer : String (1 .. Max_Width + Prefix'Length); Buffer_Last : Natural; begin Put_Line (First_Prefix & "Last_Code =>" & Dictionary_Code'Image (Dict.Last_Code) & ','); Put_Line (Prefix & "Values_Last =>" & Natural'Image (Dict.Values_Last) & ','); Put_Line (Prefix & "Variable_Length_Verbatim => " & Image (Dict.Variable_Length_Verbatim) & ','); Put_Line (Prefix & "Max_Word_Length =>" & Natural'Image (Dict.Max_Word_Length) & ','); Line_Buffer (1 .. Prefix'Length) := Prefix; Line_Buffer (Prefix'Length + 1 .. Prefix'Length + 11) := "Offsets => "; Buffer_Last := Prefix'Length + 11; for I in Dict.Offsets'Range loop Append_Entity (Line_Buffer, Buffer_Last, Strip_Image (Positive'Image (Dict.Offsets (I)) & Offsets_Suffix (I))); if I = Dict.Offsets'First then Line_Buffer (Prefix'Length + 12) := '('; end if; end loop; Put_Line (Line_Buffer (Line_Buffer'First .. Buffer_Last)); Line_Buffer (Prefix'Length + 1 .. Prefix'Length + 9) := "Values =>"; Buffer_Last := Prefix'Length + 9; declare I : Positive := Dict.Values'First; First, Last : Positive; Quote_Count : Natural; begin Values_Loop : while I <= Dict.Values'Last loop Add_Unprintable : while Dict.Values (I) not in ' ' .. '~' loop Append_Entity (Line_Buffer, Buffer_Last, Values_Separator (I) & Character'Image (Dict.Values (I))); I := I + 1; exit Values_Loop when I > Dict.Values'Last; end loop Add_Unprintable; First := I; Quote_Count := 0; Find_Printable_Substring : loop if Dict.Values (I) = '"' then Quote_Count := Quote_Count + 1; end if; I := I + 1; exit Find_Printable_Substring when I > Dict.Values'Last or else Dict.Values (I) not in ' ' .. '~'; end loop Find_Printable_Substring; Last := I - 1; Split_Lines : loop declare Partial_Quote_Count : Natural := 0; Partial_Width : Natural := 0; Partial_Last : Natural := First - 1; Sep : constant String := Values_Separator (First); Available_Length : constant Natural := (if Line_Buffer'Last > Buffer_Last + Sep'Length + 4 then Line_Buffer'Last - Buffer_Last - Sep'Length - 4 else Line_Buffer'Length - Prefix'Length - Half_Indent'Length - Sep'Length - 3); begin if 1 + Last - First + Quote_Count < Available_Length then Append_Entity (Line_Buffer, Buffer_Last, Sep & '"' & Double_Quote (Dict.Values (First .. Last), Quote_Count) & '"'); exit Split_Lines; else Count_Quotes : loop if Dict.Values (Partial_Last + 1) = '"' then exit Count_Quotes when Partial_Width + 2 > Available_Length; Partial_Width := Partial_Width + 1; Partial_Quote_Count := Partial_Quote_Count + 1; else exit Count_Quotes when Partial_Width + 1 > Available_Length; end if; Partial_Width := Partial_Width + 1; Partial_Last := Partial_Last + 1; end loop Count_Quotes; Append_Entity (Line_Buffer, Buffer_Last, Sep & '"' & Double_Quote (Dict.Values (First .. Partial_Last), Partial_Quote_Count) & '"'); First := Partial_Last + 1; Quote_Count := Quote_Count - Partial_Quote_Count; end if; end; end loop Split_Lines; end loop Values_Loop; Put_Line (Line_Buffer (Line_Buffer'First .. Buffer_Last) & ','); end; Line_Buffer (Prefix'Length + 1 .. Prefix'Length + 7) := "Hash =>"; Buffer_Last := Prefix'Length + 7; Append_Entity (Line_Buffer, Buffer_Last, Hash_Image & ");"); Put_Line (Line_Buffer (Line_Buffer'First .. Buffer_Last)); end Print_Dictionary_In_Ada; function Remove_Element (Dict : in Dictionary; Index : in Dictionary_Code) return Dictionary is Removed_Length : constant Positive := Dict_Entry_Length (Dict, Index); function New_Offsets return Offset_Array; function New_Values return String; function New_Offsets return Offset_Array is Result : Offset_Array (Dict.Offsets'First .. Dictionary_Code'Pred (Dict.Last_Code)); begin for I in Result'Range loop if I < Index then Result (I) := Dict.Offsets (I); else Result (I) := Dict.Offsets (Dictionary_Code'Succ (I)) - Removed_Length; end if; end loop; return Result; end New_Offsets; function New_Values return String is begin if Index = Dictionary_Code'First then return Dict.Values (Dict.Offsets (Dictionary_Code'Succ (Index)) .. Dict.Values'Last); elsif Index < Dict.Last_Code then return Dict.Values (1 .. Dict.Offsets (Index) - 1) & Dict.Values (Dict.Offsets (Dictionary_Code'Succ (Index)) .. Dict.Values'Last); else return Dict.Values (1 .. Dict.Offsets (Index) - 1); end if; end New_Values; New_Max_Word_Length : Positive := Dict.Max_Word_Length; begin if Removed_Length = Dict.Max_Word_Length then New_Max_Word_Length := 1; for I in Dict.Offsets'Range loop if I /= Index and then Dict_Entry_Length (Dict, I) > New_Max_Word_Length then New_Max_Word_Length := Dict_Entry_Length (Dict, I); end if; end loop; end if; return Dictionary' (Last_Code => Dictionary_Code'Pred (Dict.Last_Code), Values_Last => Dict.Values_Last - Removed_Length, Variable_Length_Verbatim => Dict.Variable_Length_Verbatim, Max_Word_Length => New_Max_Word_Length, Offsets => New_Offsets, Values => New_Values, Hash => Smaz_Tools.Dummy_Hash'Access); end Remove_Element; function Replace_Element (Dict : in Dictionary; Index : in Dictionary_Code; Value : in String) return Dictionary is Removed_Length : constant Positive := Dict_Entry_Length (Dict, Index); Length_Delta : constant Integer := Value'Length - Removed_Length; function New_Offsets return Offset_Array; function New_Values return String; function New_Offsets return Offset_Array is Result : Offset_Array (Dict.Offsets'First .. Dict.Last_Code); begin for I in Result'Range loop if I <= Index then Result (I) := Dict.Offsets (I); else Result (I) := Dict.Offsets (I) + Length_Delta; end if; end loop; return Result; end New_Offsets; function New_Values return String is begin if Index = Dictionary_Code'First then return Value & Dict.Values (Dict.Offsets (Dictionary_Code'Succ (Index)) .. Dict.Values'Last); elsif Index < Dict.Last_Code then return Dict.Values (1 .. Dict.Offsets (Index) - 1) & Value & Dict.Values (Dict.Offsets (Dictionary_Code'Succ (Index)) .. Dict.Values'Last); else return Dict.Values (1 .. Dict.Offsets (Index) - 1) & Value; end if; end New_Values; New_Max_Word_Length : Positive := Dict.Max_Word_Length; begin if Removed_Length = Dict.Max_Word_Length then New_Max_Word_Length := 1; for I in Dict.Offsets'Range loop if I /= Index and then Dict_Entry_Length (Dict, I) > New_Max_Word_Length then New_Max_Word_Length := Dict_Entry_Length (Dict, I); end if; end loop; end if; if New_Max_Word_Length < Value'Length then New_Max_Word_Length := Value'Length; end if; return Dictionary' (Last_Code => Dict.Last_Code, Values_Last => Dict.Values_Last + Length_Delta, Variable_Length_Verbatim => Dict.Variable_Length_Verbatim, Max_Word_Length => New_Max_Word_Length, Offsets => New_Offsets, Values => New_Values, Hash => Smaz_Tools.Dummy_Hash'Access); end Replace_Element; function To_Dictionary (List : in String_Lists.List; Variable_Length_Verbatim : in Boolean) return Dictionary is Code_After_Last : Dictionary_Code := Dictionary_Code'First; String_Size : Natural := 0; Max_Word_Length : Positive := 1; begin for S of List loop Code_After_Last := Dictionary_Code'Succ (Code_After_Last); String_Size := String_Size + S'Length; if S'Length > Max_Word_Length then Max_Word_Length := S'Length; end if; end loop; declare Last_Code : constant Dictionary_Code := Dictionary_Code'Pred (Code_After_Last); Offsets : Offset_Array (Dictionary_Code'Succ (Dictionary_Code'First) .. Last_Code); Values : String (1 .. String_Size); Current_Offset : Positive := 1; Current_Index : Dictionary_Code := Dictionary_Code'First; Next_Offset : Positive; begin for S of List loop if Current_Index in Offsets'Range then Offsets (Current_Index) := Current_Offset; end if; Next_Offset := Current_Offset + S'Length; Values (Current_Offset .. Next_Offset - 1) := S; Current_Offset := Next_Offset; Current_Index := Dictionary_Code'Succ (Current_Index); end loop; pragma Assert (Current_Index = Code_After_Last); pragma Assert (Current_Offset = String_Size + 1); return (Last_Code => Last_Code, Values_Last => String_Size, Variable_Length_Verbatim => Variable_Length_Verbatim, Max_Word_Length => Max_Word_Length, Offsets => Offsets, Values => Values, Hash => Smaz_Tools.Dummy_Hash'Access); end; end To_Dictionary; function To_String_List (Dict : in Dictionary) return String_Lists.List is Result : String_Lists.List; begin for Code in Dictionary_Code'First .. Dict.Last_Code loop String_Lists.Append (Result, Dict_Entry (Dict, Code)); end loop; return Result; end To_String_List; --------------------------- -- Dictionary Evaluation -- --------------------------- procedure Evaluate_Dictionary (Dict : in Dictionary; Corpus : in String_Lists.List; Compressed_Size : out Ada.Streams.Stream_Element_Count; Counts : out Dictionary_Counts) is begin Compressed_Size := 0; Counts := (others => 0); for S of Corpus loop Evaluate_Dictionary_Partial (Dict, S, Compressed_Size, Counts); end loop; end Evaluate_Dictionary; procedure Evaluate_Dictionary_Partial (Dict : in Dictionary; Corpus_Entry : in String; Compressed_Size : in out Ada.Streams.Stream_Element_Count; Counts : in out Dictionary_Counts) is use type Ada.Streams.Stream_Element_Offset; use type Smaz_Tools.String_Count; Verbatim_Length : Natural; Code : Dictionary_Code; Compressed : constant Ada.Streams.Stream_Element_Array := Compress (Dict, Corpus_Entry); Index : Ada.Streams.Stream_Element_Offset := Compressed'First; begin Compressed_Size := Compressed_Size + Compressed'Length; while Index in Compressed'Range loop Read_Code (Compressed, Index, Code, Verbatim_Length, Dict.Last_Code, Dict.Variable_Length_Verbatim); if Verbatim_Length > 0 then Skip_Verbatim (Compressed, Index, Verbatim_Length); else Counts (Code) := Counts (Code) + 1; end if; end loop; end Evaluate_Dictionary_Partial; function Worst_Index (Dict : in Dictionary; Counts : in Dictionary_Counts; Method : in Smaz_Tools.Methods.Enum; First, Last : in Dictionary_Code) return Dictionary_Code is use type Smaz_Tools.Score_Value; Result : Dictionary_Code := First; Worst_Score : Smaz_Tools.Score_Value := Score (Dict, Counts, Result, Method); S : Smaz_Tools.Score_Value; begin for I in Dictionary_Code'Succ (First) .. Last loop S := Score (Dict, Counts, I, Method); if S < Worst_Score then Result := I; Worst_Score := S; end if; end loop; return Result; end Worst_Index; end Natools.Smaz_Generic.Tools;
generic type Element_Type is private; type Index is (<>); type Collection is array(Index) of Element_Type; with function "<=" (Left, Right : Element_Type) return Boolean is <>; procedure Gnome_Sort(Item : in out Collection);
-- ___ _ ___ _ _ -- -- / __| |/ (_) | | Common SKilL implementation -- -- \__ \ ' <| | | |__ API types for skill types -- -- |___/_|\_\_|_|____| by: Timm Felden, Dennis Przytarski -- -- -- pragma Ada_2012; with Interfaces; package body Skill.Types.Iterators is function New_Array (Data : Array_Iterator_T_Array) return Iterator is (new Array_Iterator_T'(Data, Data'First, Data'Last)); function New_Array (Data : Array_Iterator_T_Array; First : Index_Type; Last : Index_Type) return Iterator is (new Array_Iterator_T'(Data, First, Last)); function Next (This : access Array_Iterator_T) return T is R : T := This.Data (This.Position); begin This.Position := This.Position + 1; return R; end Next; function Has_Next (This : access Array_Iterator_T) return Boolean is (This.Position < This.Last); The_Empty_Iterator : Iterator := new Empty_Iterator_T; function New_Empty return Iterator is (The_Empty_Iterator); end Skill.Types.Iterators;
package Web.HTML is -- input function Checkbox_Value (S : String) return Boolean; -- output type HTML_Version is (HTML, XHTML); generic with procedure Write (Item : in String); Version : in HTML_Version; procedure Generic_Write_In_HTML ( Item : in String; Pre : in Boolean := False); procedure Write_In_HTML ( Stream : not null access Ada.Streams.Root_Stream_Type'Class; Version : in HTML_Version; Item : in String; Pre : in Boolean := False); generic with procedure Write (Item : in String); procedure Generic_Write_Begin_Attribute (Name : in String); procedure Write_Begin_Attribute ( Stream : not null access Ada.Streams.Root_Stream_Type'Class; Name : in String); generic with procedure Write (Item : in String); Version : in HTML_Version; procedure Generic_Write_In_Attribute (Item : in String); procedure Write_In_Attribute ( Stream : not null access Ada.Streams.Root_Stream_Type'Class; Version : in HTML_Version; Item : in String); generic with procedure Write (Item : in String); procedure Generic_Write_End_Attribute; procedure Write_End_Attribute ( Stream : not null access Ada.Streams.Root_Stream_Type'Class); -- write <input type="hidden" name="KEY" value="ELEMENT">... generic with procedure Write (Item : in String); Version : in HTML_Version; procedure Generic_Write_Query_In_HTML (Item : in Query_Strings); procedure Write_Query_In_HTML ( Stream : not null access Ada.Streams.Root_Stream_Type'Class; Version : in HTML_Version; Item : in Query_Strings); -- write ?KEY=ELEMENT&... generic with procedure Write (Item : in String); Version : in HTML_Version; procedure Generic_Write_Query_In_Attribute (Item : in Query_Strings); procedure Write_Query_In_Attribute ( Stream : not null access Ada.Streams.Root_Stream_Type'Class; Version : in HTML_Version; Item : in Query_Strings); end Web.HTML;
pragma SPARK_Mode(ON); with Types; use Types; package gpsModule with SPARK_Mode is Top_Left : constant Types.Point := (667271.0, 6398091.0, 0.0); Bottom_Right : constant Types.Point := (677862.0, 6397724.0, 0.0); function gpstest(Position : Types.Point) return Boolean with Post => (if Gpstest'Result then (Position.X > Top_Left.X and Position.Y < Top_Left.Y and Position.X < Bottom_Right.X and Position.Y > Bottom_Right.Y)) and (if not Gpstest'Result then not (Position.X > Top_Left.X and Position.Y < Top_Left.Y and Position.X < Bottom_Right.X and Position.Y > Bottom_Right.Y)), Global => null; end gpsModule;
with Interfaces; with kv.avm.Actor_References; with kv.avm.Tuples; with kv.avm.Registers; with kv.avm.Messages; package kv.avm.Control is NO_FUTURE : constant Interfaces.Unsigned_32 := 0; type Status_Type is (Active, Blocked, Deferred, Idle, Error); subtype Running_Status_Type is Status_Type range Active .. Deferred; type Control_Interface is interface; type Control_Access is access all Control_Interface'CLASS; procedure New_Actor (Self : in out Control_Interface; Name : in String; Instance : out kv.avm.Actor_References.Actor_Reference_Type) is abstract; procedure Post_Message (Self : in out Control_Interface; Message : in kv.avm.Messages.Message_Type; Status : out Status_Type) is abstract; procedure Post_Response (Self : in out Control_Interface; Reply_To : in kv.avm.Actor_References.Actor_Reference_Type; Answer : in kv.avm.Tuples.Tuple_Type; Future : in Interfaces.Unsigned_32) is abstract; procedure Generate_Next_Future (Self : in out Control_Interface; Future : out Interfaces.Unsigned_32) is abstract; procedure Trap_To_The_Machine (Self : in out Control_Interface; Trap : in String; Data : in kv.avm.Registers.Register_Type; Answer : out kv.avm.Registers.Register_Type; Status : out Status_Type) is abstract; procedure Activate_Instance (Self : in out Control_Interface; Instance : in kv.avm.Actor_References.Actor_Reference_Type) is abstract; end kv.avm.Control;
-- WORDS, a Latin dictionary, by Colonel William Whitaker (USAF, Retired) -- -- Copyright William A. Whitaker (1936–2010) -- -- This is a free program, which means it is proper to copy it and pass -- it on to your friends. Consider it a developmental item for which -- there is no charge. However, just for form, it is Copyrighted -- (c). Permission is hereby freely given for any and all use of program -- and data. You can sell it as your own, but at least tell me. -- -- This version is distributed without obligation, but the developer -- would appreciate comments and suggestions. -- -- All parts of the WORDS system, source code and data files, are made freely -- available to anyone who wishes to use them, for whatever purpose. with Text_IO; with Latin_Utils.Strings_Package; use Latin_Utils.Strings_Package; with Latin_Utils.Latin_File_Names; use Latin_Utils.Latin_File_Names; with Latin_Utils.Inflections_Package; use Latin_Utils.Inflections_Package; with Latin_Utils.Dictionary_Package; use Latin_Utils.Dictionary_Package; -- with Support_Utils.Line_Stuff; use Support_Utils.Line_Stuff; procedure Dictflag is package Integer_IO is new Text_IO.Integer_IO (Integer); use Text_IO; use Dictionary_Entry_IO; use Part_Entry_IO; use Kind_Entry_IO; use Translation_Record_IO; use Age_Type_IO; use Area_Type_IO; use Geo_Type_IO; use Frequency_Type_IO; use Source_Type_IO; use Dict_IO; --be_ve : Verb_Entry := (Con => (5, 1), Kind => To_Be); D_K : Dictionary_Kind := Xxx; -- ###################### Start_Stem_1 : constant := 1; Start_Stem_2 : constant := Start_Stem_1 + Max_Stem_Size + 1; Start_Stem_3 : constant := Start_Stem_2 + Max_Stem_Size + 1; Start_Stem_4 : constant := Start_Stem_3 + Max_Stem_Size + 1; Start_Part : constant := Start_Stem_4 + Max_Stem_Size + 1; --start_tran : constant Integer := -- start_part + -- Integer (Part_Entry_IO.Default_Width + 1); --finish_line : constant Integer := -- start_tran + -- Translation_Record_IO.Default_Width - 1; Age_Array : array (Age_Type'Range) of Integer := (others => 0); Area_Array : array (Area_Type'Range) of Integer := (others => 0); Geo_Array : array (Geo_Type'Range) of Integer := (others => 0); Freq_Array : array (Frequency_Type'Range) of Integer := (others => 0); Source_Array : array (Source_Type'Range) of Integer := (others => 0); -- dictfile : Dict_IO.File_Type; Input, Output : Text_IO.File_Type; De : Dictionary_Entry; S, Line : String (1 .. 400) := (others => ' '); Blank_Line : constant String (1 .. 400) := (others => ' '); L, Last : Integer := 0; J : Dict_IO.Count := 0; --mean_to_be : constant Meaning_Type := -- Head ("to be, exist; also used to form verb perfect passive tenses" & -- " with NOM PERF PPL", Max_Meaning_Size); -- mean_to_be unreferenced - perhaps it was not meant to be... begin Put_Line ( "Takes a DICTLINE.D_K and produces a numeration of FLAGS"); Put ("What dictionary to list, GENERAL or SPECIAL =>"); Get_Line (Line, Last); if Last > 0 then if Trim (Line (1 .. Last))(1) = 'G' or else Trim (Line (1 .. Last))(1) = 'g' then D_K := General; elsif Trim (Line (1 .. Last))(1) = 'S' or else Trim (Line (1 .. Last))(1) = 's' then D_K := Special; else Put_Line ("No such dictionary"); raise Text_IO.Data_Error; end if; end if; Open (Input, In_File, Dict_Line_Name & '.' & Ext (D_K)); Create (Output, Out_File, "FLAGS." & Ext (D_K)); while not End_Of_File (Input) loop S := Blank_Line; Get_Line (Input, S, Last); if Trim (S (1 .. Last)) /= "" then L := 0; Form_De : begin De.Stems (1) := S (Start_Stem_1 .. Max_Stem_Size); --NEW_LINE; PUT (DE.STEMS (1)); De.Stems (2) := S (Start_Stem_2 .. Start_Stem_2 + Max_Stem_Size - 1); De.Stems (3) := S (Start_Stem_3 .. Start_Stem_3 + Max_Stem_Size - 1); De.Stems (4) := S (Start_Stem_4 .. Start_Stem_4 + Max_Stem_Size - 1); --PUT ('#'); PUT (INTEGER'IMAGE (L)); PUT (INTEGER'IMAGE (LAST)); --PUT ('@'); Get (S (Start_Part .. Last), De.Part, L); --PUT ('%'); PUT (INTEGER'IMAGE (L)); PUT (INTEGER'IMAGE (LAST)); --PUT ('&'); PUT (S (L+1 .. LAST)); PUT ('3'); -- GET (S (L+1 .. LAST), DE.PART.POFS, DE.KIND, L); Get (S (L + 1 .. Last), De.Tran.Age, L); Age_Array (De.Tran.Age) := Age_Array (De.Tran.Age) + 1; Get (S (L + 1 .. Last), De.Tran.Area, L); Area_Array (De.Tran.Area) := Area_Array (De.Tran.Area) + 1; Get (S (L + 1 .. Last), De.Tran.Geo, L); Geo_Array (De.Tran.Geo) := Geo_Array (De.Tran.Geo) + 1; Get (S (L + 1 .. Last), De.Tran.Freq, L); Freq_Array (De.Tran.Freq) := Freq_Array (De.Tran.Freq) + 1; Get (S (L + 1 .. Last), De.Tran.Source, L); Source_Array (De.Tran.Source) := Source_Array (De.Tran.Source) + 1; De.Mean := Head (S (L + 2 .. Last), Max_Meaning_Size); -- Note that this allows initial blanks -- L+2 skips over the SPACER, required because this is STRING, -- not ENUM exception when others => New_Line; Put_Line ("Exception"); Put_Line (S (1 .. Last)); Integer_IO.Put (Integer (J)); New_Line; Put (De); New_Line; end Form_De; J := J + 1; end if; end loop; Text_IO.Put (Output, "Number of lines in DICTLINE " & Ext (D_K) & " "); Integer_IO.Put (Output, Integer (J)); Text_IO.New_Line (Output); Text_IO.New_Line (Output, 4); Text_IO.Put_Line (Output, "AGE"); for I in Age_Type'Range loop Text_IO.Put (Output, Age_Type'Image (I)); Text_IO.Set_Col (Output, 10); Text_IO.Put_Line (Output, Integer'Image (Age_Array (I))); end loop; Text_IO.New_Line (Output, 4); Text_IO.Put_Line (Output, "AREA"); for I in Area_Type'Range loop Text_IO.Put (Output, Area_Type'Image (I)); Text_IO.Set_Col (Output, 10); Text_IO.Put_Line (Output, Integer'Image (Area_Array (I))); end loop; Text_IO.New_Line (Output, 4); Text_IO.Put_Line (Output, "GEO"); for I in Geo_Type'Range loop Text_IO.Put (Output, Geo_Type'Image (I)); Text_IO.Set_Col (Output, 10); Text_IO.Put_Line (Output, Integer'Image (Geo_Array (I))); end loop; Text_IO.New_Line (Output, 4); Text_IO.Put_Line (Output, "FREQ"); for I in Frequency_Type'Range loop Text_IO.Put (Output, Frequency_Type'Image (I)); Text_IO.Set_Col (Output, 10); Text_IO.Put_Line (Output, Integer'Image (Freq_Array (I))); end loop; Text_IO.New_Line (Output, 4); Text_IO.Put_Line (Output, "SOURCE"); for I in Source_Type'Range loop Text_IO.Put (Output, Source_Type'Image (I)); Text_IO.Set_Col (Output, 10); Text_IO.Put_Line (Output, Integer'Image (Source_Array (I))); end loop; Close (Output); exception when Text_IO.Data_Error => null; when others => Put_Line (S (1 .. Last)); Integer_IO.Put (Integer (J)); New_Line; Close (Output); end Dictflag;
pragma License (Unrestricted); -- extended unit specialized for POSIX (Darwin, FreeBSD, or Linux) package Ada.Text_IO.Terminal.Colors.Names is -- Constants for system-specific system colors. Black : constant Color; -- (R => 0.0, G => 0.0, B => 0.0) Dark_Red : constant Color; -- (R => 0.75, G => 0.0, B => 0.0) Dark_Green : constant Color; -- (R => 0.0, G => 0.75, B => 0.0) Dark_Yellow : constant Color; -- (R => 0.75, G => 0.75, B => 0.0) Dark_Blue : constant Color; -- (R => 0.0, G => 0.0, B => 0.75) Dark_Magenta : constant Color; -- (R => 0.75, G => 0.0, B => 0.75) Dark_Cyan : constant Color; -- (R => 0.0, G => 0.75, B => 0.75) Gray : constant Color; -- (R => 0.75, G => 0.75, B => 0.75) Dark_Gray : constant Color; -- (R => 0.5, G => 0.5, B => 0.5) Red : constant Color; -- (R => 1.0, G => 0.5, B => 0.5) Green : constant Color; -- (R => 0.5, G => 1.0, B => 0.5) Yellow : constant Color; -- (R => 1.0, G => 1.0, B => 0.5) Blue : constant Color; -- (R => 0.5, G => 0.5, B => 1.0) Magenta : constant Color; -- (R => 1.0, G => 0.5, B => 1.0) Cyan : constant Color; -- (R => 0.5, G => 1.0, B => 1.0) White : constant Color; -- (R => 1.0, G => 1.0, B => 1.0) private Black : constant Color := 0; Dark_Red : constant Color := 1; Dark_Green : constant Color := 2; Dark_Yellow : constant Color := 3; Dark_Blue : constant Color := 4; Dark_Magenta : constant Color := 5; Dark_Cyan : constant Color := 6; Gray : constant Color := 7; Dark_Gray : constant Color := 8; Red : constant Color := 9; Green : constant Color := 10; Yellow : constant Color := 11; Blue : constant Color := 12; Magenta : constant Color := 13; Cyan : constant Color := 14; White : constant Color := 15; end Ada.Text_IO.Terminal.Colors.Names;
with Golub_SVD; with Rectangular_Test_Matrices; with Ada.Text_IO; use Ada.Text_IO; -- Demonstrates use of SVD when No_of_Rows > No_of_Cols. -- So you have more equations than unknowns in equation solving. -- (Can't have No_of_Rows < No_of_Cols.) procedure golub_svd_tst_2 is type Real is digits 15; Start : constant := 1; Limit_r : constant := 222; Limit_c : constant := 100; -- You can make them different types if you want: type Row_Index is new Integer range Start .. Limit_r; type Col_Index is new Integer range Start .. Limit_c; --subtype Row_Index is Integer range Start .. Limit_r; --subtype Col_Index is Integer range Start .. Limit_c; type A_Matrix is array (Row_Index, Col_Index) of Real; pragma Convention (Fortran, A_Matrix); package lin_svd is new golub_svd (Real, Row_Index, Col_Index, A_Matrix); use lin_svd; package Rect_Matrix is new Rectangular_Test_Matrices(Real, Row_Index, Col_Index, A_Matrix); use Rect_Matrix; package rio is new Ada.Text_IO.Float_IO(Real); use rio; Final_Row : constant Row_Index := Row_Index'Last - 3; Final_Col : constant Col_Index := Col_Index'Last - 3; Starting_Col : constant Col_Index := Col_Index'First + 2; Starting_Row : constant Row_Index := Row_Index (Starting_Col);-- requirement of SVD A0, A, SVD_Product : A_Matrix := (others => (others => 0.0)); V : V_Matrix; VV_Product : V_Matrix; U : U_Matrix; UU_Product : U_matrix; Singular_Vals : Singular_Vector := (others => 0.0); Col_id_of_1st_Good_S_Val : Col_Index; Max_Singular_Val, Sum, Error_Off_Diag, Error_Diag, Del : Real; begin new_line(1); new_line; put ("Error in the singular value decomposition is estimated by finding"); new_line; put ("The max element of A - U*W*V', and dividing it by the largest"); new_line; put ("singular value of A. Should be somewhere around Real'Epsilon"); new_line; put ("in magnitude if all goes well."); new_line(1); new_line; put ("Error in the calculation of V is estimated by finding the max element"); new_line; put ("of I - V'*V = I - Transpose(V)*V"); new_line; put ("I - V'*V should be near Real'Epsilon."); new_line(1); new_line; put ("Error in the calculation of U is estimated by finding the max element"); new_line; put ("of I - U'*U = I - Transpose(U)*U"); new_line; put ("I - U'*U should be near Real'Epsilon."); new_line(1); new_line; put ("Notice that U'U = I implies A'A = VW'U'UWV' = VEV' where E is a"); new_line; put ("diagonal matrix (E = W'W) containing the squares of the singular"); new_line; put ("values. So U'U = I and V'V = I imply that the cols of V are the "); new_line; put ("eigvectors of A'A. (Multiply the above equality by V to get A'AV = VE.)"); new_line(1); for Chosen_Matrix in Matrix_id loop Init_Matrix (A, Chosen_Matrix); -- Get A = U * W * V' where W is diagonal containing the singular vals for i in 1..1 loop A0 := A; SVD_Decompose (A => A0, U => U, V => V, S => Singular_Vals, Id_of_1st_S_Val => Col_id_of_1st_Good_S_Val, Starting_Col => Starting_Col, Final_Col => Final_Col, Final_Row => Final_Row, Matrix_U_Desired => True, Matrix_V_Desired => True); end loop; new_line(2); put ("Testing SVD on matrix A of type: "); put (Matrix_id'Image(Chosen_Matrix)); if Col_id_of_1st_good_S_Val /= Starting_Col then new_line; put ("QR failed to fully converge at column = "); put(Col_Index'Image(Col_id_of_1st_good_S_Val)); new_line; else new_line; put ("Max Singular Val = "); put(Real'Image(Singular_Vals(Col_id_of_1st_good_S_Val))); end if; Max_Singular_Val := Singular_Vals(Col_id_of_1st_good_S_Val); Max_Singular_Val := Abs Max_Singular_Val + 2.0**(Real'Machine_Emin + 4*Real'Digits); --new_line; --for i in Singular_Vals'Range loop --put (Singular_Vals(i)); --end loop; --new_line(1); --new_line; put ("Singular_Vals printed above."); -- Get Product = V' * V = transpose(V) * V for i in Col_Index range Starting_Col .. Final_Col loop for j in Col_Index range Starting_Col .. Final_Col loop Sum := 0.0; for k in Col_Index range Starting_Col .. Final_Col loop Sum := Sum + V(k, i) * V(k, j); end loop; VV_Product(i,j) := Sum; end loop; end loop; -- Product - I = 0? Error_Diag := 0.0; Error_Off_Diag := 0.0; for i in Col_Index range Starting_Col .. Final_Col loop for j in Col_Index range Starting_Col .. Final_Col loop if i = j then Del := Abs (1.0 - VV_Product(i,j)); if Del > Error_Diag then Error_Diag := Del; end if; else Del := Abs (0.0 - VV_Product(i,j)); if Del > Error_Off_Diag then Error_Off_Diag := Del; end if; end if; end loop; end loop; new_line; put ("Max err in I - V'*V, On_Diagonal ="); put (Error_Diag); new_line; put ("Max err in I - V'*V, Off_Diagonal ="); put (Error_Off_Diag); -- Get Product = U * W * V' = U * W * transpose(V) -- U is usually Row_Index x Row_Index but can probably use Col_Index for its 2nd -- V is Col_Index x Col_Index -- -- S is conceptually Row_Index x Col_Index, with the Sing_Vals on its diagonal, -- but its really in a vector on Col_Index. -- -- So the No_of_Singular vals is MIN of No_of_Rows, No_Of_Cols -- Singular vals are sorted so that largest are at beginning of Singular_Vals(k). -- -- Get matrix product S * V'; place in matrix V': for k in Col_Index range Starting_Col .. Final_Col loop for c in Col_Index range Starting_Col .. Final_Col loop V(c, k) := V(c, k) * Singular_Vals(k); end loop; end loop; -- V' = S*V' is now conceptually Row_Index x Col_Index, but really it -- is all zeros for Rows > Final_Col: for r in Starting_Row .. Final_Row loop -- U is Row_Index x Row_Index for c in Starting_Col .. Final_Col loop -- V' is Row_Index x Col_Index Sum := 0.0; for k in Col_Index range Starting_Col .. Final_Col loop Sum := Sum + U(r, Row_Index (k)) * V(c, k); end loop; SVD_Product(r, c) := Sum; end loop; end loop; Error_Diag := 0.0; Error_Off_Diag := 0.0; for i in Starting_Row .. Final_Row loop for j in Starting_Col .. Final_Col loop if i = Row_Index'Base (j) then Del := Abs (A(i,j) - SVD_Product(i,j)); if Del > Error_Diag then Error_Diag := Del; end if; else Del := Abs (A(i,j) - SVD_Product(i,j)); if Del > Error_Off_Diag then Error_Off_Diag := Del; end if; end if; end loop; end loop; new_line(1); put ("Max err in A - U*W*V', On_Diagonal ="); put (Error_Diag / Max_Singular_Val); new_line; put ("Max err in A - U*W*V', Off_Diagonal ="); put (Error_Off_Diag / Max_Singular_Val); -- Get Product = U' * U = transpose(U) * U for i in Row_Index range Starting_Row .. Final_Row loop for j in Row_Index range Starting_Row .. Final_Row loop Sum := 0.0; for k in Starting_Row .. Final_Row loop Sum := Sum + U(k, i) * U(k, j); end loop; UU_Product(i,j) := Sum; end loop; end loop; -- Product - I = 0? Error_Diag := 0.0; Error_Off_Diag := 0.0; for i in Row_Index range Starting_Row .. Final_Row loop for j in Row_Index range Starting_Row .. Final_Row loop if i = j then Del := Abs (1.0 - UU_Product(i,j)); if Del > Error_Diag then Error_Diag := Del; end if; else Del := Abs (0.0 - UU_Product(i,j)); if Del > Error_Off_Diag then Error_Off_Diag := Del; end if; end if; end loop; end loop; new_line; put ("Max err in I - U'*U, On_Diagonal ="); put (Error_Diag); new_line; put ("Max err in I - U'*U, Off_Diagonal ="); put (Error_Off_Diag); end loop; -- over Chosen_Matrix end golub_svd_tst_2;
with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Ordered_Maps; procedure Euler14 is package Length_Map is new Ada.Containers.Ordered_Maps (Long_Long_Integer,Integer); Lengths : Length_Map.Map; function Chain_Length(Value : Long_Long_Integer) return Integer is Count : Natural := 0; V : Long_Long_Integer := Value; begin loop if V = 1 then Lengths.Insert(Value, Count + 1); return Count + 1; end if; if Lengths.Contains(V) then Lengths.Insert(Value, Count + Lengths.Element(V)); return Count + Lengths.Element(V); end if; if V mod 2 = 0 then V := V / 2; else V := 3 * V + 1; end if; Count := Count + 1; end loop; end Chain_Length; Max_Length : Natural := 0; Result : Natural := 0; C : Natural; begin for I in 1 .. 1_000_000 loop C := Chain_Length(Long_Long_Integer(I)); if C > Max_Length then Max_Length := C; Result := I; end if; end loop; Put_Line(Natural'Image(Result) & Natural'Image(Max_Length)); end Euler14;
-- Copyright (C)2021,2022 Steve Merrony -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. with Ada.Exceptions; with Ada.Unchecked_Conversion; with Logging; use Logging; with Serial; with Telnet; with Terminal; with Xmodem; package body Redirector is task body Router_TT is begin loop select accept Set_Destination (Dest : in Connection_T) do Destination := Dest; end Set_Destination; or accept Get_Destination (Dest : out Connection_T) do Dest := Destination; end Get_Destination; or accept Send_Data (Data : in String) do case Destination is when Local => Terminal.Processor_Task.Accept_Data (Data); when Async => Serial.Keyboard_Sender_Task.Accept_Data (Data); when Network => Telnet.Keyboard_Sender_Task.Accept_Data (Data); end case; exception when Telnet.Disconnected => Destination := Local; Handler := Visual; end Send_Data; or accept Set_Handler (Handlr : in Handler_T) do Handler := Handlr; end Set_Handler; or accept Handle_Data (C : in Character) do case Handler is when Visual => Terminal.Processor_Task.Accept_Data ("" & C); when Xmodem_Rx => Xmodem.Receiver_Task.Accept_Data (C); when Xmodem_Tx => Xmodem.Sender_Task.Accept_Data (C); end case; end Handle_Data; or terminate; end select; end loop; exception when E : others => Log (ERROR, "Redirector Router task has Exception"); Log (ERROR, Ada.Exceptions.Exception_Information(E)); end Router_TT; end Redirector;
pragma Ada_2012; pragma Warnings (Off, "no entities of ""Ada.Text_Io"" are referenced"); with Ada.Text_Io; use Ada.Text_Io; with Ada.Unchecked_Deallocation; package body Readable_Sequences.Generic_Sequences is type Nullable_Buffer_Access is access all Buffer_Type; procedure Free is new Ada.Unchecked_Deallocation (Object => Buffer_Type, Name => Nullable_Buffer_Access); Empty_Buffer : constant Buffer_Access := new Buffer_Type (2 .. 1); procedure Finalize (Object : in out Sequence) is Tmp : Nullable_Buffer_Access := Nullable_Buffer_Access (Object.Buffer); begin Object.Buffer := Empty_Buffer; Free (Tmp); end Finalize; ------------------ -- Set_Position -- ------------------ procedure Set_Position (Seq : in out Sequence; Pos : Cursor) is begin Seq.Position := Pos; end Set_Position; ---------- -- Next -- ---------- function Next (Seq : in out Sequence) return Element_Type is Result : constant Element_Type := Seq.Read; begin Seq.Next; return Result; end Next; ---------- -- Dump -- ---------- function Dump (Seq : Sequence; From : Cursor) return Element_Array is -- Result : Element_Array (Integer (From) .. Integer (Seq.Buffer'Last)); begin -- for K in Result'Range loop -- Result (K) := Seq.Buffer (Cursor (K)); -- end loop; return Element_Array (Seq.Buffer (From .. Seq.First_Free - 1)); end Dump; function Dump (Seq : Sequence) return Element_Array is (Seq.Dump (Seq.First)); ----------- -- Clear -- ----------- procedure Clear (Seq : in out Sequence) is begin Seq.Position := Seq.Buffer'First; Seq.First_Free := Seq.Buffer'First; Seq.Position_Saved := False; end Clear; function Allocate_Buffer (Min_Size : Natural) return Buffer_Access is Blocksize : constant Positive := 2048; N_Blocks : constant Positive := Min_Size / Blocksize + 2; begin -- -- Blocksize * (min_size/blocksize) >= min_size - Blocksize -- -- Blocksize * N_blocks >= min_size + Blocksize -- -- We get at least a full block free -- pragma Assert (Blocksize * N_Blocks >= Min_Size + Blocksize); return new Buffer_Type (1 .. Cursor (Blocksize * N_Blocks)); end Allocate_Buffer; function Empty_Sequence return Sequence is Tmp : constant Buffer_Access := Allocate_Buffer (0); begin return (Sequence'(Ada.Finalization.Limited_Controlled with Buffer => Tmp, Position => Tmp'First, First_Free => Tmp'First, Old_Position => <>, Position_Saved => False, Has_End_Marker => False, End_Marker => <>)); end Empty_Sequence; ------------ -- Create -- ------------ function Create (End_Of_Sequence_Marker : Element_Type) return Sequence is begin return Result : Sequence := Empty_Sequence do Result.End_Marker := End_Of_Sequence_Marker; Result.Has_End_Marker := True; end return; end Create; ------------ -- Create -- ------------ function Create (Init : Element_Array; End_Of_Sequence_Marker : Element_Type) return Sequence is begin return Result : Sequence := Create (End_Of_Sequence_Marker) do Result.Append (Init); end return; end Create; ------------ -- Create -- ------------ function Create (Init : Element_Array) return Sequence is begin return Result : Sequence := Empty_Sequence do Result.Append (Init); end return; end Create; -- procedure Update (Seq : in out Sequence; -- Data : Buffer_Type) -- is -- begin -- Seq.Buffer.Replace_Element (Data); -- Seq.First := Data'First; -- Seq.After_Last := Data'Last + 1; -- Seq.Position := Seq.First; -- end Update; ------------ -- Append -- ------------ procedure Append (Seq : in out Sequence; Elements : Element_Array) is begin if Seq.Free_Space >= Elements'Length then declare Last : constant Cursor := Seq.First_Free + Cursor (Elements'Length)-1; begin pragma Assert (Last <= Seq.Buffer'Last); Seq.Buffer (Seq.First_Free .. Last) := Buffer_Type (Elements); Seq.First_Free := Last + 1; end; else declare Old_Buffer : Nullable_Buffer_Access := Nullable_Buffer_Access (Seq.Buffer); -- -- Why this? Because Buffer_Access has been declared "not null" -- but Unchecked_Deallocation set to null its paramete. -- New_Length : constant Natural := Seq.Length + Elements'Length; New_Buffer : constant Buffer_Access := Allocate_Buffer (New_Length); Last_Written : constant Cursor := New_Buffer'First + Cursor (New_Length) - 1; -- Q : constant Buffer_Type := Buffer_Type (Seq.Dump & Elements); begin -- Put_Line (Q'Length'Image); -- Put_Line (Cursor'Image (Last_Written - New_Buffer'First + 1)); New_Buffer (New_Buffer'First .. Last_Written) := Buffer_Type (Seq.Dump & Elements); Seq.Buffer := New_Buffer; Seq.First_Free := Last_Written + 1; Free (Old_Buffer); end; end if; end Append; ------------ -- Append -- ------------ procedure Append (To : in out Sequence; What : Element_Type) is begin To.Append (Element_Array'(1 => What)); end Append; ------------ -- Append -- ------------ procedure Append (To : in out Sequence; What : Sequence) is begin To.Append (What.Dump); end Append; function Remaining (Seq : Sequence) return Natural is begin -- Put_Line (Seq.Buffer'Last'Image); -- Put_Line (Seq.Position'Image); -- Put_Line (Cursor'(Seq.Buffer'Last - Seq.Position + 1 )'Image); -- Put_Line (Seq.Length'Image); return Integer (Seq.First_Free) - Integer (Seq.Position); end Remaining; ------------ -- Rewind -- ------------ procedure Rewind (Seq : in out Sequence; To : Cursor) is begin if not Seq.Is_Valid_Position (To) then raise Constraint_Error; end if; Seq.Position := To; end Rewind; procedure Rewind (Seq : in out Sequence) is begin Seq.Position := Seq.First; end Rewind; ------------------- -- Save_Position -- ------------------- procedure Save_Position (Seq : in out Sequence) is begin if Seq.Position_Saved then raise Constraint_Error; end if; Seq.Old_Position := Seq.Position; Seq.Position_Saved := True; end Save_Position; ---------------------- -- Restore_Position -- ---------------------- procedure Restore_Position (Seq : in out Sequence) is begin if not Seq.Position_Saved then raise Constraint_Error; end if; Seq.Position := Seq.Old_Position; Seq.Position_Saved := False; end Restore_Position; -------------------- -- Clear_Position -- -------------------- procedure Clear_Position (Seq : in out Sequence) is begin if not Seq.Position_Saved then raise Constraint_Error; end if; Seq.Position_Saved := False; end Clear_Position; ---------- -- Next -- ---------- procedure Next (Seq : in out Sequence; Step : Positive := 1) is begin if Seq.Remaining < Step then -- Put_Line (">>> a"); Seq.Position := Seq.First_Free; else -- Put_Line (">>> b"); Seq.Position := Seq.Position + Cursor (Step); end if; end Next; ---------- -- Back -- ---------- procedure Back (Seq : in out Sequence; Step : Positive := 1) is begin if Seq.Position < Seq.Buffer'First + Cursor (Step) then Seq.Position := Seq.Buffer'First; return; end if; Seq.Position := Seq.Position - Cursor (Step); end Back; ------------- -- Process -- ------------- procedure Process (Seq : Sequence; Callback : access procedure (Item : Element_Type)) is begin for El of Seq.Dump loop Callback (El); end loop; end Process; end Readable_Sequences.Generic_Sequences;
-- AUTHOR: GUILLERMO ALBERTO PEREZ GUILLEN with Last_Chance_Handler; pragma Unreferenced (Last_Chance_Handler); with STM32.Device; use STM32.Device; with HAL; use HAL; with STM32.ADC; use STM32.ADC; with STM32.GPIO; use STM32.GPIO; with Ada.Real_Time; use Ada.Real_Time; with STM32.User_Button; --PA0 button with LCD_Std_Out; procedure Digital_Blood_Pressure_Monitor is type Integer_Array is array (Integer range <>) of Integer with Default_Component_Value => 0; PressureArray : Integer_Array (0..200); Converter : Analog_To_Digital_Converter renames ADC_1; -- ADC_1 Input_Channel : constant Analog_Input_Channel := 5; --5 Input : constant GPIO_Point := PA5; -- PA5 analog input Solenoid_valve : GPIO_Point renames PD12; -- solenoid valve Motor : GPIO_Point renames PD13; -- air pump Enable_a : GPIO_Point renames PD14; Enable_b : GPIO_Point renames PD15; Ports : constant GPIO_Points := (Solenoid_valve, Motor, Enable_a, Enable_b); All_Regular_Conversions : constant Regular_Channel_Conversions := (1 => (Channel => Input_Channel, Sample_Time => Sample_144_Cycles)); Raw : UInt32 := 0; Volts : UInt32 := 0; Pressure : UInt32 := 0; Pressure_total : UInt32 := 0; X_Pos: Integer := 0; --PressureAddr : UInt32 := 1; -- No such thing as a zero Pressure address var_a : UInt32 := 0; var_b : UInt32 := 0; var_c : UInt32 := 0; inc : UInt32 := 50; Successful : Boolean; procedure Initialize_Ports; procedure Print (X, Y : Natural; Value : UInt32; Suffix : String := ""); procedure Configure_Analog_Input; ---------------------------- -- Initialize_Ports -- ---------------------------- procedure Initialize_Ports is begin Enable_Clock (GPIO_D); Configure_IO (Ports, (Mode => Mode_Out, Resistors => Floating, Speed => Speed_100MHz, Output_Type => Push_Pull)); end Initialize_Ports; ----------- -- Print -- ----------- procedure Print (X, Y : Natural; Value : UInt32; Suffix : String := "") is Value_Image : constant String := Value'Img; begin LCD_Std_Out.Put (X, Y, Value_Image (2 .. Value_Image'Last) & Suffix & " "); end Print; ---------------------------- -- Configure_Analog_Input -- ---------------------------- procedure Configure_Analog_Input is begin Enable_Clock (Input); Configure_IO (Input, (Mode => Mode_Analog, Resistors => Floating)); end Configure_Analog_Input; begin Initialize_Ports; STM32.User_Button.Initialize; Solenoid_valve.Clear; Motor.Clear; Enable_a.Clear; Enable_b.Clear; Configure_Analog_Input; Enable_Clock (Converter); Reset_All_ADC_Units; Configure_Common_Properties (Mode => Independent, Prescalar => PCLK2_Div_2, DMA_Mode => Disabled, Sampling_Delay => Sampling_Delay_5_Cycles); Configure_Unit (Converter, Resolution => ADC_Resolution_12_Bits, Alignment => Right_Aligned); Configure_Regular_Conversions (Converter, Continuous => False, Trigger => Software_Triggered, Enable_EOC => True, Conversions => All_Regular_Conversions); Enable (Converter); loop Start_Conversion (Converter); Poll_For_Status (Converter, Regular_Channel_Conversion_Complete, Successful); Solenoid_valve.Clear; Motor.Clear; Enable_a.Clear; Enable_b.Clear; Raw := UInt32 (Conversion_Value (Converter)); Volts := UInt32 ((Float (Raw) / 4096.0) * 3000.0); -- 4096 ADC = 3000 mV Pressure := UInt32 ((Float (Volts) / 3000.0) * 255.0); -- 3000 mV = 255 mmHg Pressure_total := UInt32 (float (Pressure) - 8.0); -- 3000 mV = 255 mmHg Print (0, 0, Pressure_total, " mmHg"); -- print blood pressure if STM32.User_Button.Has_Been_Pressed then -- Btn pressed then go to 170 mmHg Start_Conversion (Converter); Poll_For_Status (Converter, Regular_Channel_Conversion_Complete, Successful); Solenoid_valve.Set; -- solenoid valve is ON Motor.Set; -- air pump is ON Enable_a.Set; Enable_b.Set; Raw := UInt32 (Conversion_Value (Converter)); Volts := UInt32 ((Float (Raw) / 4096.0) * 3000.0); -- 4096 ADC = 3000 mV Pressure := UInt32 ((Float (Volts) / 3000.0) * 255.0); -- 3000 mV = 255 mmHg Pressure_total := UInt32 (float (Pressure) - 8.0); -- 3000 mV = 255 mmHg Print (0, 0, Pressure_total, " mmHg"); -- print blood pressure while Pressure_total <= 170 loop Start_Conversion (Converter); Poll_For_Status (Converter, Regular_Channel_Conversion_Complete, Successful); Raw := UInt32 (Conversion_Value (Converter)); Volts := UInt32 ((Float (Raw) / 4096.0) * 3000.0); -- 4096 ADC = 3000 mV Pressure := UInt32 ((Float (Volts) / 3000.0) * 255.0); -- 3000 mV = 255 mmHg Pressure_total := UInt32 (float (Pressure) - 8.0); -- 3000 mV = 255 mmHg Print (0, 0, Pressure_total, " mmHg"); -- print blood pressure delay until Clock + Milliseconds (75); end loop; Solenoid_valve.Set; -- solenoid valve is ON Motor.Clear; -- air pump is OFF Enable_a.Set; Enable_b.Clear; delay until Clock + Milliseconds (100); while Pressure_total > 70 and Pressure_total <= 210 loop Start_Conversion (Converter); Poll_For_Status (Converter, Regular_Channel_Conversion_Complete, Successful); Raw := UInt32 (Conversion_Value (Converter)); Volts := UInt32 ((Float (Raw) / 4096.0) * 3000.0); -- 4096 ADC = 3000 mV Pressure := UInt32 ((Float (Volts) / 3000.0) * 255.0); -- 3000 mV = 255 mmHg Pressure_total := UInt32 (float (Pressure) - 8.0); -- 3000 mV = 255 mmHg Print (0, 0, Pressure_total, " mmHg"); -- print blood pressure PressureArray(X_Pos) := Integer (Pressure_total); X_Pos := X_Pos + 1; delay until Clock + Milliseconds (190); end loop; -- for I in 1 .. 140 loop -- PressureAddr := UInt32(PressureArray(I)); -- Print (0, 50, PressureAddr, " mmHg"); -- print blood pressure -- delay until Clock + Milliseconds (50); -- 4 secs and inflating the cuff to 80 mmHg -- end loop; for I in 1 .. 130 loop var_a := UInt32(PressureArray(I)); var_b := UInt32(PressureArray(I+1)); var_c := UInt32(PressureArray(I+2)); if var_b > var_a and var_c > var_a then Print (0, Integer (inc), var_b, " mmHg-korot"); inc := inc + 25; delay until Clock + Milliseconds (1); else delay until Clock + Milliseconds (1); end if; end loop; else Start_Conversion (Converter); Poll_For_Status (Converter, Regular_Channel_Conversion_Complete, Successful); Solenoid_valve.Clear; -- valve is OFF Motor.Clear; -- stop the motor Enable_a.Clear; Enable_b.Clear; Raw := UInt32 (Conversion_Value (Converter)); Volts := UInt32 ((Float (Raw) / 4096.0) * 3000.0); -- 4096 ADC = 3000 mV Pressure := UInt32 ((Float (Volts) / 3000.0) * 255.0); -- 3000 mV = 255 mmHg Pressure_total := UInt32 (float (Pressure) - 8.0); -- 3000 mV = 255 mmHg Print (0, 0, Pressure_total, " mmHg"); -- print blood pressure delay until Clock + Milliseconds (100); -- delay to the next step end if; end loop; end Digital_Blood_Pressure_Monitor;
with Ada.Characters.Latin_1; with Ada.Numerics; with Orka.Rendering.Textures; with Orka.Resources.Textures.KTX; with Orka.Features.Terrain.Spheres; with Orka.Transforms.Doubles.Matrices; with Orka.Transforms.Doubles.Matrix_Conversions; with Orka.Transforms.Doubles.Quaternions; with Orka.Transforms.Doubles.Vectors; with Orka.Transforms.Doubles.Vector_Conversions; with GL.Types; package body Demo.Terrains is Count : constant := 6; function Create_Terrain (Planet_Model : aliased Orka.Features.Atmosphere.Model_Data; Planet_Data : Planets.Planet_Characteristics; Atmosphere_Manager : Demo.Atmospheres.Atmosphere; Location_Data : Orka.Resources.Locations.Location_Ptr; Location_Shaders : Orka.Resources.Locations.Location_Ptr) return Terrain is use Orka.Rendering.Buffers; use type Orka.Float_64; use type GL.Types.Single_Array; Planet_Radius : constant Orka.Float_64 := Planet_Data.Semi_Major_Axis / Planet_Model.Length_Unit_In_Meters; Terrain_Sphere_Side : constant Orka.Features.Terrain.Spheroid_Parameters := Orka.Features.Terrain.Get_Spheroid_Parameters (Orka.Float_32 (Planet_Radius), Orka.Float_32 (Planet_Data.Flattening), True); Terrain_Sphere_Top : constant Orka.Features.Terrain.Spheroid_Parameters := Orka.Features.Terrain.Get_Spheroid_Parameters (Orka.Float_32 (Planet_Radius), Orka.Float_32 (Planet_Data.Flattening), False); Terrain_Spheres : constant GL.Types.Single_Array := Terrain_Sphere_Side & Terrain_Sphere_Side & Terrain_Sphere_Side & Terrain_Sphere_Side & Terrain_Sphere_Top & Terrain_Sphere_Top; ------------------------------------------------------------------------- package MC renames Orka.Transforms.Doubles.Matrix_Conversions; package Quaternions renames Orka.Transforms.Doubles.Quaternions; Q_Rotate_90 : constant Quaternions.Quaternion := Quaternions.R (Orka.Transforms.Doubles.Vectors.Normalize ((0.0, 0.0, 1.0, 0.0)), -2.0 * Ada.Numerics.Pi * 0.25); Q_Rotate_180 : constant Quaternions.Quaternion := Quaternions.R (Orka.Transforms.Doubles.Vectors.Normalize ((0.0, 0.0, 1.0, 0.0)), -2.0 * Ada.Numerics.Pi * 0.50); Q_Rotate_270 : constant Quaternions.Quaternion := Quaternions.R (Orka.Transforms.Doubles.Vectors.Normalize ((0.0, 0.0, 1.0, 0.0)), -2.0 * Ada.Numerics.Pi * 0.75); Q_Rotate_90_Up : constant Quaternions.Quaternion := Quaternions.R (Orka.Transforms.Doubles.Vectors.Normalize ((0.0, 1.0, 0.0, 0.0)), 2.0 * Ada.Numerics.Pi * 0.25); Q_Rotate_90_Down : constant Quaternions.Quaternion := Quaternions.R (Orka.Transforms.Doubles.Vectors.Normalize ((0.0, 1.0, 0.0, 0.0)), -2.0 * Ada.Numerics.Pi * 0.25); package Matrices renames Orka.Transforms.Doubles.Matrices; Rotate_90 : constant Transforms.Matrix4 := MC.Convert (Matrices.R (Matrices.Vector4 (Q_Rotate_90))); Rotate_180 : constant Transforms.Matrix4 := MC.Convert (Matrices.R (Matrices.Vector4 (Q_Rotate_180))); Rotate_270 : constant Transforms.Matrix4 := MC.Convert (Matrices.R (Matrices.Vector4 (Q_Rotate_270))); Rotate_90_Up : constant Transforms.Matrix4 := MC.Convert (Matrices.R (Matrices.Vector4 (Q_Rotate_90_Up))); Rotate_90_Down : constant Transforms.Matrix4 := MC.Convert (Matrices.R (Matrices.Vector4 (Q_Rotate_90_Down))); ------------------------------------------------------------------------- DMap : constant GL.Objects.Textures.Texture := Orka.Resources.Textures.KTX.Read_Texture (Location_Data, "terrain/texture4k-dmap.ktx"); SMap : constant GL.Objects.Textures.Texture := Orka.Resources.Textures.KTX.Read_Texture (Location_Data, "terrain/texture4k-smap.ktx"); Terrain_GLSL : constant String := Orka.Resources.Convert (Orka.Resources.Byte_Array'(Location_Data.Read_Data ("terrain/terrain-render-atmosphere.frag").Get)); use Ada.Characters.Latin_1; use Orka.Rendering.Programs; use Orka.Features.Atmosphere; Terrain_FS_Shader : constant String := "#version 420" & LF & "#extension GL_ARB_shader_storage_buffer_object : require" & LF & (if Planet_Model.Luminance /= Orka.Features.Atmosphere.None then "#define USE_LUMINANCE" & LF else "") & "const float kLengthUnitInMeters = " & Planet_Model.Length_Unit_In_Meters'Image & ";" & LF & Terrain_GLSL & LF; Modules_Terrain_Render : constant Modules.Module_Array := Modules.Module_Array' (Atmosphere_Manager.Shader_Module, Modules.Create_Module_From_Sources (FS => Terrain_FS_Shader)); begin return (Terrain_Transforms => Create_Buffer ((Dynamic_Storage => True, others => False), Orka.Types.Single_Matrix_Type, Length => Count), Terrain_Sphere_Params => Create_Buffer ((others => False), Terrain_Spheres), Terrain_Spheroid_Parameters => Terrain_Sphere_Side, Rotate_90 => Rotate_90, Rotate_180 => Rotate_180, Rotate_270 => Rotate_270, Rotate_90_Up => Rotate_90_Up, Rotate_90_Down => Rotate_90_Down, Planet_Radius => Planet_Radius, Planet_Unit_Length => Planet_Model.Length_Unit_In_Meters, -- Program => Orka.Features.Terrain.Create_Terrain -- (Count => Count, -- Min_Depth => 6, -- Max_Depth => 20, -- Scale => 0.0, -- Wireframe => True, -- Location => Location_Shaders, -- Render_Modules => Modules_Terrain_Render, -- Initialize_Render => null), -- Initialize_Render => Initialize_Atmosphere_Terrain_Program'Access), Modules_Terrain_Render => Modules_Terrain_Render, DMap => DMap, SMap => SMap); end Create_Terrain; procedure Render (Object : in out Terrain; Terrain : in out Orka.Features.Terrain.Terrain; Parameters : Orka.Features.Terrain.Subdivision_Parameters; Visible_Tiles : out Natural; Camera : Orka.Cameras.Camera_Ptr; Planet, Star : Orka.Behaviors.Behavior_Ptr; Rotation : Orka.Types.Singles.Matrix4; Center : Orka.Cameras.Transforms.Matrix4; Freeze : Boolean; Wires : Boolean; Timer_Update : in out Orka.Timers.Timer; Timer_Render : in out Orka.Timers.Timer) is procedure Update_Atmosphere_Terrain (Program : Orka.Rendering.Programs.Program) is use type Orka.Float_64; use Orka.Transforms.Doubles.Vectors; package VC renames Orka.Transforms.Doubles.Vector_Conversions; CP : constant Orka.Types.Singles.Vector4 := VC.Convert (Camera.View_Position * (1.0 / Object.Planet_Unit_Length)); Binding_Texture_SMap : constant := 5; begin Program.Uniform ("camera_pos").Set_Vector (CP); Program.Uniform ("earth_radius").Set_Single (GL.Types.Single (Object.Planet_Radius)); Program.Uniform ("sun_direction").Set_Vector (Orka.Types.Singles.Vector4'(VC.Convert (Normalize (Star.Position - Planet.Position)))); Orka.Rendering.Textures.Bind (Object.SMap, Orka.Rendering.Textures.Texture, Binding_Texture_SMap); end Update_Atmosphere_Terrain; use Transforms; Tile_Transforms : constant Orka.Types.Singles.Matrix4_Array := (1 => Rotation, 2 => Rotation * Object.Rotate_90, 3 => Rotation * Object.Rotate_180, 4 => Rotation * Object.Rotate_270, 5 => Rotation * Object.Rotate_90_Up, 6 => Rotation * Object.Rotate_90_Down); Sphere_Visibilities : constant GL.Types.Single_Array := Orka.Features.Terrain.Spheres.Get_Sphere_Visibilities (Object.Terrain_Spheroid_Parameters, Tile_Transforms (1), Tile_Transforms (3), Center, Camera.View_Matrix); Visible_Buffers : constant Orka.Features.Terrain.Visible_Tile_Array := Orka.Features.Terrain.Spheres.Get_Visible_Tiles (Sphere_Visibilities); pragma Assert (Visible_Buffers'Length = Terrain.Count); begin Visible_Tiles := 0; for Visible of Visible_Buffers loop if Visible then Visible_Tiles := Visible_Tiles + 1; end if; end loop; Object.Terrain_Transforms.Set_Data (Tile_Transforms); Terrain.Render (Transforms => Object.Terrain_Transforms, Spheres => Object.Terrain_Sphere_Params, Center => Center, Camera => Camera, Parameters => Parameters, Visible_Tiles => Visible_Buffers, Update_Render => Update_Atmosphere_Terrain'Access, Height_Map => Object.DMap, Freeze => Freeze, Wires => Wires, Timer_Update => Timer_Update, Timer_Render => Timer_Render); end Render; end Demo.Terrains;
package c_code_h is procedure c_func; pragma Import (C, c_func); procedure c_ada_caller; pragma Import (C, c_ada_caller); end c_code_h;
with Ada.Containers.Vectors; with Ada.Strings.Wide_Unbounded; with Symbex.Lex; with Stack; pragma Elaborate_All (Stack); package Symbex.Parse is type Tree_t is private; -- -- Tree status value. -- type Tree_Status_t is (Tree_OK, Tree_Error_Excess_Closing_Parentheses, Tree_Error_Unterminated_List); -- Status values corresponding to error conditions. subtype Tree_Error_Status_t is Tree_Status_t range Tree_Error_Excess_Closing_Parentheses .. Tree_Status_t'Last; -- -- Tree node types. -- -- Kind of list element. type Node_Kind_t is (Node_String, Node_Symbol, Node_List); -- Element of list. type Node_t is private; subtype Node_Symbol_Name_t is Ada.Strings.Wide_Unbounded.Unbounded_Wide_String; subtype Node_String_Data_t is Ada.Strings.Wide_Unbounded.Unbounded_Wide_String; -- Return kind of node. function Node_Kind (Node : in Node_t) return Node_Kind_t; -- -- Tree list types. -- -- List, containing nodes. type List_t is private; -- Unique list identifier. type List_ID_t is new Positive; type List_Length_t is new Natural; type List_Position_t is new Positive; type List_Depth_t is new Natural; -- Retrieve number of nodes in list. function List_Length (List : in List_t) return List_Length_t; -- -- Tree is initialized? -- function Initialized (Tree : in Tree_t) return Boolean; -- -- Tree parsing is completed? -- function Completed (Tree : in Tree_t) return Boolean; -- -- Initialize parser state. -- procedure Initialize_Tree (Tree : in out Tree_t; Status : out Tree_Status_t); -- pragma Postcondition -- (((Status = Tree_OK) and Initialized (Tree)) or -- ((Status /= Tree_OK) and not Initialized (Tree))); -- -- Process token. -- procedure Process_Token (Tree : in out Tree_t; Token : in Lex.Token_t; Status : out Tree_Status_t); pragma Precondition (Initialized (Tree) and Token.Is_Valid and not Completed (Tree)); -- -- Subprograms only of practical use to the rest of Symbex. -- package Internal is -- -- Fetch node data (only valid for strings and symbols). -- function Get_Data (Node : in Node_t) return Ada.Strings.Wide_Unbounded.Unbounded_Wide_String; pragma Precondition (Node_Kind (Node) /= Node_List); -- -- Fetch node list ID (only valid for lists). -- function Get_List_ID (Node : in Node_t) return List_ID_t; pragma Precondition (Node_Kind (Node) = Node_List); -- -- Retrieve list. -- function Get_List (Tree : in Tree_t; List_ID : in List_ID_t) return List_t; pragma Precondition (Completed (Tree)); -- -- Iterate over nodes in list. -- procedure List_Iterate (List : in List_t; Process : access procedure (Node : in Node_t)); end Internal; private package UBW_Strings renames Ada.Strings.Wide_Unbounded; -- Node type, element of list. type Node_t (Kind : Node_Kind_t := Node_Symbol) is record case Kind is when Node_Symbol => Name : Node_Symbol_Name_t; when Node_String => Data : Node_String_Data_t; when Node_List => List : List_ID_t; end case; end record; -- -- Node list. -- package Lists is new Ada.Containers.Vectors (Index_Type => List_Position_t, Element_Type => Node_t); subtype List_Nodes_t is Lists.Vector; type List_t is record Parent : List_ID_t; Nodes : List_Nodes_t; end record; -- -- Array of node lists. -- package List_Arrays is new Ada.Containers.Vectors (Index_Type => List_ID_t, Element_Type => List_t); subtype List_Array_t is List_Arrays.Vector; -- -- List ID stack. -- package List_ID_Stack is new Stack (Element_Type => List_ID_t); -- -- Tree type. -- type Tree_t is record Inited : Boolean; Completed : Boolean; List_Stack : List_ID_Stack.Stack_t; Lists : List_Array_t; Current_List : List_ID_t; end record; end Symbex.Parse;
-- Copyright (c) 2015-2017 Maxim Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with XML.SAX.Writers; with Incr.Documents; with Incr.Parsers.Incremental; package Incr.Debug is package P renames Incr.Parsers.Incremental.Parser_Data_Providers; procedure Dump (Doc : Incr.Documents.Document'Class; Provider : P.Parser_Data_Provider'Class; Output : in out XML.SAX.Writers.SAX_Writer'Class); end Incr.Debug;
with Interfaces.C, System; use type System.Address; package body FLTK.Widgets.Groups.Wizards is procedure wizard_set_draw_hook (W, D : in System.Address); pragma Import (C, wizard_set_draw_hook, "wizard_set_draw_hook"); pragma Inline (wizard_set_draw_hook); procedure wizard_set_handle_hook (W, H : in System.Address); pragma Import (C, wizard_set_handle_hook, "wizard_set_handle_hook"); pragma Inline (wizard_set_handle_hook); function new_fl_wizard (X, Y, W, H : in Interfaces.C.int; Text : in Interfaces.C.char_array) return System.Address; pragma Import (C, new_fl_wizard, "new_fl_wizard"); pragma Inline (new_fl_wizard); procedure free_fl_wizard (S : in System.Address); pragma Import (C, free_fl_wizard, "free_fl_wizard"); pragma Inline (free_fl_wizard); procedure fl_wizard_next (W : in System.Address); pragma Import (C, fl_wizard_next, "fl_wizard_next"); pragma Inline (fl_wizard_next); procedure fl_wizard_prev (W : in System.Address); pragma Import (C, fl_wizard_prev, "fl_wizard_prev"); pragma Inline (fl_wizard_prev); function fl_wizard_get_visible (W : in System.Address) return System.Address; pragma Import (C, fl_wizard_get_visible, "fl_wizard_get_visible"); pragma Inline (fl_wizard_get_visible); procedure fl_wizard_set_visible (W, I : in System.Address); pragma Import (C, fl_wizard_set_visible, "fl_wizard_set_visible"); pragma Inline (fl_wizard_set_visible); procedure fl_wizard_draw (W : in System.Address); pragma Import (C, fl_wizard_draw, "fl_wizard_draw"); pragma Inline (fl_wizard_draw); function fl_wizard_handle (W : in System.Address; E : in Interfaces.C.int) return Interfaces.C.int; pragma Import (C, fl_wizard_handle, "fl_wizard_handle"); pragma Inline (fl_wizard_handle); procedure Finalize (This : in out Wizard) is begin if This.Void_Ptr /= System.Null_Address and then This in Wizard'Class then This.Clear; free_fl_wizard (This.Void_Ptr); This.Void_Ptr := System.Null_Address; end if; Finalize (Group (This)); end Finalize; package body Forge is function Create (X, Y, W, H : in Integer; Text : in String) return Wizard is begin return This : Wizard do This.Void_Ptr := new_fl_wizard (Interfaces.C.int (X), Interfaces.C.int (Y), Interfaces.C.int (W), Interfaces.C.int (H), Interfaces.C.To_C (Text)); fl_group_end (This.Void_Ptr); fl_widget_set_user_data (This.Void_Ptr, Widget_Convert.To_Address (This'Unchecked_Access)); wizard_set_draw_hook (This.Void_Ptr, Draw_Hook'Address); wizard_set_handle_hook (This.Void_Ptr, Handle_Hook'Address); end return; end Create; end Forge; procedure Next (This : in out Wizard) is begin fl_wizard_next (This.Void_Ptr); end Next; procedure Prev (This : in out Wizard) is begin fl_wizard_prev (This.Void_Ptr); end Prev; function Get_Visible (This : in Wizard) return access Widget'Class is Widget_Ptr : System.Address := fl_wizard_get_visible (This.Void_Ptr); Actual_Widget : access Widget'Class := Widget_Convert.To_Pointer (fl_widget_get_user_data (Widget_Ptr)); begin return Actual_Widget; end Get_Visible; procedure Set_Visible (This : in out Wizard; Item : in out Widget'Class) is begin fl_wizard_set_visible (This.Void_Ptr, Item.Void_Ptr); end Set_Visible; procedure Draw (This : in out Wizard) is begin fl_wizard_draw (This.Void_Ptr); end Draw; function Handle (This : in out Wizard; Event : in Event_Kind) return Event_Outcome is begin return Event_Outcome'Val (fl_wizard_handle (This.Void_Ptr, Event_Kind'Pos (Event))); end Handle; end FLTK.Widgets.Groups.Wizards;
with openGL.Primitive.indexed, openGL.Geometry.colored; package body openGL.Model.box.colored is --------- --- Forge -- function new_Box (Size : in Vector_3; Faces : in colored.Faces) return View is Self : constant View := new Item; begin Self.Faces := Faces; Self.Size := Size; return Self; end new_Box; -------------- --- Attributes -- overriding function to_GL_Geometries (Self : access Item; Textures : access Texture.name_Map_of_texture'Class; Fonts : in Font.font_id_Map_of_font) return Geometry.views is pragma unreferenced (Textures, Fonts); use Geometry; the_Sites : constant box.Sites := Self.vertex_Sites; the_Indices : aliased constant Indices := (1, 2, 3, 4); function new_Face (Vertices : access Geometry.colored.Vertex_array) return Geometry.colored.view is use Geometry.colored, Primitive; the_Geometry : constant Geometry.colored .view := Geometry.colored.new_Geometry; the_Primitive : constant Primitive.indexed.view := Primitive.indexed.new_Primitive (triangle_Fan, the_Indices); begin the_Geometry.Vertices_are (Vertices.all); the_Geometry.add (Primitive.view (the_Primitive)); the_Geometry.is_Transparent (now => False); return the_Geometry; end new_Face; front_Face : Geometry.colored.view; rear_Face : Geometry.colored.view; upper_Face : Geometry.colored.view; lower_Face : Geometry.colored.view; left_Face : Geometry.colored.view; right_Face : Geometry.colored.view; begin -- Front -- declare the_Vertices : aliased Geometry.colored.Vertex_array := (1 => (Site => the_Sites ( Left_Lower_Front), Color => +Self.Faces (Front).Colors (1)), 2 => (Site => the_Sites (Right_Lower_Front), Color => +Self.Faces (Front).Colors (2)), 3 => (Site => the_Sites (Right_Upper_Front), Color => +Self.Faces (Front).Colors (3)), 4 => (Site => the_Sites ( Left_Upper_Front), Color => +Self.Faces (Front).Colors (4))); begin front_Face := new_Face (Vertices => the_Vertices'Access); end; -- Rear -- declare the_Vertices : aliased Geometry.colored.Vertex_array := (1 => (Site => the_Sites (Right_Lower_Rear), Color => +Self.Faces (Rear).Colors (1)), 2 => (Site => the_Sites ( Left_Lower_Rear), Color => +Self.Faces (Rear).Colors (2)), 3 => (Site => the_Sites ( Left_Upper_Rear), Color => +Self.Faces (Rear).Colors (3)), 4 => (Site => the_Sites (Right_Upper_Rear), Color => +Self.Faces (Rear).Colors (4))); begin rear_Face := new_Face (Vertices => the_Vertices'Access); end; -- Upper -- declare the_Vertices : aliased Geometry.colored.Vertex_array := (1 => (Site => the_Sites ( Left_Upper_Front), Color => +Self.Faces (Upper).Colors (1)), 2 => (Site => the_Sites (Right_Upper_Front), Color => +Self.Faces (Upper).Colors (2)), 3 => (Site => the_Sites (Right_Upper_Rear), Color => +Self.Faces (Upper).Colors (3)), 4 => (Site => the_Sites ( Left_Upper_Rear), Color => +Self.Faces (Upper).Colors (4))); begin upper_Face := new_Face (Vertices => the_Vertices'Access); end; -- Lower -- declare the_Vertices : aliased Geometry.colored.Vertex_array := (1 => (Site => the_Sites (Right_Lower_Front), Color => +Self.Faces (Lower).Colors (1)), 2 => (Site => the_Sites ( Left_Lower_Front), Color => +Self.Faces (Lower).Colors (2)), 3 => (Site => the_Sites ( Left_Lower_Rear), Color => +Self.Faces (Lower).Colors (3)), 4 => (Site => the_Sites (Right_Lower_Rear), Color => +Self.Faces (Lower).Colors (4))); begin lower_Face := new_Face (Vertices => the_Vertices'Access); end; -- Left -- declare the_Vertices : aliased Geometry.colored.Vertex_array := (1 => (Site => the_Sites (Left_Lower_Rear), Color => +Self.Faces (Left).Colors (1)), 2 => (Site => the_Sites (Left_Lower_Front), Color => +Self.Faces (Left).Colors (2)), 3 => (Site => the_Sites (Left_Upper_Front), Color => +Self.Faces (Left).Colors (3)), 4 => (Site => the_Sites (Left_Upper_Rear), Color => +Self.Faces (Left).Colors (4))); begin left_Face := new_Face (Vertices => the_Vertices'Access); end; -- Right -- declare the_Vertices : aliased Geometry.colored.Vertex_array := (1 => (Site => the_Sites (Right_Lower_Front), Color => +Self.Faces (Right).Colors (1)), 2 => (Site => the_Sites (Right_Lower_Rear), Color => +Self.Faces (Right).Colors (2)), 3 => (Site => the_Sites (Right_Upper_Rear), Color => +Self.Faces (Right).Colors (3)), 4 => (Site => the_Sites (Right_Upper_Front), Color => +Self.Faces (Right).Colors (4))); begin right_Face := new_Face (Vertices => the_Vertices'Access); end; return (Geometry.view (front_Face), Geometry.view ( rear_Face), Geometry.view (upper_Face), Geometry.view (lower_Face), Geometry.view ( left_Face), Geometry.view (right_Face)); end to_GL_Geometries; end openGL.Model.box.colored;
-- SPDX-License-Identifier: MIT -- -- Copyright (c) 1999 - 2018 Gautier de Montmollin -- SWITZERLAND -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. package body DCF.Zip.CRC is CRC32_Table : array (Unsigned_32'(0) .. 255) of Unsigned_32; procedure Prepare_Table is -- CRC-32 algorithm, section 4.4.7 of .zip file format specification Seed : constant := 16#EDB8_8320#; L : Unsigned_32; begin for I in CRC32_Table'Range loop L := I; for Bit in 0 .. 7 loop if (L and 1) = 0 then L := Shift_Right (L, 1); else L := Shift_Right (L, 1) xor Seed; end if; end loop; CRC32_Table (I) := L; end loop; end Prepare_Table; procedure Update (CRC : in out Unsigned_32; Inbuf : Zip.Byte_Buffer) is Local_CRC : Unsigned_32; begin Local_CRC := CRC; for I in Inbuf'Range loop Local_CRC := CRC32_Table (16#FF# and (Local_CRC xor Unsigned_32 (Inbuf (I)))) xor Shift_Right (Local_CRC, 8); end loop; CRC := Local_CRC; end Update; procedure Update_Stream_Array (CRC : in out Unsigned_32; Inbuf : Ada.Streams.Stream_Element_Array) is Local_CRC : Unsigned_32; begin Local_CRC := CRC; for I in Inbuf'Range loop Local_CRC := CRC32_Table (16#FF# and (Local_CRC xor Unsigned_32 (Inbuf (I)))) xor Shift_Right (Local_CRC, 8); end loop; CRC := Local_CRC; end Update_Stream_Array; Table_Empty : Boolean := True; procedure Init (CRC : out Unsigned_32) is begin if Table_Empty then Prepare_Table; Table_Empty := False; end if; CRC := 16#FFFF_FFFF#; end Init; function Final (CRC : Unsigned_32) return Unsigned_32 is begin return not CRC; end Final; function Image (Value : Unsigned_32) return String is Alphabet : constant String := "0123456789abcdef"; V : array (1 .. 4) of Unsigned_8 with Import, Convention => Ada, Address => Value'Address; function Byte (Value : Unsigned_8) return String is (Alphabet (Natural (Value) / 16 + 1) & Alphabet (Natural (Value) mod 16 + 1)); begin return Byte (V (4)) & Byte (V (3)) & Byte (V (2)) & Byte (V (1)); end Image; end DCF.Zip.CRC;
-- This package has been generated automatically by GNATtest. -- Do not edit any part of it, see GNATtest documentation for more details. -- begin read only with Gnattest_Generated; package Tcl.Info.Test_Data.Tests is type Test is new GNATtest_Generated.GNATtest_Standard.Tcl.Info.Test_Data .Test with null record; procedure Test_Get_Arguments_58c9c6_88ad08(Gnattest_T: in out Test); -- tcl-info.ads:43:4:Get_Arguments:Test_Info_Arguments procedure Test_Get_Procedure_Body_4ab4c1_bdefa7(Gnattest_T: in out Test); -- tcl-info.ads:76:4:Get_Procedure_Body:Test_Info_Procedure_Body procedure Test_Get_Commands_Count_9e53d6_cae496(Gnattest_T: in out Test); -- tcl-info.ads:105:4:Get_Commands_Count:Test_Info_Commands_Count procedure Test_Get_Commands_f2ad9c_3093bd(Gnattest_T: in out Test); -- tcl-info.ads:131:4:Get_Commands:Test_Info_Command procedure Test_Complete_c39017_214fb5(Gnattest_T: in out Test); -- tcl-info.ads:164:4:Complete:Test_Info_Complete procedure Test_Get_Coroutine_df9ca4_613b2a(Gnattest_T: in out Test); -- tcl-info.ads:192:4:Get_Coroutine:Test_Info_Coroutine procedure Test_Get_Default_b559cf_8294d7(Gnattest_T: in out Test); -- tcl-info.ads:224:4:Get_Default:Test_Info_Default procedure Test_Get_Error_Stack_c33442_123ed2(Gnattest_T: in out Test); -- tcl-info.ads:256:4:Get_Error_Stack:Test_Info_ErrorStack procedure Test_Exists_a87cb0_c90638(Gnattest_T: in out Test); -- tcl-info.ads:281:4:Exists:Test_Info_Exists procedure Test_Get_Functions_5a1dbc_b56c6e(Gnattest_T: in out Test); -- tcl-info.ads:313:4:Get_Functions:Test_Info_Functions procedure Test_Get_Globals_1284d9_ae8ce6(Gnattest_T: in out Test); -- tcl-info.ads:349:4:Get_Globals:Test_Info_Globals procedure Test_Get_Host_Name_0a278d_b2a918(Gnattest_T: in out Test); -- tcl-info.ads:381:4:Get_Host_Name:Test_Info_HostName procedure Test_Get_Library_36938c_8b9a20(Gnattest_T: in out Test); -- tcl-info.ads:406:4:Get_Library:Test_Info_Library procedure Test_Get_Locals_09a275_95f4c0(Gnattest_T: in out Test); -- tcl-info.ads:435:4:Get_Locals:Test_Info_Locals procedure Test_Get_Name_Of_Executable_1cc16d_24ff4c (Gnattest_T: in out Test); -- tcl-info.ads:465:4:Get_Name_Of_Executable:Test_Info_Name_Of_Executable procedure Test_Get_Patch_Level_0baa9d_325136(Gnattest_T: in out Test); -- tcl-info.ads:491:4:Get_Patch_Level:Test_Info_Patch_Level procedure Test_Get_Procedures_848b43_17d3ea(Gnattest_T: in out Test); -- tcl-info.ads:521:4:Get_Procedures:Test_Info_Procs procedure Test_Get_Script_86aa75_0ba2b7(Gnattest_T: in out Test); -- tcl-info.ads:555:4:Get_Script:Test_Info_Script procedure Test_Get_Tcl_Version_d04078_6661d4(Gnattest_T: in out Test); -- tcl-info.ads:583:4:Get_Tcl_Version:Test_Info_Tcl_Version procedure Test_Get_Variables_fedbab_b301bd(Gnattest_T: in out Test); -- tcl-info.ads:612:4:Get_Variables:Test_Info_Vars end Tcl.Info.Test_Data.Tests; -- end read only
with ada.text_io, ada.Integer_text_IO, Ada.Text_IO.Text_Streams, Ada.Strings.Fixed, Interfaces.C; use ada.text_io, ada.Integer_text_IO, Ada.Strings, Ada.Strings.Fixed, Interfaces.C; procedure euler26 is type stringptr is access all char_array; procedure PString(s : stringptr) is begin String'Write (Text_Streams.Stream (Current_Output), To_Ada(s.all)); end; procedure PInt(i : in Integer) is begin String'Write (Text_Streams.Stream (Current_Output), Trim(Integer'Image(i), Left)); end; type e is Array (Integer range <>) of Integer; type e_PTR is access e; function periode(restes : in e_PTR; c : in Integer; d : in Integer; b : in Integer) return Integer is reste : Integer; len : Integer; chiffre : Integer; a : Integer; begin len := c; a := d; while a /= 0 loop chiffre := a / b; reste := a rem b; for i in integer range 0..len - 1 loop if restes(i) = reste then return len - i; end if; end loop; restes(len) := reste; len := len + 1; a := reste * 10; end loop; return 0; end; t : e_PTR; p : Integer; mi : Integer; m : Integer; begin t := new e (0..999); for j in integer range 0..999 loop t(j) := 0; end loop; m := 0; mi := 0; for i in integer range 1..1000 loop p := periode(t, 0, 1, i); if p > m then mi := i; m := p; end if; end loop; PInt(mi); PString(new char_array'( To_C("" & Character'Val(10)))); PInt(m); PString(new char_array'( To_C("" & Character'Val(10)))); end;
------------------------------------------------------------------------------- -- This file is part of libsparkcrypto. -- -- Copyright (C) 2010, Alexander Senier -- Copyright (C) 2010, secunet Security Networks AG -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- -- * Neither the name of the 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 HOLDER 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. ------------------------------------------------------------------------------- with LSC.Internal.Ops32; with LSC.Internal.Debug; pragma Unreferenced (LSC.Internal.Debug); package body LSC.Internal.HMAC_RIPEMD160 is IPad : constant RIPEMD160.Block_Type := RIPEMD160.Block_Type'(RIPEMD160.Block_Index => 16#36363636#); OPad : constant RIPEMD160.Block_Type := RIPEMD160.Block_Type'(RIPEMD160.Block_Index => 16#5C5C5C5C#); ---------------------------------------------------------------------------- function Context_Init (Key : RIPEMD160.Block_Type) return Context_Type is Result : Context_Type; Temp : RIPEMD160.Block_Type; begin pragma Debug (Debug.Put_Line ("HMAC.RIPEMD160.Context_Init:")); Result.Key := Key; Result.RIPEMD160_Context := RIPEMD160.Context_Init; Ops32.Block_XOR (IPad, Result.Key, Temp); RIPEMD160.Context_Update (Result.RIPEMD160_Context, Temp); return Result; end Context_Init; ---------------------------------------------------------------------------- procedure Context_Update (Context : in out Context_Type; Block : in RIPEMD160.Block_Type) is begin pragma Debug (Debug.Put_Line ("HMAC.RIPEMD160.Context_Update:")); RIPEMD160.Context_Update (Context.RIPEMD160_Context, Block); end Context_Update; ---------------------------------------------------------------------------- procedure Context_Finalize_Outer (Context : in out Context_Type) with Depends => (Context => Context); procedure Context_Finalize_Outer (Context : in out Context_Type) is Hash : RIPEMD160.Hash_Type; Temp : RIPEMD160.Block_Type; begin Hash := RIPEMD160.Get_Hash (Context.RIPEMD160_Context); Context.RIPEMD160_Context := RIPEMD160.Context_Init; Ops32.Block_XOR (OPad, Context.Key, Temp); RIPEMD160.Context_Update (Context.RIPEMD160_Context, Temp); Temp := RIPEMD160.Null_Block; Ops32.Block_Copy (Hash, Temp); RIPEMD160.Context_Finalize (Context.RIPEMD160_Context, Temp, 160); end Context_Finalize_Outer; ---------------------------------------------------------------------------- procedure Context_Finalize (Context : in out Context_Type; Block : in RIPEMD160.Block_Type; Length : in RIPEMD160.Block_Length_Type) is begin pragma Debug (Debug.Put_Line ("HMAC.RIPEMD160.Context_Finalize:")); RIPEMD160.Context_Finalize (Context.RIPEMD160_Context, Block, Length); Context_Finalize_Outer (Context); end Context_Finalize; ---------------------------------------------------------------------------- function Get_Auth (Context : in Context_Type) return RIPEMD160.Hash_Type is begin return RIPEMD160.Get_Hash (Context.RIPEMD160_Context); end Get_Auth; ---------------------------------------------------------------------------- function Authenticate (Key : RIPEMD160.Block_Type; Message : RIPEMD160.Message_Type; Length : Types.Word64) return RIPEMD160.Hash_Type is HMAC_Ctx : Context_Type; begin HMAC_Ctx := Context_Init (Key); RIPEMD160.Hash_Context (Message, Length, HMAC_Ctx.RIPEMD160_Context); Context_Finalize_Outer (HMAC_Ctx); return Get_Auth (HMAC_Ctx); end Authenticate; end LSC.Internal.HMAC_RIPEMD160;
with MSP430_SVD; use MSP430_SVD; with MSPGD.Board; use MSPGD.Board; with MSPGD.Clock; use MSPGD.Clock; with MSPGD.Clock.Source; with MSPGD.GPIO; use MSPGD.GPIO; with MSPGD.GPIO.Pin; with Drivers.Text_IO; with Drivers.NTC; with Interfaces; use Interfaces; procedure Main is pragma Preelaborate; package Text_IO is new Drivers.Text_IO (USART => UART); package Delay_Clock is new MSPGD.Clock.Source (Frequency => 12000, Input => VLO, Source => ACLK); package NTC is new Drivers.NTC; procedure NTC_Test is NTC_Value : Unsigned_32; begin loop LED.Set; NTC_Value := NTC.Value (Integer (Read_NTC)); Text_IO.Put ("NTC Value: "); Text_IO.Put_Hex (NTC_Value); Text_IO.New_Line; LED.Clear; Delay_Clock.Delay_Slow_Periods (1); end loop; end NTC_Test; begin Init; Delay_Clock.Init; Text_IO.Put_Line ("NTC test ..."); NTC_Test; end Main;
with ada.containers.vectors; with numbers; use numbers; with strings; use strings; with env; use env; package getter.for_loop is ERROR_NO_CLOSED : exception; function get return character; procedure create (start_i, end_i : word; var : environment_t.cursor); private end_for_statement : constant string := ".end_for"; for_statement : constant string := ".for"; type for_loop_t is record start_i, end_i, cur_i : natural; cursor : environment_t.cursor := environment_t.no_element; code : unb.unbounded_string; last : positive := 1; first_line, cur_line : pos_count; end record; package for_loops_t is new ada.containers.vectors(element_type => for_loop_t, index_type => natural); for_loops : for_loops_t.vector; cur_for_loop : for_loop_t; tmp_for_loop : for_loop_t; end getter.for_loop;
----------------------------------------------------------------------- -- asf-views-nodes -- Facelet node tree representation -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2018 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- 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. ----------------------------------------------------------------------- with EL.Contexts.Default; with ASF.Components.Core; with ASF.Contexts.Writer; with Ada.Unchecked_Deallocation; with Ada.Exceptions; with Util.Log.Loggers; package body ASF.Views.Nodes is use EL.Expressions; procedure Free is new Ada.Unchecked_Deallocation (Tag_Node'Class, Tag_Node_Access); procedure Free is new Ada.Unchecked_Deallocation (Tag_Attribute_Array, Tag_Attribute_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (Tag_Content, Tag_Content_Access); procedure Free is new Ada.Unchecked_Deallocation (EL.Expressions.Expression'Class, EL.Expressions.Expression_Access); use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Views.Nodes"); -- ------------------------------ -- Attribute of a node. -- ------------------------------ -- ------------------------------ -- Report an error message for the attribute. -- ------------------------------ procedure Error (Attribute : in Tag_Attribute; Message : in String; Param1 : in String; Param2 : in String := "") is begin if Attribute.Tag /= null then Attribute.Tag.Error (Message, Param1, Param2); else Log.Error (Message, Param1, Param2); end if; end Error; -- ------------------------------ -- Compare the attribute name. -- ------------------------------ function "=" (Left : in Tag_Attribute; Right : in String) return Boolean is begin return Left.Name = Right; end "="; function "=" (Left, Right : in Tag_Attribute) return Boolean is begin return Left.Name = Right.Name; end "="; -- ------------------------------ -- Get the attribute name. -- ------------------------------ function Get_Name (Attribute : Tag_Attribute) return String is begin return To_String (Attribute.Name); end Get_Name; -- ------------------------------ -- Returns True if the attribute is static (not an EL expression). -- ------------------------------ function Is_Static (Attribute : Tag_Attribute) return Boolean is begin return Attribute.Binding = null; end Is_Static; -- ------------------------------ -- Get the attribute value. If the attribute is an EL expression -- evaluate that expression in the context of the given UI component. -- ------------------------------ function Get_Value (Attribute : Tag_Attribute; UI : UIComponent'Class) return EL.Objects.Object is procedure Handle_Exception (E : in Ada.Exceptions.Exception_Occurrence); procedure Handle_Exception (E : in Ada.Exceptions.Exception_Occurrence) is begin Error (Attribute, "Evaluation error: {0}", Ada.Exceptions.Exception_Message (E)); end Handle_Exception; begin if Attribute.Binding /= null then declare Ctx : constant EL.Contexts.ELContext_Access := UI.Get_Context.Get_ELContext; Context : EL.Contexts.Default.Guarded_Context (Handle_Exception'Access, Ctx); begin return Attribute.Binding.Get_Value (Context); end; else return EL.Objects.To_Object (Attribute.Value); end if; end Get_Value; -- ------------------------------ -- Get the attribute value. If the attribute is an EL expression -- evaluate that expression in the context of the given UI component. -- ------------------------------ function Get_Value (Attribute : Tag_Attribute; Context : Faces_Context'Class) return EL.Objects.Object is procedure Handle_Exception (E : in Ada.Exceptions.Exception_Occurrence); procedure Handle_Exception (E : in Ada.Exceptions.Exception_Occurrence) is begin Error (Attribute, "Evaluation error: {0}", Ada.Exceptions.Exception_Message (E)); end Handle_Exception; begin if Attribute.Binding /= null then declare Ctx : constant EL.Contexts.ELContext_Access := Context.Get_ELContext; Context : EL.Contexts.Default.Guarded_Context (Handle_Exception'Access, Ctx); begin return Attribute.Binding.Get_Value (Context); end; else return EL.Objects.To_Object (Attribute.Value); end if; end Get_Value; function Get_Value (Attribute : Tag_Attribute; Context : Facelet_Context'Class) return EL.Objects.Object is procedure Handle_Exception (E : in Ada.Exceptions.Exception_Occurrence); procedure Handle_Exception (E : in Ada.Exceptions.Exception_Occurrence) is begin Error (Attribute, "Evaluation error: {0}", Ada.Exceptions.Exception_Message (E)); end Handle_Exception; begin if Attribute.Binding /= null then declare Ctx : constant EL.Contexts.ELContext_Access := Context.Get_ELContext; Context : EL.Contexts.Default.Guarded_Context (Handle_Exception'Access, Ctx); begin return Attribute.Binding.Get_Value (Context); end; else return EL.Objects.To_Object (Attribute.Value); end if; end Get_Value; -- ------------------------------ -- Get the value from the attribute. If the attribute is null or evaluates to -- a NULL object, returns the default value. Convert the value into a string. -- ------------------------------ function Get_Value (Attribute : in Tag_Attribute_Access; Context : in Facelet_Context'Class; Default : in String) return String is begin if Attribute = null then return Default; else declare Value : constant EL.Objects.Object := Get_Value (Attribute.all, Context); begin if EL.Objects.Is_Null (Value) then return Default; else return EL.Objects.To_String (Value); end if; end; end if; end Get_Value; -- ------------------------------ -- Get the EL expression associated with the given tag attribute. -- ------------------------------ function Get_Expression (Attribute : in Tag_Attribute) return EL.Expressions.Expression is begin if Attribute.Binding /= null then return EL.Expressions.Expression (Attribute.Binding.all); else return EL.Expressions.Create_Expression (EL.Objects.To_Object (Attribute.Value)); end if; end Get_Expression; function Get_Value_Expression (Attribute : Tag_Attribute) return EL.Expressions.Value_Expression is begin if Attribute.Binding /= null then return EL.Expressions.Create_Expression (Attribute.Binding.all); else return EL.Expressions.Create_ValueExpression (EL.Objects.To_Object (Attribute.Value)); end if; end Get_Value_Expression; function Get_Method_Expression (Attribute : Tag_Attribute) return EL.Expressions.Method_Expression is begin if Attribute.Binding /= null then return EL.Expressions.Create_Expression (Attribute.Binding.all); else Error (Attribute, "Invalid method expression", ""); raise Constraint_Error with "Invalid method expression"; end if; end Get_Method_Expression; -- ------------------------------ -- Reduce the expression by eliminating known variables and computing -- constant expressions. The result expression is either another -- expression or a computed constant value. -- ------------------------------ function Reduce_Expression (Attribute : Tag_Attribute; Context : Facelet_Context'Class) return EL.Expressions.Expression is E : constant EL.Expressions.Expression := EL.Expressions.Expression (Attribute.Binding.all); begin return E.Reduce_Expression (Context.Get_ELContext.all); end Reduce_Expression; -- ------------------------------ -- Find the tag attribute having the given name. -- Returns an access to the attribute cell within the array or null -- if the no attribute matches the name. -- ------------------------------ function Find_Attribute (Attributes : Tag_Attribute_Array_Access; Name : String) return Tag_Attribute_Access is begin for I in Attributes'Range loop declare Attr : constant Tag_Attribute_Access := Attributes (I)'Access; begin if Attr.Name = Name then return Attr; end if; end; end loop; return null; end Find_Attribute; -- ------------------------------ -- XHTML node -- ------------------------------ -- ------------------------------ -- Get the line information where the tag node is defined. -- ------------------------------ function Get_Line_Info (Node : Tag_Node) return Line_Info is begin return Node.Line; end Get_Line_Info; -- ------------------------------ -- Get the line information as a string. -- ------------------------------ function Get_Line_Info (Node : Tag_Node) return String is L : constant String := Natural'Image (Node.Line.Line); C : constant String := Natural'Image (Node.Line.Column); begin if Node.Line.File = null then return "?:" & L (L'First + 1 .. L'Last) & ':' & C (C'First + 1 .. C'Last); else return Node.Line.File.Path & ':' & L (L'First + 1 .. L'Last) & ':' & C (C'First + 1 .. C'Last); end if; end Get_Line_Info; -- ------------------------------ -- Get the relative path name of the XHTML file in which this tag is defined. -- ------------------------------ function Get_File_Name (Node : in Tag_Node) return String is File : constant File_Info_Access := Node.Line.File; begin return File.Path (File.Relative_Pos .. File.Path'Last); end Get_File_Name; -- ------------------------------ -- Get the node attribute with the given name. -- Returns null if the node does not have such attribute. -- ------------------------------ function Get_Attribute (Node : Tag_Node; Name : String) return Tag_Attribute_Access is begin if Node.Attributes = null then return null; end if; return Find_Attribute (Node.Attributes, Name); end Get_Attribute; -- ------------------------------ -- Initialize the node -- ------------------------------ procedure Initialize (Node : in Tag_Node_Access; Binding : in Binding_Type; Line : in Line_Info; Parent : in Tag_Node_Access; Attributes : in Tag_Attribute_Array_Access) is begin Node.Factory := Binding.Component; Node.Line := Line; Node.Parent := Parent; Node.Attributes := Attributes; if Node.Attributes /= null then for I in Attributes.all'Range loop Attributes (I).Tag := Node; end loop; end if; Append_Tag (Parent, Node); end Initialize; -- ------------------------------ -- Append a child tag node. -- ------------------------------ procedure Append_Tag (Node : in Tag_Node_Access; Child : in Tag_Node_Access) is begin if Node.First_Child = null then Node.First_Child := Child; else Node.Last_Child.Next := Child; end if; Node.Last_Child := Child; Child.Parent := Node; Child.Next := null; end Append_Tag; -- ------------------------------ -- Freeze the tag node tree and perform any initialization steps -- necessary to build the components efficiently. After this call -- the tag node tree should not be modified and it represents a read-only -- tree. -- ------------------------------ procedure Freeze (Node : access Tag_Node) is begin null; end Freeze; -- ------------------------------ -- Delete the node and its children freeing the memory as necessary -- ------------------------------ procedure Delete (Node : access Tag_Node) is Child : Tag_Node_Access := Node.First_Child; Next : Tag_Node_Access; begin while Child /= null loop Next := Child.Next; Child.Delete; Free (Child); Child := Next; end loop; if Node.Attributes /= null then for I in Node.Attributes'Range loop declare Expr : EL.Expressions.Expression_Access := Node.Attributes (I).Binding; begin Free (Expr); end; end loop; Free (Node.Attributes); end if; end Delete; procedure Destroy (Node : in out Tag_Node_Access) is begin Node.Delete; Free (Node); end Destroy; -- ------------------------------ -- Report an error message -- ------------------------------ procedure Error (Node : in Tag_Node'Class; Message : in String; Param1 : in String := ""; Param2 : in String := "") is L : constant String := Node.Get_Line_Info; begin Log.Error (L & ":" & Message, Param1, Param2); end Error; -- ------------------------------ -- Build the component attributes from the facelet tag node and the facelet context. -- ------------------------------ procedure Build_Attributes (UI : in out UIComponent'Class; Node : in Tag_Node'Class; Context : in out Facelet_Context'Class) is procedure Process_Attribute (Attr : in Tag_Attribute_Access); procedure Process_Attribute (Attr : in Tag_Attribute_Access) is begin if Attr.Binding /= null then -- Reduce the expression by eliminating variables which are defined in -- the Facelet context. We can obtain another expression or a constant value. declare Ctx : constant EL.Contexts.ELContext_Access := Context.Get_ELContext; Expr : constant EL.Expressions.Expression := EL.Expressions.Expression (Attr.Binding.all).Reduce_Expression (Ctx.all); begin if Expr.Is_Constant then UI.Set_Attribute (Def => Attr, Value => Expr.Get_Value (Ctx.all)); else UI.Set_Attribute (Def => Attr, Value => Expr); end if; end; end if; end Process_Attribute; -- Iterate over the attributes to resolve some value expressions. procedure Iterate_Attributes is new ASF.Views.Nodes.Iterate_Attributes (Process_Attribute); begin Iterate_Attributes (Node); end Build_Attributes; -- ------------------------------ -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. -- ------------------------------ procedure Build_Components (Node : access Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class) is UI : constant UIComponent_Access := Node.Factory.all; begin Append (Parent, UI, Node); Build_Attributes (UI.all, Node.all, Context); UI.Initialize (UI.Get_Context.all); Node.Build_Children (UI, Context); end Build_Components; procedure Build_Children (Node : access Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class) is Child : Tag_Node_Access; begin Child := Node.First_Child; while Child /= null loop Child.Build_Components (Parent, Context); Child := Child.Next; end loop; end Build_Children; -- ------------------------------ -- Iterate over the attributes defined on the node and -- execute the <b>Process</b> procedure. -- ------------------------------ procedure Iterate_Attributes (Node : in Tag_Node'Class) is begin for I in Node.Attributes'Range loop declare Attr : constant Tag_Attribute_Access := Node.Attributes (I)'Access; begin Process (Attr); end; end loop; end Iterate_Attributes; -- ------------------------------ -- Freeze the tag node tree. -- Count the number of Tag_Content represented by this node. -- ------------------------------ overriding procedure Freeze (Node : access Text_Tag_Node) is Content : access constant Tag_Content := Node.Content'Access; Count : Natural := 0; begin loop Content := Content.Next; Count := Count + 1; exit when Content = null; end loop; Node.Count := Count; end Freeze; overriding procedure Build_Components (Node : access Text_Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class) is UI : constant ASF.Components.Core.UIText_Access := ASF.Components.Core.Create_UIText (Node.all'Access); Expr_Table : Expression_Access_Array_Access := null; Ctx : constant EL.Contexts.ELContext_Access := Context.Get_ELContext; Content : access constant Tag_Content := Node.Content'Access; Pos : Natural := 1; begin Append (Parent, UI.all'Access, Node); loop if not Content.Expr.Is_Null then -- Reduce the expression by eliminating variables which are defined in -- the Facelet context. We can obtain another expression or a constant value. declare Expr : constant EL.Expressions.Expression := Content.Expr.Reduce_Expression (Ctx.all); begin if Expr /= Content.Expr then if Expr_Table = null then Expr_Table := new Expression_Access_Array (1 .. Node.Count); UI.Set_Expression_Table (Expr_Table); end if; Expr_Table (Pos) := new EL.Expressions.Expression '(Expr); end if; end; end if; Content := Content.Next; Pos := Pos + 1; exit when Content = null; end loop; end Build_Components; -- ------------------------------ -- Delete the node and its children freeing the memory as necessary -- ------------------------------ procedure Delete (Node : access Text_Tag_Node) is Content : Tag_Content_Access := Node.Content.Next; begin while Content /= null loop declare Next : constant Tag_Content_Access := Content.Next; begin Free (Content); Content := Next; end; end loop; Node.Content.Next := null; Node.Last := null; end Delete; -- ------------------------------ -- Encode the content represented by this text node. -- The expressions are evaluated if necessary. -- ------------------------------ procedure Encode_All (Node : in Text_Tag_Node; Expr : in Expression_Access_Array_Access; Context : in Faces_Context'Class) is Writer : constant ASF.Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Content : access constant Tag_Content := Node.Content'Access; Pos : Natural := 1; begin loop Writer.Write (Content.Text); begin if Expr /= null and then Expr (Pos) /= null then declare Value : constant EL.Objects.Object := Expr (Pos).Get_Value (Context.Get_ELContext.all); begin if not EL.Objects.Is_Null (Value) then Writer.Write_Text (Value); end if; end; else declare Value : constant EL.Objects.Object := Content.Expr.Get_Value (Context.Get_ELContext.all); begin if not EL.Objects.Is_Null (Value) then Writer.Write_Text (Value); end if; end; end if; exception when E : others => Node.Error ("Evaluation error: {0}", Ada.Exceptions.Exception_Message (E)); end; Content := Content.Next; Pos := Pos + 1; exit when Content = null; end loop; end Encode_All; function First (Node : in Tag_Node_Access) return Cursor is Result : Cursor; begin Result.Node := Node.First_Child; return Result; end First; function Has_Element (C : Cursor) return Boolean is begin return C.Node /= null; end Has_Element; function Element (Position : Cursor) return Tag_Node_Access is begin return Position.Node; end Element; procedure Next (Position : in out Cursor) is begin Position.Node := Position.Node.Next; end Next; -- Create a tag node -- Create the text Tag function Create_Component_Node (Binding : in Binding_Type; Line : in Line_Info; Parent : in Tag_Node_Access; Attributes : in Tag_Attribute_Array_Access) return Tag_Node_Access is Node : constant Tag_Node_Access := new Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); return Node.all'Access; end Create_Component_Node; end ASF.Views.Nodes;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- I N T E R F A C E S -- -- -- -- S p e c -- -- -- -- Copyright (C) 2002-2013, Free Software Foundation, Inc. -- -- -- -- This specification is derived from the Ada Reference Manual for use with -- -- GNAT. The copyright notice above, and the license provisions that follow -- -- apply solely to the implementation dependent sections of this file. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ pragma Compiler_Unit_Warning; package Interfaces is pragma Pure; -- All identifiers in this unit are implementation defined pragma Implementation_Defined; type Integer_8 is range -2 ** 7 .. 2 ** 7 - 1; for Integer_8'Size use 8; type Integer_16 is range -2 ** 15 .. 2 ** 15 - 1; for Integer_16'Size use 16; type Integer_32 is range -2 ** 31 .. 2 ** 31 - 1; for Integer_32'Size use 32; type Integer_64 is range -2 ** 63 .. 2 ** 63 - 1; for Integer_64'Size use 64; type Unsigned_8 is mod 2 ** 8; for Unsigned_8'Size use 8; type Unsigned_16 is mod 2 ** 16; for Unsigned_16'Size use 16; type Unsigned_32 is mod 2 ** 32; for Unsigned_32'Size use 32; type Unsigned_64 is mod 2 ** 64; for Unsigned_64'Size use 64; function Shift_Left (Value : Unsigned_8; Amount : Natural) return Unsigned_8; function Shift_Right (Value : Unsigned_8; Amount : Natural) return Unsigned_8; function Shift_Right_Arithmetic (Value : Unsigned_8; Amount : Natural) return Unsigned_8; function Rotate_Left (Value : Unsigned_8; Amount : Natural) return Unsigned_8; function Rotate_Right (Value : Unsigned_8; Amount : Natural) return Unsigned_8; function Shift_Left (Value : Unsigned_16; Amount : Natural) return Unsigned_16; function Shift_Right (Value : Unsigned_16; Amount : Natural) return Unsigned_16; function Shift_Right_Arithmetic (Value : Unsigned_16; Amount : Natural) return Unsigned_16; function Rotate_Left (Value : Unsigned_16; Amount : Natural) return Unsigned_16; function Rotate_Right (Value : Unsigned_16; Amount : Natural) return Unsigned_16; function Shift_Left (Value : Unsigned_32; Amount : Natural) return Unsigned_32; function Shift_Right (Value : Unsigned_32; Amount : Natural) return Unsigned_32; function Shift_Right_Arithmetic (Value : Unsigned_32; Amount : Natural) return Unsigned_32; function Rotate_Left (Value : Unsigned_32; Amount : Natural) return Unsigned_32; function Rotate_Right (Value : Unsigned_32; Amount : Natural) return Unsigned_32; function Shift_Left (Value : Unsigned_64; Amount : Natural) return Unsigned_64; function Shift_Right (Value : Unsigned_64; Amount : Natural) return Unsigned_64; function Shift_Right_Arithmetic (Value : Unsigned_64; Amount : Natural) return Unsigned_64; function Rotate_Left (Value : Unsigned_64; Amount : Natural) return Unsigned_64; function Rotate_Right (Value : Unsigned_64; Amount : Natural) return Unsigned_64; pragma Import (Intrinsic, Shift_Left); pragma Import (Intrinsic, Shift_Right); pragma Import (Intrinsic, Shift_Right_Arithmetic); pragma Import (Intrinsic, Rotate_Left); pragma Import (Intrinsic, Rotate_Right); -- IEEE Floating point types. Note that the form of these definitions -- ensures that the work on VMS, even if the standard library is compiled -- using a Float_Representation pragma for Vax_Float. pragma Warnings (Off); -- Turn off warnings for targets not providing IEEE floating-point types type IEEE_Float_32 is digits 6; pragma Float_Representation (IEEE_Float, IEEE_Float_32); for IEEE_Float_32'Size use 32; type IEEE_Float_64 is digits 15; pragma Float_Representation (IEEE_Float, IEEE_Float_64); for IEEE_Float_64'Size use 64; -- If there is an IEEE extended float available on the machine, we assume -- that it is available as Long_Long_Float. -- Note: it is harmless, and explicitly permitted, to include additional -- types in interfaces, so it is not wrong to have IEEE_Extended_Float -- defined even if the extended format is not available. type IEEE_Extended_Float is new Long_Long_Float; end Interfaces;
with Extraction.Node_Edge_Types; with Extraction.Utilities; package body Extraction.Renamings is use type LALCO.Ada_Node_Kind_Type; function Is_Renaming (Node : LAL.Ada_Node'Class) return Boolean; function Is_Renaming (Node : LAL.Ada_Node'Class) return Boolean is begin return Node.Kind in LALCO.Ada_Package_Renaming_Decl | LALCO.Ada_Generic_Package_Renaming_Decl | LALCO.Ada_Subp_Renaming_Decl | LALCO.Ada_Generic_Subp_Renaming_Decl or else (Node.Kind = LALCO.Ada_Exception_Decl and then not Node.As_Exception_Decl.F_Renames.Is_Null) or else (Node.Kind = LALCO.Ada_Object_Decl and then not Node.As_Object_Decl.F_Renaming_Clause.Is_Null); end Is_Renaming; function Get_Renamed_Name (Basic_Decl : LAL.Basic_Decl'Class) return LAL.Name; function Get_Renamed_Name (Basic_Decl : LAL.Basic_Decl'Class) return LAL.Name is begin case LALCO.Ada_Basic_Decl (Basic_Decl.Kind) is when LALCO.Ada_Package_Renaming_Decl => return Basic_Decl.As_Package_Renaming_Decl.F_Renames.F_Renamed_Object; when LALCO.Ada_Generic_Package_Renaming_Decl => return Basic_Decl.As_Generic_Package_Renaming_Decl.F_Renames; when LALCO.Ada_Subp_Renaming_Decl => return Basic_Decl.As_Subp_Renaming_Decl.F_Renames.F_Renamed_Object; when LALCO.Ada_Generic_Subp_Renaming_Decl => return Basic_Decl.As_Generic_Subp_Renaming_Decl.F_Renames; when LALCO.Ada_Exception_Decl => return Basic_Decl.As_Exception_Decl.F_Renames.F_Renamed_Object; when LALCO.Ada_Object_Decl => return Basic_Decl.As_Object_Decl.F_Renaming_Clause.F_Renamed_Object; when others => raise Internal_Extraction_Error with "Cases in Is_Renaming and Get_Renamed_Name do not match"; end case; end Get_Renamed_Name; procedure Extract_Edges (Node : LAL.Ada_Node'Class; Graph : Graph_Operations.Graph_Context) is begin if Utilities.Is_Relevant_Basic_Decl (Node) and then Is_Renaming (Node) and then not Utilities.Get_Referenced_Decl (Get_Renamed_Name (Node.As_Basic_Decl)) .Is_Null -- Ignore builtins. then declare Renaming_Decl : constant LAL.Basic_Decl := Node.As_Basic_Decl; Renamed_Name : constant LAL.Defining_Name := Utilities.Get_Referenced_Defining_Name (Get_Renamed_Name (Renaming_Decl)); Renamed_Decl : constant LAL.Basic_Decl := Utilities.Get_Referenced_Decl (Get_Renamed_Name (Renaming_Decl)); begin Graph.Write_Edge (Renaming_Decl, Renamed_Name, Renamed_Decl, Node_Edge_Types.Edge_Type_Renames); end; end if; end Extract_Edges; end Extraction.Renamings;
with MathUtils; with NNClassifier; with DataBatch; with PixelArray; with Ada.Strings.Unbounded; package TrainingData is pragma Elaborate_Body; pragma Assertion_Policy (Pre => Check, Post => Check, Type_Invariant => Check); type Set is tagged limited record values: DataBatch.Batch; labels: NNClassifier.LabelVector; end record with Dynamic_Predicate => values.size = Natural(labels.Length); blockSize: constant Positive := 28; blockArea: constant Positive := blockSize * blockSize; function size(data: in Set) return Natural; procedure add(data: in out Set; label: Natural; vec: MathUtils.Vector); procedure loadFrom(data: in out Set; path: in Ada.Strings.Unbounded.Unbounded_String); function toDataVector(img: in PixelArray.ImagePlane; invertPixels: Boolean := False) return MathUtils.Vector with Post => Natural(toDataVector'Result.Length) = img.width * img.height; end TrainingData;
with Ada.Directories; with Ada.Strings.Unbounded; with Ada.Tags; with Ahven.Framework; with Aircraft.Api; package Test_Aircraft.Append is package Skill renames Aircraft.Api; use Aircraft; use Api; type Test is new Ahven.Framework.Test_Case with null record; procedure Initialize (T : in out Test); procedure Set_Up (T : in out Test); procedure Tear_Down (T : in out Test); procedure Create_Write_Read_Append_Write_Read (T : in out Ahven.Framework.Test_Case'Class); procedure Check_Tags_After_Append (T : in out Ahven.Framework.Test_Case'Class); end Test_Aircraft.Append;
------------------------------------------------------------------------------ -- -- -- ASIS-for-GNAT INTERFACE COMPONENTS -- -- -- -- A S I S . S T A T E M E N T S -- -- -- -- S p e c -- -- -- -- Copyright (C) 2006-2012, AdaCore -- -- -- -- This specification is adapted from the Ada Semantic Interface -- -- Specification Standard (ISO/IEC 15291) for use with GNAT. In accordance -- -- with the copyright of that document, you can freely copy and modify this -- -- specification, provided that if you redistribute a modified version, any -- -- changes that you have made are clearly indicated. -- -- -- -- This specification also contains suggestions and discussion items -- -- related to revising the ASIS Standard according to the changes proposed -- -- for the new revision of the Ada standard. The copyright notice above, -- -- and the license provisions that follow apply solely to these suggestions -- -- and discussion items that are separated by the corresponding comment -- -- sentinels -- -- -- -- ASIS-for-GNAT is free software; you can redistribute it and/or modify it -- -- under terms of the GNU General Public License as published by the Free -- -- Software Foundation; either version 2, or (at your option) any later -- -- version. ASIS-for-GNAT is distributed in the hope that it will be use- -- -- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- -- -- CHANTABILITY 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 distributed with ASIS-for-GNAT; see file -- -- COPYING. If not, write to the Free Software Foundation, 51 Franklin -- -- Street, Fifth Floor, Boston, MA 02110-1301, USA. -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the -- -- Software Engineering Laboratory of the Swiss Federal Institute of -- -- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the -- -- Scientific Research Computer Center of Moscow State University (SRCC -- -- MSU), Russia, with funding partially provided by grants from the Swiss -- -- National Science Foundation and the Swiss Academy of Engineering -- -- Sciences. ASIS-for-GNAT is now maintained by AdaCore -- -- (http://www.adacore.com). -- -- -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- 18 package Asis.Statements -- Suggestions related to changing this specification to accept new Ada -- features as defined in incoming revision of the Ada Standard (ISO 8652) -- are marked by following comment sentinels: -- -- --|A2005 start -- ... the suggestion goes here ... -- --|A2005 end -- -- and the discussion items are marked by the comment sentinels of teh form: -- -- --|D2005 start -- ... the discussion item goes here ... -- --|D2005 end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ package Asis.Statements is ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Asis.Statements encapsulates a set of queries that operate on A_Statement, -- A_Path, and An_Exception_Handler elements. ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- 18.1 function Label_Names ------------------------------------------------------------------------------ function Label_Names (Statement : Asis.Statement) return Asis.Defining_Name_List; ------------------------------------------------------------------------------ -- Statement - Specifies the statement to query -- -- Returns label_statement_identifier elements (A_Defining_Name elements) that -- define the labels attached to the statement, in their order of appearance. -- -- Returns a Nil_Element_List if there are no labels attached to the -- statement. -- -- The Enclosing_Element of the A_Defining_Name elements is the statement. -- -- --|A2012 start -- In case of 'floating' labels in Ada 2012 (labels that completes -- sequence_of_statements and that are not attached to any statement) ASIS -- treats them as being attached to the implicit A_Null_Statement element that -- is the last Element in a statement list returned by the corresponding -- structural query. Such an implicit A_Null_Statement can be the given as -- the actual for this query to get 'floating' labels. -- --|A2012 end -- -- Appropriate Element_Kinds: -- A_Statement -- -- Returns Defining_Name_Kinds: -- A_Defining_Identifier -- ------------------------------------------------------------------------------ -- 18.2 function Assignment_Variable_Name ------------------------------------------------------------------------------ function Assignment_Variable_Name (Statement : Asis.Statement) return Asis.Expression; ------------------------------------------------------------------------------ -- Statement - Specifies the assignment statement to query -- -- Returns the expression that names the left hand side of the assignment. -- -- Appropriate Element_Kinds: -- A_Statement -- -- Appropriate Statement_Kinds: -- An_Assignment_Statement -- -- Returns Element_Kinds: -- An_Expression -- ------------------------------------------------------------------------------ -- 18.3 function Assignment_Expression ------------------------------------------------------------------------------ function Assignment_Expression (Statement : Asis.Statement) return Asis.Expression; ------------------------------------------------------------------------------ -- Statement - Specifies the assignment statement to query -- -- Returns the expression from the right hand side of the assignment. -- -- Appropriate Element_Kinds: -- A_Statement -- -- Appropriate Statement_Kinds: -- An_Assignment_Statement -- -- Returns Element_Kinds: -- An_Expression ------------------------------------------------------------------------------ -- 18.4 function Statement_Paths ------------------------------------------------------------------------------ function Statement_Paths (Statement : Asis.Statement; Include_Pragmas : Boolean := False) return Asis.Path_List; ------------------------------------------------------------------------------ -- Statement - Specifies the statement to query -- Include_Pragmas - Specifies whether pragmas are to be returned -- -- Returns a list of the execution paths of the statement, in -- their order of appearance. -- -- The only pragmas returned are those preceding the first alternative in -- a case statement. -- -- Appropriate Statement_Kinds: -- An_If_Statement -- A_Case_Statement -- A_Selective_Accept_Statement -- A_Timed_Entry_Call_Statement -- A_Conditional_Entry_Call_Statement -- An_Asynchronous_Select_Statement -- -- Returns Element_Kinds: -- A_Path -- A_Pragma -- ------------------------------------------------------------------------------ -- 18.5 function Condition_Expression ------------------------------------------------------------------------------ function Condition_Expression (Path : Asis.Path) return Asis.Expression; ------------------------------------------------------------------------------ -- Path - Specifies the execution path to query -- -- Returns the condition expression for an IF path or an ELSIF statement or -- expression path. -- -- Appropriate Path_Kinds: -- An_If_Path -- An_Elsif_Path -- An_If_Expression_Path -- ASIS 2012 -- An_Elsif_Expression_Path -- ASIS 2012 -- -- Returns Element_Kinds: -- An_Expression -- ------------------------------------------------------------------------------ -- 18.6 function Sequence_Of_Statements ------------------------------------------------------------------------------ function Sequence_Of_Statements (Path : Asis.Path; Include_Pragmas : Boolean := False) return Asis.Statement_List; ------------------------------------------------------------------------------ -- Path - Specifies the execution path to query -- Include_Pragmas - Specifies whether pragmas are to be returned -- -- Returns a list of the statements and pragmas from an execution path, -- in their order of appearance. -- -- --|A2012 start -- In case if a sequence_of_Statements in the argument Element contains -- 'floating' labels (labels that completes sequence_of_statements and that -- are not attached to any statement in the source code), the result list -- contains as its last element an implicit A_Null_Statement element these -- 'floating' labels are attached to. The Enclosing_Element of this implicit -- A_Null_Statement element is the argument Element. -- --|A2012 start -- -- Appropriate Element_Kinds: -- A_Path -- -- Returns Element_Kinds: -- A_Statement -- A_Pragma -- ------------------------------------------------------------------------------ -- 18.7 function Case_Expression ------------------------------------------------------------------------------ function Case_Expression (Statement : Asis.Statement) return Asis.Expression; ------------------------------------------------------------------------------ -- Statement - Specifies the case statement to query -- -- --|A2012 start -- -- Adapted for Ada 2012: -- Returns the expression of the case statement or case expression that -- determines which execution path is taken or which alternative is used to -- get the value of the expression. -- -- Appropriate Element_Kinds: -- A_Statement -- An_Expression -- -- Appropriate Statement_Kinds: -- A_Case_Statement -- -- Appropriate Expression_Kinds: -- A_Case_Expression -- -- Returns Element_Kinds: -- An_Expression -- -- --|A2012 end ------------------------------------------------------------------------------ -- 18.8 function Case_Statement_Alternative_Choices ------------------------------------------------------------------------------ function Case_Statement_Alternative_Choices (Path : Asis.Path) return Asis.Element_List; ------------------------------------------------------------------------------ -- Path - Specifies the case_statement_alternative execution path to query -- -- Returns a list of the 'when <choice> | <choice>' elements, in their -- order of appearance. -- -- Appropriate Path_Kinds: -- A_Case_Path -- -- Returns Element_Kinds: -- An_Expression -- A_Definition -- -- Returns Definition_Kinds: -- A_Discrete_Range -- An_Others_Choice -- ------------------------------------------------------------------------------ -- 18.9 function Statement_Identifier ------------------------------------------------------------------------------ function Statement_Identifier (Statement : Asis.Statement) return Asis.Defining_Name; ------------------------------------------------------------------------------ -- Statement - Specifies the statement to query -- -- Returns the identifier for the loop_statement or block_statement. -- -- Returns a Nil_Element if the loop has no identifier. -- -- The Enclosing_Element of the name is the statement. -- -- Appropriate Statement_Kinds: -- A_Loop_Statement -- A_While_Loop_Statement -- A_For_Loop_Statement -- A_Block_Statement -- -- Returns Defining_Name_Kinds: -- Not_A_Defining_Name -- A_Defining_Identifier -- ------------------------------------------------------------------------------ -- 18.10 function Is_Name_Repeated ------------------------------------------------------------------------------ function Is_Name_Repeated (Statement : Asis.Statement) return Boolean; ------------------------------------------------------------------------------ -- Statement - Specifies the statement to query -- -- Returns True if the name of the accept, loop, or block is repeated after -- the end of the statement. Always returns True for loop or block -- statements since the name is required. -- -- Returns False for any unexpected Element. -- -- Expected Statement_Kinds: -- A_Block_Statement -- A_Loop_Statement -- An_Accept_Statement -- ------------------------------------------------------------------------------ -- 18.11 function While_Condition ------------------------------------------------------------------------------ function While_Condition (Statement : Asis.Statement) return Asis.Expression; ------------------------------------------------------------------------------ -- Statement - Specifies the loop statement to query -- -- Returns the condition expression associated with the while loop. -- -- Appropriate Element_Kinds: -- A_Statement -- -- Appropriate Statement_Kinds: -- A_While_Loop_Statement -- -- Returns Element_Kinds: -- An_Expression -- ------------------------------------------------------------------------------ -- 18.12 function For_Loop_Parameter_Specification ------------------------------------------------------------------------------ function For_Loop_Parameter_Specification (Statement : Asis.Statement) return Asis.Declaration; ------------------------------------------------------------------------------ -- Statement - Specifies the loop statement to query -- -- Returns the declaration of the A_Loop_Parameter_Specification. -- -- Appropriate Statement_Kinds: -- A_For_Loop_Statement -- -- Returns Declaration_Kinds: -- A_Loop_Parameter_Specification -- ------------------------------------------------------------------------------ -- 18.13 function Loop_Statements ------------------------------------------------------------------------------ function Loop_Statements (Statement : Asis.Statement; Include_Pragmas : Boolean := False) return Asis.Statement_List; ------------------------------------------------------------------------------ -- Statement - Specifies the loop statement to query -- Include_Pragmas - Specifies whether pragmas are to be returned -- -- Returns the sequence_of_statements and any pragmas from the loop_statement, -- in their order of appearance. -- -- --|A2012 start -- In case if a sequence_of_Statements in the argument Element contains -- 'floating' labels (labels that completes sequence_of_statements and that -- are not attached to any statement in the source code), the result list -- contains as its last element an implicit A_Null_Statement element these -- 'floating' labels are attached to. The Enclosing_Element of this implicit -- A_Null_Statement element is the argument Element. -- --|A2012 start -- -- Appropriate Statement_Kinds: -- A_Loop_Statement -- A_While_Loop_Statement -- A_For_Loop_Statement -- -- Returns Element_Kinds: -- A_Pragma -- A_Statement -- ------------------------------------------------------------------------------ -- 18.14 function Is_Declare_Block ------------------------------------------------------------------------------ function Is_Declare_Block (Statement : Asis.Statement) return Boolean; ------------------------------------------------------------------------------ -- Statement - Specifies the statement to query -- -- Returns True if the statement is a block_statement and it was created with -- the use of the "declare" reserved word. The presence or absence of any -- declarative_item elements is not relevant. -- -- Returns False if the "declare" reserved word does not appear in the -- block_statement, or for any unexpected Element. -- -- Expected Statement_Kinds: -- A_Block_Statement -- ------------------------------------------------------------------------------ -- 18.15 function Block_Declarative_Items ------------------------------------------------------------------------------ function Block_Declarative_Items (Statement : Asis.Statement; Include_Pragmas : Boolean := False) return Asis.Declarative_Item_List; ------------------------------------------------------------------------------ -- Statement - Specifies the block statement to query -- Include_Pragmas - Specifies whether pragmas are to be returned -- -- Returns a list of the declarations, representation_clause elements, -- pragmas, and use_clause elements in the declarative_part of the -- block_statement, in their order of appearance. -- -- Returns a Nil_Element_List if there are no declarative items. -- -- Appropriate Statement_Kinds: -- A_Block_Statement -- -- Returns Element_Kinds: -- A_Declaration -- A_Pragma -- A_Clause -- ------------------------------------------------------------------------------ -- 18.16 function Block_Statements ------------------------------------------------------------------------------ function Block_Statements (Statement : Asis.Statement; Include_Pragmas : Boolean := False) return Asis.Statement_List; ------------------------------------------------------------------------------ -- Statement - Specifies the block statement to query -- Include_Pragmas - Specifies whether pragmas are to be returned -- -- Returns a list of the statements and pragmas for the block_statement, in -- their order of appearance. -- -- Returns a Nil_Element_List if there are no statements or pragmas. This -- can only occur for a block_statement obtained from the obsolescent query -- Body_Block_Statement when its argument is a package_body -- that has no sequence_of_statements. -- -- --|A2012 start -- In case if a sequence_of_Statements in the argument Element contains -- 'floating' labels (labels that completes sequence_of_statements and that -- are not attached to any statement in the source code), the result list -- contains as its last element an implicit A_Null_Statement element these -- 'floating' labels are attached to. The Enclosing_Element of this implicit -- A_Null_Statement element is the argument Element. -- --|A2012 start -- -- Appropriate Statement_Kinds: -- A_Block_Statement -- -- Returns Element_Kinds: -- A_Pragma -- A_Statement -- ------------------------------------------------------------------------------ -- 18.17 function Block_Exception_Handlers ------------------------------------------------------------------------------ function Block_Exception_Handlers (Statement : Asis.Statement; Include_Pragmas : Boolean := False) return Asis.Exception_Handler_List; ------------------------------------------------------------------------------ -- Statement - Specifies the block statement to query -- Include_Pragmas - Specifies whether pragmas are to be returned -- -- Returns a list of the exception_handler elements of the block_statement, -- in their order of appearance. -- -- The only pragmas returned are those following the reserved word "exception" -- and preceding the reserved word "when" of first exception handler. -- -- Returns a Nil_Element_List if there are no exception_handler elements. -- -- Appropriate Statement_Kinds: -- A_Block_Statement -- -- Returns Element_Kinds: -- An_Exception_Handler -- A_Pragma -- ------------------------------------------------------------------------------ -- 18.18 function Exit_Loop_Name ------------------------------------------------------------------------------ function Exit_Loop_Name (Statement : Asis.Statement) return Asis.Expression; ------------------------------------------------------------------------------ -- Statement - Specifies the exit statement to query -- -- Returns the name of the exited loop. -- -- Returns a Nil_Element if no loop name is present. -- -- Appropriate Statement_Kinds: -- An_Exit_Statement -- -- Returns Expression_Kinds: -- Not_An_Expression -- An_Identifier -- A_Selected_Component -- ------------------------------------------------------------------------------ -- 18.19 function Exit_Condition ------------------------------------------------------------------------------ function Exit_Condition (Statement : Asis.Statement) return Asis.Expression; ------------------------------------------------------------------------------ -- Statement - Specifies the exit statement to query -- -- Returns the "when" condition of the exit statement. -- -- Returns a Nil_Element if no condition is present. -- -- Appropriate Statement_Kinds: -- An_Exit_Statement -- -- Returns Element_Kinds: -- Not_An_Element -- An_Expression -- ------------------------------------------------------------------------------ -- 18.20 function Corresponding_Loop_Exited ------------------------------------------------------------------------------ function Corresponding_Loop_Exited (Statement : Asis.Statement) return Asis.Statement; ------------------------------------------------------------------------------ -- Statement - Specifies the exit statement to query -- -- Returns the loop statement exited by the exit statement. -- -- Appropriate Statement_Kinds: -- An_Exit_Statement -- -- Returns Element_Kinds: -- A_Loop_Statement -- A_While_Loop_Statement -- A_For_Loop_Statement -- ------------------------------------------------------------------------------ -- 18.21 function Return_Expression ------------------------------------------------------------------------------ function Return_Expression (Statement : Asis.Statement) return Asis.Expression; ------------------------------------------------------------------------------ -- Statement - Specifies the return statement to query -- -- Returns the expression in the return statement. -- -- Returns a Nil_Element if no expression is present. -- -- Appropriate Statement_Kinds: -- A_Return_Statement -- -- Returns Element_Kinds: -- Not_An_Element -- An_Expression -- -- |A2005 start ------------------------------------------------------------------------------ -- 18.#??? function Return_Object_Declaration ------------------------------------------------------------------------------ function Return_Object_Declaration (Statement : Asis.Statement) return Asis.Declaration; ------------------------------------------------------------------------------ -- Statement - Specifies the extended return statement to query -- -- Returns the declaration of the return object. -- -- Appropriate Statement_Kinds: -- An_Extended_Return_Statement -- -- Returns Declaration_Kinds: -- A_Return_Object_Declaration -- -- |D2005 end -- It Ada 95 there was no notion of a return object, and it was quite logical -- when ASIS returned An_Expression element for A_Return_Statement as a -- value returned by a return statement. For An_Extended_Return_Statement -- we do not have any An_Expression element to be returned as a returned -- value, the only possibility is to return A_Declaration Element representing -- the declaration of returned object. This corresponds to the semantics -- of the return statement defined by Ada 2005. -- -- So the problem is that for two forms of a return statement ASIS 2005 -- provides two different ways of providing information about what is returned -- by the statement - an expression or a declaration. Moreover, the old -- Return_Expression query in Ada 2005 does not correspond any more to the -- (formal) semantic of the return statement. -- -- I do not know how to improve this situation at the ASIS side. Probably, -- we need an Application Note discussing this situation -- |D2005 start ------------------------------------------------------------------------------ -- 18.#??? function Extended_Return_Statements ------------------------------------------------------------------------------ function Extended_Return_Statements (Statement : Asis.Statement; Include_Pragmas : Boolean := False) return Asis.Statement_List; ------------------------------------------------------------------------------ -- Statement - Specifies the extended return statement to query -- Include_Pragmas - Specifies whether pragmas are to be returned -- -- Returns a list of the statements and pragmas from the extended return -- statement, in their order of appearance. -- -- Returns a Nil_Element_List if the argument extended return statement does -- not include handled_sequence_of_statements. -- -- --|A2012 start -- In case if a sequence_of_Statements in the argument Element contains -- 'floating' labels (labels that completes sequence_of_statements and that -- are not attached to any statement in the source code), the result list -- contains as its last element an implicit A_Null_Statement element these -- 'floating' labels are attached to. The Enclosing_Element of this implicit -- A_Null_Statement element is the argument Element. -- --|A2012 start -- -- Appropriate Statement_Kinds: -- An_Extended_Return_Statement -- -- Returns Element_Kinds: -- A_Statement -- A_Pragma -- ------------------------------------------------------------------------------ -- 18.#??? function Extended_Return_Exception_Handlers ------------------------------------------------------------------------------ function Extended_Return_Exception_Handlers (Statement : Asis.Statement; Include_Pragmas : Boolean := False) return Asis.Exception_Handler_List; ------------------------------------------------------------------------------ -- Statement - Specifies the extended return statement to query -- Include_Pragmas - Specifies whether pragmas are to be returned -- -- Returns a list of the exception_handler elements of the extended return -- statement, in their order of appearance. -- -- The only pragmas returned are those following the reserved word "exception" -- and preceding the reserved word "when" of first exception handler. -- -- Returns a Nil_Element_List if there are no exception_handler elements. -- -- Appropriate Statement_Kinds: -- An_Extended_Return_Statement -- -- Returns Element_Kinds: -- An_Exception_Handler -- A_Pragma -- -- |D2005 start -- These two proposed queries - Extended_Return_Statements and -- Extended_Return_Exception_Handlers duplicates queries for getting statement -- lists and exception handlers from block and accept statements. Can we -- somehow avoid this duplication? -- Are these query names - Extended_Return_Statements and -- Extended_Return_Exception_Handlers - really good? -- |D2005 end -- |A2005 end ------------------------------------------------------------------------------ -- 18.22 function Goto_Label ------------------------------------------------------------------------------ function Goto_Label (Statement : Asis.Statement) return Asis.Expression; ------------------------------------------------------------------------------ -- Statement - Specifies the goto statement to query -- -- Returns the expression reference for the label, as specified by the goto -- statement. -- -- Appropriate Statement_Kinds: -- A_Goto_Statement -- -- Returns Expression_Kinds: -- An_Identifier -- ------------------------------------------------------------------------------ -- 18.23 function Corresponding_Destination_Statement ------------------------------------------------------------------------------ function Corresponding_Destination_Statement (Statement : Asis.Statement) return Asis.Statement; ------------------------------------------------------------------------------ -- Statement - Specifies the goto statement to query -- -- Returns the target statement specified by the goto statement. -- -- Appropriate Statement_Kinds: -- A_Goto_Statement -- -- Returns Element_Kinds: -- A_Statement -- -- --|AN Application Note: -- --|AN -- --|AN The Reference Manual allows a pragma between a statement and a label -- --|AN attached to it. If so, when the label is passed as an actual -- --|AN parameter to this query, the query returns the statement, but not -- --|AN the label. The only way for an application to know that there are -- --|AN any pragmas between a statement and its label is to get the spans -- --|AN of these program elements and analyze the coverspending positions in -- --|AN the source text. -- ------------------------------------------------------------------------------ -- 18.24 function Called_Name ------------------------------------------------------------------------------ function Called_Name (Statement : Asis.Statement) return Asis.Expression; ------------------------------------------------------------------------------ -- Statement - Specifies the procedure call or entry call statement to query -- -- Returns the name of the called procedure or entry. The name of an entry -- family takes the form of An_Indexed_Component. -- -- Appropriate Statement_Kinds: -- An_Entry_Call_Statement -- A_Procedure_Call_Statement -- -- Returns Element_Kinds: -- An_Expression -- ------------------------------------------------------------------------------ -- 18.25 function Corresponding_Called_Entity ------------------------------------------------------------------------------ function Corresponding_Called_Entity (Statement : Asis.Statement) return Asis.Declaration; ------------------------------------------------------------------------------ -- Statement - Specifies the procedure_call_statement or -- entry_call_statement to query -- -- Returns the declaration of the procedure or entry denoted by the call. -- -- Returns a Nil_Element if the: -- -- - prefix of the call denotes an access to a procedure implicit -- or explicit dereference, -- -- - argument is a dispatching call, -- -- - argument is a call to a dispatching operation of a tagged type which -- is not statically determined. -- -- If procedure_prefix denotes an attribute_reference, and if -- the corresponding attribute is (re)defined by an attribute definition -- clause, an implementation is encouraged, but not required, to return the -- definition of the corresponding subprogram whose name is used after "use" -- in this attribute definition clause. If an implementation cannot return -- such a subprogram definition, a Nil_Element should be returned. For an -- attribute reference which is not (re)defined by an attribute definition -- clause, a Nil_Element should be returned. -- -- --|D2005 start -- If the arrument call is located in expanded generic and it is a call to an -- artificial null procedure used as the default actual for a formal procedure -- with null default, Nil_Element is returned. -- -- If the argument call is a dispatching call, Nil_Element should be returned. -- this is correct, but of no real help for a client. What about adding -- another semantic query (let's say - Corresponding_Ancestor_Procedure), that -- in case if the argument Is_Dispatching_Call returns the very beginning of -- the chain of inherited/overriding procedures that may be called here. This -- at least would allow a client to get some information about the profile -- of the called procedure. -- -- The same problem exists for dynamic calls (when a called subprogram is -- pointed by an access value. It would be nice to get the called profile. -- This problem would be solved if we would add -- Corresponding_Expression_Type_Definition to Asis.Expression - we could -- apply it to Called_Name. -- -- The same problems exist for function calls - -- Asis.Expressions.Corresponding_Called_Function (17.29) just return -- Nil_Element for dispatching and dynamic calls, but a client may need a -- profile. -- -- May be, we need to clarify explicitly, that in case when a called -- procedure is declared by subprogram instantiation, then -- Corresponding_Called_Entity returns A_Procedure_Instantiation Element, but -- not the corresponding expanded A_Procedure_Declaration (the same problem -- exists for Asis.Expressions.Corresponding_Called_Function (17.29) -- --|D2005 end -- -- Appropriate Statement_Kinds: -- An_Entry_Call_Statement -- A_Procedure_Call_Statement -- -- Returns Declaration_Kinds: -- Not_A_Declaration -- A_Procedure_Declaration -- A_Procedure_Body_Declaration -- A_Procedure_Body_Stub -- A_Procedure_Renaming_Declaration -- A_Procedure_Instantiation -- A_Formal_Procedure_Declaration -- An_Entry_Declaration -- A_Generic_Procedure_Declaration -- -- --|IP Implementation Permissions -- --|IP -- --|IP An implementation may choose to return any part of multi-part -- --|IP declarations and definitions. Multi-part declaration/definitions -- --|IP can occur for: -- --|IP -- --|IP - Subprogram specification in package specification, package body, -- --|IP and subunits (is separate); -- --|IP - Entries in package specification, package body, and subunits -- --|IP (is separate); -- --|IP - Private type and full type declarations; -- --|IP - Incomplete type and full type declarations; and -- --|IP - Deferred constant and full constant declarations. -- --|IP -- --|IP No guarantee is made that the element will be the first part or -- --|IP that the determination will be made due to any visibility rules. -- --|IP An application should make its own analysis for each case based -- --|IP on which part is returned. -- ------------------------------------------------------------------------------ -- 18.26 function Call_Statement_Parameters ------------------------------------------------------------------------------ function Call_Statement_Parameters (Statement : Asis.Statement; Normalized : Boolean := False) return Asis.Association_List; ------------------------------------------------------------------------------ -- Statement - Specifies the procedure_call_statement or -- entry_call_statement to query -- Normalized - Specifies whether the normalized form is desired -- -- Returns a list of parameter_association elements of the call. -- -- Returns a Nil_Element_List if there are no parameter_association elements. -- -- An unnormalized list contains only explicit associations ordered as they -- appear in the program text. Each unnormalized association has an optional -- formal_parameter_selector_name and an explicit_actual_parameter component. -- -- A normalized list contains artificial associations representing all -- explicit and default associations. It has a length equal to the number of -- parameter_specification elements of the formal_part of the -- parameter_and_result_profile. The order of normalized associations matches -- the order of parameter_specification elements. -- -- Each normalized association represents a one on one mapping of a -- parameter_specification elements to the explicit or default expression. -- A normalized association has one A_Defining_Name component that denotes the -- parameter_specification, and one An_Expression component that is either the -- explicit_actual_parameter or a default_expression. -- -- If the prefix of the call denotes an access to a procedure implicit or -- explicit deference, normalized associations are constructed on the basis -- of the formal_part of the parameter_profile from the corresponding -- access_to_subprogram definition. -- -- Returns Nil_Element for normalized associations in the case where -- the called procedure can be determined only dynamically (dispatching -- calls). ASIS cannot produce any meaningful result in this case. -- --|D2005 start -- The cases when the called entity can be determined only dynamically also -- include calls to the procedures pointed by access values -- --|D2005 end -- -- The exception ASIS_Inappropriate_Element is raised when the procedure -- call is an attribute reference and Is_Normalized is True. -- -- Appropriate Statement_Kinds: -- An_Entry_Call_Statement -- A_Procedure_Call_Statement -- -- Returns Element_Kinds: -- A_Parameter_Association -- -- --|IR Implementation Requirements: -- --|IR -- --|IR Normalized associations are Is_Normalized and Is_Part_Of_Implicit. -- --|IR Normalized associations provided by default are -- --|IR Is_Defaulted_Association. Normalized associations are never -- --|IR Is_Equal to unnormalized associations. -- --|IR -- --|IP Implementation Permissions: -- --|IP -- --|IP An implementation may choose to always include default parameters in -- --|IP its internal representation. -- --|IP -- --|IP An implementation may also choose to normalize its representation -- --|IP to use defining_identifier elements rather than -- --|IP formal_parameter_selector_name elements. -- --|IP -- --|IP In either case, this query will return Is_Normalized associations -- --|IP even if Normalized is False, and the query -- --|IP Call_Statement_Parameters_Normalized will return True. -- ------------------------------------------------------------------------------ -- 18.27 function Accept_Entry_Index ------------------------------------------------------------------------------ function Accept_Entry_Index (Statement : Asis.Statement) return Asis.Expression; ------------------------------------------------------------------------------ -- Statement - Specifies the accept statement to query -- -- Returns the entry index expression in the accept statement. -- -- Returns a Nil_Element if the statement has no explicit entry index, -- -- Appropriate Statement_Kinds: -- An_Accept_Statement -- -- Returns Element_Kinds: -- Not_An_Element -- An_Expression -- ------------------------------------------------------------------------------ -- 18.28 function Accept_Entry_Direct_Name ------------------------------------------------------------------------------ function Accept_Entry_Direct_Name (Statement : Asis.Statement) return Asis.Name; ------------------------------------------------------------------------------ -- Statement - Specifies the accept statement to query -- -- Returns the direct name of the entry. The name follows the reserved word -- "accept". -- -- Appropriate Statement_Kinds: -- An_Accept_Statement -- -- Returns Expression_Kinds: -- An_Identifier -- ------------------------------------------------------------------------------ -- 18.29 function Accept_Parameters ------------------------------------------------------------------------------ function Accept_Parameters (Statement : Asis.Statement) return Asis.Parameter_Specification_List; ------------------------------------------------------------------------------ -- Statement - Specifies the accept statement to query -- -- Returns a list of parameter specifications in the formal part of the accept -- statement, in their order of appearance. -- -- Returns a Nil_Element_List if the accept_statement has no parameters. -- -- Results of this query may vary across ASIS implementations. Some -- implementations normalize all multiple name parameter specifications into -- an equivalent sequence of corresponding single name parameter -- specifications. See Reference Manual 3.3.1(7). -- -- Appropriate Statement_Kinds: -- An_Accept_Statement -- -- Returns Declaration_Kinds: -- A_Parameter_Specification -- ------------------------------------------------------------------------------ -- 18.30 function Accept_Body_Statements ------------------------------------------------------------------------------ function Accept_Body_Statements (Statement : Asis.Statement; Include_Pragmas : Boolean := False) return Asis.Statement_List; ------------------------------------------------------------------------------ -- Statement - Specifies the accept statement to query -- Include_Pragmas - Specifies whether pragmas are to be returned -- -- Returns the list of statements and pragmas from the body of the accept -- statement, in their order of appearance. -- -- --|A2012 start -- In case if a sequence_of_Statements in the argument Element contains -- 'floating' labels (labels that completes sequence_of_statements and that -- are not attached to any statement in the source code), the result list -- contains as its last element an implicit A_Null_Statement element these -- 'floating' labels are attached to. The Enclosing_Element of this implicit -- A_Null_Statement element is the argument Element. -- --|A2012 start -- -- Appropriate Statement_Kinds: -- An_Accept_Statement -- -- Returns Element_Kinds: -- A_Pragma -- A_Statement -- ------------------------------------------------------------------------------ -- 18.31 function Accept_Body_Exception_Handlers ------------------------------------------------------------------------------ function Accept_Body_Exception_Handlers (Statement : Asis.Statement; Include_Pragmas : Boolean := False) return Asis.Statement_List; ------------------------------------------------------------------------------ -- Statement - Specifies the accept statement to query -- Include_Pragmas - Specifies whether pragmas are to be returned -- -- Returns the list of exception handlers and pragmas from the body of the -- accept statement, in their order of appearance. -- -- Appropriate Statement_Kinds: -- An_Accept_Statement -- -- Returns Element_Kinds: -- A_Pragma -- An_Exception_Handler -- ------------------------------------------------------------------------------ -- 18.32 function Corresponding_Entry ------------------------------------------------------------------------------ function Corresponding_Entry (Statement : Asis.Statement) return Asis.Declaration; ------------------------------------------------------------------------------ -- Statement - Specifies the accept statement to query -- -- Returns the declaration of the entry accepted in this statement. -- -- Appropriate Statement_Kinds: -- An_Accept_Statement -- -- Returns Declaration_Kinds: -- An_Entry_Declaration -- ------------------------------------------------------------------------------ -- 18.33 function Requeue_Entry_Name ------------------------------------------------------------------------------ function Requeue_Entry_Name (Statement : Asis.Statement) return Asis.Name; ------------------------------------------------------------------------------ -- Statement - Specifies the requeue statement to query -- -- Returns the entry name following the reserved word "accept". The name of -- an entry family takes the form of An_Indexed_Component. -- -- Appropriate Statement_Kinds: -- A_Requeue_Statement -- A_Requeue_Statement_With_Abort -- -- Returns Element_Kinds: -- An_Expression -- ------------------------------------------------------------------------------ -- 18.34 function Delay_Expression ------------------------------------------------------------------------------ function Delay_Expression (Statement : Asis.Statement) return Asis.Expression; ------------------------------------------------------------------------------ -- Statement - Specifies the delay statement to query -- -- Returns the expression for the duration of the delay. -- -- Appropriate Statement_Kinds: -- A_Delay_Until_Statement -- A_Delay_Relative_Statement -- -- Returns Element_Kinds: -- An_Expression -- ------------------------------------------------------------------------------ -- 18.35 function Guard ------------------------------------------------------------------------------ function Guard (Path : Asis.Path) return Asis.Expression; ------------------------------------------------------------------------------ -- Path - Specifies the select statement execution path to query -- -- Returns the conditional expression guard for the path. -- -- Returns a Nil_Element if there is no guard, or if the path is from a -- timed_entry_call, a conditional_entry_call, or an asynchronous_select -- statement where a guard is not legal. -- -- Appropriate Path_Kinds: -- A_Select_Path -- An_Or_Path -- -- Returns Element_Kinds: -- Not_An_Element -- An_Expression -- ------------------------------------------------------------------------------ -- 18.36 function Aborted_Tasks ------------------------------------------------------------------------------ function Aborted_Tasks (Statement : Asis.Statement) return Asis.Expression_List; ------------------------------------------------------------------------------ -- Statement - Specifies the abort statement to query -- -- Returns a list of the task names from the ABORT statement, in their order -- of appearance. -- -- Appropriate Statement_Kinds: -- An_Abort_Statement -- -- Returns Element_Kinds: -- An_Expression -- ------------------------------------------------------------------------------ -- 18.37 function Choice_Parameter_Specification ------------------------------------------------------------------------------ function Choice_Parameter_Specification (Handler : Asis.Exception_Handler) return Asis.Declaration; ------------------------------------------------------------------------------ -- Handler - Specifies the exception handler to query -- -- Returns the choice parameter specification following the reserved word -- "when" in the exception handler. -- -- Returns a Nil_Element if there is no explicit choice parameter. -- -- Appropriate Element_Kinds: -- An_Exception_Handler -- -- Returns Declaration_Kinds: -- Not_A_Declaration -- A_Choice_Parameter_Specification -- ------------------------------------------------------------------------------ -- 18.38 function Exception_Choices ------------------------------------------------------------------------------ function Exception_Choices (Handler : Asis.Exception_Handler) return Asis.Element_List; ------------------------------------------------------------------------------ -- Handler - Specifies the exception handler to query -- -- Returns a list of the 'when <choice> | <choice>' elements, in their -- order of appearance. Choices are either the exception name expression or -- an others choice. -- -- Appropriate Element_Kinds: -- An_Exception_Handler -- -- Returns Expression_Kinds: -- An_Identifier -- A_Selected_Component -- -- Returns Definition_Kinds: -- An_Others_Choice -- ------------------------------------------------------------------------------ -- 18.39 function Handler_Statements ------------------------------------------------------------------------------ function Handler_Statements (Handler : Asis.Exception_Handler; Include_Pragmas : Boolean := False) return Asis.Statement_List; ------------------------------------------------------------------------------ -- Handler - Specifies the exception handler to query -- Include_Pragmas - Specifies whether pragmas are to be returned -- -- Returns the list of statements and pragmas from the body of the -- exception handler, in their order of appearance. -- -- --|A2012 start -- In case if a sequence_of_Statements in the argument Element contains -- 'floating' labels (labels that completes sequence_of_statements and that -- are not attached to any statement in the source code), the result list -- contains as its last element an implicit A_Null_Statement element these -- 'floating' labels are attached to. The Enclosing_Element of this implicit -- A_Null_Statement element is the argument Element. -- --|A2012 start -- -- Appropriate Element_Kinds: -- An_Exception_Handler -- -- Returns Element_Kinds: -- A_Pragma -- A_Statement -- ------------------------------------------------------------------------------ -- 18.40 function Raised_Exception ------------------------------------------------------------------------------ function Raised_Exception (Statement : Asis.Statement) return Asis.Expression; ------------------------------------------------------------------------------ -- Statement - Specifies the raise statement to query -- -- Returns the expression that names the raised exception. -- -- Returns a Nil_Element if there is no explicitly named exception. -- -- Appropriate Statement_Kinds: -- A_Raise_Statement -- -- Returns Expression_Kinds: -- Not_An_Expression -- An_Identifier -- A_Selected_Component -- ------------------------------------------------------------------------------ -- |A2005 start -- 18.40 function ------------------------------------------------------------------------------ function Associated_Message (Statement : Asis.Statement) return Asis.Expression; ------------------------------------------------------------------------------ -- Statement - Specifies the raise statement to query -- -- Returns the string expression that is associated with the raised -- exception and follows the WITH keyword in the raise statement -- -- Returns a Nil_Element if there is no string expression. -- -- Appropriate Statement_Kinds: -- A_Raise_Statement -- -- Returns Element_Kinds: -- Not_An_Element -- An_Expression -- -- |A2005 end ------------------------------------------------------------------------------ -- 18.41 function Qualified_Expression ------------------------------------------------------------------------------ function Qualified_Expression (Statement : Asis.Statement) return Asis.Expression; ------------------------------------------------------------------------------ -- Statement - Specifies the code statement to query -- -- Returns the qualified aggregate expression representing the code statement. -- -- Appropriate Statement_Kinds: -- A_Code_Statement -- -- Returns Expression_Kinds: -- A_Qualified_Expression -- ------------------------------------------------------------------------------ -- 18.42 function Is_Dispatching_Call ------------------------------------------------------------------------------ function Is_Dispatching_Call (Call : Asis.Element) return Boolean; ------------------------------------------------------------------------------ -- Call - Specifies the element to query. -- -- Returns True if the controlling tag of Call is dynamically determined. -- -- This function shall always return False when pragma -- Restrictions (No_Dispatch) applies. -- -- Returns False for any unexpected Element. -- -- Expected Element_Kinds: -- A_Function_Call -- A_Procedure_Call_Statement -- ------------------------------------------------------------------------------ -- 18.43 function Is_Call_On_Dispatching_Operation ------------------------------------------------------------------------------ function Is_Call_On_Dispatching_Operation (Call : Asis.Element) return Boolean; ------------------------------------------------------------------------------ -- Call - Specifies the element to query. -- -- Returns True if the name or prefix of Call denotes the declaration of a -- primitive operation of a tagged type. -- -- Returns False for any unexpected Element. -- -- Expected Element_Kinds: -- A_Function_Call -- A_Procedure_Call_Statement -- ------------------------------------------------------------------------------ end Asis.Statements;
------------------------------------------------------------------------------- -- Copyright (c) 2020 Daniel King -- -- Permission is hereby granted, free of charge, to any person obtaining a -- copy of this software and associated documentation files (the "Software"), -- to deal in the Software without restriction, including without limitation -- the rights to use, copy, modify, merge, publish, distribute, sublicense, -- and/or sell copies of the Software, and to permit persons to whom the -- Software is furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------- with AUnit.Test_Fixtures; with AUnit.Test_Suites; package COBS_Tests is type Test is new AUnit.Test_Fixtures.Test_Fixture with null record; -------------------- -- Encode tests -- -------------------- procedure Test_Encode_Empty (T : in out Test); procedure Test_Encode_All_Zeroes (T : in out Test); procedure Test_Encode_No_Zeroes (T : in out Test); -------------------- -- Decode tests -- -------------------- procedure Test_Decode_Empty_Frame (T : in out Test); procedure Test_Decode_No_Frame_Delimiter (T : in out Test); procedure Test_Decode_Test_Vectors (T : in out Test); --------------------------- -- Encode/decode tests -- --------------------------- procedure Test_Encode_Decode_Loopback (T : in out Test); ---------------------------------------- -- Array_Length_Within_Bounds tests -- ---------------------------------------- procedure Test_Array_Upper_Limit_Positive_Range (T : in out Test); procedure Test_Array_Upper_Limit_Negative_Range (T : in out Test); procedure Test_Array_Upper_Limit_Zero_Crossing_Range (T : in out Test); procedure Test_Bounds_Exceeded_Positive_Range (T : in out Test); procedure Test_Bounds_Exceeded_Negative_Range (T : in out Test); procedure Test_Bounds_Exceeded_Zero_Crossing_Range (T : in out Test); procedure Test_Bounds_Check_Empty_Range (T : in out Test); -------------------------------- -- Max_Overhead_Bytes tests -- -------------------------------- procedure Test_Max_Overhead_Bytes_Empty (T : in out Test); procedure Test_Max_Overhead_Bytes_Under_One_Block (T : in out Test); procedure Test_Max_Overhead_Bytes_One_Block (T : in out Test); procedure Test_Max_Overhead_Bytes_Over_Block (T : in out Test); procedure Test_Max_Overhead_Bytes_Two_Blocks (T : in out Test); ---------------- -- Test suite -- ---------------- function Suite return AUnit.Test_Suites.Access_Test_Suite; end COBS_Tests;
-- This spec has been automatically generated from STM32F40x.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; with HAL; with System; package STM32_SVD.I2C is pragma Preelaborate; --------------- -- Registers -- --------------- ------------------ -- CR1_Register -- ------------------ -- Control register 1 type CR1_Register is record -- Peripheral enable PE : Boolean := False; -- SMBus mode SMBUS : Boolean := False; -- unspecified Reserved_2_2 : HAL.Bit := 16#0#; -- SMBus type SMBTYPE : Boolean := False; -- ARP enable ENARP : Boolean := False; -- PEC enable ENPEC : Boolean := False; -- General call enable ENGC : Boolean := False; -- Clock stretching disable (Slave mode) NOSTRETCH : Boolean := False; -- Start generation START : Boolean := False; -- Stop generation STOP : Boolean := False; -- Acknowledge enable ACK : Boolean := False; -- Acknowledge/PEC Position (for data reception) POS : Boolean := False; -- Packet error checking PEC : Boolean := False; -- SMBus alert ALERT : Boolean := False; -- unspecified Reserved_14_14 : HAL.Bit := 16#0#; -- Software reset SWRST : Boolean := False; -- unspecified Reserved_16_31 : HAL.Short := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CR1_Register use record PE at 0 range 0 .. 0; SMBUS at 0 range 1 .. 1; Reserved_2_2 at 0 range 2 .. 2; SMBTYPE at 0 range 3 .. 3; ENARP at 0 range 4 .. 4; ENPEC at 0 range 5 .. 5; ENGC at 0 range 6 .. 6; NOSTRETCH at 0 range 7 .. 7; START at 0 range 8 .. 8; STOP at 0 range 9 .. 9; ACK at 0 range 10 .. 10; POS at 0 range 11 .. 11; PEC at 0 range 12 .. 12; ALERT at 0 range 13 .. 13; Reserved_14_14 at 0 range 14 .. 14; SWRST at 0 range 15 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; ------------------ -- CR2_Register -- ------------------ subtype CR2_FREQ_Field is HAL.UInt6; -- Control register 2 type CR2_Register is record -- Peripheral clock frequency FREQ : CR2_FREQ_Field := 16#0#; -- unspecified Reserved_6_7 : HAL.UInt2 := 16#0#; -- Error interrupt enable ITERREN : Boolean := False; -- Event interrupt enable ITEVTEN : Boolean := False; -- Buffer interrupt enable ITBUFEN : Boolean := False; -- DMA requests enable DMAEN : Boolean := False; -- DMA last transfer LAST : Boolean := False; -- unspecified Reserved_13_31 : HAL.UInt19 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CR2_Register use record FREQ at 0 range 0 .. 5; Reserved_6_7 at 0 range 6 .. 7; ITERREN at 0 range 8 .. 8; ITEVTEN at 0 range 9 .. 9; ITBUFEN at 0 range 10 .. 10; DMAEN at 0 range 11 .. 11; LAST at 0 range 12 .. 12; Reserved_13_31 at 0 range 13 .. 31; end record; ------------------- -- OAR1_Register -- ------------------- subtype OAR1_ADD7_Field is HAL.UInt7; subtype OAR1_ADD10_Field is HAL.UInt2; -- Own address register 1 type OAR1_Register is record -- Interface address ADD0 : Boolean := False; -- Interface address ADD7 : OAR1_ADD7_Field := 16#0#; -- Interface address ADD10 : OAR1_ADD10_Field := 16#0#; -- unspecified Reserved_10_14 : HAL.UInt5 := 16#0#; -- Addressing mode (slave mode) ADDMODE : Boolean := False; -- unspecified Reserved_16_31 : HAL.Short := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for OAR1_Register use record ADD0 at 0 range 0 .. 0; ADD7 at 0 range 1 .. 7; ADD10 at 0 range 8 .. 9; Reserved_10_14 at 0 range 10 .. 14; ADDMODE at 0 range 15 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; ------------------- -- OAR2_Register -- ------------------- subtype OAR2_ADD2_Field is HAL.UInt7; -- Own address register 2 type OAR2_Register is record -- Dual addressing mode enable ENDUAL : Boolean := False; -- Interface address ADD2 : OAR2_ADD2_Field := 16#0#; -- unspecified Reserved_8_31 : HAL.UInt24 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for OAR2_Register use record ENDUAL at 0 range 0 .. 0; ADD2 at 0 range 1 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; ----------------- -- DR_Register -- ----------------- subtype DR_DR_Field is HAL.Byte; -- Data register type DR_Register is record -- 8-bit data register DR : DR_DR_Field := 16#0#; -- unspecified Reserved_8_31 : HAL.UInt24 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for DR_Register use record DR at 0 range 0 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; ------------------ -- SR1_Register -- ------------------ -- Status register 1 type SR1_Register is record -- Read-only. Start bit (Master mode) SB : Boolean := False; -- Read-only. Address sent (master mode)/matched (slave mode) ADDR : Boolean := False; -- Read-only. Byte transfer finished BTF : Boolean := False; -- Read-only. 10-bit header sent (Master mode) ADD10 : Boolean := False; -- Read-only. Stop detection (slave mode) STOPF : Boolean := False; -- unspecified Reserved_5_5 : HAL.Bit := 16#0#; -- Read-only. Data register not empty (receivers) RxNE : Boolean := False; -- Read-only. Data register empty (transmitters) TxE : Boolean := False; -- Bus error BERR : Boolean := False; -- Arbitration lost (master mode) ARLO : Boolean := False; -- Acknowledge failure AF : Boolean := False; -- Overrun/Underrun OVR : Boolean := False; -- PEC Error in reception PECERR : Boolean := False; -- unspecified Reserved_13_13 : HAL.Bit := 16#0#; -- Timeout or Tlow error TIMEOUT : Boolean := False; -- SMBus alert SMBALERT : Boolean := False; -- unspecified Reserved_16_31 : HAL.Short := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for SR1_Register use record SB at 0 range 0 .. 0; ADDR at 0 range 1 .. 1; BTF at 0 range 2 .. 2; ADD10 at 0 range 3 .. 3; STOPF at 0 range 4 .. 4; Reserved_5_5 at 0 range 5 .. 5; RxNE at 0 range 6 .. 6; TxE at 0 range 7 .. 7; BERR at 0 range 8 .. 8; ARLO at 0 range 9 .. 9; AF at 0 range 10 .. 10; OVR at 0 range 11 .. 11; PECERR at 0 range 12 .. 12; Reserved_13_13 at 0 range 13 .. 13; TIMEOUT at 0 range 14 .. 14; SMBALERT at 0 range 15 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; ------------------ -- SR2_Register -- ------------------ subtype SR2_PEC_Field is HAL.Byte; -- Status register 2 type SR2_Register is record -- Read-only. Master/slave MSL : Boolean; -- Read-only. Bus busy BUSY : Boolean; -- Read-only. Transmitter/receiver TRA : Boolean; -- unspecified Reserved_3_3 : HAL.Bit; -- Read-only. General call address (Slave mode) GENCALL : Boolean; -- Read-only. SMBus device default address (Slave mode) SMBDEFAULT : Boolean; -- Read-only. SMBus host header (Slave mode) SMBHOST : Boolean; -- Read-only. Dual flag (Slave mode) DUALF : Boolean; -- Read-only. acket error checking register PEC : SR2_PEC_Field; -- unspecified Reserved_16_31 : HAL.Short; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for SR2_Register use record MSL at 0 range 0 .. 0; BUSY at 0 range 1 .. 1; TRA at 0 range 2 .. 2; Reserved_3_3 at 0 range 3 .. 3; GENCALL at 0 range 4 .. 4; SMBDEFAULT at 0 range 5 .. 5; SMBHOST at 0 range 6 .. 6; DUALF at 0 range 7 .. 7; PEC at 0 range 8 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; ------------------ -- CCR_Register -- ------------------ subtype CCR_CCR_Field is HAL.UInt12; -- Clock control register type CCR_Register is record -- Clock control register in Fast/Standard mode (Master mode) CCR : CCR_CCR_Field := 16#0#; -- unspecified Reserved_12_13 : HAL.UInt2 := 16#0#; -- Fast mode duty cycle DUTY : Boolean := False; -- I2C master mode selection F_S : Boolean := False; -- unspecified Reserved_16_31 : HAL.Short := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CCR_Register use record CCR at 0 range 0 .. 11; Reserved_12_13 at 0 range 12 .. 13; DUTY at 0 range 14 .. 14; F_S at 0 range 15 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -------------------- -- TRISE_Register -- -------------------- subtype TRISE_TRISE_Field is HAL.UInt6; -- TRISE register type TRISE_Register is record -- Maximum rise time in Fast/Standard mode (Master mode) TRISE : TRISE_TRISE_Field := 16#2#; -- unspecified Reserved_6_31 : HAL.UInt26 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for TRISE_Register use record TRISE at 0 range 0 .. 5; Reserved_6_31 at 0 range 6 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Inter-integrated circuit type I2C_Peripheral is record -- Control register 1 CR1 : CR1_Register; -- Control register 2 CR2 : CR2_Register; -- Own address register 1 OAR1 : OAR1_Register; -- Own address register 2 OAR2 : OAR2_Register; -- Data register DR : DR_Register; -- Status register 1 SR1 : SR1_Register; -- Status register 2 SR2 : SR2_Register; -- Clock control register CCR : CCR_Register; -- TRISE register TRISE : TRISE_Register; end record with Volatile; for I2C_Peripheral use record CR1 at 0 range 0 .. 31; CR2 at 4 range 0 .. 31; OAR1 at 8 range 0 .. 31; OAR2 at 12 range 0 .. 31; DR at 16 range 0 .. 31; SR1 at 20 range 0 .. 31; SR2 at 24 range 0 .. 31; CCR at 28 range 0 .. 31; TRISE at 32 range 0 .. 31; end record; -- Inter-integrated circuit I2C1_Periph : aliased I2C_Peripheral with Import, Address => I2C1_Base; -- Inter-integrated circuit I2C2_Periph : aliased I2C_Peripheral with Import, Address => I2C2_Base; -- Inter-integrated circuit I2C3_Periph : aliased I2C_Peripheral with Import, Address => I2C3_Base; end STM32_SVD.I2C;
package Encoding is function Encode (Text : String) return Wide_Wide_String; private end Encoding;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <denkpadje@gmail.com> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. package Orka.SIMD.AVX.Singles.Math is pragma Pure; function Min (Left, Right : m256) return m256 with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_minps256"; -- Compare each 32-bit float in Left and Right and take the minimum values. -- -- Result (I) := Float'Min (Left (I), Right (I)) for I in 1 ..4 function Max (Left, Right : m256) return m256 with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_maxps256"; -- Compare each 32-bit float in Left and Right and take the maximum values. -- -- Result (I) := Float'Max (Left (I), Right (I)) for I in 1 ..4 function Reciprocal (Elements : m256) return m256 with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_rcpps256"; -- Return the reciprocal (1/X) of each element function Reciprocal_Sqrt (Elements : m256) return m256 with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_rsqrtps256"; -- Return the reciprocal of the square root (1/Sqrt(X)) of each element function Sqrt (Elements : m256) return m256 with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_sqrtps256"; -- Return the square root (Sqrt(X)) of each element function Round (Elements : m256; Rounding : Unsigned_32) return m256 with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_roundps256"; function Round_Nearest_Integer (Elements : m256) return m256 is (Round (Elements, 0)); -- Round each element to the nearest integer function Floor (Elements : m256) return m256 is (Round (Elements, 1)); -- Round each element down to an integer value function Ceil (Elements : m256) return m256 is (Round (Elements, 2)); -- Round each element up to an integer value function Round_Truncate (Elements : m256) return m256 is (Round (Elements, 3)); -- Round each element to zero end Orka.SIMD.AVX.Singles.Math;
with Ada.IO_Exceptions; with AWS.Config.Set; with Swagger.Servers.AWS; with Swagger.Servers.Applications; with Util.Log.Loggers; with Util.Properties; with .Servers; procedure .Server is procedure Configure (Config : in out AWS.Config.Object); CONFIG_PATH : constant String := ".properties"; procedure Configure (Config : in out AWS.Config.Object) is begin AWS.Config.Set.Server_Port (Config, 8080); AWS.Config.Set.Max_Connection (Config, 8); AWS.Config.Set.Accept_Queue_Size (Config, 512); end Configure; App : aliased Swagger.Servers.Applications.Application_Type; WS : Swagger.Servers.AWS.AWS_Container; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (".Server"); Props : Util.Properties.Manager; begin Props.Load_Properties (CONFIG_PATH); Util.Log.Loggers.Initialize (Props); App.Configure (Props); .Servers.Server_Impl.Register (App); WS.Configure (Configure'Access); WS.Register_Application ("", App'Unchecked_Access); App.Dump_Routes (Util.Log.INFO_LEVEL); Log.Info ("Connect you browser to: http://localhost:8080/ui/index.html"); WS.Start; delay 6000.0; exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH); end .Server;
-- Advanced Resource Embedder 1.2.0 package Lines is type Content_Array is array (Positive range <>) of access constant String; type Content_Access is access constant Content_Array; Id_multiple_txt : aliased constant Content_Array; private L_1 : aliased constant String := "line 1"; L_2 : aliased constant String := "line 2"; L_3 : aliased constant String := "line 3"; L_4 : aliased constant String := "line 4"; Id_multiple_txt : aliased constant Content_Array := (L_1'Access, L_2'Access, L_3'Access, L_4'Access); end Lines;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <denkpadje@gmail.com> -- -- 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. with Ada.Unchecked_Deallocation; with GL.API; with GL.Debug_Types; with GL.Enums.Getter; package body GL.Debug.Logs is function Message_Log return Message_Array is use GL.Debug_Types; Length : Size := 0; Number_Messages : constant Size := Logged_Messages; Log_Length : constant Size := Number_Messages * Max_Message_Length; Sources : Source_Array_Access := new Source_Array (1 .. Number_Messages); Types : Type_Array_Access := new Type_Array (1 .. Number_Messages); Levels : Severity_Array_Access := new Severity_Array (1 .. Number_Messages); IDs : UInt_Array_Access := new UInt_Array (1 .. Number_Messages); Lengths : Size_Array_Access := new Size_Array (1 .. Number_Messages); Log : Debug_Types.String_Access := new String'(1 .. Natural (Log_Length) => ' '); procedure Free is new Ada.Unchecked_Deallocation (Object => String, Name => Debug_Types.String_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => Source_Array, Name => Source_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => Type_Array, Name => Type_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => Severity_Array, Name => Severity_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => UInt_Array, Name => UInt_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => Size_Array, Name => Size_Array_Access); begin Length := Size (API.Get_Debug_Message_Log.Ref (UInt (Number_Messages), Log_Length, Sources, Types, IDs, Levels, Lengths, Log)); pragma Assert (Length <= Number_Messages); declare Messages : Message_Array (1 .. Length); Offset : Natural := 1; begin for Index in 1 .. Length loop Messages (Index) := (From => Sources (Index), Kind => Types (Index), Level => Levels (Index), ID => IDs (Index), Message => String_Holder.To_Holder (Log (Offset .. Offset + Natural (Lengths (Index)) - 1))); Offset := Offset + Natural (Lengths (Index)); end loop; Free (Sources); Free (Types); Free (Levels); Free (IDs); Free (Lengths); Free (Log); return Messages; end; end Message_Log; function Logged_Messages return Size is Result : Int := 0; begin API.Get_Integer.Ref (Enums.Getter.Debug_Logged_Messages, Result); return Result; end Logged_Messages; end GL.Debug.Logs;
-- { dg-do compile } package body Incomplete3 is function Get_Tracer (This : access Output_T'Class) return Tracer_T'class is begin return Tracer_T'Class (Tracer_T'(Output => This)); end ; function Get_Output (This : in Tracer_T) return access Output_T'Class is begin return This.Output; end; end Incomplete3;
with Trendy_Test; package Trendy_Terminal.Lines.Tests is function All_Tests return Trendy_Test.Test_Group; end Trendy_Terminal.Lines.Tests;
-- BinToAsc -- Binary data to ASCII codecs -- Copyright (c) 2015, James Humphry - see LICENSE file for details with Ada.Characters.Handling; package body BinToAsc is use Ada.Characters.Handling; function To_String (Input : in Bin_Array) return String is C : Codec; Buffer_Length : constant Integer := (Input'Length / Input_Group_Size(C) + 1) * Output_Group_Size(C); Buffer : String(1 .. Buffer_Length); Result_Length : Integer; Tail_Length : Integer; begin Reset(C); Process(C => C, Input => Input, Output => Buffer, Output_Length => Result_Length); if C.State /= Ready then raise Program_Error with "Could not convert data"; end if; Complete(C => C, Output => Buffer(Result_Length + 1 .. Buffer'Last), Output_Length => Tail_Length); if C.State /= Completed then raise Program_Error with "Could not convert data"; end if; return Buffer(1 .. Result_Length + Tail_Length); end To_String; function To_Bin (Input : in String) return Bin_Array is C : Codec; Buffer_Length : constant Bin_Array_Index := Bin_Array_Index((Input'Length / Input_Group_Size(C) + 1) * Output_Group_Size(C)); Buffer : Bin_Array(1 .. Buffer_Length); Result_Length : Bin_Array_Index; Tail_Length : Bin_Array_Index; begin Reset(C); Process(C => C, Input => Input, Output => Buffer, Output_Length => Result_Length); if C.State /= Ready then raise Invalid_Data_Encoding; end if; Complete(C => C, Output => Buffer(Result_Length + 1 .. Buffer'Last), Output_Length => Tail_Length); if C.State /= Completed then raise Invalid_Data_Encoding; end if; return Buffer(1 .. Result_Length + Tail_Length); end To_Bin; function Valid_Alphabet (A : in Alphabet; Case_Sensitive : in Boolean) return Boolean is begin for I in A'First + 1 ..A'Last loop for J in A'First .. I - 1 loop if A(I) = A(J) or (not Case_Sensitive and To_Lower(A(I)) = To_Lower(A(J))) then return False; end if; end loop; end loop; return True; end Valid_Alphabet; function Make_Reverse_Alphabet (A : in Alphabet; Case_Sensitive : Boolean) return Reverse_Alphabet_Lookup is begin -- The precondition on Valid_Alphabet ensures that the input A does not -- contain any duplicate characters. return R : Reverse_Alphabet_Lookup do R := (others => Invalid_Character_Input); for I in A'Range loop if Case_Sensitive then R(A(I)) := I; else R(To_Lower(A(I))) := I; R(To_Upper(A(I))) := I; end if; end loop; end return; end Make_Reverse_Alphabet; end BinToAsc;
-- Copyright 2015-2017 Free Software Foundation, Inc. -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. with Bar; use Bar; procedure Foo_O224_021 is O1 : constant Object_Type := Get_Str ("Foo"); procedure Child1 is O2 : constant Object_Type := Get_Str ("Foo"); function Child2 (S : String) return Boolean is -- STOP begin for C of S loop Do_Nothing (C); if C = 'o' then return True; end if; end loop; return False; end Child2; R : Boolean; begin R := Child2 ("Foo"); R := Child2 ("Bar"); R := Child2 ("Foobar"); end Child1; begin Child1; end Foo_O224_021;
----------------------------------------------------------------------- -- awa-events-dispatchers-tasks -- AWA Event Dispatchers -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- 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. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Concurrent.Fifos; with AWA.Events.Queues; with AWA.Events.Services; package AWA.Events.Dispatchers.Tasks is type Task_Dispatcher is limited new Dispatcher with private; type Task_Dispatcher_Access is access all Task_Dispatcher; -- Start the dispatcher. procedure Start (Manager : in out Task_Dispatcher); -- Stop the dispatcher. procedure Stop (Manager : in out Task_Dispatcher); -- Add the queue to the dispatcher. procedure Add_Queue (Manager : in out Task_Dispatcher; Queue : in AWA.Events.Queues.Queue_Ref; Added : out Boolean); overriding procedure Finalize (Object : in out Task_Dispatcher) renames Stop; function Create_Dispatcher (Service : in AWA.Events.Services.Event_Manager_Access; Match : in String; Count : in Positive; Priority : in Positive) return Dispatcher_Access; private package Queue_Of_Queue is new Util.Concurrent.Fifos (Element_Type => AWA.Events.Queues.Queue_Ref, Default_Size => 10, Clear_On_Dequeue => True); task type Consumer is entry Start (D : in Task_Dispatcher_Access); entry Stop; end Consumer; type Consumer_Array is array (Positive range <>) of Consumer; type Consumer_Array_Access is access Consumer_Array; type Task_Dispatcher is limited new Dispatcher with record Workers : Consumer_Array_Access; Queues : Queue_Of_Queue.Fifo; Task_Count : Positive; Match : Ada.Strings.Unbounded.Unbounded_String; Priority : Positive; end record; end AWA.Events.Dispatchers.Tasks;
with Ada.Directories; use Ada.Directories; with Ada.Text_IO; use Ada.Text_IO; with Ada.Calendar.Formatting; use Ada.Calendar.Formatting; procedure File_Time_Test is begin Put_Line (Image (Modification_Time ("file_time_test.adb"))); end File_Time_Test;
------------------------------------------------------------------------------ -- -- -- GNAT RUNTIME COMPONENTS -- -- -- -- S Y S T E M . U N S I G N E D _ T Y P E S -- -- -- -- S p e c -- -- -- -- $Revision: 2 $ -- -- -- -- Copyright (c) 1992,1993,1994 NYU, All Rights Reserved -- -- -- -- The GNAT library is free software; you can redistribute it and/or modify -- -- it under terms of the GNU Library General Public License as published by -- -- the Free Software Foundation; either version 2, or (at your option) any -- -- later version. The GNAT library is distributed in the hope that it will -- -- be useful, but WITHOUT ANY WARRANTY; without even the implied warranty -- -- of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- -- Library General Public License for more details. You should have -- -- received a copy of the GNU Library General Public License along with -- -- the GNAT library; see the file COPYING.LIB. If not, write to the Free -- -- Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. -- -- -- ------------------------------------------------------------------------------ -- This package contains definitions of standard unsigned types that -- correspond in size to the standard signed types declared in Standard. -- and (unlike the types in Interfaces have corresponding names). package System.Unsigned_Types is pragma Pure (Unsigned_Types); type Short_Short_Unsigned is mod 2 ** Short_Short_Integer'Size; type Short_Unsigned is mod 2 ** Short_Integer'Size; type Unsigned is mod 2 ** Integer'Size; type Long_Unsigned is mod 2 ** Long_Integer'Size; type Long_Long_Unsigned is mod 2 ** Long_Long_Integer'Size; function Shift_Left (Value : Short_Short_Unsigned; Amount : Natural) return Short_Short_Unsigned; function Shift_Right (Value : Short_Short_Unsigned; Amount : Natural) return Short_Short_Unsigned; function Shift_Right_Arithmetic (Value : Short_Short_Unsigned; Amount : Natural) return Short_Short_Unsigned; function Rotate_Left (Value : Short_Short_Unsigned; Amount : Natural) return Short_Short_Unsigned; function Rotate_Right (Value : Short_Short_Unsigned; Amount : Natural) return Short_Short_Unsigned; function Shift_Left (Value : Short_Unsigned; Amount : Natural) return Short_Unsigned; function Shift_Right (Value : Short_Unsigned; Amount : Natural) return Short_Unsigned; function Shift_Right_Arithmetic (Value : Short_Unsigned; Amount : Natural) return Short_Unsigned; function Rotate_Left (Value : Short_Unsigned; Amount : Natural) return Short_Unsigned; function Rotate_Right (Value : Short_Unsigned; Amount : Natural) return Short_Unsigned; function Shift_Left (Value : Unsigned; Amount : Natural) return Unsigned; function Shift_Right (Value : Unsigned; Amount : Natural) return Unsigned; function Shift_Right_Arithmetic (Value : Unsigned; Amount : Natural) return Unsigned; function Rotate_Left (Value : Unsigned; Amount : Natural) return Unsigned; function Rotate_Right (Value : Unsigned; Amount : Natural) return Unsigned; function Shift_Left (Value : Long_Unsigned; Amount : Natural) return Long_Unsigned; function Shift_Right (Value : Long_Unsigned; Amount : Natural) return Long_Unsigned; function Shift_Right_Arithmetic (Value : Long_Unsigned; Amount : Natural) return Long_Unsigned; function Rotate_Left (Value : Long_Unsigned; Amount : Natural) return Long_Unsigned; function Rotate_Right (Value : Long_Unsigned; Amount : Natural) return Long_Unsigned; function Shift_Left (Value : Long_Long_Unsigned; Amount : Natural) return Long_Long_Unsigned; function Shift_Right (Value : Long_Long_Unsigned; Amount : Natural) return Long_Long_Unsigned; function Shift_Right_Arithmetic (Value : Long_Long_Unsigned; Amount : Natural) return Long_Long_Unsigned; function Rotate_Left (Value : Long_Long_Unsigned; Amount : Natural) return Long_Long_Unsigned; function Rotate_Right (Value : Long_Long_Unsigned; Amount : Natural) return Long_Long_Unsigned; pragma Convention (Intrinsic, Shift_Left); pragma Convention (Intrinsic, Shift_Right); pragma Convention (Intrinsic, Shift_Right_Arithmetic); pragma Convention (Intrinsic, Rotate_Left); pragma Convention (Intrinsic, Rotate_Right); pragma Import (Intrinsic, Shift_Left); pragma Import (Intrinsic, Shift_Right); pragma Import (Intrinsic, Shift_Right_Arithmetic); pragma Import (Intrinsic, Rotate_Left); pragma Import (Intrinsic, Rotate_Right); end System.Unsigned_Types;
-- The Village of Vampire by YT, このソースコードはNYSLです with Web.HTML; with Vampire.Villages.Text; procedure Vampire.R3.Target_Page ( Output : not null access Ada.Streams.Root_Stream_Type'Class; Form : in Forms.Root_Form_Type'Class; Template : in String; Village_Id : in Tabula.Villages.Village_Id; Village : in Villages.Village_Type; Player : in Tabula.Villages.Person_Index; Target : in Tabula.Villages.Person_Index; User_Id : in String; User_Password : in String) is Person : Villages.Person_Type renames Village.People.Constant_Reference(Player); Target_Person : Villages.Person_Type renames Village.People.Constant_Reference(Target); procedure Handle ( Output : not null access Ada.Streams.Root_Stream_Type'Class; Tag : in String; Contents : in Web.Producers.Template) is begin if Tag = "action_cgi" then Forms.Write_Attribute_Name (Output, "action"); Forms.Write_Link ( Output, Form, Current_Directory => ".", Resource => Forms.Self); elsif Tag = "parameters" then Web.HTML.Write_Query_In_HTML ( Output, Form.HTML_Version, Form.Parameters_To_Village_Page ( Village_Id => Village_Id, User_Id => User_Id, User_Password => User_Password)); elsif Tag = "action_page" then Forms.Write_Attribute_Name (Output, "action"); Forms.Write_Link ( Output, Form, Current_Directory => ".", Resource => Forms.Self, Parameters => Form.Parameters_To_Village_Page ( Village_Id => Village_Id, User_Id => User_Id, User_Password => User_Password)); elsif Tag = "villagename" then Forms.Write_In_HTML (Output, Form, Village.Name.Constant_Reference); elsif Tag = "message" then case Person.Role is when Villages.Doctor => Forms.Write_In_HTML ( Output, Form, Villages.Text.Name (Target_Person) & "を診察しますか?"); when Villages.Detective => if Target_Person.Records.Constant_Reference (Village.Today).Note.Is_Null then Forms.Write_In_HTML ( Output, Form, "遺言を読み解くにはもう少しかかりそうですが、現時点で"); end if; Forms.Write_In_HTML ( Output, Form, Villages.Text.Name (Target_Person) & "を調査しますか?"); when others => raise Program_Error; end case; elsif Tag = "value_submit" then Forms.Write_Attribute_Name (Output, "value"); Forms.Write_Attribute_Open (Output); case Person.Role is when Villages.Doctor => Forms.Write_In_Attribute (Output, Form, "診察"); when Villages.Detective => Forms.Write_In_Attribute (Output, Form, "調査"); when others => raise Program_Error; end case; Forms.Write_Attribute_Close (Output); elsif Tag = "value_target" then Forms.Write_Attribute_Name (Output, "value"); Forms.Write_Attribute_Open (Output); Forms.Write_In_Attribute (Output, Form, Image (Target)); Forms.Write_Attribute_Close (Output); else Raise_Unknown_Tag (Tag); end if; end Handle; begin Web.Producers.Produce (Output, Read (Template), Handler => Handle'Access); end Vampire.R3.Target_Page;
-- Fuel Management System with Ada.Text_IO; with Ada.Strings.Maps; with Ada.Strings.Fixed; with Ada.Strings.Unbounded; with Ada.Strings.Hash; package body FMS is package TIO renames Ada.Text_IO; function to_dir(c : in Character) return Direction is begin case c is when 'U' => return Up; when 'D' => return Down; when 'L' => return Left; when 'R' => return Right; when others => raise Constraint_Error; end case; end to_dir; function to_string(d : in Direction) return String is begin case d is when Up => return "U"; when Down => return "D"; when Left => return "L"; when Right => return "R"; end case; end to_string; function to_string(p : in Position) return String is begin return "(" & Integer'IMAGE(p.x) & "," & Integer'IMAGE(p.y) & "): " & Natural'IMAGE(p.dist); end to_string; function distance(p : in Position) return Natural is begin return abs(p.x) + abs(p.y); end distance; function hash(p : in Position) return Ada.Containers.Hash_Type is begin return Ada.Strings.Hash(p.x'IMAGE & "," & p.y'IMAGE); end hash; function equivalent_positions(left, right: Position) return Boolean is begin return (left.x = right.x) and then (left.y = right.y); end equivalent_positions; -- function "=" (left : in Position; right : in Position) return Boolean is -- begin -- return (left.x = right.x) and (left.y = right.y); -- end "="; function to_string(wp : in Wire_Points.Set) return String is package Unbounded renames Ada.Strings.Unbounded; s : Unbounded.Unbounded_String; begin for elt of wp loop Unbounded.append(s, to_string(elt) & ", "); end loop; return Unbounded.to_string(s); end to_string; function to_string(ws : in Wire_Segment) return String is begin return to_string(ws.dir) & Integer'Image(ws.distance); end to_string; function to_string(w : in Wire.Vector) return String is package Unbounded renames Ada.Strings.Unbounded; s : Unbounded.Unbounded_String; begin for elt of w loop Unbounded.append(s, to_string(elt) & ", "); end loop; return Unbounded.to_string(s); end to_string; procedure parse_wire(w_str : in String; w : in out Wire.Vector) is start : Natural := w_str'First; finish : Natural; delimiters : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.to_set(Sequence => ","); begin w.clear; while start <= w_str'Last loop Ada.Strings.Fixed.find_token(Source => w_str(start .. w_str'Last), Set => delimiters, Test => Ada.Strings.outside, First => start, Last => finish); if not(finish = 0 and then start = w_str'First) then w.append((dir => to_dir(w_str(start)), distance => Integer'Value(w_str(start+1 .. finish)))); end if; start := finish + 1; end loop; end parse_wire; procedure step(pos : in out Position; dir : in Direction) is begin case dir is when Up => pos := (x => pos.x, y => pos.y - 1, dist => pos.dist + 1); when Down => pos := (x => pos.x, y => pos.y + 1, dist => pos.dist + 1); when Left => pos := (x => pos.x - 1, y => pos.y, dist => pos.dist + 1); when Right => pos := (x => pos.x + 1, y => pos.y, dist => pos.dist + 1); end case; end step; procedure expand(pos : in out Position; segment : in Wire_Segment; points : in out Wire_Points.Set) is begin for i in 1 .. segment.distance loop step(pos => pos, dir => segment.dir); points.include(pos); end loop; end expand; procedure expand_segments(w : in Wire.Vector; points : in out Wire_Points.Set) is start_pos : constant Position := (x => 0, y => 0, dist => 0); curr_pos : Position := start_pos; begin points.clear; for segment of w loop expand(pos => curr_pos, segment => segment, points => points); end loop; end expand_segments; procedure load(w1 : in String; w2 : in String) is begin parse_wire(w1, wire_1); expand_segments(wire_1, wire_points_1); parse_wire(w2, wire_2); expand_segments(wire_2, wire_points_2); end load; procedure load_file(path : String) is file : TIO.File_Type; begin TIO.open(File => file, Mode => TIO.In_File, Name => path); declare str1 : constant String := TIO.get_line(file); str2 : constant String := TIO.get_line(file); begin load(w1 => str1, w2 => str2); end; TIO.close(file); end load_file; function closest_intersection return Positive is use Wire_Points; best : Positive := Positive'LAST; in_common : constant Wire_Points.Set := wire_points_1 and wire_points_2; begin for elt of in_common loop declare curr : constant Natural := distance(elt); begin if curr < best then best := curr; end if; end; end loop; return best; end closest_intersection; function shortest_intersection return Positive is use Wire_Points; best : Positive := Positive'LAST; in_common : constant Wire_Points.Set := wire_points_1 and wire_points_2; begin for elt of in_common loop declare e1 : constant cursor := find(wire_points_1, elt); d1 : constant natural := element(e1).dist; e2 : constant cursor := find(wire_points_2, elt); d2 : constant natural := element(e2).dist; curr : constant Natural := d1 + d2; begin if curr < best then best := curr; end if; end; end loop; return best; end shortest_intersection; end FMS;
-- CA1108B.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- CHECK THAT IF WITH_CLAUSES ARE GIVEN FOR BOTH A SPEC AND A BODY, AND -- THE CLAUSES NAME DIFFERENT LIBRARY UNITS, THE UNITS NAMED IN ALL THE -- CLAUSES ARE VISIBLE IN THE BODY AND IN SUBUNITS OF THE BODY. -- BHS 7/31/84 -- JBG 5/1/85 PACKAGE FIRST_PKG IS FUNCTION F (X : INTEGER := 1) RETURN INTEGER; END FIRST_PKG; PACKAGE BODY FIRST_PKG IS FUNCTION F (X : INTEGER := 1) RETURN INTEGER IS BEGIN RETURN X; END F; END FIRST_PKG; PACKAGE LATER_PKG IS FUNCTION F (Y : INTEGER := 2) RETURN INTEGER; END LATER_PKG; PACKAGE BODY LATER_PKG IS FUNCTION F (Y : INTEGER := 2) RETURN INTEGER IS BEGIN RETURN Y + 1; END F; END LATER_PKG; WITH REPORT, FIRST_PKG; USE REPORT; PRAGMA ELABORATE (FIRST_PKG); PACKAGE CA1108B_PKG IS I, J : INTEGER; PROCEDURE PROC; PROCEDURE CALL_SUBS (X, Y : IN OUT INTEGER); END CA1108B_PKG; WITH LATER_PKG; PRAGMA ELABORATE (LATER_PKG); PACKAGE BODY CA1108B_PKG IS PROCEDURE SUB (X, Y : IN OUT INTEGER) IS SEPARATE; PROCEDURE PROC IS I, J : INTEGER; BEGIN I := FIRST_PKG.F; IF I /= 1 THEN FAILED ("FIRST_PKG FUNCTION NOT VISIBLE IN " & "PACKAGE BODY PROCEDURE"); END IF; J := LATER_PKG.F; IF J /= 3 THEN FAILED ("LATER_PKG FUNCITON NOT VISIBLE IN " & "PACKAGE BODY PROCEDURE"); END IF; END PROC; PROCEDURE CALL_SUBS (X, Y : IN OUT INTEGER) IS BEGIN SUB (X, Y); END CALL_SUBS; BEGIN I := FIRST_PKG.F; IF I /= 1 THEN FAILED ("FIRST_PKG FUNCTION NOT VISIBLE IN PACKAGE BODY"); END IF; J := LATER_PKG.F; IF J /= 3 THEN FAILED ("LATER_PKG FUNCTION NOT VISIBLE IN PACKAGE BODY"); END IF; END CA1108B_PKG; WITH REPORT, CA1108B_PKG; USE REPORT, CA1108B_PKG; PROCEDURE CA1108B IS VAR1, VAR2 : INTEGER; BEGIN TEST ("CA1108B", "IF DIFFERENT WITH_CLAUSES GIVEN FOR PACKAGE " & "SPEC AND BODY, ALL NAMED UNITS ARE VISIBLE " & "IN THE BODY AND ITS SUBUNITS"); PROC; VAR1 := 0; VAR2 := 1; CALL_SUBS (VAR1, VAR2); IF VAR1 /= 1 THEN FAILED ("FIRST_PKG FUNCTION NOT VISIBLE IN SUBUNIT"); END IF; IF VAR2 /= 3 THEN FAILED ("LATER_PKG FUNCTION NOT VISIBLE IN SUBUNIT"); END IF; RESULT; END CA1108B; SEPARATE (CA1108B_PKG) PROCEDURE SUB (X, Y : IN OUT INTEGER) IS PROCEDURE SUB2 (A, B : IN OUT INTEGER) IS SEPARATE; BEGIN SUB2 (Y, X); IF Y /= 1 THEN FAILED ("FIRST_PKG FUNCTION NOT VISIBLE IN SUBUNIT " & "OF SUBUNIT"); END IF; IF X /= 3 THEN FAILED ("LATER_PKG FUNCTION NOT VISIBLE IN SUBUNIT " & "OF SUBUNIT"); END IF; X := FIRST_PKG.F; Y := LATER_PKG.F; END SUB; SEPARATE (CA1108B_PKG.SUB) PROCEDURE SUB2 (A, B : IN OUT INTEGER) IS BEGIN A := FIRST_PKG.F; B := LATER_PKG.F; END SUB2;
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- SQL Database Access -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011-2014, Vadim Godunko <vgodunko@gmail.com> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE 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 -- -- HOLDER 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. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This package provides abstract types to define database and query -- abstractions for databases. Database drivers should provide implementation -- of both abstractions. -- -- Note: database driver should avoid raising of exceptions, instead it should -- reports failures of operations in specified way and be ready to provide -- diagnosis message in Error_Message function. -- -- Note: all operations except Is_Object_Valid on Abstract_Query are called -- only when query is valid, so database drivers should use this to optimize -- code. ------------------------------------------------------------------------------ with League.Strings; with League.Holders; private with Matreshka.Atomics.Counters; with SQL.Options; package Matreshka.Internals.SQL_Drivers is pragma Preelaborate; type Abstract_Database is abstract tagged limited private; type Database_Access is access all Abstract_Database'Class; type Abstract_Query is abstract tagged limited private; type Query_Access is access all Abstract_Query'Class; ----------------------- -- Abstract_Database -- ----------------------- not overriding procedure Finalize (Self : not null access Abstract_Database) is null; -- Release all used resources. not overriding function Open (Self : not null access Abstract_Database; Options : SQL.Options.SQL_Options) return Boolean is abstract; -- Opens database connection. -- -- The function must return True on success and False on failure. not overriding procedure Close (Self : not null access Abstract_Database) is abstract; -- Closes the database connection, freeing any resources acquired, and -- invalidating any existing QSqlQuery objects that are used with the -- database. not overriding procedure Commit (Self : not null access Abstract_Database) is abstract; -- Commits active transaction. not overriding function Query (Self : not null access Abstract_Database) return not null Query_Access is abstract; not overriding function Error_Message (Self : not null access Abstract_Database) return League.Strings.Universal_String is abstract; procedure Invalidate_Queries (Self : not null access Abstract_Database'Class); -- Invalidates all queries. -------------------- -- Abstract_Query -- -------------------- not overriding procedure Bind_Value (Self : not null access Abstract_Query; Name : League.Strings.Universal_String; Value : League.Holders.Holder; Direction : SQL.Parameter_Directions) is abstract; not overriding function Bound_Value (Self : not null access Abstract_Query; Name : League.Strings.Universal_String) return League.Holders.Holder is abstract; -- XXX not overriding function Error_Message (Self : not null access Abstract_Query) return League.Strings.Universal_String is abstract; not overriding procedure Finalize (Self : not null access Abstract_Query); -- Called before memory deallocation. At Abstract_Query level it -- invalidates query object. not overriding procedure Finish (Self : not null access Abstract_Query) is abstract; -- Instruct the database driver that no more data will be fetched from this -- query until it is re-executed. There is normally no need to call this -- function, but it may be helpful in order to free resources such as locks -- or cursors if you intend to re-use the query at a later time. -- -- Sets the query to inactive. Bound values retain their values. not overriding procedure Invalidate (Self : not null access Abstract_Query); -- Invalidates object. At Abstract_Query level it detachs query object from -- database object and dereference database object. Database drivers should -- release other resources before call to this inherited procedure. not overriding function Is_Active (Self : not null access Abstract_Query) return Boolean is abstract; -- Returns True when prepared statement is active, so was executed but not -- finished. function Is_Object_Valid (Self : not null access Abstract_Query'Class) return Boolean; -- Returns True when query object is valid. not overriding function Is_Valid (Self : not null access Abstract_Query) return Boolean is abstract; -- Returns True if the query is currently positioned on a valid record; -- otherwise returns false. not overriding function Prepare (Self : not null access Abstract_Query; Query : League.Strings.Universal_String) return Boolean is abstract; -- Prepares the SQL query query for execution. Returns True if the query is -- prepared successfully; otherwise returns False. -- -- The query may contain placeholders for binding values. Both Oracle style -- colon-name (e.g., :surname), and ODBC style (?) placeholders are -- supported; but they cannot be mixed in the same query. not overriding function Execute (Self : not null access Abstract_Query) return Boolean is abstract; -- Executes a previously prepared SQL query. Returns True if the query -- executed successfully; otherwise returns False. -- -- After the query is executed, the query is positioned on an invalid -- record and must be navigated to a valid record before data values can be -- retrieved. -- -- Note that the last error for this query is reset when Execute is called. not overriding function Next (Self : not null access Abstract_Query) return Boolean is abstract; not overriding function Value (Self : not null access Abstract_Query; Index : Positive) return League.Holders.Holder is abstract; --------------------- -- Database_Access -- --------------------- procedure Reference (Self : not null Database_Access); pragma Inline (Reference); -- Increments internal reference counter. procedure Dereference (Self : in out Database_Access); -- Decrements internal reference counter and deallocates object when there -- are no reference to it any more. Sets Self to null always. ------------------ -- Query_Access -- ------------------ procedure Reference (Self : not null Query_Access); pragma Inline (Reference); -- Increments internal reference counter. procedure Dereference (Self : in out Query_Access); -- Decrements internal reference counter and deallocates object when there -- are no reference to it any more. Sets Self to null always. ------------- -- Factory -- ------------- function Create (Driver : League.Strings.Universal_String) return not null Database_Access; -- Creates new database object using registered factory. Returns reference -- to dummy database object when driver is not registered. private type Abstract_Database is abstract tagged limited record Counter : Matreshka.Atomics.Counters.Counter; Head : Query_Access; Tail : Query_Access; end record; type Abstract_Query is abstract tagged limited record Counter : Matreshka.Atomics.Counters.Counter; Database : Database_Access; Next : Query_Access; Previous : Query_Access; end record; procedure Initialize (Self : not null access Abstract_Query'Class; Database : not null Database_Access); -- Initializes new object of Abstract_Query type. It inserts object into -- the list of query objects of database. type Abstract_Factory is abstract tagged limited null record; type Factory_Access is access all Abstract_Factory'Class; not overriding function Create (Self : not null access Abstract_Factory) return not null Database_Access is abstract; -- Creates new database object. procedure Register (Name : League.Strings.Universal_String; Factory : not null Factory_Access); -- Register factory. Factory is never deallocated and can be allocated -- statically. end Matreshka.Internals.SQL_Drivers;
----------------------------------------------------------------------- -- awa-users-principals -- User principals -- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body AWA.Users.Principals is -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Principal) return String is begin return From.User.Get_Name; end Get_Name; -- ------------------------------ -- Get the principal identifier (name) -- ------------------------------ function Get_Id (From : in Principal) return String is begin return From.User.Get_Name; end Get_Id; -- ------------------------------ -- Get the user associated with the principal. -- ------------------------------ function Get_User (From : in Principal) return AWA.Users.Models.User_Ref is begin return From.User; end Get_User; -- ------------------------------ -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none. -- ------------------------------ function Get_User_Identifier (From : in Principal) return ADO.Identifier is begin return From.User.Get_Id; end Get_User_Identifier; -- ------------------------------ -- Get the connection session used by the user. -- ------------------------------ function Get_Session (From : in Principal) return AWA.Users.Models.Session_Ref is begin return From.Session; end Get_Session; -- ------------------------------ -- Get the connection session identifier used by the user. -- ------------------------------ function Get_Session_Identifier (From : in Principal) return ADO.Identifier is begin return From.Session.Get_Id; end Get_Session_Identifier; -- ------------------------------ -- Create a principal for the given user. -- ------------------------------ function Create (User : in AWA.Users.Models.User_Ref; Session : in AWA.Users.Models.Session_Ref) return Principal_Access is Result : constant Principal_Access := new Principal; begin Result.User := User; Result.Session := Session; return Result; end Create; -- ------------------------------ -- Create a principal for the given user. -- ------------------------------ function Create (User : in AWA.Users.Models.User_Ref; Session : in AWA.Users.Models.Session_Ref) return Principal is begin return Result : Principal do Result.User := User; Result.Session := Session; end return; end Create; -- ------------------------------ -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none or if the principal is not an AWA principal. -- ------------------------------ function Get_User_Identifier (From : in ASF.Principals.Principal_Access) return ADO.Identifier is use type ASF.Principals.Principal_Access; begin if From = null then return ADO.NO_IDENTIFIER; elsif not (From.all in Principal'Class) then return ADO.NO_IDENTIFIER; else return Principal'Class (From.all).Get_User_Identifier; end if; end Get_User_Identifier; end AWA.Users.Principals;
pragma Ada_2012; pragma Style_Checks (Off); with Interfaces.C; use Interfaces.C; with bits_types_h; with bits_types_u_mbstate_t_h; package bits_types_u_fpos64_t_h is -- The tag name of this struct is _G_fpos64_t to preserve historic -- C++ mangled names for functions taking fpos_t and/or fpos64_t -- arguments. That name should not be used in new code. type u_G_fpos64_t is record uu_pos : aliased bits_types_h.uu_off64_t; -- /usr/include/bits/types/__fpos64_t.h:12 uu_state : aliased bits_types_u_mbstate_t_h.uu_mbstate_t; -- /usr/include/bits/types/__fpos64_t.h:13 end record with Convention => C_Pass_By_Copy; -- /usr/include/bits/types/__fpos64_t.h:10 subtype uu_fpos64_t is u_G_fpos64_t; -- /usr/include/bits/types/__fpos64_t.h:14 end bits_types_u_fpos64_t_h;
-- Abstract : -- -- See spec. -- -- Copyright (C) 2018 - 2019 Free Software Foundation, Inc. -- -- This library is free software; you can redistribute it and/or modify it -- under terms of the GNU General Public License as published by the Free -- Software Foundation; either version 3, or (at your option) any later -- version. This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- -- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- As a special exception under Section 7 of GPL version 3, you are granted -- additional permissions described in the GCC Runtime Library Exception, -- version 3.1, as published by the Free Software Foundation. pragma License (Modified_GPL); package body SAL.Gen_Bounded_Definite_Vectors_Sorted is function Length (Container : in Vector) return Ada.Containers.Count_Type is (Ada.Containers.Count_Type (Container.Last)); function Is_Full (Container : in Vector) return Boolean is begin return Container.Last = Peek_Type (Capacity); end Is_Full; procedure Clear (Container : in out Vector) is begin Container.Last := No_Index; end Clear; function Last_Index (Container : in Vector) return Base_Peek_Type is (Container.Last); function Element (Container : in Vector; Index : in Peek_Type) return Element_Type is (Container.Elements (Index)); procedure Insert (Container : in out Vector; New_Item : in Element_Type; Ignore_If_Equal : in Boolean := False) is K : constant Base_Peek_Type := Container.Last; J : Base_Peek_Type := K; begin if K = 0 then -- Container empty Container.Last := 1; Container.Elements (1) := New_Item; return; end if; loop pragma Loop_Invariant (J < Container.Elements'Last); pragma Loop_Variant (Decreases => J); exit when J < 1; case Element_Compare (New_Item, Container.Elements (J)) is when Less => J := J - 1; when Equal => if Ignore_If_Equal then return; else -- Insert after J exit; end if; when Greater => -- Insert after J exit; end case; end loop; Container.Elements (J + 2 .. K + 1) := Container.Elements (J + 1 .. K); Container.Elements (J + 1) := New_Item; Container.Last := Container.Last + 1; end Insert; end SAL.Gen_Bounded_Definite_Vectors_Sorted;
-- part of OpenGLAda, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "COPYING" with System; with Glfw.Input.Mouse; with Glfw.Input.Keys; with Glfw.Monitors; private with Ada.Finalization; package Glfw.Windows is type Window is tagged private; type Window_Reference is not null access all Window; Creation_Error : exception; package Callbacks is -- avoid pollution of Glfw.Windows package with symbols type Kind is (Position, Size, Close, Refresh, Focus, Iconify, Framebuffer_Size, Mouse_Button, Mouse_Position, Mouse_Scroll, Mouse_Enter, Key, Char); end Callbacks; subtype Coordinate is Interfaces.C.int; -- throws Creation_Error if the window cannot be created procedure Init (Object : not null access Window; Width, Height : Size; Title : String; -- interpreted as UTF-8 Monitor : Monitors.Monitor := Monitors.No_Monitor; Share_Resources_With : access Window'Class := null); function Initialized (Object : not null access Window) return Boolean; procedure Destroy (Object : not null access Window); procedure Show (Object : not null access Window); procedure Hide (Object : not null access Window); procedure Set_Title (Object : not null access Window; Value : String); procedure Get_OpenGL_Version (Object : not null access Window; Major, Minor, Revision : out Natural); function Key_State (Object : not null access Window; Key : Input.Keys.Key) return Input.Button_State; function Mouse_Button_State (Object : not null access Window; Button : Input.Mouse.Button) return Input.Button_State; procedure Set_Input_Toggle (Object : not null access Window; Kind : Input.Sticky_Toggle; Value : Boolean); function Get_Cursor_Mode (Object : not null access Window) return Input.Mouse.Cursor_Mode; procedure Set_Cursor_Mode (Object : not null access Window; Mode : Input.Mouse.Cursor_Mode); procedure Get_Cursor_Pos (Object : not null access Window; X, Y : out Input.Mouse.Coordinate); procedure Set_Cursor_Pos (Object : not null access Window; X, Y : Input.Mouse.Coordinate); procedure Get_Position (Object : not null access Window; X, Y : out Coordinate); procedure Set_Position (Object : not null access Window; X, Y : Coordinate); procedure Get_Size (Object : not null access Window; Width, Height : out Size); procedure Set_Size (Object : not null access Window; Width, Height : Size); procedure Get_Framebuffer_Size (Object : not null access Window; Width, Height : out Size); function Visible (Object : not null access Window) return Boolean; function Iconified (Object : not null access Window) return Boolean; function Focused (Object : not null access Window) return Boolean; function Should_Close (Object : not null access Window) return Boolean; procedure Set_Should_Close (Object : not null access Window; Value : Boolean); ----------------------------------------------------------------------------- -- Event API ----------------------------------------------------------------------------- procedure Enable_Callback (Object : not null access Window; Subject : Callbacks.Kind); procedure Disable_Callback (Object : not null access Window; Subject : Callbacks.Kind); procedure Position_Changed (Object : not null access Window; X, Y : Integer) is null; procedure Size_Changed (Object : not null access Window; Width, Height : Natural) is null; procedure Close_Requested (Object : not null access Window) is null; procedure Refresh (Object : not null access Window) is null; procedure Focus_Changed (Object : not null access Window; Focused : Boolean) is null; procedure Iconification_Changed (Object : not null access Window; Iconified : Boolean) is null; procedure Framebuffer_Size_Changed (Object : not null access Window; Width, Height : Natural) is null; procedure Mouse_Button_Changed (Object : not null access Window; Button : Input.Mouse.Button; State : Input.Button_State; Mods : Input.Keys.Modifiers) is null; procedure Mouse_Position_Changed (Object : not null access Window; X, Y : Input.Mouse.Coordinate) is null; procedure Mouse_Scrolled (Object : not null access Window; X, Y : Input.Mouse.Scroll_Offset) is null; procedure Mouse_Entered (Object : not null access Window; Action : Input.Mouse.Enter_Action) is null; procedure Key_Changed (Object : not null access Window; Key : Input.Keys.Key; Scancode : Input.Keys.Scancode; Action : Input.Keys.Action; Mods : Input.Keys.Modifiers) is null; procedure Character_Entered (Object : not null access Window; Char : Wide_Wide_Character) is null; private type Window is new Ada.Finalization.Controlled with record Handle : System.Address := System.Null_Address; end record; function Window_Ptr (Raw : System.Address) return not null access Window'Class; end Glfw.Windows;
------------------------------------------------------------------------------ -- -- -- Ada User Repository Annex (AURA) -- -- ANNEXI-STRAYLINE Reference Implementation -- -- -- -- Command Line Interface -- -- -- -- ------------------------------------------------------------------------ -- -- -- -- Copyright (C) 2020, ANNEXI-STRAYLINE Trans-Human Ltd. -- -- All rights reserved. -- -- -- -- Original Contributors: -- -- * Richard Wai (ANNEXI-STRAYLINE) -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- -- -- * Neither the name of the copyright holder 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. -- -- -- ------------------------------------------------------------------------------ with Ada.Containers; with Ada.Characters.Conversions; with Specification_Scanner; use Specification_Scanner; separate (Configuration) procedure Step_3a (Target: in out Subsystem) is use type Ada.Containers.Count_Type; package ACC renames Ada.Characters.Conversions; package Subsystems renames Registrar.Subsystems; Config_Tree: Declaration_Trees.Tree; -- We now expect the Configuration unit to be present Config_Unit: constant Library_Unit := Reg_Qs.Lookup_Unit (Config_Unit_Name (Target)); -- Utilities function Find_In_Branch (Root: in Declaration_Trees.Cursor; Name: in Wide_Wide_String) return Declaration_Trees.Cursor; -- Searches for an entity Name within the branch rooted at Root - i.e. -- only within the immediate children of Root function Find_Package_In_Branch (Root: in Declaration_Trees.Cursor; Name: in Wide_Wide_String) return Declaration_Trees.Cursor; -- Invokes Find_In_Branch for Root and Name, and then asserts that -- the entity (if any) denoted by Name is a non-generic package procedure Load_Names (Package_Root: in Declaration_Trees.Cursor; List : in out Subsystems.Configuration_Vector); -- Load names expected to be given the root cursor of a package entity. -- Load names then iterates over the immediate children of that package -- entity, isolating constant String objects, and appending their names -- to List. -- Stages procedure Process_Build; procedure Process_Ada_Package (Build_Root: in Declaration_Trees.Cursor); procedure Process_C_Package (Build_Root: in Declaration_Trees.Cursor); procedure Process_Codepaths; procedure Process_Information; -------------------- -- Find_In_Branch -- -------------------- function Find_In_Branch (Root: in Declaration_Trees.Cursor; Name: in Wide_Wide_String) return Declaration_Trees.Cursor is use Declaration_Trees; Index: Cursor := First_Child (Root); begin while Index /= No_Element loop if WWU.To_Wide_Wide_String (Config_Tree(Index).Name) = Name then return Index; end if; Index := Next_Sibling (Index); end loop; return No_Element; end Find_In_Branch; ---------------------------- -- Find_Package_In_Branch -- ---------------------------- function Find_Package_In_Branch (Root: in Declaration_Trees.Cursor; Name: in Wide_Wide_String) return Declaration_Trees.Cursor is use Declaration_Trees; PC: constant Cursor := Find_In_Branch (Root, Name); begin if PC = No_Element then return PC; end if; declare PE: Declared_Entity renames Config_Tree(PC); begin Assert (Check => PE.Kind = Package_Declaration and then not PE.Is_Generic, Message => ACC.To_String (WWU.To_Wide_Wide_String (PE.Name)) & " shall be a non-generic package declaration." ); return PC; end; end Find_Package_In_Branch; ---------------- -- Load_Names -- ---------------- procedure Load_Names (Package_Root: in Declaration_Trees.Cursor; List : in out Subsystems.Configuration_Vector) is use Declaration_Trees; Index: Cursor := First_Child (Package_Root); begin while Index /= No_Element loop declare Ent: Declared_Entity renames Config_Tree(Index); begin if Ent.Kind = Object_Declaration and then Ent.Is_Constant and then WWU.To_Wide_Wide_String (Ent.Subtype_Mark) = "string" then List.Append ((Name => Ent.Name, Value => UBS.Null_Unbounded_String)); end if; Index := Next_Sibling (Index); end; end loop; end Load_Names; ------------------- -- Process_Build -- ------------------- procedure Process_Build is use Declaration_Trees; Build_Root: constant Cursor := Find_Package_In_Branch (Root => First_Child (Config_Tree.Root), Name => "build"); begin if Build_Root = No_Element then return; end if; -- Load the External_Libraries, if present declare P: constant Cursor := Find_Package_In_Branch (Root => Build_Root, Name => "external_libraries"); begin if P /= No_Element then Load_Names (Package_Root => P, List => Target.Configuration.External_Libraries); end if; end; Process_Ada_Package (Build_Root); Process_C_Package (Build_Root); end Process_Build; ------------------------- -- Process_Ada_Package -- ------------------------- procedure Process_Ada_Package (Build_Root: in Declaration_Trees.Cursor) is use Declaration_Trees; Ada_Root: constant Cursor := Find_Package_In_Branch (Root => Build_Root, Name => "ada"); Comp_Opt: Cursor; begin if Ada_Root /= No_Element then Comp_Opt := Find_Package_In_Branch (Root => Ada_Root, Name => "compiler_options"); if Comp_Opt /= No_Element then Load_Names (Package_Root => Comp_Opt, List => Target.Configuration.Ada_Compiler_Opts); end if; end if; end Process_Ada_Package; ----------------------- -- Process_C_Package -- ----------------------- procedure Process_C_Package (Build_Root: in Declaration_Trees.Cursor) is use Declaration_Trees; C_Root: constant Cursor := Find_Package_In_Branch (Root => Build_Root, Name => "c"); Comp_Opt: Cursor; CPP_Defs: Cursor; begin if C_Root /= No_Element then Comp_Opt := Find_Package_In_Branch (Root => C_Root, Name => "compiler_options"); if Comp_Opt /= No_Element then Load_Names (Package_Root => Comp_Opt, List => Target.Configuration.C_Compiler_Opts); end if; CPP_Defs := Find_Package_In_Branch (Root => C_Root, Name => "preprocessor_definitions"); if CPP_Defs /= No_Element then Load_Names (Package_Root => CPP_Defs, List => Target.Configuration.C_Definitions); end if; end if; end Process_C_Package; ----------------------- -- Process_Codepaths -- ----------------------- procedure Process_Codepaths is use Declaration_Trees; CP_Root: constant Cursor := Find_Package_In_Branch (Root => First_Child (Config_Tree.Root), Name => "codepaths"); begin if CP_Root /= No_Element then Assert (Check => Target.Name.To_String /= "aura", Message => "Root Configuration (AURA.Root) shall not " & "have a codepaths package"); Load_Names (Package_Root => CP_Root, List => Target.Configuration.Codepaths); end if; end Process_Codepaths; ------------------------- -- Process_Information -- ------------------------- procedure Process_Information is use Declaration_Trees; Info_Root: constant Cursor := Find_Package_In_Branch (Root => First_Child (Config_Tree.Root), Name => "information"); begin if Info_Root /= No_Element then Load_Names (Package_Root => Info_Root, List => Target.Configuration.Codepaths); end if; end Process_Information; begin Target.Configuration := (others => Subsystems.Configuration_Vectors.Empty_Vector); Scan_Package_Spec (Unit => Config_Unit, Unit_Tree => Config_Tree); Process_Build; -- Includes Ada and C packages Process_Codepaths; Process_Information; -- Now we have a sense of which packages are in the configuration unit, and -- which objects need to be exported from the loader program, executed in -- Step 3b -- However if we *know* we don't have anything to load, then we can skip -- right to step 4. This can happen when the configuration file is empty. if Target.Configuration.External_Libraries.Length = 0 and then Target.Configuration.Ada_Compiler_Opts.Length = 0 and then Target.Configuration.C_Compiler_Opts.Length = 0 and then Target.Configuration.C_Definitions.Length = 0 and then Target.Configuration.Codepaths.Length = 0 and then Target.Configuration.Information.Length = 0 then Step_4 (Target); else Step_3b (Target); end if; end Step_3a;
----------------------------------------------------------------------- -- atlas-server -- Application server -- Copyright (C) 2011, 2012, 2013, 2016, 2017, 2018, 2019, 2020, 2021 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- 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. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Commands; with AWS.Net.SSL; with Servlet.Server.Web; with AWA.Commands.Drivers; with AWA.Commands.Start; with AWA.Commands.Setup; with AWA.Commands.Stop; with AWA.Commands.List; with AWA.Commands.Info; with ADO.Drivers; -- with ADO.Sqlite; -- with ADO.Mysql; -- with ADO.Postgresql; with Atlas.Applications; procedure Atlas.Server is package Server_Commands is new AWA.Commands.Drivers (Driver_Name => "atlas", Container_Type => Servlet.Server.Web.AWS_Container); package List_Command is new AWA.Commands.List (Server_Commands); package Start_Command is new AWA.Commands.Start (Server_Commands); package Stop_Command is new AWA.Commands.Stop (Server_Commands); package Info_Command is new AWA.Commands.Info (Server_Commands); package Setup_Command is new AWA.Commands.Setup (Start_Command); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas.Server"); App : constant Atlas.Applications.Application_Access := new Atlas.Applications.Application; WS : Servlet.Server.Web.AWS_Container renames Server_Commands.WS; Context : AWA.Commands.Context_Type; Arguments : Util.Commands.Dynamic_Argument_List; begin -- Initialize the database drivers (all of them or specific ones). ADO.Drivers.Initialize; -- ADO.Sqlite.Initialize; -- ADO.Mysql.Initialize; -- ADO.Postgresql.Initialize; WS.Register_Application (Atlas.Applications.CONTEXT_PATH, App.all'Access); if not AWS.Net.SSL.Is_Supported then Log.Error ("SSL is not supported by AWS."); Log.Error ("SSL is required for the OAuth2/OpenID connector to " & "connect to OAuth2/OpenID providers."); Log.Error ("Please, rebuild AWS with SSL support."); end if; Log.Info ("Connect you browser to: http://localhost:8080{0}/index.html", Atlas.Applications.CONTEXT_PATH); Server_Commands.Run (Context, Arguments); exception when E : others => Context.Print (E); end Atlas.Server;