content
stringlengths
23
1.05M
pragma License (Unrestricted); -- implementation unit package Ada.Streams.Naked_Stream_IO.Standard_Files is pragma Elaborate_Body; Standard_Input : aliased constant Non_Controlled_File_Type; Standard_Output : aliased constant Non_Controlled_File_Type; Standard_Error : aliased constant Non_Controlled_File_Type; private Standard_Input_Name : aliased System.Native_IO.Name_String (0 .. 6) := ( System.Native_IO.Name_Character'Val (Character'Pos ('*')), System.Native_IO.Name_Character'Val (Character'Pos ('s')), System.Native_IO.Name_Character'Val (Character'Pos ('t')), System.Native_IO.Name_Character'Val (Character'Pos ('d')), System.Native_IO.Name_Character'Val (Character'Pos ('i')), System.Native_IO.Name_Character'Val (Character'Pos ('n')), System.Native_IO.Name_Character'Val (0)); Standard_Input_Stream : aliased Stream_Type := ( Handle => System.Native_IO.Uninitialized_Standard_Input, Mode => System.Native_IO.Read_Only_Mode, Name => Standard_Input_Name (0)'Access, Form => Default_Form, Kind => Standard_Handle, Has_Full_Name => False, Buffer_Inline => 0, Buffer => System.Null_Address, Buffer_Length => Uninitialized_Buffer, Buffer_Index => 0, Reading_Index => 0, Writing_Index => 0, Closer => null, Dispatcher => (Tags.No_Tag, null)); Standard_Output_Name : aliased System.Native_IO.Name_String (0 .. 7) := ( System.Native_IO.Name_Character'Val (Character'Pos ('*')), System.Native_IO.Name_Character'Val (Character'Pos ('s')), System.Native_IO.Name_Character'Val (Character'Pos ('t')), System.Native_IO.Name_Character'Val (Character'Pos ('d')), System.Native_IO.Name_Character'Val (Character'Pos ('o')), System.Native_IO.Name_Character'Val (Character'Pos ('u')), System.Native_IO.Name_Character'Val (Character'Pos ('t')), System.Native_IO.Name_Character'Val (0)); Standard_Output_Stream : aliased Stream_Type := ( Handle => System.Native_IO.Uninitialized_Standard_Output, Mode => System.Native_IO.Write_Only_Mode, Name => Standard_Output_Name (0)'Access, Form => Default_Form, Kind => Standard_Handle, Has_Full_Name => False, Buffer_Inline => 0, Buffer => System.Null_Address, Buffer_Length => Uninitialized_Buffer, Buffer_Index => 0, Reading_Index => 0, Writing_Index => 0, Closer => null, Dispatcher => (Tags.No_Tag, null)); Standard_Error_Name : aliased System.Native_IO.Name_String (0 .. 7) := ( System.Native_IO.Name_Character'Val (Character'Pos ('*')), System.Native_IO.Name_Character'Val (Character'Pos ('s')), System.Native_IO.Name_Character'Val (Character'Pos ('t')), System.Native_IO.Name_Character'Val (Character'Pos ('d')), System.Native_IO.Name_Character'Val (Character'Pos ('e')), System.Native_IO.Name_Character'Val (Character'Pos ('r')), System.Native_IO.Name_Character'Val (Character'Pos ('r')), System.Native_IO.Name_Character'Val (0)); Standard_Error_Stream : aliased Stream_Type := ( Handle => System.Native_IO.Uninitialized_Standard_Error, Mode => System.Native_IO.Write_Only_Mode, Name => Standard_Error_Name (0)'Access, Form => Default_Form, Kind => Standard_Handle, Has_Full_Name => False, Buffer_Inline => 0, Buffer => System.Null_Address, Buffer_Length => Uninitialized_Buffer, Buffer_Index => 0, Reading_Index => 0, Writing_Index => 0, Closer => null, Dispatcher => (Tags.No_Tag, null)); Standard_Input : aliased constant Non_Controlled_File_Type := Standard_Input_Stream'Access; Standard_Output : aliased constant Non_Controlled_File_Type := Standard_Output_Stream'Access; Standard_Error : aliased constant Non_Controlled_File_Type := Standard_Error_Stream'Access; end Ada.Streams.Naked_Stream_IO.Standard_Files;
with lace.Environ.OS_Commands, posix.user_Database, posix.process_Identification; package body lace.Environ.Users is function "+" (Source : in unbounded_String) return String renames to_String; function to_User (Name : in String) return User is begin return (Name => to_unbounded_String (Name)); end to_User; function Name (Self : in User) return String is begin return to_String (Self.Name); end Name; procedure add_User (Self : in User; Super : in Boolean := False) is use lace.Environ.OS_Commands; begin if Super then declare Output : constant String := run_OS ("useradd " & (+Self.Name) & " -m -G sudo -G root"); begin if Output /= "" then raise Error with Output; end if; end; else declare Output : constant String := run_OS ("useradd " & (+Self.Name) & " -m"); begin if Output /= "" then raise Error with Output; end if; end; end if; end add_User; procedure rid_User (Self : in User) is use lace.Environ.OS_Commands; Output : constant String := run_OS ("userdel -r " & (+Self.Name)); begin if Output /= "" then raise Error with Output; end if; end rid_User; procedure switch_to (Self : in User) is use Posix, posix.User_Database, posix.Process_Identification; User_in_DB : constant User_Database_Item := get_User_Database_Item (to_Posix_String (+Self.Name)); ID : constant User_ID := User_ID_of (User_in_DB); begin set_User_ID (ID); end switch_to; function current_User return User is use Posix, posix.process_Identification; begin return to_User (to_String (get_Login_Name)); end current_User; function home_Folder (Self : in User := current_User) return Paths.Folder is use Paths, Posix, posix.User_Database; User_in_DB : constant User_Database_Item := get_User_Database_Item (to_Posix_String (+Self.Name)); begin return to_Folder (to_String (initial_Directory_of (User_in_DB))); end home_Folder; end lace.Environ.Users;
with Scape; use Scape; with Ada.Characters.Conversions; use Ada.Characters.Conversions; with Ada.Strings.Wide_Wide_Unbounded; use Ada.Strings.Wide_Wide_Unbounded; with AWS.Client; use AWS.Client; with GNAT.Regpat; use Gnat.Regpat; with AWS.Response; use AWS.Response; with ZLib; use ZLib; use AWS; package body Plugin.URL is function Unescape (Str : String) return String is (To_String (To_Wide_Wide_String (Decode (Str)))); -- FIXME: Fix this crap function Get_Body (URL : Unbounded_String) return String is Limit : constant Content_Range := (1, 3000); begin return Message_Body (Get (URL => To_String (URL), Data_Range => Limit)); exception when Zlib_Error => return Message_Body (Get (To_String (URL))); end Get_Body; -- Strip newlines from title, just a corner case. function Normalize_Title (Raw : String) return Unbounded_String is (GSub (To_Unbounded_String (Bold ("Title: ") & Unescape (Raw)), ASCII.CR & ASCII.LF, "")); function Get_Title (URL : Unbounded_String) return Unbounded_String is Header : constant Data := Head (To_String (URL)); Regex : constant Pattern_Matcher := Compile ("<title>(.*)<\/title>", Case_Insensitive or Single_Line); Result : Match_Array (0 .. 1); begin if Response.Header (Header, "Content-Type") (1 .. 4) = "text" then declare Content : constant String := Get_Body (URL); begin Match(Regex, Content, Result); if not (Result(1) = No_Match) then return Normalize_Title (Content (Result(1).First .. Result(1).Last)); else return To_Unbounded_String ("Title not found"); end if; end; else return To_Unbounded_String (Bold ("Content-Type: ") & Response.Header (Header, "Content-Type") & ", " & Bold ("Size: ") & Response.Header (Header, "Content-Length")); end if; end Get_Title; procedure URL_Title (Message : IRC.Message) is Answer : IRC.Message := Message; begin for C in Iterate (Words (Message.Content)) loop if Link (Element (C)) then Answer.Content := Get_Title (Element (C)); IRC.Put_Message (Answer); exit; end if; end loop; exception -- Silently ignore exceptions like malformed url or connection problems when others => null; end URL_Title; end Plugin.URL;
with Entities; use Entities; with Materials; use Materials; with Vectors2D; use Vectors2D; package Rectangles is type Rectangle is new Entities.Entity with record Dim : Vec2D; -- (x => width, y => height) end record; pragma Pack (Rectangle); type RectangleAcc is access all Rectangle; -- Create a new Rectangle function Create(Pos, Vel, Grav, Dim : in Vec2D; Mat : in Material) return EntityClassAcc; function GetWidth(This : in Rectangle) return Float; function GetHeight(This : in Rectangle) return Float; function GetCenter(This : in Rectangle) return Vec2D; overriding function GetPosition(This : in Rectangle) return Vec2D; private -- Initialization of a Rectangle procedure Initialize(This : in RectangleAcc; Pos, Vel, Grav, Dim : in Vec2D; Mat : in Material); overriding procedure ComputeMass(This : in out Rectangle); overriding procedure FreeEnt(This : access Rectangle); end Rectangles;
with Ada.Text_IO; use Ada.Text_IO; package body Aids.Env is function Index_Of(Line: in String; X: in Character; Result: out Integer) return Boolean is begin for Index in Line'Range loop if Line(Index) = X then Result := Index; return True; end if; end loop; return False; end; function Slurp(File_Path: String) return Env_Hashed_Map.Map is Result: Env_Hashed_Map.Map; File: File_Type; Line_Number: Integer := 1; begin Open(File => File, Mode => In_File, Name => File_Path); while not End_Of_File(File) loop declare Line: String := Get_Line(File); Index : Integer; begin if Index_Of(Line, '=', Index) then declare Key : Unbounded_String := To_Unbounded_String(Line(Line'First..Index-1)); Value : Unbounded_String := To_Unbounded_String(Line(Index+1..Line'Last)); begin Env_Hashed_Map.Insert(Result, Key, Value); end; else raise Syntax_Error with (File_Path & ":" & Integer'Image(Line_Number) & ": Expected separator `=`"); end if; Line_Number := Line_Number + 1; end; end loop; Close(File); return Result; end; function Find(Env: in Typ; Key: in Unbounded_String; Value: out Unbounded_String) return Boolean is C: Env_Hashed_Map.Cursor := Env_Hashed_Map.Find(Env, Key); begin if Env_Hashed_Map.Has_Element(C) then Value := Env_Hashed_Map.Element(C); return True; end if; return False; end; end Aids.Env;
with Ada.Text_IO; use Ada.Text_IO; procedure Test is function F return character is begin return 'a' end F; begin Put(F); end;
----------------------------------------------------------------------- -- awa-services -- Services -- 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. ----------------------------------------------------------------------- with AWA.Applications; with AWA.Users.Principals; with AWA.Users.Models; with ADO; with ADO.Sessions; with Util.Beans.Objects; with Ada.Finalization; -- The service context provides additional information to a service operation. -- This context is composed of: -- <ul> -- <li>the optional user context which allows to identify the current user invoking the service, -- <li>the database connections that the service can use, -- <li>the other services provided by the application. -- </ul> package AWA.Services.Contexts is type Service_Context is new Ada.Finalization.Limited_Controlled with private; type Service_Context_Access is access all Service_Context'Class; -- Get the application associated with the current service operation. function Get_Application (Ctx : in Service_Context) return AWA.Applications.Application_Access; -- Get the current database connection for reading. function Get_Session (Ctx : in Service_Context_Access) return ADO.Sessions.Session; -- Get the current database connection for reading and writing. function Get_Master_Session (Ctx : in Service_Context_Access) return ADO.Sessions.Master_Session; -- Get the current user invoking the service operation. -- Returns a null user if there is none. function Get_User (Ctx : in Service_Context) return AWA.Users.Models.User_Ref; -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none. function Get_User_Identifier (Ctx : in Service_Context) return ADO.Identifier; -- Get the current user session from the user invoking the service operation. -- Returns a null session if there is none. function Get_User_Session (Ctx : in Service_Context) return AWA.Users.Models.Session_Ref; -- Starts a transaction. procedure Start (Ctx : in out Service_Context); -- Commits the current transaction. The database transaction is really committed by the -- last <b>Commit</b> called. procedure Commit (Ctx : in out Service_Context); -- Rollback the current transaction. The database transaction is rollback at the first -- call to <b>Rollback</b>. procedure Rollback (Ctx : in out Service_Context); -- Get the attribute registered under the given name in the HTTP session. function Get_Session_Attribute (Ctx : in Service_Context; Name : in String) return Util.Beans.Objects.Object; -- Set the attribute registered under the given name in the HTTP session. procedure Set_Session_Attribute (Ctx : in out Service_Context; Name : in String; Value : in Util.Beans.Objects.Object); -- Initializes the service context. overriding procedure Initialize (Ctx : in out Service_Context); -- Finalize the service context, rollback non-committed transaction, releases any object. overriding procedure Finalize (Ctx : in out Service_Context); -- Set the current application and user context. procedure Set_Context (Ctx : in out Service_Context; Application : in AWA.Applications.Application_Access; Principal : in AWA.Users.Principals.Principal_Access); -- Get the current service context. -- Returns null if the current thread is not associated with any service context. function Current return Service_Context_Access; -- Run the process procedure on behalf of the specific user and session. -- This operation changes temporarily the identity of the current user principal and -- executes the <tt>Process</tt> procedure. generic with procedure Process; procedure Run_As (User : in AWA.Users.Models.User_Ref; Session : in AWA.Users.Models.Session_Ref); private type Service_Context is new Ada.Finalization.Limited_Controlled with record Previous : Service_Context_Access := null; Application : AWA.Applications.Application_Access := null; Principal : AWA.Users.Principals.Principal_Access := null; Master : ADO.Sessions.Master_Session; Slave : ADO.Sessions.Session; Transaction : Integer := 0; Active_Transaction : Boolean := False; end record; end AWA.Services.Contexts;
with System.Storage_Elements; use System.Storage_Elements; with Ada.Containers.Vectors; with Ada.Unchecked_Deallocation; with AAA.Strings; private with Ada.Containers.Indefinite_Vectors; package Test_Utils is package Data_Frame_Package is new Ada.Containers.Vectors (Storage_Count, Storage_Element); type Data_Frame is new Data_Frame_Package.Vector with null record; type Storage_Array_Access is access all Storage_Array; procedure Free is new Ada.Unchecked_Deallocation (Storage_Array, Storage_Array_Access); function From_Array (Data : Storage_Array) return Data_Frame; function To_Array_Access (Data : Data_Frame'Class) return Storage_Array_Access; function Hex_Dump (Data : Data_Frame'Class) return AAA.Strings.Vector; function Diff (A, B : Data_Frame'Class; A_Name : String := "Expected"; B_Name : String := "Output"; Skip_Header : Boolean := False) return AAA.Strings.Vector; function Image (D : Storage_Array) return String; function Image (D : Data_Frame) return String; type Abstract_Data_Processing is abstract tagged limited private; function Number_Of_Frames (This : Abstract_Data_Processing) return Storage_Count; -- Return the number of output data frames available procedure Clear (This : in out Abstract_Data_Processing) with Post => This.Number_Of_Frames = 0; function Get_Frame (This : Abstract_Data_Processing'Class; Index : Storage_Count) return Data_Frame with Pre => Index <= This.Number_Of_Frames - 1; -- Return an output data frames from it index private package Data_Frame_Vectors is new Ada.Containers.Indefinite_Vectors (Storage_Count, Data_Frame); type Abstract_Data_Processing is abstract tagged limited record Frames : Data_Frame_Vectors.Vector; Current_Frame : Data_Frame; end record; procedure Start_New_Frame (This : in out Abstract_Data_Processing); procedure Push_To_Frame (This : in out Abstract_Data_Processing; Data : Storage_Element); procedure Save_Frame (This : in out Abstract_Data_Processing); end Test_Utils;
function Multiply (A, B : Number) return Number is begin return A * B; end Multiply;
with PixelArray; with Ada.Text_IO; use PixelArray; package body HistogramGenerator is function verticalProjection(image: PixelArray.ImagePlane; r: ImageRegions.Rect) return Histogram.Data is result: Histogram.Data(r.height); begin for h in 0 .. r.height - 1 loop declare total: Float := 0.0; begin for w in 0 .. r.width - 1 loop if image.get(r.x + w, r.y + h) /= PixelArray.Background then total := total + 1.0; end if; end loop; result.set(h, total); end; end loop; return result; end verticalProjection; function horizontalProjection(image:PixelArray.ImagePlane; r: ImageRegions.Rect) return Histogram.Data is result: Histogram.Data(r.width); begin for h in 0 .. r.height - 1 loop for w in 0 .. r.width - 1 loop if image.get(r.x + w, r.y + h) /= PixelArray.Background then result.set(w, result.get(w) + 1.0); end if; end loop; end loop; return result; end horizontalProjection; end HistogramGenerator;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S I N P U T -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2020, 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 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 Style_Checks (All_Checks); -- Subprograms not all in alpha order with Atree; use Atree; with Debug; use Debug; with Opt; use Opt; with Output; use Output; with Scans; use Scans; with Widechar; use Widechar; with GNAT.Byte_Order_Mark; use GNAT.Byte_Order_Mark; with System.Storage_Elements; with System.Memory; with System.WCh_Con; use System.WCh_Con; with Unchecked_Conversion; with Unchecked_Deallocation; package body Sinput is use ASCII, System; -- Routines to support conversion between types Lines_Table_Ptr, -- Logical_Lines_Table_Ptr and System.Address. pragma Warnings (Off); -- These unchecked conversions are aliasing safe, since they are never -- used to construct improperly aliased pointer values. function To_Address is new Unchecked_Conversion (Lines_Table_Ptr, Address); function To_Address is new Unchecked_Conversion (Logical_Lines_Table_Ptr, Address); function To_Pointer is new Unchecked_Conversion (Address, Lines_Table_Ptr); function To_Pointer is new Unchecked_Conversion (Address, Logical_Lines_Table_Ptr); pragma Warnings (On); ----------------------------- -- Source_File_Index_Table -- ----------------------------- -- The Get_Source_File_Index function is called very frequently. Earlier -- versions cached a single entry, but then reverted to a serial search, -- and this proved to be a significant source of inefficiency. We then -- switched to using a table with a start point followed by a serial -- search. Now we make sure source buffers are on a reasonable boundary -- (see Types.Source_Align), and we can just use a direct look up in the -- following table. -- Note that this array is pretty large, but in most operating systems -- it will not be allocated in physical memory unless it is actually used. Source_File_Index_Table : array (Int range 0 .. 1 + (Int'Last / Source_Align)) of Source_File_Index; --------------------------- -- Add_Line_Tables_Entry -- --------------------------- procedure Add_Line_Tables_Entry (S : in out Source_File_Record; P : Source_Ptr) is LL : Physical_Line_Number; begin -- Reallocate the lines tables if necessary -- Note: the reason we do not use the normal Table package -- mechanism is that we have several of these tables. We could -- use the new GNAT.Dynamic_Tables package and that would probably -- be a good idea ??? if S.Last_Source_Line = S.Lines_Table_Max then Alloc_Line_Tables (S, Int (S.Last_Source_Line) * ((100 + Alloc.Lines_Increment) / 100)); if Debug_Flag_D then Write_Str ("--> Reallocating lines table, size = "); Write_Int (Int (S.Lines_Table_Max)); Write_Eol; end if; end if; S.Last_Source_Line := S.Last_Source_Line + 1; LL := S.Last_Source_Line; S.Lines_Table (LL) := P; -- Deal with setting new entry in logical lines table if one is -- present. Note that there is always space (because the call to -- Alloc_Line_Tables makes sure both tables are the same length), if S.Logical_Lines_Table /= null then -- We can always set the entry from the previous one, because -- the processing for a Source_Reference pragma ensures that -- at least one entry following the pragma is set up correctly. S.Logical_Lines_Table (LL) := S.Logical_Lines_Table (LL - 1) + 1; end if; end Add_Line_Tables_Entry; ----------------------- -- Alloc_Line_Tables -- ----------------------- procedure Alloc_Line_Tables (S : in out Source_File_Record; New_Max : Nat) is subtype size_t is Memory.size_t; New_Table : Lines_Table_Ptr; New_Logical_Table : Logical_Lines_Table_Ptr; New_Size : constant size_t := size_t (New_Max * Lines_Table_Type'Component_Size / Storage_Unit); begin if S.Lines_Table = null then New_Table := To_Pointer (Memory.Alloc (New_Size)); else New_Table := To_Pointer (Memory.Realloc (To_Address (S.Lines_Table), New_Size)); end if; if New_Table = null then raise Storage_Error; else S.Lines_Table := New_Table; S.Lines_Table_Max := Physical_Line_Number (New_Max); end if; if S.Num_SRef_Pragmas /= 0 then if S.Logical_Lines_Table = null then New_Logical_Table := To_Pointer (Memory.Alloc (New_Size)); else New_Logical_Table := To_Pointer (Memory.Realloc (To_Address (S.Logical_Lines_Table), New_Size)); end if; if New_Logical_Table = null then raise Storage_Error; else S.Logical_Lines_Table := New_Logical_Table; end if; end if; end Alloc_Line_Tables; ----------------- -- Backup_Line -- ----------------- procedure Backup_Line (P : in out Source_Ptr) is Sindex : constant Source_File_Index := Get_Source_File_Index (P); Src : constant Source_Buffer_Ptr := Source_File.Table (Sindex).Source_Text; Sfirst : constant Source_Ptr := Source_File.Table (Sindex).Source_First; begin P := P - 1; if P = Sfirst then return; end if; if Src (P) = CR then if Src (P - 1) = LF then P := P - 1; end if; else -- Src (P) = LF if Src (P - 1) = CR then P := P - 1; end if; end if; -- Now find first character of the previous line while P > Sfirst and then Src (P - 1) /= LF and then Src (P - 1) /= CR loop P := P - 1; end loop; end Backup_Line; --------------------------- -- Build_Location_String -- --------------------------- procedure Build_Location_String (Buf : in out Bounded_String; Loc : Source_Ptr) is Ptr : Source_Ptr := Loc; begin -- Loop through instantiations loop Append (Buf, Reference_Name (Get_Source_File_Index (Ptr))); Append (Buf, ':'); Append (Buf, Nat (Get_Logical_Line_Number (Ptr))); Ptr := Instantiation_Location (Ptr); exit when Ptr = No_Location; Append (Buf, " instantiated at "); end loop; end Build_Location_String; function Build_Location_String (Loc : Source_Ptr) return String is Buf : Bounded_String; begin Build_Location_String (Buf, Loc); return +Buf; end Build_Location_String; ------------------- -- Check_For_BOM -- ------------------- procedure Check_For_BOM is BOM : BOM_Kind; Len : Natural; Tst : String (1 .. 5); C : Character; begin for J in 1 .. 5 loop C := Source (Scan_Ptr + Source_Ptr (J) - 1); -- Definitely no BOM if EOF character marks either end of file, or -- an illegal non-BOM character if not at the end of file. if C = EOF then return; end if; Tst (J) := C; end loop; Read_BOM (Tst, Len, BOM, XML_Support => False); case BOM is when UTF8_All => Scan_Ptr := Scan_Ptr + Source_Ptr (Len); First_Non_Blank_Location := Scan_Ptr; Current_Line_Start := Scan_Ptr; Wide_Character_Encoding_Method := WCEM_UTF8; Upper_Half_Encoding := True; when UTF16_BE | UTF16_LE => Set_Standard_Error; Write_Line ("UTF-16 encoding format not recognized"); Set_Standard_Output; raise Unrecoverable_Error; when UTF32_BE | UTF32_LE => Set_Standard_Error; Write_Line ("UTF-32 encoding format not recognized"); Set_Standard_Output; raise Unrecoverable_Error; when Unknown => null; when others => raise Program_Error; end case; end Check_For_BOM; ----------------------------- -- Clear_Source_File_Table -- ----------------------------- procedure Free is new Unchecked_Deallocation (Lines_Table_Type, Lines_Table_Ptr); procedure Free is new Unchecked_Deallocation (Logical_Lines_Table_Type, Logical_Lines_Table_Ptr); procedure Clear_Source_File_Table is begin for X in 1 .. Source_File.Last loop declare S : Source_File_Record renames Source_File.Table (X); begin if S.Instance = No_Instance_Id then Free_Source_Buffer (S.Source_Text); else Free_Dope (S.Source_Text'Address); S.Source_Text := null; end if; Free (S.Lines_Table); Free (S.Logical_Lines_Table); end; end loop; Source_File.Free; Sinput.Initialize; end Clear_Source_File_Table; --------------------------------- -- Comes_From_Inherited_Pragma -- --------------------------------- function Comes_From_Inherited_Pragma (S : Source_Ptr) return Boolean is SIE : Source_File_Record renames Source_File.Table (Get_Source_File_Index (S)); begin return SIE.Inherited_Pragma; end Comes_From_Inherited_Pragma; ----------------------------- -- Comes_From_Inlined_Body -- ----------------------------- function Comes_From_Inlined_Body (S : Source_Ptr) return Boolean is SIE : Source_File_Record renames Source_File.Table (Get_Source_File_Index (S)); begin return SIE.Inlined_Body; end Comes_From_Inlined_Body; ------------------------ -- Free_Source_Buffer -- ------------------------ procedure Free_Source_Buffer (Src : in out Source_Buffer_Ptr) is -- Unchecked_Deallocation doesn't work for access-to-constant; we need -- to first Unchecked_Convert to access-to-variable. function To_Source_Buffer_Ptr_Var is new Unchecked_Conversion (Source_Buffer_Ptr, Source_Buffer_Ptr_Var); Temp : Source_Buffer_Ptr_Var := To_Source_Buffer_Ptr_Var (Src); procedure Free_Ptr is new Unchecked_Deallocation (Source_Buffer, Source_Buffer_Ptr_Var); begin Free_Ptr (Temp); Src := null; end Free_Source_Buffer; ----------------------- -- Get_Column_Number -- ----------------------- function Get_Column_Number (P : Source_Ptr) return Column_Number is S : Source_Ptr; C : Column_Number; Sindex : Source_File_Index; Src : Source_Buffer_Ptr; begin -- If the input source pointer is not a meaningful value then return -- at once with column number 1. This can happen for a file not found -- condition for a file loaded indirectly by RTE, and also perhaps on -- some unknown internal error conditions. In either case we certainly -- don't want to blow up. if P < 1 then return 1; else Sindex := Get_Source_File_Index (P); Src := Source_File.Table (Sindex).Source_Text; S := Line_Start (P); C := 1; while S < P loop if Src (S) = HT then C := (C - 1) / 8 * 8 + (8 + 1); S := S + 1; -- Deal with wide character case, but don't include brackets -- notation in this circuit, since we know that this will -- display unencoded (no one encodes brackets notation). elsif Src (S) /= '[' and then Is_Start_Of_Wide_Char (Src, S) then C := C + 1; Skip_Wide (Src, S); -- Normal (non-wide) character case or brackets sequence else C := C + 1; S := S + 1; end if; end loop; return C; end if; end Get_Column_Number; ----------------------------- -- Get_Logical_Line_Number -- ----------------------------- function Get_Logical_Line_Number (P : Source_Ptr) return Logical_Line_Number is SFR : Source_File_Record renames Source_File.Table (Get_Source_File_Index (P)); L : constant Physical_Line_Number := Get_Physical_Line_Number (P); begin if SFR.Num_SRef_Pragmas = 0 then return Logical_Line_Number (L); else return SFR.Logical_Lines_Table (L); end if; end Get_Logical_Line_Number; --------------------------------- -- Get_Logical_Line_Number_Img -- --------------------------------- function Get_Logical_Line_Number_Img (P : Source_Ptr) return String is begin Name_Len := 0; Add_Nat_To_Name_Buffer (Nat (Get_Logical_Line_Number (P))); return Name_Buffer (1 .. Name_Len); end Get_Logical_Line_Number_Img; ------------------------------ -- Get_Physical_Line_Number -- ------------------------------ function Get_Physical_Line_Number (P : Source_Ptr) return Physical_Line_Number is Sfile : Source_File_Index; Table : Lines_Table_Ptr; Lo : Physical_Line_Number; Hi : Physical_Line_Number; Mid : Physical_Line_Number; Loc : Source_Ptr; begin -- If the input source pointer is not a meaningful value then return -- at once with line number 1. This can happen for a file not found -- condition for a file loaded indirectly by RTE, and also perhaps on -- some unknown internal error conditions. In either case we certainly -- don't want to blow up. if P < 1 then return 1; -- Otherwise we can do the binary search else Sfile := Get_Source_File_Index (P); Loc := P + Source_File.Table (Sfile).Sloc_Adjust; Table := Source_File.Table (Sfile).Lines_Table; Lo := 1; Hi := Source_File.Table (Sfile).Last_Source_Line; loop Mid := (Lo + Hi) / 2; if Loc < Table (Mid) then Hi := Mid - 1; else -- Loc >= Table (Mid) if Mid = Hi or else Loc < Table (Mid + 1) then return Mid; else Lo := Mid + 1; end if; end if; end loop; end if; end Get_Physical_Line_Number; --------------------------- -- Get_Source_File_Index -- --------------------------- function Get_Source_File_Index (S : Source_Ptr) return Source_File_Index is Result : Source_File_Index; procedure Assertions; -- Assert various properties of the result procedure Assertions is -- ???The old version using zero-origin array indexing without array -- bounds checks returned 1 (i.e. system.ads) for these special -- locations, presumably by accident. We are mimicing that here. Special : constant Boolean := S = No_Location or else S = Standard_Location or else S = Standard_ASCII_Location or else S = System_Location; pragma Assert ((S > No_Location) xor Special); pragma Assert (Result in Source_File.First .. Source_File.Last); SFR : Source_File_Record renames Source_File.Table (Result); begin -- SFR.Source_Text = null if and only if this is the SFR for a debug -- output file (*.dg), and that file is under construction. S can be -- slightly past Source_Last in that case because we haven't updated -- Source_Last. if Null_Source_Buffer_Ptr (SFR.Source_Text) then pragma Assert (S >= SFR.Source_First); null; else pragma Assert (SFR.Source_Text'First = SFR.Source_First); pragma Assert (SFR.Source_Text'Last = SFR.Source_Last); if not Special then pragma Assert (S in SFR.Source_First .. SFR.Source_Last); null; end if; end if; end Assertions; -- Start of processing for Get_Source_File_Index begin if S > No_Location then Result := Source_File_Index_Table (Int (S) / Source_Align); else Result := 1; end if; pragma Debug (Assertions); return Result; end Get_Source_File_Index; ---------------- -- Initialize -- ---------------- procedure Initialize is begin Source_gnat_adc := No_Source_File; Source_File.Init; Instances.Init; Instances.Append (No_Location); pragma Assert (Instances.Last = No_Instance_Id); end Initialize; ------------------- -- Instantiation -- ------------------- function Instantiation (S : SFI) return Source_Ptr is SIE : Source_File_Record renames Source_File.Table (S); begin if SIE.Inlined_Body or SIE.Inherited_Pragma then return SIE.Inlined_Call; else return Instances.Table (SIE.Instance); end if; end Instantiation; ------------------------- -- Instantiation_Depth -- ------------------------- function Instantiation_Depth (S : Source_Ptr) return Nat is Sind : Source_File_Index; Sval : Source_Ptr; Depth : Nat; begin Sval := S; Depth := 0; loop Sind := Get_Source_File_Index (Sval); Sval := Instantiation (Sind); exit when Sval = No_Location; Depth := Depth + 1; end loop; return Depth; end Instantiation_Depth; ---------------------------- -- Instantiation_Location -- ---------------------------- function Instantiation_Location (S : Source_Ptr) return Source_Ptr is begin return Instantiation (Get_Source_File_Index (S)); end Instantiation_Location; -------------------------- -- Iterate_On_Instances -- -------------------------- procedure Iterate_On_Instances is begin for J in 1 .. Instances.Last loop Process (J, Instances.Table (J)); end loop; end Iterate_On_Instances; ---------------------- -- Last_Source_File -- ---------------------- function Last_Source_File return Source_File_Index is begin return Source_File.Last; end Last_Source_File; ---------------- -- Line_Start -- ---------------- function Line_Start (P : Source_Ptr) return Source_Ptr is Sindex : constant Source_File_Index := Get_Source_File_Index (P); Src : constant Source_Buffer_Ptr := Source_File.Table (Sindex).Source_Text; Sfirst : constant Source_Ptr := Source_File.Table (Sindex).Source_First; S : Source_Ptr; begin S := P; while S > Sfirst and then Src (S - 1) /= CR and then Src (S - 1) /= LF loop S := S - 1; end loop; return S; end Line_Start; function Line_Start (L : Physical_Line_Number; S : Source_File_Index) return Source_Ptr is begin return Source_File.Table (S).Lines_Table (L); end Line_Start; ---------- -- Lock -- ---------- procedure Lock is begin Source_File.Release; Source_File.Locked := True; end Lock; ---------------------- -- Num_Source_Files -- ---------------------- function Num_Source_Files return Nat is begin return Int (Source_File.Last) - Int (Source_File.First) + 1; end Num_Source_Files; ---------------------- -- Num_Source_Lines -- ---------------------- function Num_Source_Lines (S : Source_File_Index) return Nat is begin return Nat (Source_File.Table (S).Last_Source_Line); end Num_Source_Lines; ----------------------- -- Original_Location -- ----------------------- function Original_Location (S : Source_Ptr) return Source_Ptr is Sindex : Source_File_Index; Tindex : Source_File_Index; begin if S <= No_Location then return S; else Sindex := Get_Source_File_Index (S); if Instantiation (Sindex) = No_Location then return S; else Tindex := Template (Sindex); while Instantiation (Tindex) /= No_Location loop Tindex := Template (Tindex); end loop; return S - Source_First (Sindex) + Source_First (Tindex); end if; end if; end Original_Location; ------------------------- -- Physical_To_Logical -- ------------------------- function Physical_To_Logical (Line : Physical_Line_Number; S : Source_File_Index) return Logical_Line_Number is SFR : Source_File_Record renames Source_File.Table (S); begin if SFR.Num_SRef_Pragmas = 0 then return Logical_Line_Number (Line); else return SFR.Logical_Lines_Table (Line); end if; end Physical_To_Logical; -------------------------------- -- Register_Source_Ref_Pragma -- -------------------------------- procedure Register_Source_Ref_Pragma (File_Name : File_Name_Type; Stripped_File_Name : File_Name_Type; Mapped_Line : Nat; Line_After_Pragma : Physical_Line_Number) is subtype size_t is Memory.size_t; SFR : Source_File_Record renames Source_File.Table (Current_Source_File); ML : Logical_Line_Number; begin if File_Name /= No_File then SFR.Reference_Name := Stripped_File_Name; SFR.Full_Ref_Name := File_Name; if not Debug_Generated_Code then SFR.Debug_Source_Name := Stripped_File_Name; SFR.Full_Debug_Name := File_Name; end if; SFR.Num_SRef_Pragmas := SFR.Num_SRef_Pragmas + 1; end if; if SFR.Num_SRef_Pragmas = 1 then SFR.First_Mapped_Line := Logical_Line_Number (Mapped_Line); end if; if SFR.Logical_Lines_Table = null then SFR.Logical_Lines_Table := To_Pointer (Memory.Alloc (size_t (SFR.Lines_Table_Max * Logical_Lines_Table_Type'Component_Size / Storage_Unit))); end if; SFR.Logical_Lines_Table (Line_After_Pragma - 1) := No_Line_Number; ML := Logical_Line_Number (Mapped_Line); for J in Line_After_Pragma .. SFR.Last_Source_Line loop SFR.Logical_Lines_Table (J) := ML; ML := ML + 1; end loop; end Register_Source_Ref_Pragma; --------------------------------- -- Set_Source_File_Index_Table -- --------------------------------- procedure Set_Source_File_Index_Table (Xnew : Source_File_Index) is Ind : Int; SP : Source_Ptr; SL : constant Source_Ptr := Source_File.Table (Xnew).Source_Last; begin SP := Source_File.Table (Xnew).Source_First; pragma Assert (SP mod Source_Align = 0); Ind := Int (SP) / Source_Align; while SP <= SL loop Source_File_Index_Table (Ind) := Xnew; SP := SP + Source_Align; Ind := Ind + 1; end loop; end Set_Source_File_Index_Table; --------------------------- -- Skip_Line_Terminators -- --------------------------- procedure Skip_Line_Terminators (P : in out Source_Ptr; Physical : out Boolean) is Chr : constant Character := Source (P); begin if Chr = CR then if Source (P + 1) = LF then P := P + 2; else P := P + 1; end if; elsif Chr = LF then P := P + 1; elsif Chr = FF or else Chr = VT then P := P + 1; Physical := False; return; -- Otherwise we have a wide character else Skip_Wide (Source, P); end if; -- Fall through in the physical line terminator case. First deal with -- making a possible entry into the lines table if one is needed. -- Note: we are dealing with a real source file here, this cannot be -- the instantiation case, so we need not worry about Sloc adjustment. declare S : Source_File_Record renames Source_File.Table (Current_Source_File); begin Physical := True; -- Make entry in lines table if not already made (in some scan backup -- cases, we will be rescanning previously scanned source, so the -- entry may have already been made on the previous forward scan). if Source (P) /= EOF and then P > S.Lines_Table (S.Last_Source_Line) then Add_Line_Tables_Entry (S, P); end if; end; end Skip_Line_Terminators; -------------- -- Set_Dope -- -------------- procedure Set_Dope (Src : System.Address; New_Dope : Dope_Ptr) is -- A fat pointer is a pair consisting of data pointer and dope pointer, -- in that order. So we want to overwrite the second word. Dope : System.Address; pragma Import (Ada, Dope); use System.Storage_Elements; for Dope'Address use Src + System.Address'Size / 8; begin Dope := New_Dope.all'Address; end Set_Dope; procedure Free_Dope (Src : System.Address) is Dope : Dope_Ptr; pragma Import (Ada, Dope); use System.Storage_Elements; for Dope'Address use Src + System.Address'Size / 8; procedure Free is new Unchecked_Deallocation (Dope_Rec, Dope_Ptr); begin Free (Dope); end Free_Dope; ---------------- -- Sloc_Range -- ---------------- procedure Sloc_Range (N : Node_Id; Min, Max : out Source_Ptr) is Indx : constant Source_File_Index := Get_Source_File_Index (Sloc (N)); function Process (N : Node_Id) return Traverse_Result; -- Process function for traversing the node tree procedure Traverse is new Traverse_Proc (Process); ------------- -- Process -- ------------- function Process (N : Node_Id) return Traverse_Result is Orig : constant Node_Id := Original_Node (N); begin -- Skip nodes that may have been added during expansion and -- that originate in other units, such as code for contracts -- in subprogram bodies. if Get_Source_File_Index (Sloc (Orig)) /= Indx then return Skip; end if; if Sloc (Orig) < Min then if Sloc (Orig) > No_Location then Min := Sloc (Orig); end if; elsif Sloc (Orig) > Max then if Sloc (Orig) > No_Location then Max := Sloc (Orig); end if; end if; return OK_Orig; end Process; -- Start of processing for Sloc_Range begin Min := Sloc (N); Max := Sloc (N); Traverse (N); end Sloc_Range; ------------------- -- Source_Offset -- ------------------- function Source_Offset (S : Source_Ptr) return Nat is Sindex : constant Source_File_Index := Get_Source_File_Index (S); Sfirst : constant Source_Ptr := Source_File.Table (Sindex).Source_First; begin return Nat (S - Sfirst); end Source_Offset; ------------------------ -- Top_Level_Location -- ------------------------ function Top_Level_Location (S : Source_Ptr) return Source_Ptr is Oldloc : Source_Ptr; Newloc : Source_Ptr; begin Newloc := S; loop Oldloc := Newloc; Newloc := Instantiation_Location (Oldloc); exit when Newloc = No_Location; end loop; return Oldloc; end Top_Level_Location; -------------------- -- Write_Location -- -------------------- procedure Write_Location (P : Source_Ptr) is begin if P = No_Location then Write_Str ("<no location>"); elsif P <= Standard_Location then Write_Str ("<standard location>"); else declare SI : constant Source_File_Index := Get_Source_File_Index (P); begin Write_Name (Debug_Source_Name (SI)); Write_Char (':'); Write_Int (Int (Get_Logical_Line_Number (P))); Write_Char (':'); Write_Int (Int (Get_Column_Number (P))); if Instantiation (SI) /= No_Location then Write_Str (" ["); Write_Location (Instantiation (SI)); Write_Char (']'); end if; end; end if; end Write_Location; ---------------------- -- Write_Time_Stamp -- ---------------------- procedure Write_Time_Stamp (S : Source_File_Index) is T : constant Time_Stamp_Type := Time_Stamp (S); P : Natural; begin if T (1) = '9' then Write_Str ("19"); P := 0; else Write_Char (T (1)); Write_Char (T (2)); P := 2; end if; Write_Char (T (P + 1)); Write_Char (T (P + 2)); Write_Char ('-'); Write_Char (T (P + 3)); Write_Char (T (P + 4)); Write_Char ('-'); Write_Char (T (P + 5)); Write_Char (T (P + 6)); Write_Char (' '); Write_Char (T (P + 7)); Write_Char (T (P + 8)); Write_Char (':'); Write_Char (T (P + 9)); Write_Char (T (P + 10)); Write_Char (':'); Write_Char (T (P + 11)); Write_Char (T (P + 12)); end Write_Time_Stamp; ---------------------------------------------- -- Access Subprograms for Source File Table -- ---------------------------------------------- function Debug_Source_Name (S : SFI) return File_Name_Type is begin return Source_File.Table (S).Debug_Source_Name; end Debug_Source_Name; function Instance (S : SFI) return Instance_Id is begin return Source_File.Table (S).Instance; end Instance; function File_Name (S : SFI) return File_Name_Type is begin return Source_File.Table (S).File_Name; end File_Name; function File_Type (S : SFI) return Type_Of_File is begin return Source_File.Table (S).File_Type; end File_Type; function First_Mapped_Line (S : SFI) return Logical_Line_Number is begin return Source_File.Table (S).First_Mapped_Line; end First_Mapped_Line; function Full_Debug_Name (S : SFI) return File_Name_Type is begin return Source_File.Table (S).Full_Debug_Name; end Full_Debug_Name; function Full_File_Name (S : SFI) return File_Name_Type is begin return Source_File.Table (S).Full_File_Name; end Full_File_Name; function Full_Ref_Name (S : SFI) return File_Name_Type is begin return Source_File.Table (S).Full_Ref_Name; end Full_Ref_Name; function Identifier_Casing (S : SFI) return Casing_Type is begin return Source_File.Table (S).Identifier_Casing; end Identifier_Casing; function Inherited_Pragma (S : SFI) return Boolean is begin return Source_File.Table (S).Inherited_Pragma; end Inherited_Pragma; function Inlined_Body (S : SFI) return Boolean is begin return Source_File.Table (S).Inlined_Body; end Inlined_Body; function Inlined_Call (S : SFI) return Source_Ptr is begin return Source_File.Table (S).Inlined_Call; end Inlined_Call; function Keyword_Casing (S : SFI) return Casing_Type is begin return Source_File.Table (S).Keyword_Casing; end Keyword_Casing; function Last_Source_Line (S : SFI) return Physical_Line_Number is begin return Source_File.Table (S).Last_Source_Line; end Last_Source_Line; function License (S : SFI) return License_Type is begin return Source_File.Table (S).License; end License; function Num_SRef_Pragmas (S : SFI) return Nat is begin return Source_File.Table (S).Num_SRef_Pragmas; end Num_SRef_Pragmas; function Reference_Name (S : SFI) return File_Name_Type is begin return Source_File.Table (S).Reference_Name; end Reference_Name; function Source_Checksum (S : SFI) return Word is begin return Source_File.Table (S).Source_Checksum; end Source_Checksum; function Source_First (S : SFI) return Source_Ptr is begin return Source_File.Table (S).Source_First; end Source_First; function Source_Last (S : SFI) return Source_Ptr is begin return Source_File.Table (S).Source_Last; end Source_Last; function Source_Text (S : SFI) return Source_Buffer_Ptr is begin return Source_File.Table (S).Source_Text; end Source_Text; function Template (S : SFI) return SFI is begin return Source_File.Table (S).Template; end Template; function Time_Stamp (S : SFI) return Time_Stamp_Type is begin return Source_File.Table (S).Time_Stamp; end Time_Stamp; function Unit (S : SFI) return Unit_Number_Type is begin return Source_File.Table (S).Unit; end Unit; ------------------------------------------ -- Set Procedures for Source File Table -- ------------------------------------------ procedure Set_Identifier_Casing (S : SFI; C : Casing_Type) is begin Source_File.Table (S).Identifier_Casing := C; end Set_Identifier_Casing; procedure Set_Keyword_Casing (S : SFI; C : Casing_Type) is begin Source_File.Table (S).Keyword_Casing := C; end Set_Keyword_Casing; procedure Set_License (S : SFI; L : License_Type) is begin Source_File.Table (S).License := L; end Set_License; procedure Set_Unit (S : SFI; U : Unit_Number_Type) is begin Source_File.Table (S).Unit := U; end Set_Unit; ---------------------- -- Trim_Lines_Table -- ---------------------- procedure Trim_Lines_Table (S : Source_File_Index) is Max : constant Nat := Nat (Source_File.Table (S).Last_Source_Line); begin -- Release allocated storage that is no longer needed Source_File.Table (S).Lines_Table := To_Pointer (Memory.Realloc (To_Address (Source_File.Table (S).Lines_Table), Memory.size_t (Max * (Lines_Table_Type'Component_Size / System.Storage_Unit)))); Source_File.Table (S).Lines_Table_Max := Physical_Line_Number (Max); end Trim_Lines_Table; ------------ -- Unlock -- ------------ procedure Unlock is begin Source_File.Locked := False; Source_File.Release; end Unlock; -------- -- wl -- -------- procedure wl (P : Source_Ptr) is begin Write_Location (P); Write_Eol; end wl; end Sinput;
----------------------------------------------------------------------- -- net-protos-arp -- ARP Network protocol -- Copyright (C) 2016 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.Real_Time; with Net.Headers; package body Net.Protos.Arp is use type Ada.Real_Time.Time; Broadcast_Mac : constant Ether_Addr := (others => 16#ff#); Arp_Retry_Timeout : constant Ada.Real_Time.Time_Span := Ada.Real_Time.Seconds (1); Arp_Entry_Timeout : constant Ada.Real_Time.Time_Span := Ada.Real_Time.Seconds (30); Arp_Unreachable_Timeout : constant Ada.Real_Time.Time_Span := Ada.Real_Time.Seconds (120); Arp_Stale_Timeout : constant Ada.Real_Time.Time_Span := Ada.Real_Time.Seconds (120); -- The ARP table index uses the last byte of the IP address. We assume our network is -- a /24 which means we can have 253 valid IP addresses (0 and 255 are excluded). subtype Arp_Index is Uint8 range 1 .. 254; -- Maximum number of ARP entries we can remember. We could increase to 253 but most -- application will only send packets to a small number of hosts. ARP_MAX_ENTRIES : constant Positive := 32; -- Accept to queue at most 30 packets. QUEUE_LIMIT : constant Natural := 30; -- The maximum number of packets which can be queued for each entry. QUEUE_ENTRY_LIMIT : constant Uint8 := 3; ARP_MAX_RETRY : constant Positive := 15; type Arp_Entry; type Arp_Entry_Access is access all Arp_Entry; type Arp_Entry is record Ether : Ether_Addr; Expire : Ada.Real_Time.Time; Queue : Net.Buffers.Buffer_List; Retry : Natural := 0; Index : Arp_Index := Arp_Index'First; Queue_Size : Uint8 := 0; Valid : Boolean := False; Unreachable : Boolean := False; Pending : Boolean := False; Stale : Boolean := False; Free : Boolean := True; end record; type Arp_Entry_Table is array (1 .. ARP_MAX_ENTRIES) of aliased Arp_Entry; type Arp_Table is array (Arp_Index) of Arp_Entry_Access; type Arp_Refresh is array (1 .. ARP_MAX_ENTRIES) of Arp_Index; -- ARP database. -- To make it simple and avoid dynamic memory allocation, we maintain a maximum of 256 -- entries which correspond to a class C network. We only keep entries that are for our -- network. The lookup is in O(1). protected Database is procedure Timeout (Ifnet : in out Net.Interfaces.Ifnet_Type'Class; Refresh : out Arp_Refresh; Count : out Natural); procedure Resolve (Ifnet : in out Net.Interfaces.Ifnet_Type'Class; Ip : in Ip_Addr; Mac : out Ether_Addr; Packet : in out Net.Buffers.Buffer_Type; Result : out Arp_Status); procedure Update (Ip : in Ip_Addr; Mac : in Ether_Addr; List : out Net.Buffers.Buffer_List); private Entries : Arp_Entry_Table; Table : Arp_Table := (others => null); Queue_Size : Natural := 0; end Database; protected body Database is procedure Drop_Queue (Ifnet : in out Net.Interfaces.Ifnet_Type'Class; Rt : in Arp_Entry_Access) is pragma Unreferenced (Ifnet); begin if Rt.Queue_Size > 0 then Queue_Size := Queue_Size - Natural (Rt.Queue_Size); Rt.Queue_Size := 0; Net.Buffers.Release (Rt.Queue); end if; end Drop_Queue; procedure Timeout (Ifnet : in out Net.Interfaces.Ifnet_Type'Class; Refresh : out Arp_Refresh; Count : out Natural) is Now : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; begin Count := 0; for I in Entries'Range loop if not Entries (I).Free and then Entries (I).Expire < Now then if Entries (I).Valid then Entries (I).Valid := False; Entries (I).Stale := True; Entries (I).Expire := Now + Arp_Stale_Timeout; elsif Entries (I).Stale then Entries (I).Free := True; Table (Entries (I).Index) := null; elsif Entries (I).Retry > 5 then Entries (I).Unreachable := True; Entries (I).Expire := Now + Arp_Unreachable_Timeout; Entries (I).Retry := 0; Drop_Queue (Ifnet, Entries (I)'Access); else Count := Count + 1; Refresh (Count) := Entries (I).Index; Entries (I).Retry := Entries (I).Retry + 1; Entries (I).Expire := Now + Arp_Retry_Timeout; end if; end if; end loop; end Timeout; procedure Resolve (Ifnet : in out Net.Interfaces.Ifnet_Type'Class; Ip : in Ip_Addr; Mac : out Ether_Addr; Packet : in out Net.Buffers.Buffer_Type; Result : out Arp_Status) is Index : constant Arp_Index := Ip (Ip'Last); Rt : Arp_Entry_Access := Table (Index); Now : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; begin if Rt = null then for I in Entries'Range loop if Entries (I).Free then Rt := Entries (I)'Access; Rt.Free := False; Rt.Index := Index; Table (Index) := Rt; exit; end if; end loop; if Rt = null then Result := ARP_QUEUE_FULL; return; end if; end if; if Rt.Valid and then Now < Rt.Expire then Mac := Rt.Ether; Result := ARP_FOUND; elsif Rt.Unreachable and then Now < Rt.Expire then Result := ARP_UNREACHABLE; -- Send the first ARP request for the target IP resolution. elsif not Rt.Pending then Rt.Pending := True; Rt.Retry := 1; Rt.Stale := False; Rt.Expire := Now + Arp_Retry_Timeout; Result := ARP_NEEDED; elsif Rt.Expire < Now then if Rt.Retry > ARP_MAX_RETRY then Rt.Unreachable := True; Rt.Expire := Now + Arp_Unreachable_Timeout; Rt.Pending := False; Result := ARP_UNREACHABLE; Drop_Queue (Ifnet, Rt); else Rt.Retry := Rt.Retry + 1; Rt.Expire := Now + Arp_Retry_Timeout; Result := ARP_NEEDED; end if; else Result := ARP_PENDING; end if; -- Queue the packet unless the queue is full. if (Result = ARP_PENDING or Result = ARP_NEEDED) and then not Packet.Is_Null then if Queue_Size < QUEUE_LIMIT and Rt.Queue_Size < QUEUE_ENTRY_LIMIT then Queue_Size := Queue_Size + 1; Net.Buffers.Insert (Rt.Queue, Packet); Rt.Queue_Size := Rt.Queue_Size + 1; else Result := ARP_QUEUE_FULL; end if; end if; end Resolve; procedure Update (Ip : in Ip_Addr; Mac : in Ether_Addr; List : out Net.Buffers.Buffer_List) is Rt : constant Arp_Entry_Access := Table (Ip (Ip'Last)); begin -- We may receive a ARP response without having a valid arp entry in our table. -- This could happen when packets are forged (ARP poisoning) or when we dropped -- the arp entry before we received any ARP response. if Rt /= null then Rt.Ether := Mac; Rt.Valid := True; Rt.Unreachable := False; Rt.Pending := False; Rt.Stale := False; Rt.Expire := Ada.Real_Time.Clock + Arp_Entry_Timeout; -- If we have some packets waiting for the ARP resolution, return the packet list. if Rt.Queue_Size > 0 then Net.Buffers.Transfer (List, Rt.Queue); Queue_Size := Queue_Size - Natural (Rt.Queue_Size); Rt.Queue_Size := 0; end if; end if; end Update; end Database; -- ------------------------------ -- Proceed to the ARP database timeouts, cleaning entries and re-sending pending -- ARP requests. The procedure should be called once every second. -- ------------------------------ procedure Timeout (Ifnet : in out Net.Interfaces.Ifnet_Type'Class) is Refresh : Arp_Refresh; Count : Natural; Ip : Net.Ip_Addr; begin Database.Timeout (Ifnet, Refresh, Count); for I in 1 .. Count loop Ip := Ifnet.Ip; Ip (Ip'Last) := Refresh (I); Request (Ifnet, Ifnet.Ip, Ip, Ifnet.Mac); end loop; end Timeout; -- ------------------------------ -- Resolve the target IP address to obtain the associated Ethernet address -- from the ARP table. The Status indicates whether the IP address is -- found, or a pending ARP resolution is in progress or it was unreachable. -- ------------------------------ procedure Resolve (Ifnet : in out Net.Interfaces.Ifnet_Type'Class; Target_Ip : in Ip_Addr; Mac : out Ether_Addr; Packet : in out Net.Buffers.Buffer_Type; Status : out Arp_Status) is begin Database.Resolve (Ifnet, Target_Ip, Mac, Packet, Status); if Status = ARP_NEEDED then Request (Ifnet, Ifnet.Ip, Target_Ip, Ifnet.Mac); end if; end Resolve; -- ------------------------------ -- Update the arp table with the IP address and the associated Ethernet address. -- ------------------------------ procedure Update (Ifnet : in out Net.Interfaces.Ifnet_Type'Class; Target_Ip : in Ip_Addr; Mac : in Ether_Addr) is Waiting : Net.Buffers.Buffer_List; Ether : Net.Headers.Ether_Header_Access; Packet : Net.Buffers.Buffer_Type; begin Database.Update (Target_Ip, Mac, Waiting); while not Net.Buffers.Is_Empty (Waiting) loop Net.Buffers.Peek (Waiting, Packet); Ether := Packet.Ethernet; Ether.Ether_Dhost := Mac; Ifnet.Send (Packet); end loop; end Update; procedure Request (Ifnet : in out Net.Interfaces.Ifnet_Type'Class; Source_Ip : in Ip_Addr; Target_Ip : in Ip_Addr; Mac : in Ether_Addr) is Buf : Net.Buffers.Buffer_Type; Req : Net.Headers.Arp_Packet_Access; begin Net.Buffers.Allocate (Buf); if Buf.Is_Null then return; end if; Req := Buf.Arp; Req.Ethernet.Ether_Dhost := Broadcast_Mac; Req.Ethernet.Ether_Shost := Mac; Req.Ethernet.Ether_Type := Net.Headers.To_Network (ETHERTYPE_ARP); Req.Arp.Ea_Hdr.Ar_Hdr := Net.Headers.To_Network (ARPOP_REQUEST); Req.Arp.Ea_Hdr.Ar_Pro := Net.Headers.To_Network (ETHERTYPE_IP); Req.Arp.Ea_Hdr.Ar_Hln := Mac'Length; Req.Arp.Ea_Hdr.Ar_Pln := Source_Ip'Length; Req.Arp.Ea_Hdr.Ar_Op := Net.Headers.To_Network (ARPOP_REQUEST); Req.Arp.Arp_Sha := Mac; Req.Arp.Arp_Spa := Source_Ip; Req.Arp.Arp_Tha := (others => 0); Req.Arp.Arp_Tpa := Target_Ip; Buf.Set_Length ((Req.all'Size) / 8); Ifnet.Send (Buf); end Request; procedure Receive (Ifnet : in out Net.Interfaces.Ifnet_Type'Class; Packet : in out Net.Buffers.Buffer_Type) is Req : constant Net.Headers.Arp_Packet_Access := Packet.Arp; begin -- Check for valid hardware length, protocol length, hardware type and protocol type. if Req.Arp.Ea_Hdr.Ar_Hln /= Ifnet.Mac'Length or Req.Arp.Ea_Hdr.Ar_Pln /= Ifnet.Ip'Length or Req.Arp.Ea_Hdr.Ar_Hdr /= Net.Headers.To_Network (ARPOP_REQUEST) or Req.Arp.Ea_Hdr.Ar_Pro /= Net.Headers.To_Network (ETHERTYPE_IP) then Ifnet.Rx_Stats.Ignored := Ifnet.Rx_Stats.Ignored + 1; return; end if; case Net.Headers.To_Host (Req.Arp.Ea_Hdr.Ar_Op) is when ARPOP_REQUEST => -- This ARP request is for our IP address. -- Send the corresponding ARP reply with our Ethernet address. if Req.Arp.Arp_Tpa = Ifnet.Ip then Req.Ethernet.Ether_Dhost := Req.Arp.Arp_Sha; Req.Ethernet.Ether_Shost := Ifnet.Mac; Req.Arp.Ea_Hdr.Ar_Op := Net.Headers.To_Network (ARPOP_REPLY); Req.Arp.Arp_Tpa := Req.Arp.Arp_Spa; Req.Arp.Arp_Tha := Req.Arp.Arp_Sha; Req.Arp.Arp_Sha := Ifnet.Mac; Req.Arp.Arp_Spa := Ifnet.Ip; Ifnet.Send (Packet); end if; when ARPOP_REPLY => if Req.Arp.Arp_Tpa = Ifnet.Ip and Req.Arp.Arp_Tha = Ifnet.Mac then Update (Ifnet, Req.Arp.Arp_Spa, Req.Arp.Arp_Sha); end if; when others => Ifnet.Rx_Stats.Ignored := Ifnet.Rx_Stats.Ignored + 1; end case; end Receive; end Net.Protos.Arp;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- S Y S T E M . T E X T _ I O -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2013, 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 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. -- -- -- ------------------------------------------------------------------------------ with System; with Interfaces; package body System.Text_IO is use Interfaces; ESCI_CR1 : Unsigned_32; for ESCI_CR1'Address use 16#FFFB_0000# + 0; pragma Import (Ada, ESCI_CR1); pragma Volatile (ESCI_CR1); ESCI_CR2 : Unsigned_16; for ESCI_CR2'Address use 16#FFFB_0000# + 4; pragma Import (Ada, ESCI_CR2); pragma Volatile (ESCI_CR2); ESCI_DR : Unsigned_16; for ESCI_DR'Address use 16#FFFB_0000# + 6; pragma Import (Ada, ESCI_DR); pragma Volatile (ESCI_DR); ESCI_SR : Unsigned_32; for ESCI_SR'Address use 16#FFFB_0000# + 8; pragma Import (Ada, ESCI_SR); pragma Volatile (ESCI_SR); RDRF : constant := 16#2000_0000#; TDRE : constant := 16#8000_0000#; -- ESCI_SR bits SIU_PCR89 : Unsigned_16; for SIU_PCR89'Address use 16#C3F9_00F2#; pragma Import (Ada, SIU_PCR89); pragma Volatile (SIU_PCR89); SIU_PCR90 : Unsigned_16; for SIU_PCR90'Address use 16#C3F9_00F4#; pragma Import (Ada, SIU_PCR90); pragma Volatile (SIU_PCR90); --------- -- Get -- --------- function Get return Character is begin -- Clear rdrf (w1c bit) ESCI_SR := RDRF; -- Send the character return Character'Val (ESCI_DR and 16#FF#); end Get; ---------------- -- Initialize -- ---------------- procedure Initialize is begin -- Enable ESCI module ESCI_CR2 := 16#2000#; -- Enable Tx & Rx, 8n1, keep baud rate. -- Note that br = Fsys/(16 * baud) ESCI_CR1 := (ESCI_CR1 and 16#FFFF_0000#) or 16#000C#; -- Configure pads, enable txda and rxda SIU_PCR89 := 16#400#; SIU_PCR90 := 16#400#; Initialized := True; end Initialize; ----------------- -- Is_Rx_Ready -- ----------------- function Is_Rx_Ready return Boolean is begin return (ESCI_SR and RDRF) /= 0; end Is_Rx_Ready; ----------------- -- Is_Tx_Ready -- ----------------- function Is_Tx_Ready return Boolean is begin return (ESCI_SR and TDRE) /= 0; end Is_Tx_Ready; --------- -- Put -- --------- procedure Put (C : Character) is begin -- Clear tdre (w1c bit) ESCI_SR := TDRE; -- Send the character ESCI_DR := Character'Pos (C); end Put; ---------------------------- -- Use_Cr_Lf_For_New_Line -- ---------------------------- function Use_Cr_Lf_For_New_Line return Boolean is begin return True; end Use_Cr_Lf_For_New_Line; end System.Text_IO;
-- { dg-do compile } -- { dg-final { scan-assembler-not "elabs" } } package body OCONST5 is procedure Check (Arg : R; Bit : U1) is begin if Arg.Bit /= Bit or else Arg.Agg.A /= 3 or else Arg.Agg.B /= 7 then raise Program_Error; end if; end; end;
with Ada.Finalization; with kv.avm.Control; limited with kv.avm.Instances; package kv.avm.Warrants is type Warrant_Type is new Ada.Finalization.Controlled with private; overriding procedure Initialize (Self : in out Warrant_Type); overriding procedure Adjust (Self : in out Warrant_Type); overriding procedure Finalize (Self : in out Warrant_Type); procedure Initialize (Self : in out Warrant_Type; Machine : in kv.avm.Control.Control_Access; Instance : access kv.avm.Instances.Instance_Type); private type Warrant_Type is new Ada.Finalization.Controlled with record Machine : kv.avm.Control.Control_Access; Instance : access kv.avm.Instances.Instance_Type; end record; end kv.avm.Warrants;
------------------------------------------------------------------------------ -- Copyright (c) 2015-2017, 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. -- ------------------------------------------------------------------------------ with Ada.Characters.Latin_1; with Ada.Streams; with Ada.Strings.Fixed; with Ada.Strings.Unbounded; with Natools.S_Expressions; with Natools.Smaz_256; with Natools.Smaz_4096; with Natools.Smaz_64; with Natools.Smaz_Generic; with Natools.Smaz_Implementations.Base_4096; with Natools.Smaz_Original; with Natools.Smaz_Test_Base_64_Hash; package body Natools.Smaz_Tests is generic with package Smaz is new Natools.Smaz_Generic (<>); with function Image (S : Ada.Streams.Stream_Element_Array) return String; procedure Generic_Roundtrip_Test (Test : in out NT.Test; Dict : in Smaz.Dictionary; Decompressed : in String; Compressed : in Ada.Streams.Stream_Element_Array); function Decimal_Image (S : Ada.Streams.Stream_Element_Array) return String; function Dictionary_256_Without_VLV return Smaz_256.Dictionary; function Dictionary_4096 (Variable_Length_Verbatim : in Boolean) return Natools.Smaz_4096.Dictionary; function Dictionary_4096_Hash (S : in String) return Natural; function Direct_Image (S : Ada.Streams.Stream_Element_Array) return String renames Natools.S_Expressions.To_String; function To_SEA (S : String) return Ada.Streams.Stream_Element_Array renames Natools.S_Expressions.To_Atom; procedure Impure_Stream_4096 (Report : in out NT.Reporter'Class; Dictionary : in Smaz_4096.Dictionary); procedure Sample_Strings_4096 (Report : in out NT.Reporter'Class; Dictionary : in Smaz_4096.Dictionary); procedure Sample_Strings_VLV_4096 (Report : in out NT.Reporter'Class; Dictionary : in Smaz_4096.Dictionary); procedure Test_Validity_4096 (Report : in out NT.Reporter'Class; Dictionary : in Smaz_4096.Dictionary); ----------------------- -- Test Dictionaries -- ----------------------- LF : constant Character := Ada.Characters.Latin_1.LF; Dict_64 : constant Natools.Smaz_64.Dictionary := (Last_Code => 59, Values_Last => 119, Variable_Length_Verbatim => False, Max_Word_Length => 6, Offsets => (2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 18, 20, 22, 24, 25, 26, 28, 30, 31, 32, 36, 38, 40, 42, 44, 45, 47, 49, 51, 53, 56, 60, 63, 65, 68, 70, 72, 74, 76, 80, 82, 84, 88, 90, 92, 94, 98, 101, 102, 103, 105, 111, 112, 114, 115, 118), Values => " ee stainruos l dt enescm p" & Character'Val (16#C3#) & Character'Val (16#A9#) & "pd de lere ld" & "e" & LF & "on cqumede mentes aiquen teerou r sque , is m q" & "ue" & Character'Val (16#C3#) & Character'Val (16#A0#) & " v'tiweblogfanj." & LF & LF & "ch", Hash => Natools.Smaz_Test_Base_64_Hash.Hash'Access); Dict_64_V : constant Natools.Smaz_64.Dictionary := (Last_Code => 59, Values_Last => 119, Variable_Length_Verbatim => True, Max_Word_Length => 6, Offsets => (2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 18, 20, 22, 24, 25, 26, 28, 30, 31, 32, 36, 38, 40, 42, 44, 45, 47, 49, 51, 53, 56, 60, 63, 65, 68, 70, 72, 74, 76, 80, 82, 84, 88, 90, 92, 94, 98, 101, 102, 103, 105, 111, 112, 114, 115, 118), Values => " ee stainruos l dt enescm p" & Character'Val (16#C3#) & Character'Val (16#A9#) & "pd de lere ld" & "e" & LF & "on cqumede mentes aiquen teerou r sque , is m q" & "ue" & Character'Val (16#C3#) & Character'Val (16#A0#) & " v'tiweblogfanj." & LF & LF & "ch", Hash => Natools.Smaz_Test_Base_64_Hash.Hash'Access); ------------------------------ -- Local Helper Subprograms -- ------------------------------ function Decimal_Image (S : Ada.Streams.Stream_Element_Array) return String is use Ada.Strings.Unbounded; Result : Unbounded_String; begin for I in S'Range loop Append (Result, Ada.Streams.Stream_Element'Image (S (I))); end loop; return To_String (Result); end Decimal_Image; function Dictionary_256_Without_VLV return Smaz_256.Dictionary is begin return Dict : Smaz_256.Dictionary := Smaz_Original.Dictionary do Dict.Variable_Length_Verbatim := False; end return; end Dictionary_256_Without_VLV; function Dictionary_4096 (Variable_Length_Verbatim : in Boolean) return Natools.Smaz_4096.Dictionary is subtype Letter_Rank is Natural range 1 .. 26; function Lower (N : Letter_Rank) return Character is (Character'Val (Character'Pos ('a') - 1 + N)); function Upper (N : Letter_Rank) return Character is (Character'Val (Character'Pos ('A') - 1 + N)); subtype Digit_Rank is Natural range 0 .. 9; function Image (N : Digit_Rank) return Character is (Character'Val (Character'Pos ('0') + N)); subtype Alphanum is Character with Static_Predicate => Alphanum in '0' .. '9' | 'A' .. 'Z' | 'a' .. 'z'; Current_Index : Smaz_Implementations.Base_4096.Base_4096_Digit := 0; Current_Offset : Positive := 1; use type Smaz_Implementations.Base_4096.Base_4096_Digit; procedure Push_Value (Dict : in out Natools.Smaz_4096.Dictionary; Value : in String); procedure Push_Value (Dict : in out Natools.Smaz_4096.Dictionary; Value : in String) is begin if Current_Index > 0 then Dict.Offsets (Current_Index) := Current_Offset; end if; Dict.Values (Current_Offset .. Current_Offset + Value'Length - 1) := Value; Current_Index := Current_Index + 1; Current_Offset := Current_Offset + Value'Length; end Push_Value; begin return Dict : Natools.Smaz_4096.Dictionary := (Last_Code => 4059, Values_Last => 9120, Variable_Length_Verbatim => Variable_Length_Verbatim, Max_Word_Length => 3, Offsets => <>, Values => <>, Hash => Dictionary_4096_Hash'Access) do -- 0 .. 61: space + letter for L in Alphanum loop Push_Value (Dict, (1 => ' ', 2 => L)); end loop; -- 62 .. 123: letter + space for L in Alphanum loop Push_Value (Dict, (1 => L, 2 => ' ')); end loop; -- 124 .. 185: letter + comma for L in Alphanum loop Push_Value (Dict, (1 => L, 2 => ',')); end loop; -- 186 .. 247: letter + period for L in Alphanum loop Push_Value (Dict, (1 => L, 2 => '.')); end loop; -- 248 .. 255: double punctuation for L in Character range ' ' .. ''' loop Push_Value (Dict, (1 => L, 2 => L)); end loop; -- 256 .. 355: two-digit numbers for U in Digit_Rank loop for V in Digit_Rank loop Push_Value (Dict, (1 => Image (U), 2 => Image (V))); end loop; end loop; -- 356 .. 1355: three-digit numbers for U in Digit_Rank loop for V in Digit_Rank loop for W in Digit_Rank loop Push_Value (Dict, (1 => Image (U), 2 => Image (V), 3 => Image (W))); end loop; end loop; end loop; -- 1356 .. 2031: two lower-case letters for M in Letter_Rank loop for N in Letter_Rank loop Push_Value (Dict, (1 => Lower (M), 2 => Lower (N))); end loop; end loop; -- 2032 .. 2707: lower-case then upper-case letter for M in Letter_Rank loop for N in Letter_Rank loop Push_Value (Dict, (1 => Lower (M), 2 => Upper (N))); end loop; end loop; -- 2708 .. 3383: upper-case then lower-case letter for M in Letter_Rank loop for N in Letter_Rank loop Push_Value (Dict, (1 => Upper (M), 2 => Lower (N))); end loop; end loop; -- 3384 .. 4059: two upper-case letters for M in Letter_Rank loop for N in Letter_Rank loop Push_Value (Dict, (1 => Upper (M), 2 => Upper (N))); end loop; end loop; pragma Assert (Current_Index = Dict.Last_Code + 1); pragma Assert (Current_Offset = Dict.Values_Last + 1); end return; end Dictionary_4096; function Dictionary_4096_Hash (S : in String) return Natural is function Rank (C : Character) return Natural is (case C is when '0' .. '9' => Character'Pos (C) - Character'Pos ('0'), when 'a' .. 'z' => Character'Pos (C) - Character'Pos ('a'), when 'A' .. 'Z' => Character'Pos (C) - Character'Pos ('A'), when others => raise Program_Error); begin case S'Length is when 2 => declare U : constant Character := S (S'First); V : constant Character := S (S'Last); begin if U = ' ' and then V in '0' .. '9' then return Rank (V); elsif U = ' ' and then V in 'A' .. 'Z' then return 10 + Rank (V); elsif U = ' ' and then V in 'a' .. 'z' then return 36 + Rank (V); elsif U in '0' .. '9' and then V in ' ' | ',' | '.' then return Rank (U) + (case V is when ' ' => 62, when ',' => 124, when '.' => 186, when others => raise Program_Error); elsif U in 'A' .. 'Z' and then V in ' ' | ',' | '.' then return Rank (U) + 10 + (case V is when ' ' => 62, when ',' => 124, when '.' => 186, when others => raise Program_Error); elsif U in 'a' .. 'z' and then V in ' ' | ',' | '.' then return Rank (U) + 36 + (case V is when ' ' => 62, when ',' => 124, when '.' => 186, when others => raise Program_Error); elsif U in ' ' .. ''' and then U = V then return 248 + Character'Pos (U) - Character'Pos (' '); elsif U in '0' .. '9' and then V in '0' .. '9' then return 256 + Rank (U) * 10 + Rank (V); elsif U in 'a' .. 'z' and then V in 'a' .. 'z' then return 1356 + Rank (U) * 26 + Rank (V); elsif U in 'a' .. 'z' and then V in 'A' .. 'Z' then return 2032 + Rank (U) * 26 + Rank (V); elsif U in 'A' .. 'Z' and then V in 'a' .. 'z' then return 2708 + Rank (U) * 26 + Rank (V); elsif U in 'A' .. 'Z' and then V in 'A' .. 'Z' then return 3384 + Rank (U) * 26 + Rank (V); else return 4096; end if; end; when 3 => declare U : constant Character := S (S'First); V : constant Character := S (S'First + 1); W : constant Character := S (S'First + 2); begin if U in '0' .. '9' and then V in '0' .. '9' and then W in '0' .. '9' then return 356 + Rank (U) * 100 + Rank (V) * 10 + Rank (W); else return 4096; end if; end; when others => return 4096; end case; end Dictionary_4096_Hash; procedure Generic_Roundtrip_Test (Test : in out NT.Test; Dict : in Smaz.Dictionary; Decompressed : in String; Compressed : in Ada.Streams.Stream_Element_Array) is use type Ada.Streams.Stream_Element_Array; use type Ada.Streams.Stream_Element_Offset; begin declare First_OK : Boolean := False; begin declare Buffer : constant Ada.Streams.Stream_Element_Array := Smaz.Compress (Dict, Decompressed); begin First_OK := True; if Buffer /= Compressed then Test.Fail ("Bad compression of """ & Decompressed & '"'); Test.Info ("Found: " & Image (Buffer)); Test.Info ("Expected:" & Image (Compressed)); declare Round : constant String := Smaz.Decompress (Dict, Buffer); begin if Round /= Decompressed then Test.Info ("Roundtrip failed, got: """ & Round & '"'); else Test.Info ("Roundtrip OK"); end if; end; end if; end; exception when Error : others => if not First_OK then Test.Info ("During compression of """ & Decompressed & '"'); end if; Test.Report_Exception (Error, NT.Fail); end; declare First_OK : Boolean := False; begin declare Buffer : constant String := Smaz.Decompress (Dict, Compressed); begin First_OK := True; if Buffer /= Decompressed then Test.Fail ("Bad decompression of " & Image (Compressed)); Test.Info ("Found: """ & Buffer & '"'); Test.Info ("Expected:""" & Decompressed & '"'); declare Round : constant Ada.Streams.Stream_Element_Array := Smaz.Compress (Dict, Buffer); begin if Round /= Compressed then Test.Info ("Roundtrip failed, got: " & Image (Round)); else Test.Info ("Roundtrip OK"); end if; end; end if; end; exception when Error : others => if not First_OK then Test.Info ("During decompression of " & Image (Compressed)); end if; Test.Report_Exception (Error, NT.Fail); end; end Generic_Roundtrip_Test; procedure Roundtrip_Test is new Generic_Roundtrip_Test (Natools.Smaz_256, Decimal_Image); procedure Roundtrip_Test is new Generic_Roundtrip_Test (Natools.Smaz_4096, Direct_Image); procedure Roundtrip_Test is new Generic_Roundtrip_Test (Natools.Smaz_64, Direct_Image); ------------------------- -- Complete Test Suite -- ------------------------- procedure All_Tests (Report : in out NT.Reporter'Class) is begin Report.Section ("Base 256"); All_Tests_256 (Report); Report.End_Section; Report.Section ("Base 64"); All_Tests_64 (Report); Report.End_Section; Report.Section ("Base 4096"); All_Tests_4096 (Report); Report.End_Section; end All_Tests; ------------------------------ -- Test Suite for Each Base -- ------------------------------ procedure All_Tests_256 (Report : in out NT.Reporter'Class) is begin Test_Validity_256 (Report); Sample_Strings_256 (Report); Sample_Strings_VLV_256 (Report); end All_Tests_256; procedure All_Tests_4096 (Report : in out NT.Reporter'Class) is begin declare Dict : constant Smaz_4096.Dictionary := Dictionary_4096 (False); begin Report.Section ("Without variable-length verbatim"); Test_Validity_4096 (Report, Dict); Sample_Strings_4096 (Report, Dict); Impure_Stream_4096 (Report, Dict); Report.End_Section; end; declare Dict : constant Smaz_4096.Dictionary := Dictionary_4096 (True); begin Report.Section ("With variable-length verbatim"); Test_Validity_4096 (Report, Dict); Sample_Strings_VLV_4096 (Report, Dict); Report.End_Section; end; end All_Tests_4096; procedure All_Tests_64 (Report : in out NT.Reporter'Class) is begin Test_Validity_64 (Report); Sample_Strings_64 (Report); Sample_Strings_VLV_64 (Report); Impure_Stream_64 (Report); end All_Tests_64; ------------------------------- -- Individual Base-256 Tests -- ------------------------------- procedure Sample_Strings_256 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Roundtrip on sample strings without VLV"); Dict : constant Smaz_256.Dictionary := Dictionary_256_Without_VLV; begin Roundtrip_Test (Test, Dict, "This is a small string", (255, 84, 76, 56, 172, 62, 173, 152, 62, 195, 70)); Roundtrip_Test (Test, Dict, "foobar", (220, 6, 90, 79)); Roundtrip_Test (Test, Dict, "the end", (1, 171, 61)); Roundtrip_Test (Test, Dict, "not-a-g00d-Exampl333", (132, 204, 4, 204, 59, 254, 48, 48, 24, 204, 255, 69, 250, 4, 45, 60, 22, 254, 51, 51, 255, 51)); Roundtrip_Test (Test, Dict, "Smaz is a simple compression library", (255, 83, 173, 219, 56, 172, 62, 226, 60, 87, 161, 45, 60, 33, 166, 107, 205, 8, 90, 130, 12, 83)); Roundtrip_Test (Test, Dict, "Nothing is more difficult, and therefore more precious, " & "than to be able to decide", (255, 78, 223, 102, 99, 116, 45, 42, 11, 129, 44, 44, 131, 38, 22, 3, 148, 63, 210, 68, 11, 45, 42, 11, 60, 33, 28, 144, 164, 36, 203, 143, 96, 92, 25, 90, 87, 82, 165, 215, 237, 2)); Roundtrip_Test (Test, Dict, "this is an example of what works very well with smaz", (155, 56, 172, 41, 2, 250, 4, 45, 60, 87, 32, 159, 135, 65, 42, 255, 107, 23, 231, 71, 145, 152, 243, 227, 10, 173, 219)); Roundtrip_Test (Test, Dict, "1000 numbers 2000 will 10 20 30 compress very little", (254, 49, 48, 254, 48, 48, 236, 38, 45, 92, 221, 0, 254, 50, 48, 254, 48, 48, 243, 152, 0, 254, 49, 48, 0, 254, 50, 48, 0, 254, 51, 48, 161, 45, 60, 33, 166, 0, 231, 71, 151, 3, 3, 87)); Roundtrip_Test (Test, Dict, ": : : :", (254, 58, 32, 254, 58, 32, 254, 58, 32, 255, 58)); exception when Error : others => Test.Report_Exception (Error); end Sample_Strings_256; procedure Sample_Strings_VLV_256 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Roundtrip on sample strings with variable-length verbatim"); begin Roundtrip_Test (Test, Smaz_Original.Dictionary, "This is a small string", (254, 84, 76, 56, 172, 62, 173, 152, 62, 195, 70)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "foobar", (220, 6, 90, 79)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "the end", (1, 171, 61)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "not-a-g00d-Exampl333", (132, 204, 4, 204, 59, 255, 12, 48, 48, 100, 45, 69, 120, 97, 109, 112, 108, 51, 51, 51)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "Smaz is a simple compression library", (254, 83, 173, 219, 56, 172, 62, 226, 60, 87, 161, 45, 60, 33, 166, 107, 205, 8, 90, 130, 12, 83)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "Nothing is more difficult, and therefore more precious, " & "than to be able to decide", (254, 78, 223, 102, 99, 116, 45, 42, 11, 129, 44, 44, 131, 38, 22, 3, 148, 63, 210, 68, 11, 45, 42, 11, 60, 33, 28, 144, 164, 36, 203, 143, 96, 92, 25, 90, 87, 82, 165, 215, 237, 2)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "this is an example of what works very well with smaz", (155, 56, 172, 41, 2, 250, 4, 45, 60, 87, 32, 159, 135, 65, 42, 254, 107, 23, 231, 71, 145, 152, 243, 227, 10, 173, 219)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "1000 numbers 2000 will 10 20 30 compress very little", (255, 3, 49, 48, 48, 48, 236, 38, 45, 92, 221, 0, 255, 3, 50, 48, 48, 48, 243, 152, 0, 255, 7, 49, 48, 32, 50, 48, 32, 51, 48, 161, 45, 60, 33, 166, 0, 231, 71, 151, 3, 3, 87)); Roundtrip_Test (Test, Smaz_Original.Dictionary, ": : : :", (255, 6, 58, 32, 58, 32, 58, 32, 58)); Roundtrip_Test (Test, Smaz_Original.Dictionary, (1 .. 300 => ':'), (1 .. 2 => 255, 3 .. 258 => 58, 259 => 255, 260 => 43, 261 .. 304 => 58)); exception when Error : others => Test.Report_Exception (Error); end Sample_Strings_VLV_256; procedure Test_Validity_256 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Test dictionary validity"); begin if not Natools.Smaz_256.Is_Valid (Smaz_Original.Dictionary) then Test.Fail; end if; exception when Error : others => Test.Report_Exception (Error); end Test_Validity_256; -------------------------------- -- Individual Base-4096 Tests -- -------------------------------- procedure Impure_Stream_4096 (Report : in out NT.Reporter'Class; Dictionary : in Smaz_4096.Dictionary) is Test : NT.Test := Report.Item ("Input stream with non-base-64 symbols"); begin declare CRLF : constant String := (Character'Val (13), Character'Val (10)); Input : constant Ada.Streams.Stream_Element_Array := To_SEA ("0vBdpYoBuYwAJbmB iWTXeYfdzCkAha3A" & CRLF & "GYKccXKcwAJbmBjb 2WqYmd//sA3ACYvB" & CRLF & "IdlAmBNVuZ3AwBeW IWeW" & CRLF); Output : constant String := Smaz_4096.Decompress (Dictionary, Input); Expected : constant String := "Nothing is more difficult, and therefore more precious, " & "than to be able to decide"; begin if Output /= Expected then Test.Fail ("Bad decompression"); Test.Info ("Found: """ & Output & '"'); Test.Info ("Expected:""" & Expected & '"'); end if; end; exception when Error : others => Test.Report_Exception (Error); end Impure_Stream_4096; procedure Impure_Stream_4096 (Report : in out NT.Reporter'Class) is begin Impure_Stream_4096 (Report, Dictionary_4096 (False)); end Impure_Stream_4096; procedure Sample_Strings_4096 (Report : in out NT.Reporter'Class; Dictionary : in Smaz_4096.Dictionary) is Test : NT.Test := Report.Item ("Roundtrip on sample strings"); begin Roundtrip_Test (Test, Dictionary, "This is a small string", To_SEA ("JyuYsA0BiBscXVtBzcOcka")); -- This is a small string Roundtrip_Test (Test, Dictionary, "foobar", To_SEA ("cX5adV")); -- foobar Roundtrip_Test (Test, Dictionary, "the end", To_SEA ("BdmBBX//kB")); -- the en<d > Roundtrip_Test (Test, Dictionary, "not-a-g00d-Exampl333", To_SEA ("sa3/01SYtcGMwQWLTsYVdbxK")); -- no< t-a -g0 0d->Exampl333 -- t-a 001011_10 1011_0100 10_000110 -- -g0 101101_00 1110_0110 00_001100 -- 0d- 000011_00 0010_0110 10_110100 Roundtrip_Test (Test, Dictionary, "Smaz is a simple compression library", To_SEA ("0xlVsA0BiBocTauZmAEbjbGXocFbvAdYGcec")); -- Smaz is a simple compression library Roundtrip_Test (Test, Dictionary, "Nothing is more difficult, and therefore more precious, " & "than to be able to decide", To_SEA ("0vBdpYoBuYwAJbmBiWTXeYfdzCkAha3AGYKccXKcwAJbmBjb2WqYmd//sA" -- Nothing is more difficult, and therefore more precious< ,> & "3ACYvBIdlAmBNVuZ3AwBeWIWeW")); -- than to be able to decide Roundtrip_Test (Test, Dictionary, "this is an example of what works very well with smaz", To_SEA ("BduYsA0BZVoAieTauZyAnBPefV6AJbiZ5AFX6BMe1Z6AvYpBsclV")); -- this is an example of what works very well with smaz Roundtrip_Test (Test, Dictionary, "1000 numbers 2000 will 10 20 30 compress very little", To_SEA ("IH+AyaFaFX0BsI+AQe1ZBA+AUEDA+AOWTaKcyc5AFX6ByZNduZ")); -- 1000 numbers 2*0 will 10 20 30 compress very little", Roundtrip_Test (Test, Dictionary, ": : : :", To_SEA ("5/6AiOgoDI6A")); -- :_: 010111_00 0000_0100 01_011100 -- _:_ 000001_00 0101_1100 00_000100 -- : 010111_00 0000 Roundtrip_Test (Test, Dictionary, (1 .. 80 => ':'), To_SEA (Ada.Strings.Fixed."*" (2, "c/" & Ada.Strings.Fixed."*" (12, "6ojO")) & "4/6ojO6ojO6oD")); -- ::: 010111_00 0101_1100 01_011100 exception when Error : others => Test.Report_Exception (Error); end Sample_Strings_4096; procedure Sample_Strings_4096 (Report : in out NT.Reporter'Class) is begin Sample_Strings_4096 (Report, Dictionary_4096 (False)); end Sample_Strings_4096; procedure Sample_Strings_VLV_4096 (Report : in out NT.Reporter'Class; Dictionary : in Smaz_4096.Dictionary) is Test : NT.Test := Report.Item ("Roundtrip on sample strings"); begin Roundtrip_Test (Test, Dictionary, "This is a small string", To_SEA ("JyuYsA0BiBscXVtBzcOcka")); -- This is a small string Roundtrip_Test (Test, Dictionary, "foobar", To_SEA ("cX5adV")); -- foobar Roundtrip_Test (Test, Dictionary, "the end", To_SEA ("BdmBBX+/kB")); -- the en<d > Roundtrip_Test (Test, Dictionary, "not-a-g00d-Exampl333", To_SEA ("sa2/01SYtcGMwQWLTsYVdbxK")); -- no< t-a -g0 0d->Exampl333 -- t-a 001011_10 1011_0100 10_000110 -- -g0 101101_00 1110_0110 00_001100 -- 0d- 000011_00 0010_0110 10_110100 Roundtrip_Test (Test, Dictionary, "Smaz is a simple compression library", To_SEA ("0xlVsA0BiBocTauZmAEbjbGXocFbvAdYGcec")); -- Smaz is a simple compression library Roundtrip_Test (Test, Dictionary, "Nothing is more difficult, and therefore more precious, " & "than to be able to decide", To_SEA ("0vBdpYoBuYwAJbmBiWTXeYfdzCkAha3AGYKccXKcwAJbmBjb2WqYmd+/sA" -- Nothing is more difficult, and therefore more precious< ,> & "3ACYvBIdlAmBNVuZ3AwBeWIWeW")); -- than to be able to decide Roundtrip_Test (Test, Dictionary, "this is an example of what works very well with smaz", To_SEA ("BduYsA0BZVoAieTauZyAnBPefV6AJbiZ5AFX6BMe1Z6AvYpBsclV")); -- this is an example of what works very well with smaz Roundtrip_Test (Test, Dictionary, "1000 numbers 2000 will 10 20 30 compress very little", To_SEA ("IH+AyaFaFX0BsI+AQe1ZBA+AUEDA+AOWTaKcyc5AFX6ByZNduZ")); -- 1000 numbers 2*0 will 10 20 30 compress very little", Roundtrip_Test (Test, Dictionary, ": : : :", To_SEA ("4/6AiOgoDI6A")); -- :_: 010111_00 0000_0100 01_011100 -- _:_ 000001_00 0101_1100 00_000100 -- : 010111_00 0000 Roundtrip_Test (Test, Dictionary, (1 .. 4096 + 36 => ':'), To_SEA ("////" & Ada.Strings.Fixed."*" (1377, "6ojO") & "+/6A")); -- ::: 010111_00 0101_1100 01_011100 exception when Error : others => Test.Report_Exception (Error); end Sample_Strings_VLV_4096; procedure Sample_Strings_VLV_4096 (Report : in out NT.Reporter'Class) is begin Sample_Strings_VLV_4096 (Report, Dictionary_4096 (True)); end Sample_Strings_VLV_4096; procedure Test_Validity_4096 (Report : in out NT.Reporter'Class; Dictionary : in Smaz_4096.Dictionary) is Test : NT.Test := Report.Item ("Test dictionary validity"); begin if not Smaz_4096.Is_Valid (Dictionary) then Test.Fail; end if; exception when Error : others => Test.Report_Exception (Error); end Test_Validity_4096; procedure Test_Validity_4096 (Report : in out NT.Reporter'Class) is begin Test_Validity_4096 (Report, Dictionary_4096 (False)); Test_Validity_4096 (Report, Dictionary_4096 (True)); end Test_Validity_4096; ------------------------------ -- Individual Base-64 Tests -- ------------------------------ procedure Impure_Stream_64 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Input stream with non-base-64 symbols"); begin declare CRLF : constant String := (Character'Val (13), Character'Val (10)); Input : constant Ada.Streams.Stream_Element_Array := To_SEA ("090kTgIW enLK3NFE FAEKs/Ao" & CRLF & "92dAFAzo +iBF1Sep HOvDJB0="); Output : constant String := Smaz_64.Decompress (Dict_64, Input); Expected : constant String := "'49 bytes of data to show a verbatim count issue'"; begin if Output /= Expected then Test.Fail ("Bad decompression"); Test.Info ("Found: """ & Output & '"'); Test.Info ("Expected:""" & Expected & '"'); end if; end; exception when Error : others => Test.Report_Exception (Error); end Impure_Stream_64; procedure Sample_Strings_64 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Roundtrip on sample strings"); begin Roundtrip_Test (Test, Dict_64, "Simple Test", To_SEA ("+TBGSVYA+UBQE")); -- <S>imp* <T>*t Roundtrip_Test (Test, Dict_64, "SiT", To_SEA ("/ATlGV")); -- <SiT> smaller than <S>i<T> ("+TBG+UB") Roundtrip_Test (Test, Dict_64, "sIMple TEST_WITH_14_B", To_SEA ("D9J1EVYA8UVETR1XXlEVI9VM08lQ")); -- s<IM>p* <TE ST_ WIT H_1 4_B> -- TE 001010_10 1010_0010 00 -- ST_ 110010_10 0010_1010 11_111010 -- WIT 111010_10 1001_0010 00_101010 -- H_1 000100_10 1111_1010 10_001100 -- 4_B 001011_00 1111_1010 01_000010 Roundtrip_Test (Test, Dict_64, "'7B_Verbatim'", To_SEA ("0+3IC9lVlJnYF1S0")); -- '<7B_Verb >a*m' -- 7 111011_00 0100 -- B_V 010000_10 1111_1010 01_101010 -- erb 101001_10 0100_1110 01_000110 -- "erb" could have been encoded separately as "o+iB", which has -- the same length, but the tie is broken in favor of the longer -- verbatim fragment to help with corner cases. Roundtrip_Test (Test, Dict_64, "'49 bytes of data to show a verbatim count issue'", To_SEA ("090kTgIWenLK3NFEFAEKs/Ao92dAFAzo+iBF1SepHOvDJB0")); -- '<49 by >tsof_ata_to_< how>_a_ve<b>atm_ontisue' -- e_ d s r i cu _s -- 49 001011_00 1001_1100 10 -- by 000001_00 0100_0110 10_011110 -- how 000101_10 1111_0110 11_101110 -- b 010001_10 0000 Roundtrip_Test (Test, Dict_64, Character'Val (16#C3#) & Character'Val (16#A9#) & 'v' & Character'Val (16#C3#) & Character'Val (16#A8#) & "nement", To_SEA ("Uz9DjKHBi")); -- év<è >nement -- è 110000_11 0001_0101 00 Roundtrip_Test (Test, Dict_64, "12345345345345345345345345", To_SEA ("8xIzzQTNzQTNzQTNzQTNzQTNzQTNzQTN/AzQTN")); -- Smallest 3n+2 that requires multiple verbatim blocks -- 12 100011_00 0100_1100 nn -- 345 110011_00 0010_1100 10_101100 exception when Error : others => Test.Report_Exception (Error); end Sample_Strings_64; procedure Sample_Strings_VLV_64 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Roundtrip on sample strings with variable-length verbatim"); begin Roundtrip_Test (Test, Dict_64_V, "Simple Test", To_SEA ("+TBGSVYA+UBQE")); -- <S>imp* <T>*t Roundtrip_Test (Test, Dict_64_V, "SiT", To_SEA ("8TlGV")); -- <SiT> smaller than <S>i<T> ("+TBG+UB") Roundtrip_Test (Test, Dict_64_V, "sIMple TEST_WITH_14_B", To_SEA ("D9J1EVYA/KUVETR1XXlEVI9VM08lQ")); -- s<IM>p* < TE ST_ WIT H_1 4_B> -- TE 001010_10 1010_0010 00 -- ST_ 110010_10 0010_1010 11_111010 -- WIT 111010_10 1001_0010 00_101010 -- H_1 000100_10 1111_1010 10_001100 -- 4_B 001011_00 1111_1010 01_000010 Roundtrip_Test (Test, Dict_64_V, "'7B_Verbatim'", To_SEA ("0/D3AC9lVlJnYF1S0")); -- '< 7B_Verb >a*m' -- 7 111011_00 0000 -- B_V 010000_10 1111_1010 01_101010 -- erb 101001_10 0100_1110 01_000110 exception when Error : others => Test.Report_Exception (Error); end Sample_Strings_VLV_64; procedure Test_Validity_64 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Test dictionary validity"); begin if not Natools.Smaz_64.Is_Valid (Dict_64) then Test.Fail; end if; if not Natools.Smaz_64.Is_Valid (Dict_64_V) then Test.Fail; end if; exception when Error : others => Test.Report_Exception (Error); end Test_Validity_64; end Natools.Smaz_Tests;
----------------------------------------------------------------------- -- util-serialize-io-json -- JSON Serialization Driver -- Copyright (C) 2010, 2011, 2012, 2016, 2017, 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 Interfaces; with Ada.Characters.Latin_1; with Ada.Characters.Wide_Wide_Latin_1; with Ada.IO_Exceptions; with Util.Strings; with Util.Streams; with Util.Streams.Buffered; with Util.Streams.Texts.TR; with Util.Streams.Texts.WTR; with Util.Dates.ISO8601; with Util.Beans.Objects.Maps; with Util.Beans.Objects.Readers; package body Util.Serialize.IO.JSON is use Ada.Strings.Unbounded; -- ----------------------- -- Set the target output stream. -- ----------------------- procedure Initialize (Stream : in out Output_Stream; Output : in Util.Streams.Texts.Print_Stream_Access) is begin Stream.Stream := Output; end Initialize; -- ----------------------- -- Flush the buffer (if any) to the sink. -- ----------------------- overriding procedure Flush (Stream : in out Output_Stream) is begin Stream.Stream.Flush; end Flush; -- ----------------------- -- Close the sink. -- ----------------------- overriding procedure Close (Stream : in out Output_Stream) is begin Stream.Stream.Close; end Close; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- overriding procedure Write (Stream : in out Output_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is begin Stream.Stream.Write (Buffer); end Write; -- ----------------------- -- Write a wide character on the stream doing some conversion if necessary. -- The default implementation translates the wide character to a UTF-8 sequence. -- ----------------------- procedure Write_Wide (Stream : in out Output_Stream; Item : in Wide_Wide_Character) is begin Stream.Stream.Write_Wide (Item); end Write_Wide; -- ----------------------- -- Start a JSON document. This operation writes the initial JSON marker ('{'). -- ----------------------- procedure Start_Document (Stream : in out Output_Stream) is Current : access Node_Info; begin Node_Info_Stack.Push (Stream.Stack); Current := Node_Info_Stack.Current (Stream.Stack); Current.Is_Root := True; end Start_Document; -- ----------------------- -- Finish a JSON document by writing the final JSON marker ('}'). -- ----------------------- procedure End_Document (Stream : in out Output_Stream) is Current : constant access Node_Info := Node_Info_Stack.Current (Stream.Stack); begin if Current /= null and then Current.Has_Fields and then not Current.Is_Array then Stream.Write ('}'); end if; Node_Info_Stack.Pop (Stream.Stack); end End_Document; -- ----------------------- -- Write the string as a quoted JSON string -- ----------------------- procedure Write_String (Stream : in out Output_Stream; Value : in String) is begin Stream.Write ('"'); for I in Value'Range loop declare C : constant Character := Value (I); begin if C = '"' then Stream.Write ("\"""); elsif C = '\' then Stream.Write ("\\"); elsif Character'Pos (C) >= 16#20# then Stream.Write (C); else case C is when Ada.Characters.Latin_1.BS => Stream.Write ("\b"); when Ada.Characters.Latin_1.VT => Stream.Write ("\f"); when Ada.Characters.Latin_1.LF => Stream.Write ("\n"); when Ada.Characters.Latin_1.CR => Stream.Write ("\r"); when Ada.Characters.Latin_1.HT => Stream.Write ("\t"); when others => Util.Streams.Texts.TR.To_Hex (Stream.Stream.all, C); end case; end if; end; end loop; Stream.Write ('"'); end Write_String; -- ----------------------- -- Write the value as a JSON string. Special characters are escaped using the JSON -- escape rules. -- ----------------------- procedure Write_Wide_String (Stream : in out Output_Stream; Value : in Wide_Wide_String) is begin Stream.Write ('"'); for I in Value'Range loop declare C : constant Wide_Wide_Character := Value (I); begin if C = '"' then Stream.Write ("\"""); elsif C = '\' then Stream.Write ("\\"); elsif Wide_Wide_Character'Pos (C) >= 16#20# then Util.Streams.Texts.Write_Char (Stream.Stream.all, C); else case C is when Ada.Characters.Wide_Wide_Latin_1.BS => Stream.Write ("\b"); when Ada.Characters.Wide_Wide_Latin_1.VT => Stream.Write ("\f"); when Ada.Characters.Wide_Wide_Latin_1.LF => Stream.Write ("\n"); when Ada.Characters.Wide_Wide_Latin_1.CR => Stream.Write ("\r"); when Ada.Characters.Wide_Wide_Latin_1.HT => Stream.Write ("\t"); when others => Util.Streams.Texts.WTR.To_Hex (Stream.Stream.all, C); end case; end if; end; end loop; Stream.Write ('"'); end Write_Wide_String; procedure Write_Field_Name (Stream : in out Output_Stream; Name : in String) is Current : constant access Node_Info := Node_Info_Stack.Current (Stream.Stack); begin if Current /= null then if Current.Has_Fields then Stream.Write (','); elsif Name'Length > 0 or else not Current.Is_Root then Current.Has_Fields := True; end if; end if; if Name'Length > 0 and then (Current = null or else not Current.Is_Array) then Stream.Write_String (Name); Stream.Write (':'); end if; end Write_Field_Name; -- ----------------------- -- Start writing an object identified by the given name -- ----------------------- procedure Start_Entity (Stream : in out Output_Stream; Name : in String) is Current : access Node_Info := Node_Info_Stack.Current (Stream.Stack); begin if Current /= null and then Current.Is_Root then if Name'Length > 0 then Stream.Write ('{'); Stream.Write_Field_Name (Name); Current.Has_Fields := True; end if; else Stream.Write_Field_Name (Name); end if; Node_Info_Stack.Push (Stream.Stack); Current := Node_Info_Stack.Current (Stream.Stack); Current.Has_Fields := False; Current.Is_Array := False; Current.Is_Root := False; Stream.Write ('{'); end Start_Entity; -- ----------------------- -- Finish writing an object identified by the given name -- ----------------------- procedure End_Entity (Stream : in out Output_Stream; Name : in String) is pragma Unreferenced (Name); begin Node_Info_Stack.Pop (Stream.Stack); Stream.Write ('}'); end End_Entity; -- ----------------------- -- Write the attribute name/value pair. -- ----------------------- overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String) is begin Stream.Write_Field_Name (Name); Stream.Write_String (Value); end Write_Attribute; overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin Stream.Write_Field_Name (Name); Stream.Write_Wide_String (Value); end Write_Wide_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer) is begin Stream.Write_Field_Name (Name); Stream.Write (Integer'Image (Value)); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is begin Stream.Write_Field_Name (Name); if Value then Stream.Write ("true"); else Stream.Write ("false"); end if; end Write_Attribute; -- ----------------------- -- Write an attribute member from the current object -- ----------------------- procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin Stream.Write_Field_Name (Name); case Util.Beans.Objects.Get_Type (Value) is when TYPE_NULL => Stream.Write ("null"); when TYPE_BOOLEAN => if Util.Beans.Objects.To_Boolean (Value) then Stream.Write ("true"); else Stream.Write ("false"); end if; when TYPE_INTEGER => Stream.Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value)); when others => Stream.Write_String (Util.Beans.Objects.To_String (Value)); end case; end Write_Attribute; -- ----------------------- -- Write the attribute with a null value. -- ----------------------- overriding procedure Write_Null_Attribute (Stream : in out Output_Stream; Name : in String) is begin Stream.Write_Field_Name (Name); Stream.Write ("null"); end Write_Null_Attribute; -- ----------------------- -- Write an object value as an entity -- ----------------------- procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin case Util.Beans.Objects.Get_Type (Value) is when TYPE_NULL => Stream.Write_Field_Name (Name); Stream.Write ("null"); when TYPE_BOOLEAN => Stream.Write_Field_Name (Name); if Util.Beans.Objects.To_Boolean (Value) then Stream.Write ("true"); else Stream.Write ("false"); end if; when TYPE_INTEGER => Stream.Write_Field_Name (Name); Stream.Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value)); when TYPE_FLOAT => Stream.Write_Field_Name (Name); Stream.Stream.Write (Long_Long_Float'Image (Util.Beans.Objects.To_Long_Long_Float (Value))); when TYPE_BEAN | TYPE_ARRAY => if Is_Array (Value) then Stream.Start_Array (Name); declare Count : constant Natural := Util.Beans.Objects.Get_Count (Value); begin for I in 1 .. Count loop Stream.Write_Entity ("", Util.Beans.Objects.Get_Value (Value, I)); end loop; end; Stream.End_Array (Name); else declare procedure Process (Name : in String; Item : in Object); procedure Process (Name : in String; Item : in Object) is begin Stream.Write (ASCII.LF); if Name'Length = 0 then Stream.Write (""""":"); end if; Stream.Write_Entity (Name, Item); end Process; begin Stream.Start_Entity (Name); Util.Beans.Objects.Maps.Iterate (Value, Process'Access); Stream.End_Entity (Name); end; end if; when others => Stream.Write_Field_Name (Name); Stream.Write_String (Util.Beans.Objects.To_String (Value)); end case; end Write_Entity; -- ----------------------- -- Write a JSON name/value pair (see Write_Attribute). -- ----------------------- overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is begin Stream.Write_Attribute (Name, Value); end Write_Entity; overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin Stream.Write_Wide_Attribute (Name, Value); end Write_Wide_Entity; -- ----------------------- -- Write a JSON name/value pair (see Write_Attribute). -- ----------------------- overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer) is begin Stream.Write_Attribute (Name, Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time) is begin Stream.Write_Entity (Name, Util.Dates.ISO8601.Image (Value, Util.Dates.ISO8601.SUBSECOND)); end Write_Entity; -- ----------------------- -- Write an entity with a null value. -- ----------------------- overriding procedure Write_Null_Entity (Stream : in out Output_Stream; Name : in String) is begin Stream.Write_Null_Attribute (Name); end Write_Null_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is begin Stream.Write_Attribute (Name, Value); end Write_Entity; overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer) is begin Stream.Write_Field_Name (Name); Stream.Write (Long_Long_Integer'Image (Value)); end Write_Long_Entity; overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is begin Stream.Write_Entity (Name, Value); end Write_Enum_Entity; -- ----------------------- -- Start an array that will contain the specified number of elements -- Example: "list": [ -- ----------------------- overriding procedure Start_Array (Stream : in out Output_Stream; Name : in String) is Current : access Node_Info := Node_Info_Stack.Current (Stream.Stack); begin if Current /= null then if Current.Has_Fields then Stream.Write (','); elsif not Current.Is_Root then Current.Has_Fields := True; elsif Name'Length > 0 then Stream.Write ('{'); Current.Has_Fields := True; else Current.Is_Array := True; Current.Has_Fields := True; end if; end if; Node_Info_Stack.Push (Stream.Stack); Current := Node_Info_Stack.Current (Stream.Stack); Current.Has_Fields := False; Current.Is_Array := True; Current.Is_Root := False; if Name'Length > 0 then Stream.Write_String (Name); Stream.Write (':'); end if; Stream.Write ('['); end Start_Array; -- ----------------------- -- Finishes an array -- ----------------------- overriding procedure End_Array (Stream : in out Output_Stream; Name : in String) is pragma Unreferenced (Name); begin Node_Info_Stack.Pop (Stream.Stack); Stream.Write (']'); end End_Array; -- ----------------------- -- Get the current location (file and line) to report an error message. -- ----------------------- function Get_Location (Handler : in Parser) return String is begin return Util.Strings.Image (Handler.Line_Number); end Get_Location; procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Input_Buffer_Stream'Class; Sink : in out Reader'Class) is -- Put back a token in the buffer. procedure Put_Back (P : in out Parser'Class; Token : in Token_Type); -- Parse the expression buffer to find the next token. procedure Peek (P : in out Parser'Class; Token : out Token_Type); function Hexdigit (C : in Character) return Interfaces.Unsigned_32; -- Parse a list of members -- members ::= pair | pair ',' members -- pair ::= string ':' value -- value ::= string | number | object | array | true | false | null procedure Parse_Pairs (P : in out Parser'Class); -- Parse a value -- value ::= string | number | object | array | true | false | null procedure Parse_Value (P : in out Parser'Class; Name : in String); -- ------------------------------ -- Parse a list of members -- members ::= pair | pair ',' members -- pair ::= string ':' value -- value ::= string | number | object | array | true | false | null -- ------------------------------ procedure Parse_Pairs (P : in out Parser'Class) is Current_Name : Unbounded_String; Token : Token_Type; begin loop Peek (P, Token); if Token /= T_STRING then Put_Back (P, Token); return; end if; Current_Name := P.Token; Peek (P, Token); if Token /= T_COLON then P.Error ("Missing ':'"); end if; Parse_Value (P, To_String (Current_Name)); Peek (P, Token); if Token /= T_COMMA then Put_Back (P, Token); return; end if; end loop; end Parse_Pairs; function Hexdigit (C : in Character) return Interfaces.Unsigned_32 is use type Interfaces.Unsigned_32; begin if C >= '0' and C <= '9' then return Character'Pos (C) - Character'Pos ('0'); elsif C >= 'a' and C <= 'f' then return Character'Pos (C) - Character'Pos ('a') + 10; elsif C >= 'A' and C <= 'F' then return Character'Pos (C) - Character'Pos ('A') + 10; else raise Constraint_Error with "Invalid hexdigit: " & C; end if; end Hexdigit; -- ------------------------------ -- Parse a value -- value ::= string | number | object | array | true | false | null -- ------------------------------ procedure Parse_Value (P : in out Parser'Class; Name : in String) is Token : Token_Type; Index : Natural; begin Peek (P, Token); case Token is when T_LEFT_BRACE => Sink.Start_Object (Name, P); Parse_Pairs (P); Peek (P, Token); if Token /= T_RIGHT_BRACE then P.Error ("Missing '}'"); end if; Sink.Finish_Object (Name, P); -- when T_LEFT_BRACKET => Sink.Start_Array (Name, P); Peek (P, Token); Index := 0; if Token /= T_RIGHT_BRACKET then Put_Back (P, Token); loop Parse_Value (P, Util.Strings.Image (Index)); Peek (P, Token); exit when Token = T_RIGHT_BRACKET; if Token /= T_COMMA then P.Error ("Missing ']'"); exit when Token = T_EOF; end if; Index := Index + 1; end loop; end if; Sink.Finish_Array (Name, Index, P); when T_NULL => Sink.Set_Member (Name, Util.Beans.Objects.Null_Object, P); when T_NUMBER => declare Value : Long_Long_Integer; begin Value := Long_Long_Integer'Value (To_String (P.Token)); Sink.Set_Member (Name, Util.Beans.Objects.To_Object (Value), P); end; when T_FLOAT => declare Value : Long_Long_Float; begin Value := Long_Long_Float'Value (To_String (P.Token)); Sink.Set_Member (Name, Util.Beans.Objects.To_Object (Value), P); exception when Constraint_Error => P.Error ("Invalid number"); end; when T_STRING => Sink.Set_Member (Name, Util.Beans.Objects.To_Object (P.Token), P); when T_TRUE => Sink.Set_Member (Name, Util.Beans.Objects.To_Object (True), P); when T_FALSE => Sink.Set_Member (Name, Util.Beans.Objects.To_Object (False), P); when T_EOF => P.Error ("End of stream reached"); return; when others => P.Error ("Invalid token"); end case; end Parse_Value; -- ------------------------------ -- Put back a token in the buffer. -- ------------------------------ procedure Put_Back (P : in out Parser'Class; Token : in Token_Type) is begin P.Pending_Token := Token; end Put_Back; -- ------------------------------ -- Parse the expression buffer to find the next token. -- ------------------------------ procedure Peek (P : in out Parser'Class; Token : out Token_Type) is use Ada.Characters; C, C1 : Character; begin -- If a token was put back, return it. if P.Pending_Token /= T_EOF then Token := P.Pending_Token; P.Pending_Token := T_EOF; return; end if; if P.Has_Pending_Char then C := P.Pending_Char; else -- Skip white spaces loop Stream.Read (Char => C); if C = Ada.Characters.Latin_1.LF then P.Line_Number := P.Line_Number + 1; else exit when C /= ' ' and C /= Ada.Characters.Latin_1.CR and C /= Ada.Characters.Latin_1.HT; end if; end loop; end if; P.Has_Pending_Char := False; -- See what we have and continue parsing. case C is -- Literal string using double quotes -- Collect up to the end of the string and put -- the result in the parser token result. when '"' => Delete (P.Token, 1, Length (P.Token)); loop Stream.Read (Char => C1); if C1 = '\' then Stream.Read (Char => C1); case C1 is when '"' | '\' | '/' => null; when 'b' => C1 := Ada.Characters.Latin_1.BS; when 'f' => C1 := Ada.Characters.Latin_1.VT; when 'n' => C1 := Ada.Characters.Latin_1.LF; when 'r' => C1 := Ada.Characters.Latin_1.CR; when 't' => C1 := Ada.Characters.Latin_1.HT; when 'u' => declare use Interfaces; C2, C3, C4 : Character; Val : Interfaces.Unsigned_32; begin Stream.Read (Char => C1); Stream.Read (Char => C2); Stream.Read (Char => C3); Stream.Read (Char => C4); Val := Interfaces.Shift_Left (Hexdigit (C1), 12); Val := Val + Interfaces.Shift_Left (Hexdigit (C2), 8); Val := Val + Interfaces.Shift_Left (Hexdigit (C3), 4); Val := Val + Hexdigit (C4); -- Encode the value as an UTF-8 string. if Val >= 16#1000# then Append (P.Token, Character'Val (16#E0# or Shift_Right (Val, 12))); Val := Val and 16#0fff#; Append (P.Token, Character'Val (16#80# or Shift_Right (Val, 6))); Val := Val and 16#03f#; C1 := Character'Val (16#80# or Val); elsif Val >= 16#80# then Append (P.Token, Character'Val (16#C0# or Shift_Right (Val, 6))); Val := Val and 16#03f#; C1 := Character'Val (16#80# or Val); else C1 := Character'Val (Val); end if; end; when others => P.Error ("Invalid character '" & C1 & "' in \x sequence"); end case; elsif C1 = C then Token := T_STRING; return; end if; Append (P.Token, C1); end loop; -- Number when '-' | '0' .. '9' => Delete (P.Token, 1, Length (P.Token)); Append (P.Token, C); Token := T_NUMBER; begin loop Stream.Read (Char => C); exit when C not in '0' .. '9'; Append (P.Token, C); end loop; if C = '.' then Token := T_FLOAT; Append (P.Token, C); loop Stream.Read (Char => C); exit when C not in '0' .. '9'; Append (P.Token, C); end loop; end if; if C = 'e' or C = 'E' then Token := T_FLOAT; Append (P.Token, C); Stream.Read (Char => C); if C = '+' or C = '-' then Append (P.Token, C); Stream.Read (Char => C); end if; while C in '0' .. '9' loop Append (P.Token, C); Stream.Read (Char => C); end loop; end if; if not (C in ' ' | Latin_1.HT | Latin_1.LF | Latin_1.CR) then P.Has_Pending_Char := True; P.Pending_Char := C; end if; exception when Ada.IO_Exceptions.Data_Error => null; end; return; -- Parse a name composed of letters or digits. when 'a' .. 'z' | 'A' .. 'Z' => Delete (P.Token, 1, Length (P.Token)); Append (P.Token, C); loop Stream.Read (Char => C); exit when not (C in 'a' .. 'z' or C in 'A' .. 'Z' or C in '0' .. '9' or C = '_'); Append (P.Token, C); end loop; -- Putback the last character unless we can ignore it. if not (C in ' ' | Latin_1.HT | Latin_1.LF | Latin_1.CR) then P.Has_Pending_Char := True; P.Pending_Char := C; end if; -- and empty eq false ge gt le lt ne not null true case Element (P.Token, 1) is when 'n' | 'N' => if P.Token = "null" then Token := T_NULL; return; end if; when 'f' | 'F' => if P.Token = "false" then Token := T_FALSE; return; end if; when 't' | 'T' => if P.Token = "true" then Token := T_TRUE; return; end if; when others => null; end case; Token := T_UNKNOWN; return; when '{' => Token := T_LEFT_BRACE; return; when '}' => Token := T_RIGHT_BRACE; return; when '[' => Token := T_LEFT_BRACKET; return; when ']' => Token := T_RIGHT_BRACKET; return; when ':' => Token := T_COLON; return; when ',' => Token := T_COMMA; return; when others => Token := T_UNKNOWN; return; end case; exception when Ada.IO_Exceptions.Data_Error => Token := T_EOF; return; end Peek; begin Parse_Value (Handler, ""); end Parse; -- Read a JSON file and return an object. function Read (Path : in String) return Util.Beans.Objects.Object is P : Parser; R : Util.Beans.Objects.Readers.Reader; begin P.Parse (Path, R); if P.Has_Error then return Util.Beans.Objects.Null_Object; else return R.Get_Root; end if; end Read; function Read (Content : in String) return Util.Properties.Manager is P : Parser; R : Util.Beans.Objects.Readers.Reader; begin P.Parse_String (Content, R); if P.Has_Error then return Util.Properties.To_Manager (Util.Beans.Objects.Null_Object); else return Util.Properties.To_Manager (R.Get_Root); end if; end Read; end Util.Serialize.IO.JSON;
with C.crt_externs; function System.Environment_Block return C.char_ptr_ptr is begin return C.crt_externs.NSGetEnviron.all; end System.Environment_Block;
-- -- -- package Copyright (c) Dmitry A. Kazakov -- -- GNAT.Sockets.Connection_State_Machine Luebeck -- -- Interface Winter, 2012 -- -- -- -- Last revision : 18:41 01 Aug 2019 -- -- -- -- 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 package provides an implementation of server's side connection -- object that implements a state machine to receive packets from the -- client side. The structure of a packet is described by the contents -- of connection object itself. Fields of the object derived from a -- special abstract type (Data_Item) fed with the input received from -- the client in the order they are declared in the object. Once all -- fields are received a primitive operation is called to process the -- packet. After that the cycle repeats. -- Enumeration of the fields (introspection) is based on Ada stream -- attributes. See ARM 13.13.2(9) for the legality of the approach. -- with Ada.Finalization; use Ada.Finalization; with Ada.Streams; use Ada.Streams; with GNAT.Sockets.Server; use GNAT.Sockets.Server; with System.Storage_Elements; use System.Storage_Elements; with Generic_Unbounded_Array; with Interfaces; with System.Storage_Pools; package GNAT.Sockets.Connection_State_Machine is -- -- State_Machine -- Connection client driven by the contents. This is -- the base type to derive from. The derived type -- should contain a set of fields with the types derived from Data_Item. -- These objects will be read automatically in their order. -- type State_Machine is abstract new Connection with private; -- -- Connected -- Overrides Connections_Server... -- -- If the derived type overrides this procedure, it should call this one -- from new implemetation. -- procedure Connected (Client : in out State_Machine); -- -- Finalize -- Destruction -- -- Client - The connection client -- -- This procedure is to be called from implementation when overridden. -- procedure Finalize (Client : in out State_Machine); -- -- Received -- Overrides GNAT.Sockets.Server... -- procedure Received ( Client : in out State_Machine; Data : Stream_Element_Array; Pointer : in out Stream_Element_Offset ); -- -- Enumerate -- Fake stream I/O procedure -- -- This procedure is used internally in order to enumerate the contents -- of the record type. -- procedure Enumerate ( Stream : access Root_Stream_Type'Class; Item : State_Machine ); for State_Machine'Write use Enumerate; ------------------------------------------------------------------------ -- -- Data_Item -- Base type of a data item to read -- type Data_Item is abstract new Ada.Finalization.Limited_Controlled with null record; type Data_Item_Ptr is access all Data_Item'Class; type Data_Item_Offset is new Integer; subtype Data_Item_Address is Data_Item_Offset range 1..Data_Item_Offset'Last; type Data_Item_Ptr_Array is array (Data_Item_Address range <>) of Data_Item_Ptr; -- -- Feed -- Incoming data -- -- Item - The data item -- Data - The array of stream elements containing incoming data -- Pointer - The first element in the array -- Client - The connection client -- State - Of the data item processing -- -- This procedure is called when data become available to get item -- contents. The stream elements are Data (Pointer..Data'Last). The -- procedure consumes data and advances Pointer beyond consumed elements -- The parameter State indicates processing state. It is initially 0. -- When Item contents is read in full State is set to 0. When State is -- not 0 then Pointer must be set to Data'Last + 1, indicating that more -- data required. Feed will be called again on the item when new data -- come with the value of State returned from the last call. -- procedure Feed ( Item : in out Data_Item; Data : Stream_Element_Array; Pointer : in out Stream_Element_Offset; Client : in out State_Machine'Class; State : in out Stream_Element_Offset ) is abstract; -- -- Freed -- Deallocation notification -- -- Item - The data item -- -- This procedure is called when the shared data item is about to -- deallocate items allocated there. See External_String_Buffer. The -- default implementation does nothing. -- procedure Freed (Item : in out Data_Item); -- -- Get_Children -- Get list of immediate children -- -- Item - The data item -- -- Returns : -- -- The list of immediate children (nested) data items -- -- Exceptions : -- -- Use_Error - The data item is not initialized -- function Get_Children (Item : Data_Item) return Data_Item_Ptr_Array; -- -- Get_Size -- Size of the data item in data items -- -- Item - The data item -- -- Returns : -- -- The default implementation returns 1 -- function Get_Size (Item : Data_Item) return Natural; -- -- End_Of_Subsequence -- Completion of a subsequence -- -- Item - The data item -- Data - The array of stream elements containing incoming data -- Pointer - The first element in the array (can be Data'Last + 1) -- Client - The connection client -- State - Of the data item processing -- -- This procedure is called when a subsequence of data items has been -- processed. Item is the data item which was active prior to sequence -- start. It is called only if the data item was not completed, i.e. -- State is not 0. When the implementation changes State to 0 processing -- of the data item completes and the next item is fetched. Note that -- differently to Feed Pointer may point beyond Data when all available -- input has been processed. The default implementation does nothing. -- procedure End_Of_Subsequence ( Item : in out Data_Item; Data : Stream_Element_Array; Pointer : Stream_Element_Offset; Client : in out State_Machine'Class; State : in out Stream_Element_Offset ); -- -- Enumerate -- Fake stream I/O procedure -- -- This procedure is used internally in order to enumerate the contents -- of the record type, a descendant of Connection. The elements of the -- record type derived from Data_Item are ones which will be fed with -- data received from the socket. -- procedure Enumerate ( Stream : access Root_Stream_Type'Class; Item : Data_Item ); for Data_Item'Write use Enumerate; type Shared_Data_Item; type Shared_Data_Item_Ptr is access all Shared_Data_Item'Class; -- -- External_Initialize -- -- Item - The data item -- Shared - The shared items stack to use -- -- This procedure is used to initialize an object when it is used -- outside an instance of State_Machine. -- procedure External_Initialize ( Item : Data_Item'Class; Shared : Shared_Data_Item_Ptr := null ); -- -- Shared_Data_Item -- Base type for shared items -- type Shared_Data_Item is abstract new Data_Item with record Initialized : Boolean := False; Previous : Shared_Data_Item_Ptr; -- Stacked items end record; -- -- Enumerate -- Fake stream I/O procedure -- procedure Enumerate ( Stream : access Root_Stream_Type'Class; Item : Shared_Data_Item ); for Shared_Data_Item'Write use Enumerate; -- -- Feed -- Implementation, makes the shared item active -- procedure Feed ( Item : in out Shared_Data_Item; Data : Stream_Element_Array; Pointer : in out Stream_Element_Offset; Client : in out State_Machine'Class; State : in out Stream_Element_Offset ); ------------------------------------------------------------------------ -- Data_Block -- Base type of a sequence of data items. Derived data -- types contain fields derived from Data_Item. -- type Data_Block is abstract new Data_Item with private; -- -- Feed -- Implementation -- procedure Feed ( Item : in out Data_Block; Data : Stream_Element_Array; Pointer : in out Stream_Element_Offset; Client : in out State_Machine'Class; State : in out Stream_Element_Offset ); -- -- Enumerate -- Fake stream I/O procedure -- procedure Enumerate ( Stream : access Root_Stream_Type'Class; Item : Data_Block ); for Data_Block'Write use Enumerate; -- -- Finalize -- Destruction -- -- Item - Being finalized -- -- To be called the from derived type's Finalize if overridden -- procedure Finalize (Item : in out Data_Block); -- -- Get_Children -- Overriding -- function Get_Children (Item : Data_Block) return Data_Item_Ptr_Array; -- -- Get_Length -- The number of items contained by the block item -- -- Item - The block item -- -- Exceptions : -- -- Use_Error - The block was not initialized yet -- function Get_Length (Item : Data_Block) return Positive; -- -- Get_Size -- Overriding -- function Get_Size (Item : Data_Block) return Natural; ------------------------------------------------------------------------ -- Data_Null -- No data item, used where a data item is required -- type Data_Null is new Data_Item with null record; -- -- Feed -- Implementation -- procedure Feed ( Item : in out Data_Null; Data : Stream_Element_Array; Pointer : in out Stream_Element_Offset; Client : in out State_Machine'Class; State : in out Stream_Element_Offset ); ------------------------------------------------------------------------ -- Data_Selector -- Base type of a list of data items selected -- alternatively. A derived type has fields derived -- from Data_Item. One of the fields is used at a time. So the type -- acts as a variant record. The field to select is set by calling -- Set_Alternative. Usually it is done from Feed of some descendant -- derived from Data_Item, placed after the field controlling selection -- of the alternative. When an alternative should enclose several fields -- a Data_Block descendant is used. -- type Data_Selector is new Data_Item with private; -- -- Feed -- Implementation -- procedure Feed ( Item : in out Data_Selector; Data : Stream_Element_Array; Pointer : in out Stream_Element_Offset; Client : in out State_Machine'Class; State : in out Stream_Element_Offset ); -- -- Finalize -- Destruction -- -- Item - Being finalized -- -- To be called the from derived type's Finalize if overridden -- procedure Finalize (Item : in out Data_Selector); -- -- Get_Alternative -- The currently selected alternative -- -- Item - Selector item -- -- Returns : -- -- The alternative number 1.. -- function Get_Alternative (Item : Data_Selector) return Positive; -- -- Get_Alternatives_Number -- The number of alternatives -- -- Item - Selector item -- -- Returns : -- -- The total number of alternatives -- -- Exceptions : -- -- Use_Error - The selector was not initialized yet -- function Get_Alternatives_Number (Item : Data_Selector) return Positive; -- -- Get_Children -- Overriding -- function Get_Children ( Item : Data_Selector ) return Data_Item_Ptr_Array; -- -- Enumerate -- Fake stream I/O procedure -- procedure Enumerate ( Stream : access Root_Stream_Type'Class; Item : Data_Selector ); for Data_Selector'Write use Enumerate; -- -- Set_Alternative -- Select an alternative -- -- Item - Selector item -- Alternative - To select (number 1..Get_Alternatives_Number (Item)) -- -- Exceptions : -- -- Constraint_Error - Invalid alternative number -- Use_Error - The selector was not initialized yet -- procedure Set_Alternative ( Item : in out Data_Selector; Alternative : Positive ); -- -- Get_Size -- Overriding -- function Get_Size (Item : Data_Selector) return Natural; ------------------------------------------------------------------------ -- -- External_String_Buffer -- The arena buffer to keep bodies of strings -- and dynamically allocated elements. This -- buffer can be shared by multiple instances of Data_Item. For example: -- -- type Alternatives_Record is new Choice_Data_Item with record -- Text_1 : Implicit_External_String_Data_Item; -- Text_2 : Implicit_External_String_Data_Item; -- Text_3 : Implicit_External_String_Data_Item; -- end record; -- type Packet is new State_Machine ... with record -- Buffer : External_String_Buffer (1024); -- Shared buffer -- Choice : Alternatives_Record; -- end record; -- -- When several buffers appear the nearest one before the data item -- object is used. -- type External_String_Buffer; type External_String_Buffer_Ptr is access all External_String_Buffer'Class; -- -- Arena_Pool -- The pool component of the External_String_Buffer that -- allocates memory as substrings in the buffer. -- -- Parent - The buffer to take memory from -- type Arena_Pool ( Parent : access External_String_Buffer'Class ) is new System.Storage_Pools.Root_Storage_Pool with null record; -- -- Allocate -- Allocate memory -- -- The memory is allocated in the string buffer as a string. -- procedure Allocate ( Pool : in out Arena_Pool; Address : out System.Address; Size : Storage_Count; Alignment : Storage_Count ); -- -- Deallocate -- Free memory -- -- This a null operation. The memory is freed by Erase -- procedure Deallocate ( Pool : in out Arena_Pool; Address : System.Address; Size : Storage_Count; Alignment : Storage_Count ); function Storage_Size ( Pool : Arena_Pool ) return Storage_Count; procedure Enumerate ( Stream : access Root_Stream_Type'Class; Pool : Arena_Pool ); for Arena_Pool'Write use Enumerate; -- -- Allocator_Data -- The allocator's list. The users of the pool -- register themselves in order to get notifications -- upon erasing the buffer. They should finalize all objects then have -- allocated in the pool. -- type Allocator_Data; type Allocator_Data_Ptr is access all Allocator_Data; type Allocator_Data (Allocator : access Data_Item'Class) is record Previous : Allocator_Data_Ptr; -- List of allocators end record; type External_String_Buffer (Size : Natural) is new Shared_Data_Item with record Pool : Arena_Pool (External_String_Buffer'Access); Length : Natural := 0; Count : Natural := 0; -- Allocatied items Allocators : Allocator_Data_Ptr; -- List of objects using the pool Buffer : String (1..Size); end record; -- -- Erase -- Deallocate all elements and all strings -- -- Buffer - The buffer -- -- The implementation walks the list of allocators to notify them that -- the allocated items will be freed. The callee must finalize its -- elements if necessary. -- procedure Erase (Buffer : in out External_String_Buffer); -- -- Feed -- Implementation of the feed operation -- -- The implementation erases the buffer. -- procedure Feed ( Item : in out External_String_Buffer; Data : Stream_Element_Array; Pointer : in out Stream_Element_Offset; Client : in out State_Machine'Class; State : in out Stream_Element_Offset ); -- -- Fnalize -- Destruction -- -- Buffer - The buffer -- -- The derived type must call this if it overrides it. -- procedure Finalize (Buffer : in out External_String_Buffer); ------------------------------------------------------------------------ generic with procedure Put (Text : String) is <>; with procedure Put_Line (Line : String) is <>; package Generic_Dump is -- -- Put -- Allocator list -- -- Buffer - The external string buffer -- Prefix - Of the output lines -- procedure Put ( Buffer : in out External_String_Buffer; Prefix : String ); -- -- Put -- List item structure recursively -- -- Item - The data item -- Prefix - Of the output lines -- procedure Put ( Item : Data_Item'Class; Prefix : String := "" ); -- -- Put_Call_Stack -- List the call stack of the state machine -- -- Client - The state machine -- Prefix - Of the output lines -- procedure Put_Call_Stack ( Client : State_Machine'Class; Prefix : String := "" ); -- -- Put_Stream -- Stream and dump the result list -- -- Item - The data item -- Prefix - Of the output lines -- procedure Put_Stream ( Item : Data_Item'Class; Prefix : String := "" ); end Generic_Dump; private use Interfaces; Out_Of_Bounds : constant String := "Pointer is out of bounds"; No_Room : constant String := "No room for output"; package Data_Item_Arrays is new Generic_Unbounded_Array ( Index_Type => Data_Item_Address, Object_Type => Data_Item_Ptr, Object_Array_Type => Data_Item_Ptr_Array, Null_Element => null ); use Data_Item_Arrays; type Data_Item_Ptr_Array_Ptr is access Data_Item_Ptr_Array; procedure Free is new Ada.Unchecked_Deallocation ( Data_Item_Ptr_Array, Data_Item_Ptr_Array_Ptr ); type Sequence; type Sequence_Ptr is access all Sequence; type Sequence (Length : Data_Item_Address) is record Caller : Sequence_Ptr; State : Stream_Element_Offset := 0; -- Saved caller's state Current : Data_Item_Offset := 1; List : Data_Item_Ptr_Array (1..Length); end record; procedure Free is new Ada.Unchecked_Deallocation (Sequence, Sequence_Ptr); type State_Type is (Feeding, Packet_Processing); type State_Machine is abstract new Connection with record State : Stream_Element_Offset := 0; Start : Stream_Element_Offset := 0; -- Saved pointer Fed : Unsigned_64 := 0; -- Running count of octets processed Data : Sequence_Ptr; end record; procedure Call ( Client : in out State_Machine; Pointer : Stream_Element_Offset; Data : Sequence_Ptr; State : Stream_Element_Offset := 0 ); type Shared_Data_Item_Ptr_Ptr is access all Shared_Data_Item_Ptr; type Initialization_Stream is new Root_Stream_Type with record Shared : aliased Shared_Data_Item_Ptr; -- The latest shared item Parent : Shared_Data_Item_Ptr_Ptr; Count : Data_Item_Offset := 0; Ignore : Data_Item_Offset := 0; Data : Unbounded_Array; end record; procedure Add ( Stream : in out Initialization_Stream; Item : Data_Item'Class; Nested : Data_Item_Offset := 0 ); procedure Read ( Stream : in out Initialization_Stream; Item : out Stream_Element_Array; Last : out Stream_Element_Offset ); procedure Write ( Stream : in out Initialization_Stream; Item : Stream_Element_Array ); function Get_Prefix (Stream : Root_Stream_Type'Class) return String; procedure Set_Prefix ( Stream : Root_Stream_Type'Class; Prefix : Natural ); procedure Check_Initialization_Stream ( Item : Data_Item'Class; Stream : Root_Stream_Type'Class ); function To_Integer (Value : Unsigned_8 ) return Integer_8; function To_Integer (Value : Unsigned_16) return Integer_16; function To_Integer (Value : Unsigned_32) return Integer_32; function To_Integer (Value : Unsigned_64) return Integer_64; pragma Inline (To_Integer); function To_Unsigned (Value : Integer_8 ) return Unsigned_8; function To_Unsigned (Value : Integer_16) return Unsigned_16; function To_Unsigned (Value : Integer_32) return Unsigned_32; function To_Unsigned (Value : Integer_64) return Unsigned_64; pragma Inline (To_Unsigned); function Self (Item : Data_Item'Class) return Data_Item_Ptr; type Data_Block_Ptr is access all Data_Block'Class; type Data_Block is new Data_Item with record Data : Sequence_Ptr; Initialized : Boolean := False; end record; function Self (Item : Data_Block'Class) return Data_Block_Ptr; type Sequence_Array is array (Positive range <>) of Sequence_Ptr; type Alternatives_List (Size : Natural) is record List : Sequence_Array (1..Size); end record; type Alternatives_List_Ptr is access Alternatives_List; type Data_Selector_Ptr is access all Data_Selector'Class; type Data_Selector is new Data_Item with record Alternatives : Alternatives_List_Ptr; Current : Positive := 1; Initialized : Boolean := False; end record; function Self (Item : Data_Selector'Class) return Data_Selector_Ptr; function Self (Item : Shared_Data_Item'Class) return Shared_Data_Item_Ptr; generic with procedure Put_Line (Line : String) is <>; procedure Generic_Dump_Stream ( Stream : Initialization_Stream'Class; Prefix : String := "" ); end GNAT.Sockets.Connection_State_Machine;
-- This spec has been automatically generated from STM32L0x1.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with System; package STM32_SVD.RTC is pragma Preelaborate; --------------- -- Registers -- --------------- -- RTC time register type TR_Register is record -- Second units in BCD format SU : STM32_SVD.UInt4; -- Second tens in BCD format ST : STM32_SVD.UInt3; -- unspecified Reserved_7_7 : STM32_SVD.Bit; -- Minute units in BCD format MNU : STM32_SVD.UInt4; -- Minute tens in BCD format MNT : STM32_SVD.UInt3; -- unspecified Reserved_15_15 : STM32_SVD.Bit; -- Hour units in BCD format HU : STM32_SVD.UInt4; -- Hour tens in BCD format HT : STM32_SVD.UInt2; -- AM/PM notation PM : STM32_SVD.Bit; -- unspecified Reserved_23_31 : STM32_SVD.UInt9; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for TR_Register use record SU at 0 range 0 .. 3; ST at 0 range 4 .. 6; Reserved_7_7 at 0 range 7 .. 7; MNU at 0 range 8 .. 11; MNT at 0 range 12 .. 14; Reserved_15_15 at 0 range 15 .. 15; HU at 0 range 16 .. 19; HT at 0 range 20 .. 21; PM at 0 range 22 .. 22; Reserved_23_31 at 0 range 23 .. 31; end record; -- RTC date register type DR_Register is record -- Date units in BCD format DU : STM32_SVD.UInt4; -- Date tens in BCD format DT : STM32_SVD.UInt2; -- unspecified Reserved_6_7 : STM32_SVD.UInt2; -- Month units in BCD format MU : STM32_SVD.UInt4; -- Month tens in BCD format MT : STM32_SVD.Bit; -- Week day units WDU : STM32_SVD.UInt3; -- Year units in BCD format YU : STM32_SVD.UInt4; -- Year tens in BCD format YT : STM32_SVD.UInt4; -- unspecified Reserved_24_31 : STM32_SVD.Byte; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for DR_Register use record DU at 0 range 0 .. 3; DT at 0 range 4 .. 5; Reserved_6_7 at 0 range 6 .. 7; MU at 0 range 8 .. 11; MT at 0 range 12 .. 12; WDU at 0 range 13 .. 15; YU at 0 range 16 .. 19; YT at 0 range 20 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; -- RTC control register type CR_Register is record -- Wakeup clock selection WUCKSEL : STM32_SVD.UInt3; -- Time-stamp event active edge TSEDGE : STM32_SVD.Bit; -- RTC_REFIN reference clock detection enable (50 or 60 Hz) REFCKON : STM32_SVD.Bit; -- Bypass the shadow registers BYPSHAD : STM32_SVD.Bit; -- Hour format FMT : STM32_SVD.Bit; -- unspecified Reserved_7_7 : STM32_SVD.Bit; -- Alarm A enable ALRAE : STM32_SVD.Bit; -- Alarm B enable ALRBE : STM32_SVD.Bit; -- Wakeup timer enable WUTE : STM32_SVD.Bit; -- timestamp enable TSE : STM32_SVD.Bit; -- Alarm A interrupt enable ALRAIE : STM32_SVD.Bit; -- Alarm B interrupt enable ALRBIE : STM32_SVD.Bit; -- Wakeup timer interrupt enable WUTIE : STM32_SVD.Bit; -- Time-stamp interrupt enable TSIE : STM32_SVD.Bit; -- Write-only. Add 1 hour (summer time change) ADD1H : STM32_SVD.Bit; -- Write-only. Subtract 1 hour (winter time change) SUB1H : STM32_SVD.Bit; -- Backup BKP : STM32_SVD.Bit; -- Calibration output selection COSEL : STM32_SVD.Bit; -- Output polarity POL : STM32_SVD.Bit; -- Output selection OSEL : STM32_SVD.UInt2; -- Calibration output enable COE : STM32_SVD.Bit; -- unspecified Reserved_24_31 : STM32_SVD.Byte; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CR_Register use record WUCKSEL at 0 range 0 .. 2; TSEDGE at 0 range 3 .. 3; REFCKON at 0 range 4 .. 4; BYPSHAD at 0 range 5 .. 5; FMT at 0 range 6 .. 6; Reserved_7_7 at 0 range 7 .. 7; ALRAE at 0 range 8 .. 8; ALRBE at 0 range 9 .. 9; WUTE at 0 range 10 .. 10; TSE at 0 range 11 .. 11; ALRAIE at 0 range 12 .. 12; ALRBIE at 0 range 13 .. 13; WUTIE at 0 range 14 .. 14; TSIE at 0 range 15 .. 15; ADD1H at 0 range 16 .. 16; SUB1H at 0 range 17 .. 17; BKP at 0 range 18 .. 18; COSEL at 0 range 19 .. 19; POL at 0 range 20 .. 20; OSEL at 0 range 21 .. 22; COE at 0 range 23 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; -- RTC initialization and status register type ISR_Register is record -- Read-only. Alarm A write flag ALRAWF : STM32_SVD.Bit; -- Read-only. Alarm B write flag ALRBWF : STM32_SVD.Bit; -- Read-only. Wakeup timer write flag WUTWF : STM32_SVD.Bit; -- Read-only. Shift operation pending SHPF : STM32_SVD.Bit; -- Read-only. Initialization status flag INITS : STM32_SVD.Bit; -- Registers synchronization flag RSF : STM32_SVD.Bit; -- Read-only. Initialization flag INITF : STM32_SVD.Bit; -- Initialization mode INIT : STM32_SVD.Bit; -- Alarm A flag ALRAF : STM32_SVD.Bit; -- Alarm B flag ALRBF : STM32_SVD.Bit; -- Wakeup timer flag WUTF : STM32_SVD.Bit; -- Time-stamp flag TSF : STM32_SVD.Bit; -- Time-stamp overflow flag TSOVF : STM32_SVD.Bit; -- RTC_TAMP1 detection flag TAMP1F : STM32_SVD.Bit; -- RTC_TAMP2 detection flag TAMP2F : STM32_SVD.Bit; -- unspecified Reserved_15_31 : STM32_SVD.UInt17; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for ISR_Register use record ALRAWF at 0 range 0 .. 0; ALRBWF at 0 range 1 .. 1; WUTWF at 0 range 2 .. 2; SHPF at 0 range 3 .. 3; INITS at 0 range 4 .. 4; RSF at 0 range 5 .. 5; INITF at 0 range 6 .. 6; INIT at 0 range 7 .. 7; ALRAF at 0 range 8 .. 8; ALRBF at 0 range 9 .. 9; WUTF at 0 range 10 .. 10; TSF at 0 range 11 .. 11; TSOVF at 0 range 12 .. 12; TAMP1F at 0 range 13 .. 13; TAMP2F at 0 range 14 .. 14; Reserved_15_31 at 0 range 15 .. 31; end record; -- RTC prescaler register type PRER_Register is record -- Synchronous prescaler factor PREDIV_S : STM32_SVD.UInt16; -- Asynchronous prescaler factor PREDIV_A : STM32_SVD.UInt7; -- unspecified Reserved_23_31 : STM32_SVD.UInt9; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for PRER_Register use record PREDIV_S at 0 range 0 .. 15; PREDIV_A at 0 range 16 .. 22; Reserved_23_31 at 0 range 23 .. 31; end record; -- RTC wakeup timer register type WUTR_Register is record -- Wakeup auto-reload value bits WUT : STM32_SVD.UInt16; -- unspecified Reserved_16_31 : STM32_SVD.UInt16; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for WUTR_Register use record WUT at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- RTC alarm A register type ALRMAR_Register is record -- Second units in BCD format. SU : STM32_SVD.UInt4; -- Second tens in BCD format. ST : STM32_SVD.UInt3; -- Alarm A seconds mask MSK1 : STM32_SVD.Bit; -- Minute units in BCD format. MNU : STM32_SVD.UInt4; -- Minute tens in BCD format. MNT : STM32_SVD.UInt3; -- Alarm A minutes mask MSK2 : STM32_SVD.Bit; -- Hour units in BCD format. HU : STM32_SVD.UInt4; -- Hour tens in BCD format. HT : STM32_SVD.UInt2; -- AM/PM notation PM : STM32_SVD.Bit; -- Alarm A hours mask MSK3 : STM32_SVD.Bit; -- Date units or day in BCD format. DU : STM32_SVD.UInt4; -- Date tens in BCD format. DT : STM32_SVD.UInt2; -- Week day selection WDSEL : STM32_SVD.Bit; -- Alarm A date mask MSK4 : STM32_SVD.Bit; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for ALRMAR_Register use record SU at 0 range 0 .. 3; ST at 0 range 4 .. 6; MSK1 at 0 range 7 .. 7; MNU at 0 range 8 .. 11; MNT at 0 range 12 .. 14; MSK2 at 0 range 15 .. 15; HU at 0 range 16 .. 19; HT at 0 range 20 .. 21; PM at 0 range 22 .. 22; MSK3 at 0 range 23 .. 23; DU at 0 range 24 .. 27; DT at 0 range 28 .. 29; WDSEL at 0 range 30 .. 30; MSK4 at 0 range 31 .. 31; end record; -- RTC alarm B register type ALRMBR_Register is record -- Second units in BCD format SU : STM32_SVD.UInt4; -- Second tens in BCD format ST : STM32_SVD.UInt3; -- Alarm B seconds mask MSK1 : STM32_SVD.Bit; -- Minute units in BCD format MNU : STM32_SVD.UInt4; -- Minute tens in BCD format MNT : STM32_SVD.UInt3; -- Alarm B minutes mask MSK2 : STM32_SVD.Bit; -- Hour units in BCD format HU : STM32_SVD.UInt4; -- Hour tens in BCD format HT : STM32_SVD.UInt2; -- AM/PM notation PM : STM32_SVD.Bit; -- Alarm B hours mask MSK3 : STM32_SVD.Bit; -- Date units or day in BCD format DU : STM32_SVD.UInt4; -- Date tens in BCD format DT : STM32_SVD.UInt2; -- Week day selection WDSEL : STM32_SVD.Bit; -- Alarm B date mask MSK4 : STM32_SVD.Bit; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for ALRMBR_Register use record SU at 0 range 0 .. 3; ST at 0 range 4 .. 6; MSK1 at 0 range 7 .. 7; MNU at 0 range 8 .. 11; MNT at 0 range 12 .. 14; MSK2 at 0 range 15 .. 15; HU at 0 range 16 .. 19; HT at 0 range 20 .. 21; PM at 0 range 22 .. 22; MSK3 at 0 range 23 .. 23; DU at 0 range 24 .. 27; DT at 0 range 28 .. 29; WDSEL at 0 range 30 .. 30; MSK4 at 0 range 31 .. 31; end record; -- write protection register type WPR_Register is record -- Write-only. Write protection key KEY : STM32_SVD.Byte; -- unspecified Reserved_8_31 : STM32_SVD.UInt24; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for WPR_Register use record KEY at 0 range 0 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; -- RTC sub second register type SSR_Register is record -- Read-only. Sub second value SS : STM32_SVD.UInt16; -- unspecified Reserved_16_31 : STM32_SVD.UInt16; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for SSR_Register use record SS at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- RTC shift control register type SHIFTR_Register is record -- Write-only. Subtract a fraction of a second SUBFS : STM32_SVD.UInt15; -- unspecified Reserved_15_30 : STM32_SVD.UInt16; -- Write-only. Add one second ADD1S : STM32_SVD.Bit; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for SHIFTR_Register use record SUBFS at 0 range 0 .. 14; Reserved_15_30 at 0 range 15 .. 30; ADD1S at 0 range 31 .. 31; end record; -- RTC timestamp time register type TSTR_Register is record -- Read-only. Second units in BCD format. SU : STM32_SVD.UInt4; -- Read-only. Second tens in BCD format. ST : STM32_SVD.UInt3; -- unspecified Reserved_7_7 : STM32_SVD.Bit; -- Read-only. Minute units in BCD format. MNU : STM32_SVD.UInt4; -- Read-only. Minute tens in BCD format. MNT : STM32_SVD.UInt3; -- unspecified Reserved_15_15 : STM32_SVD.Bit; -- Read-only. Hour units in BCD format. HU : STM32_SVD.UInt4; -- Read-only. Hour tens in BCD format. HT : STM32_SVD.UInt2; -- Read-only. AM/PM notation PM : STM32_SVD.Bit; -- unspecified Reserved_23_31 : STM32_SVD.UInt9; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for TSTR_Register use record SU at 0 range 0 .. 3; ST at 0 range 4 .. 6; Reserved_7_7 at 0 range 7 .. 7; MNU at 0 range 8 .. 11; MNT at 0 range 12 .. 14; Reserved_15_15 at 0 range 15 .. 15; HU at 0 range 16 .. 19; HT at 0 range 20 .. 21; PM at 0 range 22 .. 22; Reserved_23_31 at 0 range 23 .. 31; end record; -- RTC timestamp date register type TSDR_Register is record -- Read-only. Date units in BCD format DU : STM32_SVD.UInt4; -- Read-only. Date tens in BCD format DT : STM32_SVD.UInt2; -- unspecified Reserved_6_7 : STM32_SVD.UInt2; -- Read-only. Month units in BCD format MU : STM32_SVD.UInt4; -- Read-only. Month tens in BCD format MT : STM32_SVD.Bit; -- Read-only. Week day units WDU : STM32_SVD.UInt3; -- unspecified Reserved_16_31 : STM32_SVD.UInt16; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for TSDR_Register use record DU at 0 range 0 .. 3; DT at 0 range 4 .. 5; Reserved_6_7 at 0 range 6 .. 7; MU at 0 range 8 .. 11; MT at 0 range 12 .. 12; WDU at 0 range 13 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- RTC time-stamp sub second register type TSSSR_Register is record -- Read-only. Sub second value SS : STM32_SVD.UInt16; -- unspecified Reserved_16_31 : STM32_SVD.UInt16; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for TSSSR_Register use record SS at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- RTC calibration register type CALR_Register is record -- Calibration minus CALM : STM32_SVD.UInt9; -- unspecified Reserved_9_12 : STM32_SVD.UInt4; -- Use a 16-second calibration cycle period CALW16 : STM32_SVD.Bit; -- Use an 8-second calibration cycle period CALW8 : STM32_SVD.Bit; -- Increase frequency of RTC by 488.5 ppm CALP : STM32_SVD.Bit; -- unspecified Reserved_16_31 : STM32_SVD.UInt16; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CALR_Register use record CALM at 0 range 0 .. 8; Reserved_9_12 at 0 range 9 .. 12; CALW16 at 0 range 13 .. 13; CALW8 at 0 range 14 .. 14; CALP at 0 range 15 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- RTC tamper configuration register type TAMPCR_Register is record -- RTC_TAMP1 input detection enable TAMP1E : STM32_SVD.Bit; -- Active level for RTC_TAMP1 input TAMP1TRG : STM32_SVD.Bit; -- Tamper interrupt enable TAMPIE : STM32_SVD.Bit; -- RTC_TAMP2 input detection enable TAMP2E : STM32_SVD.Bit; -- Active level for RTC_TAMP2 input TAMP2_TRG : STM32_SVD.Bit; -- unspecified Reserved_5_6 : STM32_SVD.UInt2; -- Activate timestamp on tamper detection event TAMPTS : STM32_SVD.Bit; -- Tamper sampling frequency TAMPFREQ : STM32_SVD.UInt3; -- RTC_TAMPx filter count TAMPFLT : STM32_SVD.UInt2; -- RTC_TAMPx precharge duration TAMPPRCH : STM32_SVD.UInt2; -- RTC_TAMPx pull-up disable TAMPPUDIS : STM32_SVD.Bit; -- Tamper 1 interrupt enable TAMP1IE : STM32_SVD.Bit; -- Tamper 1 no erase TAMP1NOERASE : STM32_SVD.Bit; -- Tamper 1 mask flag TAMP1MF : STM32_SVD.Bit; -- Tamper 2 interrupt enable TAMP2IE : STM32_SVD.Bit; -- Tamper 2 no erase TAMP2NOERASE : STM32_SVD.Bit; -- Tamper 2 mask flag TAMP2MF : STM32_SVD.Bit; -- unspecified Reserved_22_31 : STM32_SVD.UInt10; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for TAMPCR_Register use record TAMP1E at 0 range 0 .. 0; TAMP1TRG at 0 range 1 .. 1; TAMPIE at 0 range 2 .. 2; TAMP2E at 0 range 3 .. 3; TAMP2_TRG at 0 range 4 .. 4; Reserved_5_6 at 0 range 5 .. 6; TAMPTS at 0 range 7 .. 7; TAMPFREQ at 0 range 8 .. 10; TAMPFLT at 0 range 11 .. 12; TAMPPRCH at 0 range 13 .. 14; TAMPPUDIS at 0 range 15 .. 15; TAMP1IE at 0 range 16 .. 16; TAMP1NOERASE at 0 range 17 .. 17; TAMP1MF at 0 range 18 .. 18; TAMP2IE at 0 range 19 .. 19; TAMP2NOERASE at 0 range 20 .. 20; TAMP2MF at 0 range 21 .. 21; Reserved_22_31 at 0 range 22 .. 31; end record; -- RTC alarm A sub second register type ALRMASSR_Register is record -- Sub seconds value SS : STM32_SVD.UInt15; -- unspecified Reserved_15_23 : STM32_SVD.UInt9; -- Mask the most-significant bits starting at this bit MASKSS : STM32_SVD.UInt4; -- unspecified Reserved_28_31 : STM32_SVD.UInt4; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for ALRMASSR_Register use record SS at 0 range 0 .. 14; Reserved_15_23 at 0 range 15 .. 23; MASKSS at 0 range 24 .. 27; Reserved_28_31 at 0 range 28 .. 31; end record; -- RTC alarm B sub second register type ALRMBSSR_Register is record -- Sub seconds value SS : STM32_SVD.UInt15; -- unspecified Reserved_15_23 : STM32_SVD.UInt9; -- Mask the most-significant bits starting at this bit MASKSS : STM32_SVD.UInt4; -- unspecified Reserved_28_31 : STM32_SVD.UInt4; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for ALRMBSSR_Register use record SS at 0 range 0 .. 14; Reserved_15_23 at 0 range 15 .. 23; MASKSS at 0 range 24 .. 27; Reserved_28_31 at 0 range 28 .. 31; end record; -- option register type OR_Register is record -- RTC_ALARM on PC13 output type RTC_ALARM_TYPE : STM32_SVD.Bit; -- RTC_ALARM on PC13 output type RTC_OUT_RMP : STM32_SVD.Bit; -- unspecified Reserved_2_31 : STM32_SVD.UInt30; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OR_Register use record RTC_ALARM_TYPE at 0 range 0 .. 0; RTC_OUT_RMP at 0 range 1 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Real-time clock type RTC_Peripheral is record -- RTC time register TR : aliased TR_Register; -- RTC date register DR : aliased DR_Register; -- RTC control register CR : aliased CR_Register; -- RTC initialization and status register ISR : aliased ISR_Register; -- RTC prescaler register PRER : aliased PRER_Register; -- RTC wakeup timer register WUTR : aliased WUTR_Register; -- RTC alarm A register ALRMAR : aliased ALRMAR_Register; -- RTC alarm B register ALRMBR : aliased ALRMBR_Register; -- write protection register WPR : aliased WPR_Register; -- RTC sub second register SSR : aliased SSR_Register; -- RTC shift control register SHIFTR : aliased SHIFTR_Register; -- RTC timestamp time register TSTR : aliased TSTR_Register; -- RTC timestamp date register TSDR : aliased TSDR_Register; -- RTC time-stamp sub second register TSSSR : aliased TSSSR_Register; -- RTC calibration register CALR : aliased CALR_Register; -- RTC tamper configuration register TAMPCR : aliased TAMPCR_Register; -- RTC alarm A sub second register ALRMASSR : aliased ALRMASSR_Register; -- RTC alarm B sub second register ALRMBSSR : aliased ALRMBSSR_Register; -- option register OR_k : aliased OR_Register; -- RTC backup registers BKP0R : aliased STM32_SVD.UInt32; -- RTC backup registers BKP1R : aliased STM32_SVD.UInt32; -- RTC backup registers BKP2R : aliased STM32_SVD.UInt32; -- RTC backup registers BKP3R : aliased STM32_SVD.UInt32; -- RTC backup registers BKP4R : aliased STM32_SVD.UInt32; end record with Volatile; for RTC_Peripheral use record TR at 16#0# range 0 .. 31; DR at 16#4# range 0 .. 31; CR at 16#8# range 0 .. 31; ISR at 16#C# range 0 .. 31; PRER at 16#10# range 0 .. 31; WUTR at 16#14# range 0 .. 31; ALRMAR at 16#1C# range 0 .. 31; ALRMBR at 16#20# range 0 .. 31; WPR at 16#24# range 0 .. 31; SSR at 16#28# range 0 .. 31; SHIFTR at 16#2C# range 0 .. 31; TSTR at 16#30# range 0 .. 31; TSDR at 16#34# range 0 .. 31; TSSSR at 16#38# range 0 .. 31; CALR at 16#3C# range 0 .. 31; TAMPCR at 16#40# range 0 .. 31; ALRMASSR at 16#44# range 0 .. 31; ALRMBSSR at 16#48# range 0 .. 31; OR_k at 16#4C# range 0 .. 31; BKP0R at 16#50# range 0 .. 31; BKP1R at 16#54# range 0 .. 31; BKP2R at 16#58# range 0 .. 31; BKP3R at 16#5C# range 0 .. 31; BKP4R at 16#60# range 0 .. 31; end record; -- Real-time clock RTC_Periph : aliased RTC_Peripheral with Import, Address => RTC_Base; end STM32_SVD.RTC;
------------------------------------------------------------------------------ -- 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.Units is function Unit_Kind (Element : Any_Compilation_Unit_Node) return Asis.Unit_Kinds is begin return Element.Unit_Kind; end Unit_Kind; procedure Set_Unit_Kind (Element : in out Any_Compilation_Unit_Node; Value : in Asis.Unit_Kinds) is begin Element.Unit_Kind := Value; end Set_Unit_Kind; function Unit_Class (Element : Any_Compilation_Unit_Node) return Asis.Unit_Classes is begin return Element.Unit_Class; end Unit_Class; procedure Set_Unit_Class (Element : in out Any_Compilation_Unit_Node; Value : in Asis.Unit_Classes) is begin Element.Unit_Class := Value; end Set_Unit_Class; function Unit_Origin (Element : Any_Compilation_Unit_Node) return Asis.Unit_Origins is begin return Element.Unit_Origin; end Unit_Origin; procedure Set_Unit_Origin (Element : in out Any_Compilation_Unit_Node; Value : in Asis.Unit_Origins) is begin Element.Unit_Origin := Value; end Set_Unit_Origin; function Enclosing_Context (Element : Any_Compilation_Unit_Node) return Asis.Context is begin return Element.Enclosing_Context; end Enclosing_Context; procedure Set_Enclosing_Context (Element : in out Any_Compilation_Unit_Node; Value : in Asis.Context) is begin Element.Enclosing_Context := Value; end Set_Enclosing_Context; function Next_Element (Element : Any_Compilation_Unit_Node) return Asis.Element is begin return Element.Next_Element; end Next_Element; procedure Set_Next_Element (Element : in out Any_Compilation_Unit_Node; Value : in Asis.Element) is begin Element.Next_Element := Value; end Set_Next_Element; function Corresponding_Parent_Declaration (Element : Any_Compilation_Unit_Node) return Asis.Compilation_Unit is begin return Element.Corresponding_Parent_Declaration; end Corresponding_Parent_Declaration; procedure Set_Corresponding_Parent_Declaration (Element : in out Any_Compilation_Unit_Node; Value : in Asis.Compilation_Unit) is begin Element.Corresponding_Parent_Declaration := Value; end Set_Corresponding_Parent_Declaration; function Corresponding_Children (Element : Any_Compilation_Unit_Node) return Asis.Compilation_Unit_List is begin return Secondary_Unit_Lists.To_Compilation_Unit_List (Element.Corresponding_Children); end Corresponding_Children; procedure Add_To_Corresponding_Children (Element : in out Any_Compilation_Unit_Node; Item : in Asis.Compilation_Unit) is begin Secondary_Unit_Lists.Add (Element.Corresponding_Children, Asis.Element (Item)); end Add_To_Corresponding_Children; function Corresponding_Declaration (Element : Any_Compilation_Unit_Node) return Asis.Compilation_Unit is begin return Element.Corresponding_Declaration; end Corresponding_Declaration; procedure Set_Corresponding_Declaration (Element : in out Any_Compilation_Unit_Node; Value : in Asis.Compilation_Unit) is begin Element.Corresponding_Declaration := Value; end Set_Corresponding_Declaration; function Corresponding_Body (Element : Any_Compilation_Unit_Node) return Asis.Compilation_Unit is begin return Element.Corresponding_Body; end Corresponding_Body; procedure Set_Corresponding_Body (Element : in out Any_Compilation_Unit_Node; Value : in Asis.Compilation_Unit) is begin Element.Corresponding_Body := Value; end Set_Corresponding_Body; function Unit_Full_Name (Element : Any_Compilation_Unit_Node) return Wide_String is begin return W.To_Wide_String (Element.Unit_Full_Name); end Unit_Full_Name; procedure Set_Unit_Full_Name (Element : in out Any_Compilation_Unit_Node; Value : in Wide_String) is begin Element.Unit_Full_Name := W.To_Unbounded_Wide_String (Value); end Set_Unit_Full_Name; function Unique_Name (Element : Any_Compilation_Unit_Node) return Wide_String is begin return W.To_Wide_String (Element.Unique_Name); end Unique_Name; procedure Set_Unique_Name (Element : in out Any_Compilation_Unit_Node; Value : in Wide_String) is begin Element.Unique_Name := W.To_Unbounded_Wide_String (Value); end Set_Unique_Name; function Can_Be_Main_Program (Element : Any_Compilation_Unit_Node) return Boolean is begin return Element.Can_Be_Main_Program; end Can_Be_Main_Program; procedure Set_Can_Be_Main_Program (Element : in out Any_Compilation_Unit_Node; Value : in Boolean) is begin Element.Can_Be_Main_Program := Value; end Set_Can_Be_Main_Program; function Is_Body_Required (Element : Any_Compilation_Unit_Node) return Boolean is begin return Element.Is_Body_Required; end Is_Body_Required; procedure Set_Is_Body_Required (Element : in out Any_Compilation_Unit_Node; Value : in Boolean) is begin Element.Is_Body_Required := Value; end Set_Is_Body_Required; function Text_Name (Element : Any_Compilation_Unit_Node) return Wide_String is begin return W.To_Wide_String (Element.Text_Name); end Text_Name; procedure Set_Text_Name (Element : in out Any_Compilation_Unit_Node; Value : in Wide_String) is begin Element.Text_Name := W.To_Unbounded_Wide_String (Value); end Set_Text_Name; function Text_Form (Element : Any_Compilation_Unit_Node) return Wide_String is begin return W.To_Wide_String (Element.Text_Form); end Text_Form; procedure Set_Text_Form (Element : in out Any_Compilation_Unit_Node; Value : in Wide_String) is begin Element.Text_Form := W.To_Unbounded_Wide_String (Value); end Set_Text_Form; function Object_Name (Element : Any_Compilation_Unit_Node) return Wide_String is begin return W.To_Wide_String (Element.Object_Name); end Object_Name; procedure Set_Object_Name (Element : in out Any_Compilation_Unit_Node; Value : in Wide_String) is begin Element.Object_Name := W.To_Unbounded_Wide_String (Value); end Set_Object_Name; function Object_Form (Element : Any_Compilation_Unit_Node) return Wide_String is begin return W.To_Wide_String (Element.Object_Form); end Object_Form; procedure Set_Object_Form (Element : in out Any_Compilation_Unit_Node; Value : in Wide_String) is begin Element.Object_Form := W.To_Unbounded_Wide_String (Value); end Set_Object_Form; function Compilation_Command_Line_Options (Element : Any_Compilation_Unit_Node) return Wide_String is begin return W.To_Wide_String (Element.Compilation_Command_Line_Options); end Compilation_Command_Line_Options; procedure Set_Compilation_Command_Line_Options (Element : in out Any_Compilation_Unit_Node; Value : in Wide_String) is begin Element.Compilation_Command_Line_Options := W.To_Unbounded_Wide_String (Value); end Set_Compilation_Command_Line_Options; function Corresponding_Subunit_Parent_Body (Element : Any_Compilation_Unit_Node) return Asis.Compilation_Unit is begin return Element.Corresponding_Subunit_Parent_Body; end Corresponding_Subunit_Parent_Body; procedure Set_Corresponding_Subunit_Parent_Body (Element : in out Any_Compilation_Unit_Node; Value : in Asis.Compilation_Unit) is begin Element.Corresponding_Subunit_Parent_Body := Value; end Set_Corresponding_Subunit_Parent_Body; function Subunits (Element : Any_Compilation_Unit_Node) return Asis.Compilation_Unit_List is begin return Secondary_Unit_Lists.To_Compilation_Unit_List (Element.Subunits); end Subunits; procedure Add_To_Subunits (Element : in out Any_Compilation_Unit_Node; Item : in Asis.Compilation_Unit) is begin Secondary_Unit_Lists.Add (Element.Subunits, Asis.Element (Item)); end Add_To_Subunits; function Unit_Declaration (Element : Any_Compilation_Unit_Node) return Asis.Element is begin return Element.Unit_Declaration; end Unit_Declaration; procedure Set_Unit_Declaration (Element : in out Any_Compilation_Unit_Node; Value : in Asis.Element) is begin Element.Unit_Declaration := Value; end Set_Unit_Declaration; function Context_Clause_Elements (Element : Any_Compilation_Unit_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List is begin return Primary_Clause_Lists.To_Element_List (Element.Context_Clause_Elements, Include_Pragmas); end Context_Clause_Elements; procedure Set_Context_Clause_Elements (Element : in out Any_Compilation_Unit_Node; Value : in Asis.Element) is begin Element.Context_Clause_Elements := Primary_Clause_Lists.List (Value); end Set_Context_Clause_Elements; function Context_Clause_Elements_List (Element : Any_Compilation_Unit_Node) return Asis.Element is begin return Asis.Element (Element.Context_Clause_Elements); end Context_Clause_Elements_List; function Compilation_Pragmas (Element : Any_Compilation_Unit_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List is begin return Secondary_Pragma_Lists.To_Element_List (Element.Compilation_Pragmas, Include_Pragmas); end Compilation_Pragmas; procedure Add_To_Compilation_Pragmas (Element : in out Any_Compilation_Unit_Node; Item : in Asis.Element) is begin Secondary_Pragma_Lists.Add (Element.Compilation_Pragmas, Item); end Add_To_Compilation_Pragmas; function Start_Position (Element : Any_Compilation_Unit_Node) return Asis.Text_Position is begin return Element.Start_Position; end Start_Position; procedure Set_Start_Position (Element : in out Any_Compilation_Unit_Node; Value : in Asis.Text_Position) is begin Element.Start_Position := Value; end Set_Start_Position; function End_Position (Element : Any_Compilation_Unit_Node) return Asis.Text_Position is begin return Element.End_Position; end End_Position; procedure Set_End_Position (Element : in out Any_Compilation_Unit_Node; Value : in Asis.Text_Position) is begin Element.End_Position := Value; end Set_End_Position; function Separate_Name (Element : Any_Compilation_Unit_Node) return Asis.Element is begin return Element.Separate_Name; end Separate_Name; procedure Set_Separate_Name (Element : in out Any_Compilation_Unit_Node; Value : in Asis.Element) is begin Element.Separate_Name := Value; end Set_Separate_Name; function Separate_Name_Image (Element : Any_Compilation_Unit_Node) return Wide_String is begin return W.To_Wide_String (Element.Separate_Name_Image); end Separate_Name_Image; procedure Set_Separate_Name_Image (Element : in out Any_Compilation_Unit_Node; Value : in Wide_String) is begin Element.Separate_Name_Image := W.To_Unbounded_Wide_String (Value); end Set_Separate_Name_Image; function Hash (Element : Any_Compilation_Unit_Node) return Asis.ASIS_Integer is begin return Element.Hash; end Hash; procedure Set_Hash (Element : in out Any_Compilation_Unit_Node; Value : in Asis.ASIS_Integer) is begin Element.Hash := Value; end Set_Hash; function Compilation (Element : Any_Compilation_Unit_Node) return Compilations.Compilation is begin return Element.Compilation; end Compilation; procedure Set_Compilation (Element : in out Any_Compilation_Unit_Node; Value : in Compilations.Compilation) is begin Element.Compilation := Value; end Set_Compilation; function New_Any_Compilation_Unit_Node (The_Context : ASIS.Context) return Any_Compilation_Unit_Ptr is Result : Any_Compilation_Unit_Ptr := new Any_Compilation_Unit_Node; begin return Result; end New_Any_Compilation_Unit_Node; function Clone (Element : Any_Compilation_Unit_Node; Parent : Asis.Element) return Asis.Element is Result : constant Any_Compilation_Unit_Ptr := new Any_Compilation_Unit_Node; begin Result.Unit_Kind := Element.Unit_Kind; Result.Unit_Class := Element.Unit_Class; Result.Unit_Origin := Element.Unit_Origin; Result.Enclosing_Context := Element.Enclosing_Context; Result.Corresponding_Parent_Declaration := Element.Corresponding_Parent_Declaration; null; Result.Corresponding_Declaration := Element.Corresponding_Declaration; Result.Corresponding_Body := Element.Corresponding_Body; Result.Unit_Full_Name := Element.Unit_Full_Name; Result.Unique_Name := Element.Unique_Name; Result.Can_Be_Main_Program := Element.Can_Be_Main_Program; Result.Is_Body_Required := Element.Is_Body_Required; Result.Text_Name := Element.Text_Name; Result.Text_Form := Element.Text_Form; Result.Object_Name := Element.Object_Name; Result.Object_Form := Element.Object_Form; Result.Compilation_Command_Line_Options := Element.Compilation_Command_Line_Options; Result.Corresponding_Subunit_Parent_Body := Element.Corresponding_Subunit_Parent_Body; null; Result.Unit_Declaration := Element.Unit_Declaration; null; Result.Start_Position := Element.Start_Position; Result.End_Position := Element.End_Position; Result.Separate_Name := Element.Separate_Name; Result.Separate_Name_Image := Element.Separate_Name_Image; Result.Hash := Element.Hash; Result.Compilation := Element.Compilation; return Asis.Element (Result); end Clone; end Asis.Gela.Units;
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 sumDiv is type stringptr is access all char_array; procedure PInt(i : in Integer) is begin String'Write (Text_Streams.Stream (Current_Output), Trim(Integer'Image(i), Left)); end; procedure foo is a : Integer; begin a := 0; -- test a := a + 1; -- test 2 end; procedure foo2 is begin NULL; end; procedure foo3 is begin if 1 = 1 then NULL; end if; end; function sumdiv(n : in Integer) return Integer is out0 : Integer; begin -- On désire renvoyer la somme des diviseurs out0 := 0; -- On déclare un entier qui contiendra la somme for i in integer range 1..n loop -- La boucle : i est le diviseur potentiel if n rem i = 0 then -- Si i divise out0 := out0 + i; -- On incrémente else NULL; end if; end loop; return out0; --On renvoie out end; n : Integer; begin -- Programme principal n := 0; Get(n); -- Lecture de l'entier PInt(sumdiv(n)); end;
package ParameterDefaultValue is function someFunction (SomeInteger : in Integer := 2) return Integer; function someOtherFunction (SomeInteger : in Integer) return Integer; end ParameterDefaultValue;
----------------------------------------------------------------------- -- Add_User -- Example to add an object in the database -- Copyright (C) 2010, 2011 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 Samples.User.Model; with ADO; with ADO.Drivers; with ADO.Sessions; with ADO.Sessions.Factory; with Util.Strings; with Util.Log.Loggers; with Ada.Text_IO; with Ada.Command_Line; procedure Add_User is use Samples.User.Model; function Get_Name (Email : in String) return String; Factory : ADO.Sessions.Factory.Session_Factory; function Get_Name (Email : in String) return String is Pos : constant Natural := Util.Strings.Index (Email, '@'); begin if Pos > 0 then return Email (Email'First .. Pos - 1); else return Email; end if; end Get_Name; begin Util.Log.Loggers.Initialize ("samples.properties"); -- Initialize the database drivers. ADO.Drivers.Initialize ("samples.properties"); if Ada.Command_Line.Argument_Count < 1 then Ada.Text_IO.Put_Line ("Usage: add_user user-email ..."); Ada.Text_IO.Put_Line ("Example: add_user joe.potter@gmail.com"); Ada.Command_Line.Set_Exit_Status (2); return; end if; -- Initialize the session factory to connect to the -- database defined by 'ado.database' property. Factory.Create (ADO.Drivers.Get_Config ("ado.database")); declare DB : ADO.Sessions.Master_Session := Factory.Get_Master_Session; begin DB.Begin_Transaction; for I in 1 .. Ada.Command_Line.Argument_Count loop declare Email : constant String := Ada.Command_Line.Argument (I); Name : constant String := Get_Name (Email); User : User_Ref; begin User.Set_Name (Name); User.Set_Email (Email); User.Set_Description ("My friend " & Name); User.Set_Status (0); User.Save (DB); Ada.Text_IO.Put_Line ("User " & Name & " has id " & ADO.Identifier'Image (User.Get_Id)); end; end loop; DB.Commit; end; end Add_User;
----------------------------------------------------------------------- -- util-system-os -- Windows system operations -- 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 System; with Interfaces.C; with Interfaces.C.Strings; with Util.Systems.Types; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Windows). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '\'; -- Defines several windows specific types. type BOOL is mod 8; type WORD is new Interfaces.C.short; type DWORD is new Interfaces.C.unsigned_long; type PDWORD is access all DWORD; for PDWORD'Size use Standard'Address_Size; function Get_Last_Error return Integer; pragma Import (Stdcall, Get_Last_Error, "GetLastError"); -- Some useful error codes (See Windows document "System Error Codes (0-499)"). ERROR_BROKEN_PIPE : constant Integer := 109; -- ------------------------------ -- Handle -- ------------------------------ -- The windows HANDLE is defined as a void* in the C API. subtype HANDLE is System.Address; type PHANDLE is access all HANDLE; for PHANDLE'Size use Standard'Address_Size; function Wait_For_Single_Object (H : in HANDLE; Time : in DWORD) return DWORD; pragma Import (Stdcall, Wait_For_Single_Object, "WaitForSingleObject"); type Security_Attributes is record Length : DWORD; Security_Descriptor : System.Address; Inherit : Boolean; end record; type LPSECURITY_ATTRIBUTES is access all Security_Attributes; for LPSECURITY_ATTRIBUTES'Size use Standard'Address_Size; -- ------------------------------ -- File operations -- ------------------------------ subtype File_Type is HANDLE; NO_FILE : constant File_Type := System.Null_Address; STD_INPUT_HANDLE : constant DWORD := -10; STD_OUTPUT_HANDLE : constant DWORD := -11; STD_ERROR_HANDLE : constant DWORD := -12; function Get_Std_Handle (Kind : in DWORD) return File_Type; pragma Import (Stdcall, Get_Std_Handle, "GetStdHandle"); function Close_Handle (Fd : in File_Type) return BOOL; pragma Import (Stdcall, Close_Handle, "CloseHandle"); function Duplicate_Handle (SourceProcessHandle : in HANDLE; SourceHandle : in HANDLE; TargetProcessHandle : in HANDLE; TargetHandle : in PHANDLE; DesiredAccess : in DWORD; InheritHandle : in BOOL; Options : in DWORD) return BOOL; pragma Import (Stdcall, Duplicate_Handle, "DuplicateHandle"); function Read_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL; pragma Import (Stdcall, Read_File, "ReadFile"); function Write_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL; pragma Import (Stdcall, Write_File, "WriteFile"); function Create_Pipe (Read_Handle : in PHANDLE; Write_Handle : in PHANDLE; Attributes : in LPSECURITY_ATTRIBUTES; Buf_Size : in DWORD) return BOOL; pragma Import (Stdcall, Create_Pipe, "CreatePipe"); -- type Size_T is mod 2 ** Standard'Address_Size; subtype LPWSTR is Interfaces.C.Strings.chars_ptr; subtype PBYTE is Interfaces.C.Strings.chars_ptr; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype LPCTSTR is System.Address; subtype LPTSTR is System.Address; type CommandPtr is access all Interfaces.C.wchar_array; NULL_STR : constant LPWSTR := Interfaces.C.Strings.Null_Ptr; type Startup_Info is record cb : DWORD := 0; lpReserved : LPWSTR := NULL_STR; lpDesktop : LPWSTR := NULL_STR; lpTitle : LPWSTR := NULL_STR; dwX : DWORD := 0; dwY : DWORD := 0; dwXsize : DWORD := 0; dwYsize : DWORD := 0; dwXCountChars : DWORD := 0; dwYCountChars : DWORD := 0; dwFillAttribute : DWORD := 0; dwFlags : DWORD := 0; wShowWindow : WORD := 0; cbReserved2 : WORD := 0; lpReserved2 : PBYTE := Interfaces.C.Strings.Null_Ptr; hStdInput : HANDLE := System.Null_Address; hStdOutput : HANDLE := System.Null_Address; hStdError : HANDLE := System.Null_Address; end record; pragma Pack (Startup_Info); type Startup_Info_Access is access all Startup_Info; type PROCESS_INFORMATION is record hProcess : HANDLE := NO_FILE; hThread : HANDLE := NO_FILE; dwProcessId : DWORD; dwThreadId : DWORD; end record; type Process_Information_Access is access all PROCESS_INFORMATION; function Get_Current_Process return HANDLE; pragma Import (Stdcall, Get_Current_Process, "GetCurrentProcess"); function Get_Exit_Code_Process (Proc : in HANDLE; Code : in PDWORD) return BOOL; pragma Import (Stdcall, Get_Exit_Code_Process, "GetExitCodeProcess"); function Create_Process (Name : in LPCTSTR; Command : in System.Address; Process_Attributes : in LPSECURITY_ATTRIBUTES; Thread_Attributes : in LPSECURITY_ATTRIBUTES; Inherit_Handlers : in Boolean; Creation_Flags : in DWORD; Environment : in LPTSTR; Directory : in LPCTSTR; Startup_Info : in Startup_Info_Access; Process_Info : in Process_Information_Access) return Integer; pragma Import (Stdcall, Create_Process, "CreateProcessW"); -- Terminate the windows process and all its threads. function Terminate_Process (Proc : in HANDLE; Code : in DWORD) return Integer; pragma Import (Stdcall, Terminate_Process, "TerminateProcess"); function Sys_Stat (Path : in LPWSTR; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Stat, "_stat64"); function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Fstat, "_fstat64"); private -- kernel32 is used on Windows32 as well as Windows64. pragma Linker_Options ("-lkernel32"); end Util.Systems.Os;
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Localization, Internationalization, Globalization for Ada -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2010, 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$ ------------------------------------------------------------------------------ package Matreshka.Internals.Regexps.Compiler is pragma Preelaborate; type YY_Errors is (No_Error, Unexpected_End_Of_Literal, Unexpected_End_Of_Character_Class, Unexpected_Character_in_Multiplicity_Specifier, Unexpected_End_Of_Multiplicity_Specifier, Unexpected_End_Of_Property_Specification, Unrecognized_Character_In_Property_Specification, Unescaped_Pattern_Syntax_Character, Expression_Syntax_Error); type YY_Error_Information is record Error : YY_Errors; Index : Natural; end record; type Property_Specification_Keyword is (ASCII_Hex_Digit, -- Names of binary properties Alphabetic, Bidi_Control, -- Bidi_Mirrored, Cased, Case_Ignorable, Changes_When_Casefolded, Changes_When_Casemapped, Changes_When_NFKC_Casefolded, Changes_When_Lowercased, Changes_When_Titlecased, Changes_When_Uppercased, Composition_Exclusion, Full_Composition_Exclusion, Dash, Deprecated, Default_Ignorable_Code_Point, Diacritic, Extender, Grapheme_Base, Grapheme_Extend, Grapheme_Link, Hex_Digit, Hyphen, ID_Continue, Ideographic, ID_Start, IDS_Binary_Operator, IDS_Trinary_Operator, Join_Control, Logical_Order_Exception, Lowercase, Math, Noncharacter_Code_Point, Other_Alphabetic, Other_Default_Ignorable_Code_Point, Other_Grapheme_Extend, Other_ID_Continue, Other_ID_Start, Other_Lowercase, Other_Math, Other_Uppercase, Pattern_Syntax, Pattern_White_Space, Quotation_Mark, Radical, Soft_Dotted, STerm, Terminal_Punctuation, Unified_Ideograph, Uppercase, Variation_Selector, White_Space, XID_Continue, XID_Start, Expands_On_NFC, Expands_On_NFD, Expands_On_NFKC, Expands_On_NFKD, Other, -- Values of the General Category Control, Format, Unassigned, Private_Use, Surrogate, Letter, Cased_Letter, Lowercase_Letter, Modifier_Letter, Other_Letter, Titlecase_Letter, Uppercase_Letter, Mark, Spacing_Mark, Enclosing_Mark, Nonspacing_Mark, Number, Decimal_Number, Letter_Number, Other_Number, Punctuation, Connector_Punctuation, Dash_Punctuation, Close_Punctuation, Final_Punctuation, Initial_Punctuation, Other_Punctuation, Open_Punctuation, Symbol, Currency_Symbol, Modifier_Symbol, Math_Symbol, Other_Symbol, Separator, Line_Separator, Paragraph_Separator, Space_Separator); type Kinds is (None, Match_Code_Point, Number, Property_Keyword, AST_Node); type YYSType (Kind : Kinds := None) is record case Kind is when None => null; when Match_Code_Point => Code : Wide_Wide_Character; when Number => Value : Natural; when Property_Keyword => Keyword : Property_Specification_Keyword; when AST_Node => Node : Positive; end case; end record; type Token is (End_Of_Input, Error, Token_Code_Point, Token_Any_Code_Point, Token_Alternation, Token_Optional_Greedy, Token_Optional_Lazy, Token_Zero_Or_More_Greedy, Token_Zero_Or_More_Lazy, Token_One_Or_More_Greedy, Token_One_Or_More_Lazy, Token_Character_Class_Begin, Token_Character_Class_End, Token_Negate_Character_Class, Token_Character_Class_Range, Token_Multiplicity_Begin, Token_Multiplicity_End_Greedy, Token_Multiplicity_End_Lazy, Token_Multiplicity_Comma, Token_Multiplicity_Number, Token_Subexpression_Capture_Begin, Token_Subexpression_Begin, Token_Subexpression_End, Token_Property_Begin_Positive, Token_Property_Begin_Negative, Token_Property_End, Token_Property_Keyword, Token_Start_Of_Line, Token_End_Of_Line); -- Here is global state of the compiler. At the first stage of -- refactoring all global state variables must be moved to here. -- Later, they will be wrapped by record type to allow to have -- several compiler in the different threads at the same time. type Compiler_State is record Data : Matreshka.Internals.Strings.Shared_String_Access; YY_Start_State : Integer := 1; YY_Current_Position : Matreshka.Internals.Utf16.Utf16_String_Index := 0; YY_Current_Index : Positive := 1; YY_Error : YY_Error_Information := (No_Error, 0); YYLVal : YYSType; YYVal : YYSType; Character_Class_Mode : Boolean := False; -- Recognition of the Unicode property specification is done in the -- separate scanner's mode; this variable is used to switch back to -- original mode. end record; procedure YYError (Self : not null access Compiler_State; Error : YY_Errors; Index : Natural); -- Report error. procedure Attach (Pattern : in out Shared_Pattern; Head : Positive; Node : Positive); -- Attach Node to the list of nodes, started by Head. function Compile (Expression : not null Matreshka.Internals.Strings.Shared_String_Access) return not null Shared_Pattern_Access; function Create_Alternative (Pattern : not null Shared_Pattern_Access; Prefered : Positive; Alternative : Positive) return Positive; pragma Inline (Create_Alternative); function Create_Anchor_End_Of_Line (Pattern : not null Shared_Pattern_Access) return Positive; pragma Inline (Create_Anchor_End_Of_Line); function Create_Anchor_Start_Of_Line (Pattern : not null Shared_Pattern_Access) return Positive; pragma Inline (Create_Anchor_Start_Of_Line); function Create_Character_Class (Pattern : not null Shared_Pattern_Access) return Positive; pragma Inline (Create_Character_Class); function Create_Match_Any (Pattern : not null Shared_Pattern_Access) return Positive; pragma Inline (Create_Match_Any); function Create_Match_Character (Pattern : not null Shared_Pattern_Access; Character : Matreshka.Internals.Unicode.Code_Point) return Positive; pragma Inline (Create_Match_Character); function Create_Match_Property (Pattern : not null Shared_Pattern_Access; Value : Matreshka.Internals.Unicode.Ucd.Boolean_Properties; Negative : Boolean) return Positive; pragma Inline (Create_Match_Property); function Create_Match_Property (Pattern : not null Shared_Pattern_Access; Value : General_Category_Flags; Negative : Boolean) return Positive; pragma Inline (Create_Match_Property); procedure Create_Member_Character (Pattern : not null Shared_Pattern_Access; Class : Positive; Character : Matreshka.Internals.Unicode.Code_Point); pragma Inline (Create_Member_Character); procedure Create_Member_Property (Pattern : not null Shared_Pattern_Access; Class : Positive; Value : Matreshka.Internals.Unicode.Ucd.Boolean_Properties; Negative : Boolean); pragma Inline (Create_Member_Property); procedure Create_Member_Property (Pattern : not null Shared_Pattern_Access; Class : Positive; Value : General_Category_Flags; Negative : Boolean); pragma Inline (Create_Member_Property); procedure Create_Member_Range (Pattern : not null Shared_Pattern_Access; Class : Positive; Low : Matreshka.Internals.Unicode.Code_Point; High : Matreshka.Internals.Unicode.Code_Point); pragma Inline (Create_Member_Range); function Create_Repetition (Pattern : not null Shared_Pattern_Access; Expression : Positive; Lower : Natural; Upper : Natural; Greedy : Boolean) return Positive; pragma Inline (Create_Repetition); function Create_Subexpression (Pattern : not null Shared_Pattern_Access; Expression : Positive; Capture : Boolean) return Positive; pragma Inline (Create_Subexpression); function Get_Preferred (Pattern : not null Shared_Pattern_Access; Node : Positive) return Natural; pragma Inline (Get_Preferred); function Get_Fallback (Pattern : not null Shared_Pattern_Access; Node : Positive) return Natural; pragma Inline (Get_Fallback); function Get_Members (Pattern : not null Shared_Pattern_Access; Node : Positive) return Natural; pragma Inline (Get_Members); function Get_Expression (Pattern : not null Shared_Pattern_Access; Node : Positive) return Natural; pragma Inline (Get_Expression); function Get_Lower_Bound (Pattern : not null Shared_Pattern_Access; Node : Positive) return Natural; pragma Inline (Get_Lower_Bound); function Get_Upper_Bound (Pattern : not null Shared_Pattern_Access; Node : Positive) return Natural; pragma Inline (Get_Upper_Bound); function Get_Previous_Sibling (Pattern : not null Shared_Pattern_Access; Node : Positive) return Natural; pragma Inline (Get_Previous_Sibling); function Get_Next_Sibling (Pattern : not null Shared_Pattern_Access; Node : Positive) return Natural; pragma Inline (Get_Next_Sibling); end Matreshka.Internals.Regexps.Compiler;
-- Version 01 is derived from ExcelOut by Frank Schoonjans in Modula-2 - thanks! -- Modula-2 code has been translated with Mod2Pas and P2Ada. -- -- References to documentation are to: http://www.openoffice.org/sc/excelfileformat.pdf -- -- To do: -- ===== -- - Unicode (for binary Excel: requires BIFF8, but BIFF8 is pretty difficult) -- - border line styles (5.115 XF - Extended Format) -- - XML-based formats support -- - ... with Ada.Unchecked_Deallocation, Ada.Unchecked_Conversion; with Ada.Strings.Fixed; with Interfaces; use Interfaces; -- Package IEEE_754 is from: Simple components for Ada by Dmitry A. Kazakov -- http://www.dmitry-kazakov.de/ada/components.htm with IEEE_754.Generic_Double_Precision; package body Excel_Out is use Ada.Streams.Stream_IO, Ada.Streams; -- Very low level part which deals with transferring data in an endian-neutral way, -- and floats in the IEEE format. This is needed for having Excel Writer -- totally portable on all systems and processor architectures. type Byte_buffer is array (Integer range <>) of Unsigned_8; empty_buffer: constant Byte_buffer:= (1..0 => 0); -- Put numbers with correct endianess as bytes: generic type Number is mod <>; size: Positive; function Intel_x86_buffer( n: Number ) return Byte_buffer; pragma Inline(Intel_x86_buffer); function Intel_x86_buffer( n: Number ) return Byte_buffer is b: Byte_buffer(1..size); m: Number:= n; begin for i in b'Range loop b(i):= Unsigned_8(m and 255); m:= m / 256; end loop; return b; end Intel_x86_buffer; function Intel_32 is new Intel_x86_buffer( Unsigned_32, 4 ); function Intel_16( n: Unsigned_16 ) return Byte_buffer is pragma Inline(Intel_16); begin return (Unsigned_8(n and 255), Unsigned_8(Shift_Right(n, 8))); end Intel_16; -- 2.5.2 Byte Strings, 8-bit string length (BIFF2-BIFF5), p. 187 function To_buf_8_bit_length(s: String) return Byte_buffer is b: Byte_buffer(s'Range); begin if s'Length > 255 then -- length doesn't fit in a byte raise Constraint_Error; end if; for i in b'Range loop b(i):= Character'Pos(s(i)); end loop; return Unsigned_8(s'Length) & b; end To_buf_8_bit_length; -- 2.5.2 Byte Strings, 16-bit string length (BIFF2-BIFF5), p. 187 function To_buf_16_bit_length(s: String) return Byte_buffer is b: Byte_buffer(s'Range); begin if s'Length > 2**16-1 then -- length doesn't fit in a 16-bit number raise Constraint_Error; end if; for i in b'Range loop b(i):= Character'Pos(s(i)); end loop; return Intel_16(s'Length) & b; end To_buf_16_bit_length; -- -- 2.5.3 Unicode Strings, 16-bit string length (BIFF2-BIFF5), p. 17 -- function To_buf_16_bit_length(s: Wide_String) return Byte_buffer is -- b: Byte_buffer(1 .. 2 * s'Length); -- j: Integer:= 1; -- begin -- if s'Length > 2**16-1 then -- length doesn't fit in a 16-bit number -- raise Constraint_Error; -- end if; -- for i in s'Range loop -- b(j) := Unsigned_8(Unsigned_32'(Wide_Character'Pos(s(i))) and 255); -- b(j+1):= Unsigned_8(Shift_Right(Unsigned_32'(Wide_Character'Pos(s(i))), 8)); -- j:= j + 2; -- end loop; -- return -- Intel_16(s'Length) & -- (1 => 1) & -- Character compression (ccompr): 1 = Uncompressed (16-bit characters) -- b; -- end To_buf_16_bit_length; -- Gives a byte sequence of an IEEE 64-bit number as if taken -- from an Intel machine (i.e. with the same endianess). -- -- http://en.wikipedia.org/wiki/IEEE_754-1985#Double-precision_64_bit -- package IEEE_LF is new IEEE_754.Generic_Double_Precision (Long_Float); function IEEE_Double_Intel_Portable(x: Long_Float) return Byte_buffer is pragma Inline(IEEE_Double_Intel_Portable); d : Byte_buffer(1..8); -- f64: constant IEEE_LF.Float_64:= IEEE_LF.To_IEEE(x); begin for i in d'Range loop d(i):= f64(9-i); -- Order is reversed end loop; -- Fully tested in Test_IEEE.adb return d; end IEEE_Double_Intel_Portable; -- Just spit the bytes of the long float - fast way. -- Of course this will work only on an Intel(-like) machine. We check this later. subtype Byte_buffer_8 is Byte_buffer(0..7); function IEEE_Double_Intel_Native is new Ada.Unchecked_Conversion(Long_Float, Byte_buffer_8); x_test: constant Long_Float:= -12345.0e-67; Can_use_native_IEEE: constant Boolean:= IEEE_Double_Intel_Portable(x_test) = IEEE_Double_Intel_Native(x_test); function IEEE_Double_Intel(x: Long_Float) return Byte_buffer is pragma Inline(IEEE_Double_Intel); begin if Can_use_native_IEEE then return IEEE_Double_Intel_Native(x); -- Fast, non-portable else return IEEE_Double_Intel_Portable(x); -- Slower but portable end if; end IEEE_Double_Intel; -- Workaround for the severe xxx'Read xxx'Write performance -- problems in the GNAT and ObjectAda compilers (as in 2009) -- This is possible if and only if Byte = Stream_Element and -- arrays types are both packed and aligned the same way. -- subtype Size_test_a is Byte_buffer(1..19); subtype Size_test_b is Ada.Streams.Stream_Element_Array(1..19); workaround_possible: constant Boolean:= Size_test_a'Size = Size_test_b'Size and Size_test_a'Alignment = Size_test_b'Alignment; procedure Block_Write( stream : in out Ada.Streams.Root_Stream_Type'Class; buffer : in Byte_buffer ) is pragma Inline(Block_Write); SE_Buffer : Stream_Element_Array (1 .. buffer'Length); for SE_Buffer'Address use buffer'Address; pragma Import (Ada, SE_Buffer); begin if workaround_possible then Ada.Streams.Write(stream, SE_Buffer); else Byte_buffer'Write(stream'Access, buffer); -- ^ This was 30x to 70x slower on GNAT 2009 -- Test in the Zip-Ada project. end if; end Block_Write; ---------------- -- Excel BIFF -- ---------------- -- The original Modula-2 code counted on certain assumptions about -- record packing & endianess. We write data without these assumptions. procedure WriteBiff( xl : Excel_Out_Stream'Class; biff_id: Unsigned_16; data : Byte_buffer ) is pragma Inline(WriteBiff); begin Block_Write(xl.xl_stream.all, Intel_16(biff_id)); Block_Write(xl.xl_stream.all, Intel_16(Unsigned_16(data'Length))); Block_Write(xl.xl_stream.all, data); end WriteBiff; -- 5.8 BOF: Beginning of File, p.135 procedure Write_BOF(xl : Excel_Out_Stream'Class) is function BOF_suffix return Byte_buffer is -- 5.8.1 Record BOF begin case xl.format is when BIFF2 => return empty_buffer; when BIFF3 | BIFF4 => return (0,0); -- Not used -- when BIFF8 => -- return (1,1,1,1); end case; end BOF_suffix; -- 0005H = Workbook globals -- 0006H = Visual Basic module -- 0010H = Sheet or dialogue (see SHEETPR, S5.97) Sheet_or_dialogue: constant:= 16#10#; -- 0020H = Chart -- 0040H = Macro sheet biff_record_identifier: constant array(Excel_type) of Unsigned_16:= (BIFF2 => 16#0009#, BIFF3 => 16#0209#, BIFF4 => 16#0409# -- BIFF8 => 16#0809# ); biff_version: constant array(Excel_type) of Unsigned_16:= (BIFF2 => 16#0200#, BIFF3 => 16#0300#, BIFF4 => 16#0400# -- BIFF8 => 16#0600# ); begin WriteBiff(xl, biff_record_identifier(xl.format), Intel_16(biff_version(xl.format)) & Intel_16(Sheet_or_dialogue) & BOF_suffix ); end Write_BOF; -- 5.49 FORMAT (number format) procedure WriteFmtStr (xl : Excel_Out_Stream'Class; s : String) is begin case xl.format is when BIFF2 | BIFF3 => WriteBiff(xl, 16#001E#, To_buf_8_bit_length(s)); when BIFF4 => WriteBiff(xl, 16#041E#, (0, 0) & To_buf_8_bit_length(s)); -- when BIFF8 => -- WriteBiff(xl, 16#041E#, (0, 0) & -- should be: format index used in other records -- To_buf_8_bit_length(s)); end case; end WriteFmtStr; -- Write built-in number formats (internal) procedure WriteFmtRecords (xl : Excel_Out_Stream'Class) is sep_1000: constant Character:= ','; -- US format sep_deci: constant Character:= '.'; -- US format -- ^ If there is any evidence of an issue with those built-in separators, -- we may make them configurable. NB: MS Excel 2002 and 2007 use only -- the index of built-in formats and discards the strings for BIFF2, but not for BIFF3... begin -- 5.12 BUILTINFMTCOUNT case xl.format is when BIFF2 => WriteBiff(xl, 16#001F#, Intel_16(Unsigned_16(last_built_in - 5))); when BIFF3 => WriteBiff(xl, 16#0056#, Intel_16(Unsigned_16(last_built_in - 3))); when BIFF4 => WriteBiff(xl, 16#0056#, Intel_16(Unsigned_16(last_built_in + 1))); -- when BIFF8 => -- null; end case; -- loop & case avoid omitting any choice for n in Number_format_type'First .. last_custom loop case n is when general => WriteFmtStr(xl, "General"); when decimal_0 => WriteFmtStr(xl, "0"); when decimal_2 => WriteFmtStr(xl, "0" & sep_deci & "00"); -- 'Comma' built-in style when decimal_0_thousands_separator => WriteFmtStr(xl, "#" & sep_1000 & "##0"); when decimal_2_thousands_separator => WriteFmtStr(xl, "#" & sep_1000 & "##0" & sep_deci & "00"); when no_currency_0 => if xl.format >= BIFF4 then WriteFmtStr(xl, "#" & sep_1000 & "##0;-#" & sep_1000 & "##0"); end if; when no_currency_red_0 => if xl.format >= BIFF4 then WriteFmtStr(xl, "#" & sep_1000 & "##0;-#" & sep_1000 & "##0"); -- [Red] doesn't go with non-English versions of Excel !! end if; when no_currency_2 => if xl.format >= BIFF4 then WriteFmtStr(xl, "#" & sep_1000 & "##0" & sep_deci & "00;" & "-#" & sep_1000 & "##0" & sep_deci & "00"); end if; when no_currency_red_2 => if xl.format >= BIFF4 then WriteFmtStr(xl, "#" & sep_1000 & "##0" & sep_deci & "00;" & "-#" & sep_1000 & "##0" & sep_deci & "00"); end if; when currency_0 => WriteFmtStr(xl, "$ #" & sep_1000 & "##0;$ -#" & sep_1000 & "##0"); when currency_red_0 => WriteFmtStr(xl, "$ #" & sep_1000 & "##0;$ -#" & sep_1000 & "##0"); -- [Red] doesn't go with non-English versions of Excel !! when currency_2 => WriteFmtStr(xl, "$ #" & sep_1000 & "##0" & sep_deci & "00;" & "$ -#" & sep_1000 & "##0" & sep_deci & "00"); when currency_red_2 => WriteFmtStr(xl, "$ #" & sep_1000 & "##0" & sep_deci & "00;" & "$ -#" & sep_1000 & "##0" & sep_deci & "00"); when percent_0 => WriteFmtStr(xl, "0%"); -- 'Percent' built-in style when percent_2 => WriteFmtStr(xl, "0" & sep_deci & "00%"); when scientific => WriteFmtStr(xl, "0" & sep_deci & "00E+00"); when fraction_1 => if xl.format >= BIFF3 then WriteFmtStr(xl, "#\ ?/?"); end if; when fraction_2 => if xl.format >= BIFF3 then WriteFmtStr(xl, "#\ ??/??"); end if; when dd_mm_yyyy => WriteFmtStr(xl, "dd/mm/yyyy"); when dd_mmm_yy => WriteFmtStr(xl, "dd/mmm/yy"); when dd_mmm => WriteFmtStr(xl, "dd/mmm"); when mmm_yy => WriteFmtStr(xl, "mmm/yy"); when h_mm_AM_PM => WriteFmtStr(xl, "h:mm\ AM/PM"); when h_mm_ss_AM_PM => WriteFmtStr(xl, "h:mm:ss\ AM/PM"); when hh_mm => WriteFmtStr(xl, "hh:mm"); when hh_mm_ss => WriteFmtStr(xl, "hh:mm:ss"); when dd_mm_yyyy_hh_mm => WriteFmtStr(xl, "dd/mm/yyyy\ hh:mm"); when percent_0_plus => WriteFmtStr(xl, "+0%;-0%;0%"); when percent_2_plus => WriteFmtStr(xl, "+0" & sep_deci & "00%;-0" & sep_deci & "00%;0" & sep_deci & "00%"); when date_iso => WriteFmtStr(xl, "yyyy\-mm\-dd"); when date_h_m_iso => WriteFmtStr(xl, "yyyy\-mm\-dd\ hh:mm"); when date_h_m_s_iso => WriteFmtStr(xl, "yyyy\-mm\-dd\ hh:mm:ss"); -- !! Trouble: Excel (German Excel/French locale) writes yyyy, reads it, -- understands it and translates it into aaaa, but is unable to -- understand *our* yyyy -- Same issue as [Red] vs [Rot] above. end case; end loop; -- ^ Some formats in the original list caused problems, probably -- because of regional placeholder symbols case xl.format is when BIFF2 => for i in 1..6 loop WriteFmtStr(xl, "@"); end loop; when BIFF3 => for i in 1..4 loop WriteFmtStr(xl, "@"); end loop; when BIFF4 => null; end case; -- ^ Stuffing for having the same number of built-in and EW custom end WriteFmtRecords; -- 5.35 DIMENSION procedure Write_Dimensions(xl: Excel_Out_Stream'Class) is -- sheet bounds: 0 2 Index to first used row -- 2 2 Index to last used row, increased by 1 -- 4 2 Index to first used column -- 6 2 Index to last used column, increased by 1 -- -- Since our row / column counts are 1-based, no need to increase by 1. sheet_bounds: constant Byte_buffer:= Intel_16(0) & Intel_16(Unsigned_16(xl.maxrow)) & Intel_16(0) & Intel_16(Unsigned_16(xl.maxcolumn)); -- sheet_bounds_32_16: constant Byte_buffer:= -- Intel_32(0) & -- Intel_32(Unsigned_32(xl.maxrow)) & -- Intel_16(0) & -- Intel_16(Unsigned_16(xl.maxcolumn)); begin case xl.format is when BIFF2 => WriteBiff(xl, 16#0000#, sheet_bounds); when BIFF3 | BIFF4 => WriteBiff(xl, 16#0200#, sheet_bounds & (0,0)); -- when BIFF8 => -- WriteBiff(xl, 16#0200#, sheet_bounds_32_16 & (0,0)); end case; end Write_Dimensions; procedure Define_number_format( xl : in out Excel_Out_Stream; format : out Number_format_type; format_string: in String ) is begin xl.number_fmt:= xl.number_fmt + 1; format:= xl.number_fmt; WriteFmtStr(xl, format_string); end Define_number_format; procedure Write_Worksheet_header(xl : in out Excel_Out_Stream'Class) is procedure Define_style(fmt: Format_type; style_id: Unsigned_8) is Base_Level: constant:= 255; begin WriteBiff(xl, 16#0293#, Intel_16(Unsigned_16(fmt) + 16#8000#) & style_id & Base_Level ); end Define_style; -- Comma_Style : constant:= 3; Currency_Style : constant:= 4; Percent_Style : constant:= 5; font_for_styles, font_2, font_3 : Font_type; -- function Encoding_code return Unsigned_16 is -- 5.17 CODEPAGE, p. 145 begin case xl.encoding is when Windows_CP_874 => return 874; when Windows_CP_932 => return 932; when Windows_CP_936 => return 936; when Windows_CP_949 => return 949; when Windows_CP_950 => return 950; when Windows_CP_1250 => return 1250; when Windows_CP_1251 => return 1251; when Windows_CP_1252 => case xl.format is when BIFF2 .. BIFF3 => return 16#8001#; when BIFF4 => return 1252; end case; when Windows_CP_1253 => return 1253; when Windows_CP_1254 => return 1254; when Windows_CP_1255 => return 1255; when Windows_CP_1256 => return 1256; when Windows_CP_1257 => return 1257; when Windows_CP_1258 => return 1258; when Windows_CP_1361 => return 1361; when Apple_Roman => return 10000; end case; end Encoding_code; -- begin Write_BOF(xl); -- 5.17 CODEPAGE, p. 145 case xl.format is -- when BIFF8 => -- UTF-16 -- WriteBiff(xl, 16#0042#, Intel_16(16#04B0#)); when others => WriteBiff(xl, 16#0042#, Intel_16(Encoding_code)); end case; -- 5.14 CALCMODE WriteBiff(xl, 16#000D#, Intel_16(1)); -- 1 => automatic -- 5.85 REFMODE WriteBiff(xl, 16#000F#, Intel_16(1)); -- 1 => A1 mode -- 5.28 DATEMODE WriteBiff(xl, 16#0022#, Intel_16(0)); -- 0 => 1900; 1 => 1904 Date system -- NB: the 1904 variant (Mac) is ignored by LibreOffice (<= 3.5), then wrong dates ! -- Define_font(xl,"Arial", 10, xl.def_font); Define_font(xl,"Arial", 10, font_for_styles); -- Used by BIFF3+'s styles Define_font(xl,"Calibri", 10, font_2); -- Defined in BIFF3 files written by Excel 2002 Define_font(xl,"Calibri", 10, font_3); -- Defined in BIFF3 files written by Excel 2002 WriteFmtRecords(xl); -- 5.111 WINDOWPROTECT WriteBiff(xl, 16#0019#, Intel_16(0)); -- Define default format Define_format(xl, xl.def_font, general, xl.def_fmt); if xl.format >= BIFF3 then -- Don't ask why we need the following useless formats, but it is as Excel 2002 -- write formats. Additionally, the default format is turned into decimal_2 -- when a file without those useless formats is opened in Excel (2002) ! Define_format(xl, font_for_styles, general, xl.def_fmt); Define_format(xl, font_for_styles, general, xl.def_fmt); Define_format(xl, font_2, general, xl.def_fmt); Define_format(xl, font_2, general, xl.def_fmt); for i in 5..15 loop Define_format(xl, xl.def_font, general, xl.def_fmt); end loop; -- Final default format index is the last changed xl.def_fmt end if; Use_default_format(xl); -- Define formats for the BIFF3+ "styles": Define_format(xl, font_for_styles, decimal_2, xl.cma_fmt); Define_format(xl, font_for_styles, currency_0, xl.ccy_fmt); Define_format(xl, font_for_styles, percent_0, xl.pct_fmt); -- Define styles - 5.103 STYLE p. 212 -- NB: - it is BIFF3+ (we cheat a bit if selected format is BIFF2). -- - these "styles" seem to be a zombie feature of Excel 3 -- - the whole purpose of including this is because format -- buttons (%)(,) in Excel 95 through 2007 are using these styles; -- if the styles are not defined, those buttons are not working -- when an Excel Writer sheet is open in MS Excel. Define_style(xl.cma_fmt, Comma_Style); Define_style(xl.ccy_fmt, Currency_Style); Define_style(xl.pct_fmt, Percent_Style); xl.dimrecpos:= Index(xl); Write_Dimensions(xl); xl.is_created:= True; end Write_Worksheet_header; type Font_or_Background is (for_font, for_background); type Color_pair is array(Font_or_Background) of Unsigned_16; auto_color: constant Color_pair:= (16#7FFF#, -- system window text colour 16#0019# -- system window background colour ); color_code: constant array(Excel_type, Color_type) of Color_pair := ( BIFF2 => ( black => (0, 0), white => (1, 1), red => (2, 2), green => (3, 3), blue => (4, 4), yellow => (5, 5), magenta => (6, 6), cyan => (7, 7), others => auto_color ), BIFF3 | BIFF4 => (black => (8, 8), white => (9, 9), red => (10, 10), green => (11, 11), blue => (12, 12), yellow => (13, 13), magenta => (14, 14), cyan => (15, 15), dark_red => (16, 16), dark_green => (17, 17), dark_blue => (18, 18), olive => (19, 19), purple => (20, 20), teal => (21, 21), silver => (22, 22), grey => (23, 23), automatic => auto_color ) ); -- *** Exported procedures ********************************************** -- 5.115 XF - Extended Format procedure Define_format( xl : in out Excel_Out_Stream; font : in Font_type; -- Default_font(xl), or given by Define_font number_format : in Number_format_type; -- built-in, or given by Define_number_format cell_format : out Format_type; -- Optional parameters -- horizontal_align : in Horizontal_alignment:= general_alignment; border : in Cell_border:= no_border; shaded : in Boolean:= False; -- Add a dotted background pattern background_color : in Color_type:= automatic; wrap_text : in Boolean:= False; vertical_align : in Vertical_alignment:= bottom_alignment; text_orient : in Text_orientation:= normal ) is actual_number_format: Number_format_type:= number_format; cell_is_locked: constant:= 1; -- ^ Means actually: cell formula protection is possible, and enabled when sheet is protected. procedure Define_BIFF2_XF is border_bits, mask: Unsigned_8; begin border_bits:= 0; mask:= 8; for s in Cell_border_single loop if border(s) then border_bits:= border_bits + mask; end if; mask:= mask * 2; end loop; -- 5.115.2 XF Record Contents, p. 221 for BIFF3 WriteBiff( xl, 16#0043#, -- XF code in BIFF2 (Unsigned_8(font), -- ^ Index to FONT record 0, -- ^ Not used Number_format_type'Pos(actual_number_format) + 16#40# * cell_is_locked, -- ^ Number format and cell flags Horizontal_alignment'Pos(horizontal_align) + border_bits + Boolean'Pos(shaded) * 128 -- ^ Horizontal alignment, border style, and background ) ); end Define_BIFF2_XF; area_code: Unsigned_16; procedure Define_BIFF3_XF is begin -- 5.115.2 XF Record Contents, p. 221 for BIFF3 WriteBiff( xl, 16#0243#, -- XF code in BIFF3 (Unsigned_8(font), -- ^ 0 - Index to FONT record Number_format_type'Pos(actual_number_format), -- ^ 1 - Number format and cell flags cell_is_locked, -- ^ 2 - XF_TYPE_PROT (5.115.1) 16#FF# -- ^ 3 - XF_USED_ATTRIB ) & Intel_16( Horizontal_alignment'Pos(horizontal_align) + Boolean'Pos(wrap_text) * 8 ) & -- ^ 4 - Horizontal alignment, text break, parent style XF Intel_16(area_code) & -- ^ 6 - XF_AREA_34 ( Boolean'Pos(border(top_single)), Boolean'Pos(border(left_single)), Boolean'Pos(border(bottom_single)), Boolean'Pos(border(right_single)) ) -- ^ 8 - XF_BORDER_34 - thin (=1) line; we could have other line styles: -- Thin, Medium, Dashed, Dotted, Thick, Double, Hair ); end Define_BIFF3_XF; procedure Define_BIFF4_XF is begin -- 5.115.2 XF Record Contents, p. 222 for BIFF4 WriteBiff( xl, 16#0443#, -- XF code in BIFF4 (Unsigned_8(font), -- ^ 0 - Index to FONT record Number_format_type'Pos(actual_number_format), -- ^ 1 - Number format and cell flags cell_is_locked, 0, -- ^ 2 - XF type, cell protection, and parent style XF Horizontal_alignment'Pos(horizontal_align) + Boolean'Pos(wrap_text) * 8 + (Vertical_alignment'Pos(vertical_align) and 3) * 16 + Text_orientation'Pos(text_orient) * 64, -- ^ 4 - Alignment (hor & ver), text break, and text orientation 16#FF# -- ^ 3 - XF_USED_ATTRIB ) & -- ^ 4 - Horizontal alignment, text break, parent style XF Intel_16(area_code) & -- ^ 6 - XF_AREA_34 ( Boolean'Pos(border(top_single)), Boolean'Pos(border(left_single)), Boolean'Pos(border(bottom_single)), Boolean'Pos(border(right_single)) ) -- ^ 8 - XF_BORDER_34 - thin (=1) line; we could have other line styles: -- Thin, Medium, Dashed, Dotted, Thick, Double, Hair ); end Define_BIFF4_XF; begin -- 2.5.12 Patterns for Cell and Chart Background Area -- This is for BIFF3+ if shaded then area_code:= Boolean'Pos(shaded) * 17 + -- Sparse pattern, like BIFF2 "shade" 16#40# * color_code(BIFF3, black)(for_background) + -- pattern colour 16#800# * color_code(BIFF3, background_color)(for_background); -- pattern background elsif background_color = automatic then area_code:= 0; else area_code:= 1 + -- Full pattern 16#40# * color_code(BIFF3, background_color)(for_background) + -- pattern colour 16#800# * color_code(BIFF3, background_color)(for_background); -- pattern background end if; case xl.format is when BIFF2 => case actual_number_format is when general .. no_currency_2 => null; when currency_0 .. fraction_2 => actual_number_format:= actual_number_format - 4; when dd_mm_yyyy .. last_custom => actual_number_format:= actual_number_format - 6; when others => null; end case; Define_BIFF2_XF; when BIFF3 => if actual_number_format in currency_0 .. last_custom then actual_number_format:= actual_number_format - 4; end if; Define_BIFF3_XF; when BIFF4 => Define_BIFF4_XF; -- when BIFF8 => -- Define_BIFF8_XF; -- BIFF8: 16#00E0#, p. 224 end case; xl.xfs:= xl.xfs + 1; cell_format:= Format_type(xl.xfs); xl.xf_def(xl.xfs):= (font => font, numb => number_format); end Define_format; procedure Header(xl : Excel_Out_Stream; page_header_string: String) is begin WriteBiff(xl, 16#0014#, To_buf_8_bit_length(page_header_string)); -- 5.55 p.180 end Header; procedure Footer(xl : Excel_Out_Stream; page_footer_string: String) is begin WriteBiff(xl, 16#0015#, To_buf_8_bit_length(page_footer_string)); -- 5.48 p.173 end Footer; procedure Left_Margin(xl : Excel_Out_Stream; inches: Long_Float) is begin WriteBiff(xl, 16#0026#, IEEE_Double_Intel(inches)); end Left_Margin; procedure Right_Margin(xl : Excel_Out_Stream; inches: Long_Float) is begin WriteBiff(xl, 16#0027#, IEEE_Double_Intel(inches)); end Right_Margin; procedure Top_Margin(xl : Excel_Out_Stream; inches: Long_Float) is begin WriteBiff(xl, 16#0028#, IEEE_Double_Intel(inches)); end Top_Margin; procedure Bottom_Margin(xl : Excel_Out_Stream; inches: Long_Float) is begin WriteBiff(xl, 16#0029#, IEEE_Double_Intel(inches)); end Bottom_Margin; procedure Margins(xl : Excel_Out_Stream; left, right, top, bottom: Long_Float) is begin Left_Margin(xl, left); Right_Margin(xl, right); Top_Margin(xl, top); Bottom_Margin(xl, bottom); end Margins; procedure Print_Row_Column_Headers(xl : Excel_Out_Stream) is begin WriteBiff(xl, 16#002A#, Intel_16(1)); -- 5.81 PRINTHEADERS p.199 end Print_Row_Column_Headers; procedure Print_Gridlines(xl : Excel_Out_Stream) is begin WriteBiff(xl, 16#002B#, Intel_16(1)); -- 5.80 PRINTGRIDLINES p.199 end Print_Gridlines; procedure Page_Setup( xl : Excel_Out_Stream; scaling_percents : Positive:= 100; fit_width_with_n_pages : Natural:= 1; -- 0: as many as possible fit_height_with_n_pages: Natural:= 1; -- 0: as many as possible orientation : Orientation_choice:= portrait; scale_or_fit : Scale_or_fit_choice:= scale ) is begin -- 5.73 PAGESETUP p.192 - this is BIFF4+ (cheat if xl.format below)! WriteBiff(xl, 16#00A1#, Intel_16(0) & -- paper type undefined Intel_16(Unsigned_16(scaling_percents)) & Intel_16(1) & -- start page number Intel_16(Unsigned_16(fit_width_with_n_pages)) & Intel_16(Unsigned_16(fit_height_with_n_pages)) & Intel_16(2 * Orientation_choice'Pos(orientation)) ); -- 5.97 SHEETPR p.207 - this is BIFF3+ (cheat if xl.format below) ! -- NB: this field contains other informations, should be delayed -- in case other preferences are to be set WriteBiff(xl, 16#0081#, Intel_16(256 * Scale_or_fit_choice'Pos(scale_or_fit)) ); end Page_Setup; y_scale: constant:= 20; -- scaling to obtain character point (pt) units -- 5.31 DEFAULTROWHEIGHT procedure Write_default_row_height ( xl : Excel_Out_Stream; height : Positive ) is default_twips: constant Byte_buffer:= Intel_16(Unsigned_16(height * y_scale)); options_flags: constant Byte_buffer:= (1,0); -- 1 = Row height and default font height do not match begin case xl.format is when BIFF2 => WriteBiff(xl, 16#0025#, default_twips); when BIFF3 | BIFF4 => WriteBiff(xl, 16#0225#, options_flags & default_twips); end case; end Write_default_row_height; -- 5.32 DEFCOLWIDTH procedure Write_default_column_width ( xl : in out Excel_Out_Stream; width : Positive) is begin WriteBiff(xl, 16#0055#, Intel_16(Unsigned_16(width))); xl.defcolwdth:= 256 * width; end Write_default_column_width; procedure Write_column_width ( xl : in out Excel_Out_Stream; column : Positive; width : Natural) is begin Write_column_width(xl, column, column, width); end Write_column_width; procedure Write_column_width( xl : in out Excel_Out_Stream; first_column, last_column : Positive; width : Natural ) is begin case xl.format is when BIFF2 => -- 5.20 COLWIDTH (BIFF2 only) WriteBiff(xl, 16#0024#, Unsigned_8(first_column-1) & Unsigned_8(last_column-1) & Intel_16(Unsigned_16(width * 256))); when BIFF3 | BIFF4 => -- 5.18 COLINFO (BIFF3+) WriteBiff(xl, 16#007D#, Intel_16(Unsigned_16(first_column-1)) & Intel_16(Unsigned_16(last_column-1)) & Intel_16(Unsigned_16(width * 256)) & Intel_16(0) & -- Index to XF record (5.115) for default column formatting Intel_16(0) & -- Option flags (0,0) -- Not used ); for j in first_column .. last_column loop xl.std_col_width(j):= False; end loop; end case; end Write_column_width; -- 5.88 ROW -- The OpenOffice documentation tells nice stories about row blocks, -- but single ROW commands can also be put before in the data stream, -- where the column widths are set. Excel saves with blocks of ROW -- commands, most of them useless. procedure Write_row_height( xl : Excel_Out_Stream; row : Positive; height : Natural ) is row_info_base: Byte_buffer:= Intel_16(Unsigned_16(row - 1)) & Intel_16(0) & -- col. min. Intel_16(255) & -- col. max. Intel_16(Unsigned_16(height * y_scale)); fDyZero: Unsigned_8:= 0; begin case xl.format is when BIFF2 => WriteBiff(xl, 16#0008#, row_info_base & (1..3 => 0) & Intel_16(0) -- offset to data ); when BIFF3 | BIFF4 => if height = 0 then -- proper hiding (needed with LibreOffice) fDyZero:= 1; row_info_base(row_info_base'Last - 1 .. row_info_base'Last):= Intel_16(16#8000#); end if; WriteBiff(xl, 16#0208#, row_info_base & -- http://msdn.microsoft.com/en-us/library/dd906757(v=office.12).aspx (0, 0, -- reserved1 (2 bytes): MUST be zero, and MUST be ignored. 0, 0, -- unused1 (2 bytes): Undefined and MUST be ignored. fDyZero * 32 + -- D - fDyZero (1 bit): row is hidden 1 * 64 + -- E - fUnsynced (1 bit): row height was manually set 0 * 128, -- F - fGhostDirty (1 bit): the row was formatted 1) & -- reserved3 (1 byte): MUST be 1, and MUST be ignored Intel_16(15) -- ^ ixfe_val, then 4 bits. -- If fGhostDirty is 0, ixfe_val is undefined and MUST be ignored. ); end case; end Write_row_height; -- 5.45 FONT, p.171 procedure Define_font( xl : in out Excel_Out_Stream; font_name : String; height : Positive; font : out Font_type; style : Font_style:= regular; color : Color_type:= automatic ) is style_bits, mask: Unsigned_16; begin style_bits:= 0; mask:= 1; for s in Font_style_single loop if style(s) then style_bits:= style_bits + mask; end if; mask:= mask * 2; end loop; xl.fonts:= xl.fonts + 1; if xl.fonts = 4 then xl.fonts:= 5; -- Anomaly! The font with index 4 is omitted in all BIFF versions. -- Numbering is 0, 1, 2, 3, *5*, 6,... end if; case xl.format is when BIFF2 => WriteBiff(xl, 16#0031#, Intel_16(Unsigned_16(height * y_scale)) & Intel_16(style_bits) & To_buf_8_bit_length(font_name) ); if color /= automatic then -- 5.47 FONTCOLOR WriteBiff(xl, 16#0045#, Intel_16(color_code(BIFF2, color)(for_font))); end if; when BIFF3 | BIFF4 => -- BIFF8 has 16#0031#, p. 171 WriteBiff(xl, 16#0231#, Intel_16(Unsigned_16(height * y_scale)) & Intel_16(style_bits) & Intel_16(color_code(BIFF3, color)(for_font)) & To_buf_8_bit_length(font_name) ); end case; font:= Font_type(xl.fonts); end Define_font; procedure Jump_to_and_store_max(xl: in out Excel_Out_Stream; r, c: Integer) is pragma Inline(Jump_to_and_store_max); begin if not xl.is_created then raise Excel_stream_not_created; end if; Jump_to(xl, r, c); -- Store and check current position if r > xl.maxrow then xl.maxrow := r; end if; if c > xl.maxcolumn then xl.maxcolumn := c; end if; end Jump_to_and_store_max; -- 2.5.13 Cell Attributes (BIFF2 only) function Cell_attributes(xl: Excel_Out_Stream) return Byte_buffer is begin return (Unsigned_8(xl.xf_in_use), Unsigned_8(xl.xf_def(xl.xf_in_use).numb) + 16#40# * Unsigned_8(xl.xf_def(xl.xf_in_use).font), 0 ); end Cell_attributes; function Almost_zero(x: Long_Float) return Boolean is begin return abs x <= Long_Float'Model_Small; end Almost_zero; -- Internal -- -- 5.71 NUMBER procedure Write_as_double ( xl : in out Excel_Out_Stream; r, c : Positive; num : Long_Float ) is pragma Inline(Write_as_double); begin Jump_to_and_store_max(xl, r, c); case xl.format is when BIFF2 => WriteBiff(xl, 16#0003#, Intel_16(Unsigned_16(r-1)) & Intel_16(Unsigned_16(c-1)) & Cell_attributes(xl) & IEEE_Double_Intel(num) ); when BIFF3 | BIFF4 => WriteBiff(xl, 16#0203#, Intel_16(Unsigned_16(r-1)) & Intel_16(Unsigned_16(c-1)) & Intel_16(Unsigned_16(xl.xf_in_use)) & IEEE_Double_Intel(num) ); end case; Jump_to(xl, r, c+1); -- Store and check new position end Write_as_double; -- Internal. This is BIFF2 only. BIFF format choice unchecked here. -- procedure Write_as_16_bit_unsigned ( xl : in out Excel_Out_Stream; r, c : Positive; num : Unsigned_16) is pragma Inline(Write_as_16_bit_unsigned); begin Jump_to_and_store_max(xl, r, c); -- 5.60 INTEGER WriteBiff(xl, 16#0002#, Intel_16(Unsigned_16(r-1)) & Intel_16(Unsigned_16(c-1)) & Cell_attributes(xl) & Intel_16(num) ); Jump_to(xl, r, c+1); -- Store and check new position end Write_as_16_bit_unsigned; -- Internal. This is BIFF3+. BIFF format choice unchecked here. -- procedure Write_as_30_bit_signed ( xl : in out Excel_Out_Stream; r, c : Positive; num : Integer_32) is pragma Inline(Write_as_30_bit_signed); RK_val: Unsigned_32; RK_code: constant:= 2; -- Code for signed integer. See 2.5.5 RK Values begin if num >= 0 then RK_val:= Unsigned_32(num) * 4 + RK_code; else RK_val:= (-Unsigned_32(-num)) * 4 + RK_code; end if; Jump_to_and_store_max(xl, r, c); -- 5.87 RK WriteBiff(xl, 16#027E#, Intel_16(Unsigned_16(r-1)) & Intel_16(Unsigned_16(c-1)) & Intel_16(Unsigned_16(xl.xf_in_use)) & Intel_32(RK_val) ); Jump_to(xl, r, c+1); -- Store and check new position end Write_as_30_bit_signed; -- -- Profile with floating-point number -- procedure Write ( xl : in out Excel_Out_Stream; r, c : Positive; num : Long_Float ) is max_16_u: constant:= 2.0 ** 16 - 1.0; min_30_s: constant:= -(2.0 ** 29); max_30_s: constant:= 2.0 ** 29 - 1.0; begin case xl.format is when BIFF2 => if num >= 0.0 and then num <= max_16_u and then Almost_zero(num - Long_Float'Floor(num)) then Write_as_16_bit_unsigned(xl, r, c, Unsigned_16(Long_Float'Floor(num))); else Write_as_double(xl, r, c, num); end if; when BIFF3 | BIFF4 => if num >= min_30_s and then num <= max_30_s and then Almost_zero(num - Long_Float'Floor(num)) then Write_as_30_bit_signed(xl, r, c, Integer_32(Long_Float'Floor(num))); else Write_as_double(xl, r, c, num); end if; end case; end Write; -- -- Profile with integer number -- procedure Write ( xl : in out Excel_Out_Stream; r, c : Positive; num : Integer) is begin -- We use an integer representation (and small storage) if possible; -- we need to use a floating-point in all other cases case xl.format is when BIFF2 => if num in 0..2**16-1 then Write_as_16_bit_unsigned(xl, r, c, Unsigned_16(num)); else Write_as_double(xl, r, c, Long_Float(num)); end if; when BIFF3 | BIFF4 => if num in -2**29..2**29-1 then Write_as_30_bit_signed(xl, r, c, Integer_32(num)); else Write_as_double(xl, r, c, Long_Float(num)); end if; end case; end Write; -- -- Function taken from Wasabee.Encoding. -- function ISO_8859_1_to_UTF_16(s: String) return Wide_String is -- -- This conversion is a trivial 8-bit to 16-bit copy. -- r: Wide_String(s'Range); -- begin -- for i in s'Range loop -- r(i):= Wide_Character'Val(Character'Pos(s(i))); -- end loop; -- return r; -- end ISO_8859_1_to_UTF_16; -- 5.63 LABEL procedure Write ( xl : in out Excel_Out_Stream; r, c : Positive; str : String) is begin Jump_to_and_store_max(xl, r, c); if str'Length > 0 then case xl.format is when BIFF2 => WriteBiff(xl, 16#0004#, Intel_16(Unsigned_16(r-1)) & Intel_16(Unsigned_16(c-1)) & Cell_attributes(xl) & To_buf_8_bit_length(str) ); when BIFF3 | BIFF4 => WriteBiff(xl, 16#0204#, Intel_16(Unsigned_16(r-1)) & Intel_16(Unsigned_16(c-1)) & Intel_16(Unsigned_16(xl.xf_in_use)) & To_buf_16_bit_length(str) ); -- when BIFF8 => -- WriteBiff(xl, 16#0204#, -- Intel_16(Unsigned_16(r-1)) & -- Intel_16(Unsigned_16(c-1)) & -- Intel_16(Unsigned_16(xl.xf_in_use)) & -- To_buf_16_bit_length(ISO_8859_1_to_UTF_16(str)) -- ); end case; end if; Jump_to(xl, r, c+1); -- Store and check new position end Write; procedure Write(xl: in out Excel_Out_Stream; r,c : Positive; str : Unbounded_String) is begin Write(xl, r,c, To_String(str)); end Write; -- Excel uses a floating-point type for time - ouch! -- function To_Number(date: Time) return Long_Float is -- 1901 is the lowest year supported by Ada.Calendar. -- 1900 is not a leap year, but Lotus 1-2-3, then Excel, consider it -- as a leap year. So, with 1901, we skip that issue anyway... -- function Days_since_1901 (y, m, d : Integer) return Integer is function Is_leap (y: Integer) return Boolean is begin if y mod 4 = 0 then if y mod 100 = 0 then if y mod 400 = 0 then return True; else return False; end if; else return True; end if; else return False; end if; end Is_leap; days_of_previous_months : Integer; days_of_previous_years : Integer; y_diff, y_diff_4, y_diff_100, y_diff_400 : Integer; begin case m is when 02 => days_of_previous_months := 31; when 03 => days_of_previous_months := 59; when 04 => days_of_previous_months := 90; when 05 => days_of_previous_months := 120; when 06 => days_of_previous_months := 151; when 07 => days_of_previous_months := 181; when 08 => days_of_previous_months := 212; when 09 => days_of_previous_months := 243; when 10 => days_of_previous_months := 273; when 11 => days_of_previous_months := 304; when 12 => days_of_previous_months := 334; when others => days_of_previous_months := 0; end case; if m > 2 and then Is_leap (y) then -- February has 29 days in leap years. days_of_previous_months := days_of_previous_months + 1; end if; -- y_diff := (y - 1) - 1900; y_diff_4 := (y - 1) / 4 - 1900 / 4; y_diff_100 := (y - 1) / 100 - 1900 / 100; y_diff_400 := (y - 1) / 400 - 1900 / 400; -- Add extra days of leap years from 1901 (included) to year y (excluded). days_of_previous_years := 365 * y_diff + y_diff_4 - y_diff_100 + y_diff_400; -- return days_of_previous_years + days_of_previous_months + d - 1; end Days_since_1901; -- sec : constant Day_Duration := Seconds (date); begin -- With GNAT and perhaps other systems, Duration's range allows the following: -- return Long_Float(date - Time_Of(1901, 01, 01, 0.0)) / 86_400.0 + 367.0; -- With ObjectAda and perhaps other systems, we need to count days since 1900 ourselves. return Long_Float (sec) / 86_400.0 + Long_Float (Days_since_1901 (Year (date), Month (date), Day (date))) + 367.0; -- Days from 1899-12-31 to 1901-01-01. -- Lotus 1-2-3, then Excel, are based on 1899-12-31 (and believe it is 1900-01-01). end To_Number; procedure Write(xl: in out Excel_Out_Stream; r,c : Positive; date: Time) is begin Write(xl, r,c, To_Number(date)); end Write; -- Ada.Text_IO - like. No need to specify row & column each time procedure Put(xl: in out Excel_Out_Stream; num : Long_Float) is begin Write(xl, xl.curr_row, xl.curr_col, num); end Put; procedure Put(xl : in out Excel_Out_Stream; num : in Integer; width : in Ada.Text_IO.Field := 0; -- ignored base : in Ada.Text_IO.Number_Base := 10 ) is begin if base = 10 then Write(xl, xl.curr_row, xl.curr_col, num); else declare use Ada.Strings.Fixed; s: String(1..50 + 0*width); -- 0*width is just to skip a warning of width being unused package IIO is new Ada.Text_IO.Integer_IO(Integer); begin IIO.Put(s, num, Base => base); Put(xl, Trim(s, Ada.Strings.Left)); end; end if; end Put; procedure Put(xl: in out Excel_Out_Stream; str : String) is begin Write(xl, xl.curr_row, xl.curr_col, str); end Put; procedure Put(xl: in out Excel_Out_Stream; str : Unbounded_String) is begin Put(xl, To_String(str)); end Put; procedure Put(xl: in out Excel_Out_Stream; date: Time) is begin Put(xl, To_Number(date)); end Put; procedure Merge(xl: in out Excel_Out_Stream; cells : Positive) is -- 5.7 BLANK procedure Blank (r, c: Positive) is begin Jump_to_and_store_max(xl, r, c); case xl.format is -- NB: Only with BIFF4, and only OpenOffice -- considers the cells really merged. when BIFF2 => WriteBiff(xl, 16#0001#, Intel_16(Unsigned_16(r-1)) & Intel_16(Unsigned_16(c-1)) & Cell_attributes(xl) ); when BIFF3 | BIFF4 => WriteBiff(xl, 16#0201#, Intel_16(Unsigned_16(r-1)) & Intel_16(Unsigned_16(c-1)) & Intel_16(Unsigned_16(xl.xf_in_use)) ); end case; Jump_to(xl, r, c+1); -- Store and check new position end Blank; begin for i in 1..cells loop Blank(xl.curr_row, xl.curr_col); end loop; end Merge; procedure Write_cell_comment(xl: Excel_Out_Stream; row, column: Positive; text: String) is begin if text'Length >= 2048 then raise Constraint_Error; end if; -- 5.70 Note case xl.format is -- when BIFF8 => -- https://msdn.microsoft.com/en-us/library/dd945371(v=office.12).aspx -- WriteBiff(xl, 16#001C#, -- Intel_16(Unsigned_16(row-1)) & -- Intel_16(Unsigned_16(column-1)) & -- (0, 0) & -- Show / hide options -- (0, 0) -- idObj - it begins to be tough there... -- ); when others => WriteBiff(xl, 16#001C#, Intel_16(Unsigned_16(row-1)) & Intel_16(Unsigned_16(column-1)) & To_buf_16_bit_length(text) ); end case; end Write_cell_comment; procedure Write_cell_comment_at_cursor(xl: Excel_Out_Stream; text: String) is begin Write_cell_comment(xl, Row(xl), Column(xl), text); end Write_cell_comment_at_cursor; procedure Put_Line(xl: in out Excel_Out_Stream; num : Long_Float) is begin Put(xl, num); New_Line(xl); end Put_Line; procedure Put_Line(xl: in out Excel_Out_Stream; num : Integer) is begin Put(xl, num); New_Line(xl); end Put_Line; procedure Put_Line(xl: in out Excel_Out_Stream; str : String) is begin Put(xl, str); New_Line(xl); end Put_Line; procedure Put_Line(xl: in out Excel_Out_Stream; str : Unbounded_String) is begin Put_Line(xl, To_String(str)); end Put_Line; procedure Put_Line(xl: in out Excel_Out_Stream; date: Time) is begin Put(xl, date); New_Line(xl); end Put_Line; procedure New_Line(xl: in out Excel_Out_Stream; Spacing : Positive := 1) is begin Jump_to(xl, xl.curr_row + Spacing, 1); end New_Line; function Col(xl: in Excel_Out_Stream) return Positive is begin return xl.curr_col; end Col; function Column(xl: in Excel_Out_Stream) return Positive renames Col; function Line(xl: in Excel_Out_Stream) return Positive is begin return xl.curr_row; end Line; function Row(xl: in Excel_Out_Stream) return Positive renames Line; -- Relative / absolute jumps procedure Jump(xl: in out Excel_Out_Stream; rows, columns: Natural) is begin Jump_to(xl, xl.curr_row + rows, xl.curr_col + columns); end Jump; procedure Jump_to(xl: in out Excel_Out_Stream; row, column: Positive) is begin if row < xl.curr_row then -- trying to overwrite cells ?... raise Decreasing_row_index; end if; if row = xl.curr_row and then column < xl.curr_col then -- trying to overwrite cells on same row ?... raise Decreasing_column_index; end if; if row > 65536 then raise Row_out_of_range; elsif column > 256 then raise Column_out_of_range; end if; xl.curr_row:= row; xl.curr_col:= column; end Jump_to; procedure Next (xl: in out Excel_Out_Stream; columns: Natural:= 1) is begin Jump(xl, rows => 0, columns => columns); end Next; procedure Next_Row (xl: in out Excel_Out_Stream; rows: Natural:= 1) is begin Jump(xl, rows => rows, columns => 0); end Next_Row; procedure Use_format( xl : in out Excel_Out_Stream; format : in Format_type ) is begin xl.xf_in_use:= XF_Range(format); end Use_format; procedure Use_default_format(xl: in out Excel_Out_Stream) is begin Use_format(xl, xl.def_fmt); end Use_default_format; function Default_font(xl: Excel_Out_Stream) return Font_type is begin return xl.def_font; end Default_font; function Default_format(xl: Excel_Out_Stream) return Format_type is begin return xl.def_fmt; end Default_format; procedure Freeze_Panes(xl: in out Excel_Out_Stream; row, column: Positive) is begin xl.frz_panes:= True; xl.freeze_row:= row; xl.freeze_col:= column; end Freeze_Panes; procedure Freeze_Panes_at_cursor(xl: in out Excel_Out_Stream) is begin Freeze_Panes(xl, xl.curr_row, xl.curr_col); end Freeze_Panes_at_cursor; procedure Freeze_Top_Row(xl: in out Excel_Out_Stream) is begin Freeze_Panes(xl, 2, 1); end Freeze_Top_Row; procedure Freeze_First_Column(xl: in out Excel_Out_Stream) is begin Freeze_Panes(xl, 1, 2); end Freeze_First_Column; procedure Zoom_level(xl: in out Excel_Out_Stream; numerator, denominator: Positive) is begin xl.zoom_num:= numerator; xl.zoom_den:= denominator; end Zoom_level; procedure Reset( xl : in out Excel_Out_Stream'Class; excel_format : Excel_type; encoding : Encoding_type ) is dummy_xl_with_defaults: Excel_Out_Pre_Root_Type; begin -- Check if we are trying to re-use a half-finished object (ouch!): if xl.is_created and not xl.is_closed then raise Excel_stream_not_closed; end if; -- We will reset everything with defaults, except this: dummy_xl_with_defaults.format := excel_format; dummy_xl_with_defaults.encoding := encoding; -- Now we reset xl: Excel_Out_Pre_Root_Type(xl):= dummy_xl_with_defaults; end Reset; procedure Finish(xl : in out Excel_Out_Stream'Class) is procedure Write_Window1 is begin -- 5.109 WINDOW1, p. 215 case xl.format is when BIFF2 | BIFF3 | BIFF4 => -- NB: more options in BIFF8 WriteBiff(xl, 16#003D#, Intel_16(120) & -- Window x Intel_16(120) & -- Window y Intel_16(21900) & -- Window w Intel_16(13425) & -- Window h Intel_16(0) -- Hidden ); end case; end Write_Window1; procedure Write_Window2 is begin -- 5.110 WINDOW2 case xl.format is when BIFF2 => WriteBiff(xl, 16#003E#, (0, -- Display formulas, not results 1, -- Show grid lines 1, -- Show sheet headers Boolean'Pos(xl.frz_panes), 1 -- Show zero values as zeros, not empty cells ) & Intel_16(0) & -- First visible row Intel_16(0) & -- First visible column (1, -- Use automatic grid line colour 0,0,0,0) -- Grid line RGB colour ); when BIFF3 | BIFF4 => -- NB: more options in BIFF8 WriteBiff(xl, 16#023E#, -- http://msdn.microsoft.com/en-us/library/dd947893(v=office.12).aspx Intel_16( -- Option flags: 0 * 1 + -- Display formulas, not results 1 * 2 + -- Show grid lines 1 * 4 + -- Show sheet headers Boolean'Pos(xl.frz_panes) * 8 + -- Panes are frozen 1 * 16 + -- Show zero values as zeros, not empty cells 1 * 32 + -- Gridlines of the window drawn in the default window foreground color 0 * 64 + -- Right-to-left mode 1 * 128 + -- Show outlines (guts ?!) 0 * 256 -- Frozen, not split ) & Intel_16(0) & -- First visible row Intel_16(0) & -- First visible column Intel_32(0) -- Grid line colour ); end case; end Write_Window2; procedure Write_Pane is active_pane: Unsigned_8; begin if xl.freeze_col = 1 then if xl.freeze_row = 1 then active_pane:= 3; else active_pane:= 2; end if; else if xl.freeze_row = 1 then active_pane:= 1; else active_pane:= 0; end if; end if; -- 5.75 PANE WriteBiff(xl, 16#0041#, Intel_16(Unsigned_16(xl.freeze_col) - 1) & Intel_16(Unsigned_16(xl.freeze_row) - 1) & Intel_16(Unsigned_16(xl.freeze_row) - 1) & Intel_16(Unsigned_16(xl.freeze_col) - 1) & ( 1 => active_pane ) ); end Write_Pane; col_bits: Byte_buffer(1..32):= (others => 0); byte_idx, bit_idx: Positive:= 1; begin -- Calling Window1 and Window2 is not necessary for default settings, but without these calls, -- a Write_row_height call with a positive height results, on all MS Excel versions, in a -- completely blank row, including the header letters - clearly an Excel bug ! Write_Window1; Write_Window2; -- 5.92 SCL = Zoom, Magnification. Defined for BIFF4+ only, but works with BIFF2, BIFF3. WriteBiff(xl, 16#00A0#, Intel_16(Unsigned_16(xl.zoom_num)) & Intel_16(Unsigned_16(xl.zoom_den)) ); if xl.frz_panes and xl.format > BIFF2 then -- Enabling PANE for BIFF2 causes a very strange behaviour on MS Excel 2002. Write_Pane; end if; -- 5.93 SELECTION here !! if xl.format >= BIFF4 then for i in 1..256 loop col_bits(byte_idx):= col_bits(byte_idx) + Boolean'Pos(xl.std_col_width(i)) * (2**(bit_idx-1)); bit_idx:= bit_idx + 1; if bit_idx = 9 then bit_idx:= 1; byte_idx:= byte_idx + 1; end if; end loop; -- 5.51 GCW: Global Column Width - trying to get a correct display by LibreOffice -- Result: OK but useless on MS Excel, not working on LibreOffice :-( WriteBiff(xl, 16#00AB#, Intel_16(32) & col_bits); -- if xl.defcolwdth > 0 then -- -- 5.101 STANDARDWIDTH -- this confuses MS Excel... -- WriteBiff(xl, 16#0099#, Intel_16(Unsigned_16(xl.defcolwdth))); -- end if; end if; -- 5.37 EOF: End of File: WriteBiff(xl, 16#000A#, empty_buffer); Set_Index(xl, xl.dimrecpos); -- Go back to overwrite the DIMENSION record with correct data Write_Dimensions(xl); xl.is_closed:= True; end Finish; ---------------------- -- Output to a file -- ---------------------- procedure Create( xl : in out Excel_Out_File; file_name : String; excel_format : Excel_type := Default_Excel_type; encoding : Encoding_type := Default_encoding ) is begin Reset(xl, excel_format, encoding); xl.xl_file:= new Ada.Streams.Stream_IO.File_Type; Create(xl.xl_file.all, Out_File, file_name); xl.xl_stream:= XL_Raw_Stream_Class(Stream(xl.xl_file.all)); Write_Worksheet_header(xl); end Create; procedure Close(xl : in out Excel_Out_File) is procedure Dispose is new Ada.Unchecked_Deallocation(Ada.Streams.Stream_IO.File_Type, XL_file_acc); begin Finish(xl); Close(xl.xl_file.all); Dispose(xl.xl_file); end Close; -- Set the index on the file procedure Set_Index (xl: in out Excel_Out_File; To: Ada.Streams.Stream_IO.Positive_Count) is begin Ada.Streams.Stream_IO.Set_Index(xl.xl_file.all, To); end Set_Index; -- Return the index of the file function Index (xl: Excel_Out_File) return Ada.Streams.Stream_IO.Count is begin return Ada.Streams.Stream_IO.Index(xl.xl_file.all); end Index; function Is_Open(xl : in Excel_Out_File) return Boolean is begin if xl.xl_file = null then return False; end if; return Ada.Streams.Stream_IO.Is_Open(xl.xl_file.all); end Is_Open; ------------------------ -- Output to a string -- ------------------------ -- Code reused from Zip_Streams procedure Read (Stream : in out Unbounded_Stream; Item : out Stream_Element_Array; Last : out Stream_Element_Offset) is begin -- Item is read from the stream. If (and only if) the stream is -- exhausted, Last will be < Item'Last. In that case, T'Read will -- raise an End_Error exception. -- -- Cf: RM 13.13.1(8), RM 13.13.1(11), RM 13.13.2(37) and -- explanations by Tucker Taft -- Last:= Item'First - 1; -- if Item is empty, the following loop is skipped; if Stream.Loc -- is already indexing out of Stream.Unb, that value is also appropriate for i in Item'Range loop Item(i) := Character'Pos (Element(Stream.Unb, Stream.Loc)); Stream.Loc := Stream.Loc + 1; Last := i; end loop; exception when Ada.Strings.Index_Error => null; -- what could be read has been read; T'Read will raise End_Error end Read; procedure Write (Stream : in out Unbounded_Stream; Item : Stream_Element_Array) is begin for I in Item'Range loop if Length(Stream.Unb) < Stream.Loc then Append(Stream.Unb, Character'Val(Item(I))); else Replace_Element(Stream.Unb, Stream.Loc, Character'Val(Item(I))); end if; Stream.Loc := Stream.Loc + 1; end loop; end Write; procedure Set_Index (S : access Unbounded_Stream; To : Positive) is begin if Length(S.Unb) < To then for I in Length(S.Unb) .. To loop Append(S.Unb, ASCII.NUL); end loop; end if; S.Loc := To; end Set_Index; function Index (S : access Unbounded_Stream) return Integer is begin return S.Loc; end Index; --- *** procedure Create( xl : in out Excel_Out_String; excel_format : Excel_type := Default_Excel_type; encoding : Encoding_type := Default_encoding ) is begin Reset(xl, excel_format, encoding); xl.xl_memory:= new Unbounded_Stream; xl.xl_memory.Unb:= Null_Unbounded_String; xl.xl_memory.Loc:= 1; xl.xl_stream:= XL_Raw_Stream_Class(xl.xl_memory); Write_Worksheet_header(xl); end Create; procedure Close(xl : in out Excel_Out_String) is begin Finish(xl); end Close; function Contents(xl: Excel_Out_String) return String is begin if not xl.is_closed then raise Excel_stream_not_closed; end if; return To_String(xl.xl_memory.Unb); end Contents; -- Set the index on the Excel string stream procedure Set_Index (xl: in out Excel_Out_String; To: Ada.Streams.Stream_IO.Positive_Count) is begin Set_Index(xl.xl_memory, Integer(To)); end Set_Index; -- Return the index of the Excel string stream function Index (xl: Excel_Out_String) return Ada.Streams.Stream_IO.Count is begin return Ada.Streams.Stream_IO.Count(Index(xl.xl_memory)); end Index; function "&"(a,b: Font_style) return Font_style is begin return a or b; -- "or" is predefined for sets (=array of Boolean) end "&"; function "&"(a,b: Cell_border) return Cell_border is begin return a or b; -- "or" is predefined for sets (=array of Boolean) end "&"; end Excel_Out;
package Count_Subprogram is procedure P2A (x, y : Integer); procedure P2B (x : Integer; y : Integer); procedure P4A (k, l, m, n : Integer); procedure P4B (k : Integer; l : Integer; m : Integer; n : Integer); procedure P3A (x, y, z : Integer); procedure P3B (x, y : Integer; z : Integer); procedure P3C (x : Integer; y, z : Integer); procedure P3D (x : Integer; y : Integer; z : Integer); procedure P3E (x, y, z : Integer) is null; procedure P3F (x : Integer; y : Integer; z : Integer) is null; procedure P3G (x : Integer := 0; y : Integer := 1; z : Integer := 2); procedure P3H (x, y, z : Integer := 0); procedure P3I (x, y, z : in Integer); procedure P3J (x, y, z : in out Integer); procedure P3K (x, y, z : out Integer); procedure P3L (x, y, z : Integer) renames P3A; procedure P3M (a, b, c : Integer) renames P3A; generic type Element_T is private; procedure P3N (x, y, z : Element_T); generic type Element_T is private; procedure P3O (x : Element_T; y : Element_T; z : Element_T); generic with procedure P3P (x, y, z : Integer); with procedure P3Q (x : Integer; y : Integer; z : Integer); package My_Package is end My_Package; type Callback_Procedure_A is access procedure (x, y, z : Integer); type Callback_Procedure_B is access procedure (x : Integer; y : Integer; z : Integer); procedure S1 (Call_Back : access procedure (x, y, z : Integer)); procedure S2 (Call_Back : access procedure (x : Integer; y : Integer; z : Integer)); function F3A (x, y, z : Integer) return Integer is (x + y + z); function F3B (x : Integer; y : Integer; z : Integer) return Integer is (x + y + z); function F3Z (x, y, z : Integer) return Integer; private function F3Z (x, y, z : Integer) return Integer is (x + y + z); end Count_Subprogram;
package body Ada.Streams.Stream_IO.Naked is procedure Open ( File : in out File_Type; Mode : File_Mode; Handle : System.Native_IO.Handle_Type; Name : String := ""; Form : System.Native_IO.Packed_Form := Naked_Stream_IO.Default_Form; To_Close : Boolean := False) is NC_File : Naked_Stream_IO.Non_Controlled_File_Type renames Controlled.Reference (File).all; begin Naked_Stream_IO.Open ( NC_File, IO_Modes.File_Mode (Mode), Handle, Name => Name, Form => Form, To_Close => To_Close); end Open; function Handle (File : File_Type) return System.Native_IO.Handle_Type is NC_File : Naked_Stream_IO.Non_Controlled_File_Type renames Controlled.Reference (File).all; begin return Naked_Stream_IO.Handle (NC_File); end Handle; end Ada.Streams.Stream_IO.Naked;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015-2016, 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 Ada.Unchecked_Conversion; with STM32.DMA2D.Interrupt; with STM32.DMA2D.Polling; with STM32.SDRAM; use STM32.SDRAM; package body Framebuffer_LTDC is procedure Internal_Update_Layer (Display : in out Frame_Buffer; Layer : Positive); ---------------- -- Initialize -- ---------------- procedure Initialize (Display : in out Frame_Buffer; Width : Positive; Height : Positive; H_Sync : Natural; H_Back_Porch : Natural; H_Front_Porch : Natural; V_Sync : Natural; V_Back_Porch : Natural; V_Front_Porch : Natural; PLLSAI_N : UInt9; PLLSAI_R : UInt3; DivR : Natural; Orientation : HAL.Framebuffer.Display_Orientation := Default; Mode : HAL.Framebuffer.Wait_Mode := Interrupt) is begin Display.Width := Width; Display.Height := Height; if (Width > Height and then Orientation = Portrait) or else (Height > Width and then Orientation = Landscape) then Display.Swapped := True; else Display.Swapped := False; end if; STM32.LTDC.Initialize (Width => Width, Height => Height, H_Sync => H_Sync, H_Back_Porch => H_Back_Porch, H_Front_Porch => H_Front_Porch, V_Sync => V_Sync, V_Back_Porch => V_Back_Porch, V_Front_Porch => V_Front_Porch, PLLSAI_N => PLLSAI_N, PLLSAI_R => PLLSAI_R, DivR => DivR); STM32.SDRAM.Initialize; case Mode is when Polling => STM32.DMA2D.Polling.Initialize; when Interrupt => STM32.DMA2D.Interrupt.Initialize; end case; end Initialize; --------------------- -- Set_Orientation -- --------------------- overriding procedure Set_Orientation (Display : in out Frame_Buffer; Orientation : HAL.Framebuffer.Display_Orientation) is Old : constant Boolean := Display.Swapped; Tmp : Natural; use STM32.DMA2D_Bitmap; begin if (Display.Width > Display.Height and then Orientation = Portrait) or else (Display.Height > Display.Width and then Orientation = Landscape) then Display.Swapped := True; else Display.Swapped := False; end if; if Old = Display.Swapped then return; end if; for Layer in STM32.LTDC.LCD_Layer loop for Buf in 1 .. 2 loop if Display.Buffers (Layer, Buf) /= Null_Buffer then Display.Buffers (Layer, Buf).Currently_Swapped := Display.Swapped; Tmp := Display.Buffers (Layer, Buf).Actual_Width; Display.Buffers (Layer, Buf).Actual_Width := Display.Buffers (Layer, Buf).Height; Display.Buffers (Layer, Buf).Actual_Height := Tmp; Display.Buffers (Layer, Buf).Set_Source (HAL.Bitmap.Black); Display.Buffers (Layer, Buf).Fill; end if; end loop; end loop; end Set_Orientation; -------------- -- Set_Mode -- -------------- overriding procedure Set_Mode (Display : in out Frame_Buffer; Mode : HAL.Framebuffer.Wait_Mode) is pragma Unreferenced (Display); begin case Mode is when Polling => STM32.DMA2D.Polling.Initialize; when Interrupt => STM32.DMA2D.Interrupt.Initialize; end case; end Set_Mode; ----------------- -- Initialized -- ----------------- overriding function Initialized (Display : Frame_Buffer) return Boolean is pragma Unreferenced (Display); begin return STM32.LTDC.Initialized; end Initialized; ---------------- -- Max_Layers -- ---------------- overriding function Max_Layers (Display : Frame_Buffer) return Positive is pragma Unreferenced (Display); begin return 2; end Max_Layers; --------------- -- Supported -- --------------- overriding function Supported (Display : Frame_Buffer; Mode : HAL.Framebuffer.FB_Color_Mode) return Boolean is pragma Unreferenced (Display, Mode); begin -- The LTDC supports all HAL color modes return True; end Supported; ----------- -- Width -- ----------- overriding function Width (Display : Frame_Buffer) return Positive is begin if not Display.Swapped then return Display.Width; else return Display.Height; end if; end Width; ------------ -- Height -- ------------ overriding function Height (Display : Frame_Buffer) return Positive is begin if not Display.Swapped then return Display.Height; else return Display.Width; end if; end Height; ------------- -- Swapped -- ------------- overriding function Swapped (Display : Frame_Buffer) return Boolean is begin return Display.Swapped; end Swapped; -------------------- -- Set_Background -- -------------------- overriding procedure Set_Background (Display : Frame_Buffer; R, G, B : UInt8) is pragma Unreferenced (Display); begin STM32.LTDC.Set_Background (R, G, B); end Set_Background; ---------------------- -- Initialize_Layer -- ---------------------- overriding procedure Initialize_Layer (Display : in out Frame_Buffer; Layer : Positive; Mode : HAL.Framebuffer.FB_Color_Mode; X : Natural := 0; Y : Natural := 0; Width : Positive := Positive'Last; Height : Positive := Positive'Last) is LCD_Layer : constant STM32.LTDC.LCD_Layer := (if Layer = 1 then STM32.LTDC.Layer1 else STM32.LTDC.Layer2); W : Natural := Width; H : Natural := Height; X0 : Natural := X; Y0 : Natural := Y; begin if Display.Swapped then if Height = Positive'Last then W := Display.Width; else W := Height; end if; if Width = Positive'Last then H := Display.Height; else H := Width; end if; X0 := Y; Y0 := Display.Height - X - H; end if; if X0 >= Display.Width then raise Constraint_Error with "Layer X position outside of screen"; elsif Y0 >= Display.Height then raise Constraint_Error with "Layer Y position outside of screen"; end if; if W = Positive'Last or else X0 + W > Display.Width then W := Display.Width - X0; end if; if H = Positive'Last or else Y0 + H > Display.Height then H := Display.Height - Y0; end if; if not Display.Swapped then for Buf in 1 .. 2 loop Display.Buffers (LCD_Layer, Buf) := (Addr => Reserve (UInt32 (HAL.Bitmap.Bits_Per_Pixel (Mode) * W * H / 8)), Actual_Width => W, Actual_Height => H, Actual_Color_Mode => Mode, Currently_Swapped => False, Native_Source => 0); Display.Buffers (LCD_Layer, Buf).Set_Source (HAL.Bitmap.Black); Display.Buffers (LCD_Layer, Buf).Fill; end loop; else for Buf in 1 .. 2 loop Display.Buffers (LCD_Layer, Buf) := (Addr => Reserve (UInt32 (HAL.Bitmap.Bits_Per_Pixel (Mode) * W * H / 8)), Actual_Width => H, Actual_Height => W, Actual_Color_Mode => Mode, Currently_Swapped => True, Native_Source => 0); Display.Buffers (LCD_Layer, Buf).Set_Source (HAL.Bitmap.Black); Display.Buffers (LCD_Layer, Buf).Fill; end loop; end if; Display.Current (LCD_Layer) := 1; STM32.LTDC.Layer_Init (Layer => LCD_Layer, Config => STM32.LTDC.To_LTDC_Mode (Mode), Buffer => Display.Buffers (LCD_Layer, 1).Addr, X => X0, Y => Y0, W => W, H => H, Constant_Alpha => 255, BF => STM32.LTDC.BF_Pixel_Alpha_X_Constant_Alpha); end Initialize_Layer; ----------------- -- Initialized -- ----------------- overriding function Initialized (Display : Frame_Buffer; Layer : Positive) return Boolean is LCD_Layer : constant STM32.LTDC.LCD_Layer := (if Layer = 1 then STM32.LTDC.Layer1 else STM32.LTDC.Layer2); use type STM32.DMA2D_Bitmap.DMA2D_Bitmap_Buffer; begin return Display.Buffers (LCD_Layer, 1) /= STM32.DMA2D_Bitmap.Null_Buffer; end Initialized; --------------------------- -- Internal_Update_Layer -- --------------------------- procedure Internal_Update_Layer (Display : in out Frame_Buffer; Layer : Positive) is LCD_Layer : constant STM32.LTDC.LCD_Layer := (if Layer = 1 then STM32.LTDC.Layer1 else STM32.LTDC.Layer2); begin case Display.Current (LCD_Layer) is when 0 => null; when 1 => Display.Buffers (LCD_Layer, 2).Wait_Transfer; STM32.LTDC.Set_Frame_Buffer (Layer => LCD_Layer, Addr => Display.Buffers (LCD_Layer, 2).Addr); Display.Current (LCD_Layer) := 2; when 2 => Display.Buffers (LCD_Layer, 1).Wait_Transfer; STM32.LTDC.Set_Frame_Buffer (Layer => LCD_Layer, Addr => Display.Buffers (LCD_Layer, 1).Addr); Display.Current (LCD_Layer) := 1; end case; end Internal_Update_Layer; ------------------ -- Update_Layer -- ------------------ overriding procedure Update_Layer (Display : in out Frame_Buffer; Layer : Positive; Copy_Back : Boolean := False) is Visible, Hidden : STM32.DMA2D_Bitmap.DMA2D_Bitmap_Buffer; LCD_Layer : constant STM32.LTDC.LCD_Layer := (if Layer = 1 then STM32.LTDC.Layer1 else STM32.LTDC.Layer2); begin Internal_Update_Layer (Display, Layer); STM32.LTDC.Reload_Config (Immediate => False); if Copy_Back then if Display.Current (LCD_Layer) = 1 then Visible := Display.Buffers (LCD_Layer, 1); Hidden := Display.Buffers (LCD_Layer, 2); else Visible := Display.Buffers (LCD_Layer, 2); Hidden := Display.Buffers (LCD_Layer, 1); end if; STM32.DMA2D_Bitmap.Copy_Rect (Visible, (0, 0), Hidden, (0, 0), Visible.Width, Visible.Height, Synchronous => True); end if; end Update_Layer; ------------------- -- Update_Layers -- ------------------- overriding procedure Update_Layers (Display : in out Frame_Buffer) is begin for J in 1 .. 2 loop if Display.Initialized (J) then Internal_Update_Layer (Display, J); end if; end loop; STM32.LTDC.Reload_Config (Immediate => False); end Update_Layers; ------------------- -- Update_Layers -- ------------------- procedure Update_Layers (Display : in out Frame_Buffer; Copy_Layer1 : Boolean; Copy_Layer2 : Boolean) is use type STM32.LTDC.LCD_Layer; Visible, Hidden : STM32.DMA2D_Bitmap.DMA2D_Bitmap_Buffer; begin for J in 1 .. 2 loop if Display.Initialized (J) then Internal_Update_Layer (Display, J); end if; end loop; STM32.LTDC.Reload_Config (Immediate => False); for LCD_Layer in STM32.LTDC.LCD_Layer'Range loop if (LCD_Layer = STM32.LTDC.Layer1 and then Copy_Layer1) or else (LCD_Layer = STM32.LTDC.Layer2 and then Copy_Layer2) then if Display.Current (LCD_Layer) = 1 then Visible := Display.Buffers (LCD_Layer, 1); Hidden := Display.Buffers (LCD_Layer, 2); else Visible := Display.Buffers (LCD_Layer, 2); Hidden := Display.Buffers (LCD_Layer, 1); end if; STM32.DMA2D_Bitmap.Copy_Rect (Visible, (0, 0), Hidden, (0, 0), Visible.Width, Visible.Height, Synchronous => True); end if; end loop; end Update_Layers; ---------------- -- Color_Mode -- ---------------- overriding function Color_Mode (Display : Frame_Buffer; Layer : Positive) return HAL.Framebuffer.FB_Color_Mode is LCD_Layer : constant STM32.LTDC.LCD_Layer := (if Layer = 1 then STM32.LTDC.Layer1 else STM32.LTDC.Layer2); begin return Display.Buffers (LCD_Layer, 1).Color_Mode; end Color_Mode; ------------------- -- Hidden_Buffer -- ------------------- overriding function Hidden_Buffer (Display : in out Frame_Buffer; Layer : Positive) return not null HAL.Bitmap.Any_Bitmap_Buffer is LCD_Layer : constant STM32.LTDC.LCD_Layer := (if Layer = 1 then STM32.LTDC.Layer1 else STM32.LTDC.Layer2); begin case Display.Current (LCD_Layer) is when 0 | 2 => return Display.Buffers (LCD_Layer, 1)'Unchecked_Access; when 1 => return Display.Buffers (LCD_Layer, 2)'Unchecked_Access; end case; end Hidden_Buffer; ---------------- -- Pixel_Size -- ---------------- overriding function Pixel_Size (Display : Frame_Buffer; Layer : Positive) return Positive is LCD_Layer : constant STM32.LTDC.LCD_Layer := (if Layer = 1 then STM32.LTDC.Layer1 else STM32.LTDC.Layer2); begin return HAL.Bitmap.Bits_Per_Pixel (Display.Buffers (LCD_Layer, 1).Color_Mode) / 8; end Pixel_Size; end Framebuffer_LTDC;
----------------------------------------------------------------------- -- wiki-filters-autolink -- Autolink filter to identify links in wiki -- Copyright (C) 2016, 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. ----------------------------------------------------------------------- -- === Autolink Filters === -- The `Wiki.Filters.Autolink` package defines a filter that transforms URLs -- in the Wiki text into links. The filter should be inserted in the filter chain -- after the HTML and after the collector filters. The filter looks for the -- text and transforms `http://`, `https://`, `ftp://` and `ftps://` links into real links. -- When such links are found, the text is split so that next filters see only the text without -- links and the `Add_Link` filter operations are called with the link. package Wiki.Filters.Autolink is pragma Preelaborate; type Autolink_Filter is new Filter_Type with null record; type Autolink_Filter_Access is access all Autolink_Filter'Class; -- Find the position of the end of the link. -- Returns 0 if the content is not a link. function Find_End_Link (Filter : in Autolink_Filter; Content : in Wiki.Strings.WString) return Natural; -- Add a text content with the given format to the document. Identify URLs in the text -- and transform them into links. For each link, call the Add_Link operation. The operation -- recognizes http:// https:// ftp:// ftps:// overriding procedure Add_Text (Filter : in out Autolink_Filter; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map); end Wiki.Filters.Autolink;
package Card_Dir is type Cardinal_Direction is (N, NE, E, SE, S, SW, W, NW); end Card_Dir;
-- { dg-do run } with Controlled5_Pkg; use Controlled5_Pkg; procedure Controlled5 is V : Root'Class := Dummy (300); begin null; end;
-- This spec has been automatically generated from STM32L4x6.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package STM32_SVD.Flash is pragma Preelaborate; --------------- -- Registers -- --------------- subtype ACR_LATENCY_Field is HAL.UInt3; -- Access control register type ACR_Register is record -- Latency LATENCY : ACR_LATENCY_Field := 16#0#; -- unspecified Reserved_3_7 : HAL.UInt5 := 16#0#; -- Prefetch enable PRFTEN : Boolean := False; -- Instruction cache enable ICEN : Boolean := True; -- Data cache enable DCEN : Boolean := True; -- Instruction cache reset ICRST : Boolean := False; -- Data cache reset DCRST : Boolean := False; -- Flash Power-down mode during Low-power run mode RUN_PD : Boolean := False; -- Flash Power-down mode during Low-power sleep mode SLEEP_PD : Boolean := False; -- unspecified Reserved_15_31 : HAL.UInt17 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for ACR_Register use record LATENCY at 0 range 0 .. 2; Reserved_3_7 at 0 range 3 .. 7; PRFTEN at 0 range 8 .. 8; ICEN at 0 range 9 .. 9; DCEN at 0 range 10 .. 10; ICRST at 0 range 11 .. 11; DCRST at 0 range 12 .. 12; RUN_PD at 0 range 13 .. 13; SLEEP_PD at 0 range 14 .. 14; Reserved_15_31 at 0 range 15 .. 31; end record; -- Status register type SR_Register is record -- End of operation EOP : Boolean := False; -- Operation error OPERR : Boolean := False; -- unspecified Reserved_2_2 : HAL.Bit := 16#0#; -- Programming error PROGERR : Boolean := False; -- Write protected error WRPERR : Boolean := False; -- Programming alignment error PGAERR : Boolean := False; -- Size error SIZERR : Boolean := False; -- Programming sequence error PGSERR : Boolean := False; -- Fast programming data miss error MISERR : Boolean := False; -- Fast programming error FASTERR : Boolean := False; -- unspecified Reserved_10_13 : HAL.UInt4 := 16#0#; -- PCROP read error RDERR : Boolean := False; -- Option validity error OPTVERR : Boolean := False; -- Read-only. Busy BSY : Boolean := False; -- unspecified Reserved_17_31 : HAL.UInt15 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for SR_Register use record EOP at 0 range 0 .. 0; OPERR at 0 range 1 .. 1; Reserved_2_2 at 0 range 2 .. 2; PROGERR at 0 range 3 .. 3; WRPERR at 0 range 4 .. 4; PGAERR at 0 range 5 .. 5; SIZERR at 0 range 6 .. 6; PGSERR at 0 range 7 .. 7; MISERR at 0 range 8 .. 8; FASTERR at 0 range 9 .. 9; Reserved_10_13 at 0 range 10 .. 13; RDERR at 0 range 14 .. 14; OPTVERR at 0 range 15 .. 15; BSY at 0 range 16 .. 16; Reserved_17_31 at 0 range 17 .. 31; end record; subtype CR_PNB_Field is HAL.UInt8; -- Flash control register type CR_Register is record -- Programming PG : Boolean := False; -- Page erase PER : Boolean := False; -- Bank 1 Mass erase MER1 : Boolean := False; -- Page number PNB : CR_PNB_Field := 16#0#; -- Bank erase BKER : Boolean := False; -- unspecified Reserved_12_14 : HAL.UInt3 := 16#0#; -- Bank 2 Mass erase MER2 : Boolean := False; -- Start START : Boolean := False; -- Options modification start OPTSTRT : Boolean := False; -- Fast programming FSTPG : Boolean := False; -- unspecified Reserved_19_23 : HAL.UInt5 := 16#0#; -- End of operation interrupt enable EOPIE : Boolean := False; -- Error interrupt enable ERRIE : Boolean := False; -- PCROP read error interrupt enable RDERRIE : Boolean := False; -- Force the option byte loading OBL_LAUNCH : Boolean := False; -- unspecified Reserved_28_29 : HAL.UInt2 := 16#0#; -- Options Lock OPTLOCK : Boolean := True; -- FLASH_CR Lock LOCK : Boolean := True; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CR_Register use record PG at 0 range 0 .. 0; PER at 0 range 1 .. 1; MER1 at 0 range 2 .. 2; PNB at 0 range 3 .. 10; BKER at 0 range 11 .. 11; Reserved_12_14 at 0 range 12 .. 14; MER2 at 0 range 15 .. 15; START at 0 range 16 .. 16; OPTSTRT at 0 range 17 .. 17; FSTPG at 0 range 18 .. 18; Reserved_19_23 at 0 range 19 .. 23; EOPIE at 0 range 24 .. 24; ERRIE at 0 range 25 .. 25; RDERRIE at 0 range 26 .. 26; OBL_LAUNCH at 0 range 27 .. 27; Reserved_28_29 at 0 range 28 .. 29; OPTLOCK at 0 range 30 .. 30; LOCK at 0 range 31 .. 31; end record; subtype ECCR_ADDR_ECC_Field is HAL.UInt19; -- Flash ECC register type ECCR_Register is record -- Read-only. ECC fail address ADDR_ECC : ECCR_ADDR_ECC_Field := 16#0#; -- Read-only. ECC fail bank BK_ECC : Boolean := False; -- Read-only. System Flash ECC fail SYSF_ECC : Boolean := False; -- unspecified Reserved_21_23 : HAL.UInt3 := 16#0#; -- ECC correction interrupt enable ECCIE : Boolean := False; -- unspecified Reserved_25_29 : HAL.UInt5 := 16#0#; -- ECC correction ECCC : Boolean := False; -- ECC detection ECCD : Boolean := False; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for ECCR_Register use record ADDR_ECC at 0 range 0 .. 18; BK_ECC at 0 range 19 .. 19; SYSF_ECC at 0 range 20 .. 20; Reserved_21_23 at 0 range 21 .. 23; ECCIE at 0 range 24 .. 24; Reserved_25_29 at 0 range 25 .. 29; ECCC at 0 range 30 .. 30; ECCD at 0 range 31 .. 31; end record; subtype OPTR_RDP_Field is HAL.UInt8; subtype OPTR_BOR_LEV_Field is HAL.UInt3; -- Flash option register type OPTR_Register is record -- Read protection level RDP : OPTR_RDP_Field := 16#0#; -- BOR reset Level BOR_LEV : OPTR_BOR_LEV_Field := 16#0#; -- unspecified Reserved_11_11 : HAL.Bit := 16#0#; -- nRST_STOP nRST_STOP : Boolean := False; -- nRST_STDBY nRST_STDBY : Boolean := False; -- unspecified Reserved_14_15 : HAL.UInt2 := 16#0#; -- Independent watchdog selection IDWG_SW : Boolean := False; -- Independent watchdog counter freeze in Stop mode IWDG_STOP : Boolean := False; -- Independent watchdog counter freeze in Standby mode IWDG_STDBY : Boolean := False; -- Window watchdog selection WWDG_SW : Boolean := False; -- Dual-bank boot BFB2 : Boolean := False; -- Dual-Bank on 512 KB or 256 KB Flash memory devices DUALBANK : Boolean := False; -- unspecified Reserved_22_22 : HAL.Bit := 16#0#; -- Boot configuration nBOOT1 : Boolean := False; -- SRAM2 parity check enable SRAM2_PE : Boolean := False; -- SRAM2 Erase when system reset SRAM2_RST : Boolean := False; -- unspecified Reserved_26_31 : HAL.UInt6 := 16#3C#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for OPTR_Register use record RDP at 0 range 0 .. 7; BOR_LEV at 0 range 8 .. 10; Reserved_11_11 at 0 range 11 .. 11; nRST_STOP at 0 range 12 .. 12; nRST_STDBY at 0 range 13 .. 13; Reserved_14_15 at 0 range 14 .. 15; IDWG_SW at 0 range 16 .. 16; IWDG_STOP at 0 range 17 .. 17; IWDG_STDBY at 0 range 18 .. 18; WWDG_SW at 0 range 19 .. 19; BFB2 at 0 range 20 .. 20; DUALBANK at 0 range 21 .. 21; Reserved_22_22 at 0 range 22 .. 22; nBOOT1 at 0 range 23 .. 23; SRAM2_PE at 0 range 24 .. 24; SRAM2_RST at 0 range 25 .. 25; Reserved_26_31 at 0 range 26 .. 31; end record; subtype PCROP1SR_PCROP1_STRT_Field is HAL.UInt16; -- Flash Bank 1 PCROP Start address register type PCROP1SR_Register is record -- Bank 1 PCROP area start offset PCROP1_STRT : PCROP1SR_PCROP1_STRT_Field := 16#0#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#FFFF#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for PCROP1SR_Register use record PCROP1_STRT at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype PCROP1ER_PCROP1_END_Field is HAL.UInt16; -- Flash Bank 1 PCROP End address register type PCROP1ER_Register is record -- Bank 1 PCROP area end offset PCROP1_END : PCROP1ER_PCROP1_END_Field := 16#0#; -- unspecified Reserved_16_30 : HAL.UInt15 := 16#FFF#; -- PCROP area preserved when RDP level decreased PCROP_RDP : Boolean := False; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for PCROP1ER_Register use record PCROP1_END at 0 range 0 .. 15; Reserved_16_30 at 0 range 16 .. 30; PCROP_RDP at 0 range 31 .. 31; end record; subtype WRP1AR_WRP1A_STRT_Field is HAL.UInt8; subtype WRP1AR_WRP1A_END_Field is HAL.UInt8; -- Flash Bank 1 WRP area A address register type WRP1AR_Register is record -- Bank 1 WRP first area start offset WRP1A_STRT : WRP1AR_WRP1A_STRT_Field := 16#0#; -- unspecified Reserved_8_15 : HAL.UInt8 := 16#FF#; -- Bank 1 WRP first area A end offset WRP1A_END : WRP1AR_WRP1A_END_Field := 16#0#; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#FF#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for WRP1AR_Register use record WRP1A_STRT at 0 range 0 .. 7; Reserved_8_15 at 0 range 8 .. 15; WRP1A_END at 0 range 16 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype WRP1BR_WRP1B_END_Field is HAL.UInt8; subtype WRP1BR_WRP1B_STRT_Field is HAL.UInt8; -- Flash Bank 1 WRP area B address register type WRP1BR_Register is record -- Bank 1 WRP second area B start offset WRP1B_END : WRP1BR_WRP1B_END_Field := 16#0#; -- unspecified Reserved_8_15 : HAL.UInt8 := 16#FF#; -- Bank 1 WRP second area B end offset WRP1B_STRT : WRP1BR_WRP1B_STRT_Field := 16#0#; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#FF#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for WRP1BR_Register use record WRP1B_END at 0 range 0 .. 7; Reserved_8_15 at 0 range 8 .. 15; WRP1B_STRT at 0 range 16 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype PCROP2SR_PCROP2_STRT_Field is HAL.UInt16; -- Flash Bank 2 PCROP Start address register type PCROP2SR_Register is record -- Bank 2 PCROP area start offset PCROP2_STRT : PCROP2SR_PCROP2_STRT_Field := 16#0#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#FFFF#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for PCROP2SR_Register use record PCROP2_STRT at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype PCROP2ER_PCROP2_END_Field is HAL.UInt16; -- Flash Bank 2 PCROP End address register type PCROP2ER_Register is record -- Bank 2 PCROP area end offset PCROP2_END : PCROP2ER_PCROP2_END_Field := 16#0#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#FFFF#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for PCROP2ER_Register use record PCROP2_END at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype WRP2AR_WRP2A_STRT_Field is HAL.UInt8; subtype WRP2AR_WRP2A_END_Field is HAL.UInt8; -- Flash Bank 2 WRP area A address register type WRP2AR_Register is record -- Bank 2 WRP first area A start offset WRP2A_STRT : WRP2AR_WRP2A_STRT_Field := 16#0#; -- unspecified Reserved_8_15 : HAL.UInt8 := 16#FF#; -- Bank 2 WRP first area A end offset WRP2A_END : WRP2AR_WRP2A_END_Field := 16#0#; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#FF#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for WRP2AR_Register use record WRP2A_STRT at 0 range 0 .. 7; Reserved_8_15 at 0 range 8 .. 15; WRP2A_END at 0 range 16 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype WRP2BR_WRP2B_STRT_Field is HAL.UInt8; subtype WRP2BR_WRP2B_END_Field is HAL.UInt8; -- Flash Bank 2 WRP area B address register type WRP2BR_Register is record -- Bank 2 WRP second area B start offset WRP2B_STRT : WRP2BR_WRP2B_STRT_Field := 16#0#; -- unspecified Reserved_8_15 : HAL.UInt8 := 16#FF#; -- Bank 2 WRP second area B end offset WRP2B_END : WRP2BR_WRP2B_END_Field := 16#0#; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#FF#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for WRP2BR_Register use record WRP2B_STRT at 0 range 0 .. 7; Reserved_8_15 at 0 range 8 .. 15; WRP2B_END at 0 range 16 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Flash type FLASH_Peripheral is record -- Access control register ACR : aliased ACR_Register; -- Power down key register PDKEYR : aliased HAL.UInt32; -- Flash key register KEYR : aliased HAL.UInt32; -- Option byte key register OPTKEYR : aliased HAL.UInt32; -- Status register SR : aliased SR_Register; -- Flash control register CR : aliased CR_Register; -- Flash ECC register ECCR : aliased ECCR_Register; -- Flash option register OPTR : aliased OPTR_Register; -- Flash Bank 1 PCROP Start address register PCROP1SR : aliased PCROP1SR_Register; -- Flash Bank 1 PCROP End address register PCROP1ER : aliased PCROP1ER_Register; -- Flash Bank 1 WRP area A address register WRP1AR : aliased WRP1AR_Register; -- Flash Bank 1 WRP area B address register WRP1BR : aliased WRP1BR_Register; -- Flash Bank 2 PCROP Start address register PCROP2SR : aliased PCROP2SR_Register; -- Flash Bank 2 PCROP End address register PCROP2ER : aliased PCROP2ER_Register; -- Flash Bank 2 WRP area A address register WRP2AR : aliased WRP2AR_Register; -- Flash Bank 2 WRP area B address register WRP2BR : aliased WRP2BR_Register; end record with Volatile; for FLASH_Peripheral use record ACR at 16#0# range 0 .. 31; PDKEYR at 16#4# range 0 .. 31; KEYR at 16#8# range 0 .. 31; OPTKEYR at 16#C# range 0 .. 31; SR at 16#10# range 0 .. 31; CR at 16#14# range 0 .. 31; ECCR at 16#18# range 0 .. 31; OPTR at 16#20# range 0 .. 31; PCROP1SR at 16#24# range 0 .. 31; PCROP1ER at 16#28# range 0 .. 31; WRP1AR at 16#2C# range 0 .. 31; WRP1BR at 16#30# range 0 .. 31; PCROP2SR at 16#44# range 0 .. 31; PCROP2ER at 16#48# range 0 .. 31; WRP2AR at 16#4C# range 0 .. 31; WRP2BR at 16#50# range 0 .. 31; end record; -- Flash FLASH_Periph : aliased FLASH_Peripheral with Import, Address => System'To_Address (16#40022000#); end STM32_SVD.Flash;
with Ada.Exception_Identification.From_Here; with System.Formatting; with System.Long_Long_Integer_Types; with System.Native_Calendar; with System.Native_Time; package body Ada.Calendar.Formatting is use Exception_Identification.From_Here; use type Time_Zones.Time_Offset; use type System.Long_Long_Integer_Types.Word_Unsigned; use type System.Native_Time.Nanosecond_Number; subtype Word_Unsigned is System.Long_Long_Integer_Types.Word_Unsigned; subtype Long_Long_Unsigned is System.Long_Long_Integer_Types.Long_Long_Unsigned; -- for Year, Month, Day type Packed_Split_Time is mod 2 ** 64; -- for Packed_Split_Time use record -- Day at 0 range 0 .. 7; -- 2 ** 5 = 32 > 31 -- Month at 0 range 8 .. 15; -- 2 ** 4 = 16 > 12 -- Year at 0 range 16 .. 31; -- 2 ** 9 = 512 > 2399 - 1901 + 1 = 499 -- Day_of_Week at 0 range 32 .. 38; -- 2 ** 3 = 8 > 7 -- Leap_Second at 0 range 39 .. 39; -- Second at 0 range 40 .. 47; -- 2 ** 6 = 64 > 60 -- Minute at 0 range 48 .. 55; -- 2 ** 6 = 64 > 60 -- Hour at 0 range 56 .. 63; -- 2 ** 5 = 32 > 24 -- end record; pragma Provide_Shift_Operators (Packed_Split_Time); function Packed_Split ( Date : Time; Time_Zone : Time_Zones.Time_Offset) return Packed_Split_Time; -- The callings of this function will be unified since pure attribute -- when Year, Month, Day, Hour, Minute, Second, and Day_of_Week are -- inlined. pragma Pure_Function (Packed_Split); pragma Machine_Attribute (Packed_Split, "const"); function Packed_Split ( Date : Time; Time_Zone : Time_Zones.Time_Offset) return Packed_Split_Time is Year : Year_Number; Month : Month_Number; Day : Day_Number; Hour : Hour_Number; Minute : Minute_Number; Second : Second_Number; Sub_Second : Second_Duration; Leap_Second : Boolean; Day_of_Week : System.Native_Calendar.Day_Name; Error : Boolean; begin System.Native_Calendar.Split ( Duration (Date), Year => Year, Month => Month, Day => Day, Hour => Hour, Minute => Minute, Second => Second, Sub_Second => Sub_Second, Leap_Second => Leap_Second, Day_of_Week => Day_of_Week, Time_Zone => System.Native_Calendar.Time_Offset (Time_Zone), Error => Error); if Error then Raise_Exception (Time_Error'Identity); end if; return Packed_Split_Time (Day) or Shift_Left (Packed_Split_Time (Month), 8) or Shift_Left (Packed_Split_Time (Year), 16) or Shift_Left (Packed_Split_Time (Day_of_Week), 32) or Shift_Left (Packed_Split_Time (Boolean'Pos (Leap_Second)), 39) or Shift_Left (Packed_Split_Time (Second), 40) or Shift_Left (Packed_Split_Time (Minute), 48) or Shift_Left (Packed_Split_Time (Hour), 56); end Packed_Split; -- 99 hours procedure Split_Base ( Seconds : Duration; -- Seconds >= 0.0 Hour : out Natural; Minute : out Minute_Number; Second : out Second_Number; Sub_Second : out Second_Duration); procedure Split_Base ( Seconds : Duration; Hour : out Natural; Minute : out Minute_Number; Second : out Second_Number; Sub_Second : out Second_Duration) is X : System.Native_Time.Nanosecond_Number := System.Native_Time.Nanosecond_Number'Integer_Value (Seconds); Q, R : System.Native_Time.Nanosecond_Number; begin System.Long_Long_Integer_Types.Divide ( Long_Long_Unsigned (X), 1_000_000_000, -- unit is 1-second Long_Long_Unsigned (Q), Long_Long_Unsigned (R)); Sub_Second := Duration'Fixed_Value (R); X := Q; System.Long_Long_Integer_Types.Divide ( Long_Long_Unsigned (X), 60, -- unit is 1-minute Long_Long_Unsigned (Q), Long_Long_Unsigned (R)); Second := Second_Number (R); X := Q; System.Long_Long_Integer_Types.Divide ( Long_Long_Unsigned (X), 60, -- unit is 1-hour Long_Long_Unsigned (Q), Long_Long_Unsigned (R)); Minute := Second_Number (R); Hour := Integer (Q); end Split_Base; procedure Image ( Hour : Natural; Minute : Minute_Number; Second : Second_Number; Sub_Second : Second_Duration; Leap_Second : Boolean; Include_Time_Fraction : Boolean; Item : out String; Last : out Natural); procedure Image ( Hour : Natural; Minute : Minute_Number; Second : Second_Number; Sub_Second : Second_Duration; Leap_Second : Boolean; Include_Time_Fraction : Boolean; Item : out String; Last : out Natural) is Error : Boolean; begin System.Formatting.Image ( Word_Unsigned (Hour), Item, Last, Width => 2, Error => Error); pragma Assert (not Error); Last := Last + 1; Item (Last) := ':'; System.Formatting.Image ( Word_Unsigned (Minute), Item (Last + 1 .. Item'Last), Last, Width => 2, Error => Error); pragma Assert (not Error); Last := Last + 1; Item (Last) := ':'; declare Display_Second : Word_Unsigned; begin if Leap_Second and then Second = 59 then Display_Second := 60; else Display_Second := Word_Unsigned (Second); end if; System.Formatting.Image ( Display_Second, Item (Last + 1 .. Item'Last), Last, Width => 2, Error => Error); pragma Assert (not Error); end; if Include_Time_Fraction then Last := Last + 1; Item (Last) := '.'; System.Formatting.Image ( Word_Unsigned'Integer_Value (Sub_Second) / 10_000_000, Item (Last + 1 .. Item'Last), Last, Width => 2, Error => Error); pragma Assert (not Error); end if; end Image; procedure Value ( Item : String; Hour : out Natural; Minute : out Minute_Number; Second : out Second_Number; Sub_Second : out Second_Duration; Leap_Second : out Boolean); procedure Value ( Item : String; Hour : out Natural; Minute : out Minute_Number; Second : out Second_Number; Sub_Second : out Second_Duration; Leap_Second : out Boolean) is Last : Natural := Item'First - 1; Hour_I : Word_Unsigned; Minute_I : Word_Unsigned; Second_I : Word_Unsigned; Sub_Second_I : Word_Unsigned; Error : Boolean; begin System.Formatting.Value ( Item (Last + 1 .. Item'Last), Last, Hour_I, Error => Error); if Error or else Hour_I > Word_Unsigned (Hour_Number'Last) or else Last >= Item'Last or else Item (Last + 1) /= ':' then raise Constraint_Error; end if; Hour := Natural (Hour_I); -- not Hour_Number Last := Last + 1; -- skip ':' System.Formatting.Value ( Item (Last + 1 .. Item'Last), Last, Minute_I, Error => Error); if Error or else Minute_I > Word_Unsigned (Minute_Number'Last) or else Last >= Item'Last or else Item (Last + 1) /= ':' then raise Constraint_Error; end if; Minute := Minute_Number (Minute_I); Last := Last + 1; -- skip ':' System.Formatting.Value ( Item (Last + 1 .. Item'Last), Last, Second_I, Error => Error); if Error or else Second_I > 60 then raise Constraint_Error; end if; if Second_I = 60 then Second := 59; Leap_Second := True; else Second := Second_Number (Second_I); Leap_Second := False; end if; if Last < Item'Last and then Item (Last + 1) = '.' then declare P : constant Positive := Last + 1; -- position of '.' begin System.Formatting.Value ( Item (P + 1 .. Item'Last), Last, Sub_Second_I, Error => Error); if Error then raise Constraint_Error; end if; Sub_Second := Duration (Sub_Second_I) / Positive'(10 ** (Last - P)); end; else Sub_Second := 0.0; end if; if Last /= Item'Last then raise Constraint_Error; end if; end Value; -- implementation function Day_Of_Week ( Date : Time; Time_Zone : Time_Zones.Time_Offset := 0) return Day_Name is pragma Suppress (Range_Check); begin return Day_Name'Val ( Shift_Right (Packed_Split (Date, Time_Zone), 32) and 16#7f#); end Day_Of_Week; function Year (Date : Time; Time_Zone : Time_Zones.Time_Offset := 0) return Year_Number is pragma Suppress (Range_Check); begin return Year_Number ( Shift_Right (Packed_Split (Date, Time_Zone), 16) and 16#ffff#); end Year; function Month (Date : Time; Time_Zone : Time_Zones.Time_Offset := 0) return Month_Number is pragma Suppress (Range_Check); begin return Month_Number ( Shift_Right (Packed_Split (Date, Time_Zone), 8) and 16#ff#); end Month; function Day (Date : Time; Time_Zone : Time_Zones.Time_Offset := 0) return Day_Number is pragma Suppress (Range_Check); begin return Day_Number ( Packed_Split (Date, Time_Zone) and 16#ff#); end Day; function Hour (Date : Time; Time_Zone : Time_Zones.Time_Offset := 0) return Hour_Number is pragma Suppress (Range_Check); begin return Hour_Number ( Shift_Right (Packed_Split (Date, Time_Zone), 56)); end Hour; function Minute (Date : Time; Time_Zone : Time_Zones.Time_Offset := 0) return Minute_Number is pragma Suppress (Range_Check); begin return Minute_Number ( Shift_Right (Packed_Split (Date, Time_Zone), 48) and 16#ff#); end Minute; function Second (Date : Time) return Second_Number is pragma Suppress (Range_Check); Time_Zone : constant Time_Zones.Time_Offset := 0; -- unit of Time_Zone is minute begin return Minute_Number ( Shift_Right (Packed_Split (Date, Time_Zone), 40) and 16#ff#); end Second; function Sub_Second (Date : Time) return Second_Duration is Time_Zone : constant Time_Zones.Time_Offset := 0; -- unit of Time_Zone is minute begin return Duration'Fixed_Value ( (System.Native_Time.Nanosecond_Number'Integer_Value (Date) + System.Native_Time.Nanosecond_Number (Time_Zone) * (60 * 1_000_000_000)) mod 1_000_000_000); end Sub_Second; function Seconds (Date : Time; Time_Zone : Time_Zones.Time_Offset := 0) return Day_Duration is Year : Year_Number; Month : Month_Number; Day : Day_Number; Seconds : Day_Duration; Leap_Second : Boolean; begin Split (Date, Year => Year, Month => Month, Day => Day, Seconds => Seconds, Leap_Second => Leap_Second, Time_Zone => Time_Zone); return Seconds; end Seconds; function Seconds_Of ( Hour : Hour_Number; Minute : Minute_Number; Second : Second_Number := 0; Sub_Second : Second_Duration := 0.0) return Day_Duration is begin return Duration ((Hour * 60 + Minute) * 60 + Second) + Sub_Second; end Seconds_Of; procedure Split ( Seconds : Day_Duration; Hour : out Hour_Number; Minute : out Minute_Number; Second : out Second_Number; Sub_Second : out Second_Duration) is begin if Seconds = Day_Duration'Last then Raise_Exception (Time_Error'Identity); -- RM 9.6.1(70/3) end if; Split_Base ( Seconds, Hour => Hour, Minute => Minute, Second => Second, Sub_Second => Sub_Second); end Split; function Time_Of ( Year : Year_Number; Month : Month_Number; Day : Day_Number; Hour : Hour_Number; Minute : Minute_Number; Second : Second_Number; Sub_Second : Second_Duration := 0.0; Leap_Second : Boolean := False; Time_Zone : Time_Zones.Time_Offset := 0) return Time is Result : Duration; Error : Boolean; begin System.Native_Calendar.Time_Of ( Year => Year, Month => Month, Day => Day, Hour => Hour, Minute => Minute, Second => Second, Sub_Second => Sub_Second, Leap_Second => Leap_Second, Time_Zone => System.Native_Calendar.Time_Offset (Time_Zone), Result => Result, Error => Error); if Error then Raise_Exception (Time_Error'Identity); end if; return Time (Result); end Time_Of; function Time_Of ( Year : Year_Number; Month : Month_Number; Day : Day_Number; Seconds : Day_Duration := 0.0; Leap_Second : Boolean := False; Time_Zone : Time_Zones.Time_Offset := 0) return Time is Result : Duration; Error : Boolean; begin System.Native_Calendar.Time_Of ( Year => Year, Month => Month, Day => Day, Seconds => Seconds, Leap_Second => Leap_Second, Time_Zone => System.Native_Calendar.Time_Offset (Time_Zone), Result => Result, Error => Error); if Error then Raise_Exception (Time_Error'Identity); end if; return Time (Result); end Time_Of; procedure Split ( Date : Time; Year : out Year_Number; Month : out Month_Number; Day : out Day_Number; Hour : out Hour_Number; Minute : out Minute_Number; Second : out Second_Number; Sub_Second : out Second_Duration; Time_Zone : Time_Zones.Time_Offset := 0) is Leap_Second : Boolean; begin Split ( Date, Year => Year, Month => Month, Day => Day, Hour => Hour, Minute => Minute, Second => Second, Sub_Second => Sub_Second, Leap_Second => Leap_Second, Time_Zone => Time_Zone); end Split; procedure Split ( Date : Time; Year : out Year_Number; Month : out Month_Number; Day : out Day_Number; Hour : out Hour_Number; Minute : out Minute_Number; Second : out Second_Number; Sub_Second : out Second_Duration; Leap_Second : out Boolean; Time_Zone : Time_Zones.Time_Offset := 0) is Day_of_Week : System.Native_Calendar.Day_Name; Error : Boolean; begin System.Native_Calendar.Split ( Duration (Date), Year => Year, Month => Month, Day => Day, Hour => Hour, Minute => Minute, Second => Second, Sub_Second => Sub_Second, Leap_Second => Leap_Second, Day_of_Week => Day_of_Week, Time_Zone => System.Native_Calendar.Time_Offset (Time_Zone), Error => Error); if Error then Raise_Exception (Time_Error'Identity); end if; end Split; procedure Split ( Date : Time; Year : out Year_Number; Month : out Month_Number; Day : out Day_Number; Seconds : out Day_Duration; Leap_Second : out Boolean; Time_Zone : Time_Zones.Time_Offset := 0) is Error : Boolean; begin System.Native_Calendar.Split ( Duration (Date), Year => Year, Month => Month, Day => Day, Seconds => Seconds, Leap_Second => Leap_Second, Time_Zone => System.Native_Calendar.Time_Offset (Time_Zone), Error => Error); if Error then Raise_Exception (Time_Error'Identity); end if; end Split; function Image ( Date : Time; Include_Time_Fraction : Boolean := False; Time_Zone : Time_Zones.Time_Offset := 0) return String is Year : Year_Number; Month : Month_Number; Day : Day_Number; Hour : Hour_Number; Minute : Minute_Number; Second : Second_Number; Sub_Second : Second_Duration; Leap_Second : Boolean; Result : String (1 .. 22 + Integer'Width); -- yyyy-mm-dd hh:mm:ss.ss Last : Natural; Error : Boolean; begin Split ( Date, Year => Year, Month => Month, Day => Day, Hour => Hour, Minute => Minute, Second => Second, Sub_Second => Sub_Second, Leap_Second => Leap_Second, Time_Zone => Time_Zone); System.Formatting.Image ( Word_Unsigned (Year), Result, Last, Width => 4, Error => Error); pragma Assert (not Error); Last := Last + 1; Result (Last) := '-'; System.Formatting.Image ( Word_Unsigned (Month), Result (Last + 1 .. Result'Last), Last, Width => 2, Error => Error); pragma Assert (not Error); Last := Last + 1; Result (Last) := '-'; System.Formatting.Image ( Word_Unsigned (Day), Result (Last + 1 .. Result'Last), Last, Width => 2, Error => Error); pragma Assert (not Error); Last := Last + 1; Result (Last) := ' '; Image ( Hour, Minute, Second, Sub_Second, Leap_Second, Include_Time_Fraction, Result (Last + 1 .. Result'Last), Last); return Result (1 .. Last); end Image; function Value ( Date : String; Time_Zone : Time_Zones.Time_Offset := 0) return Time is Last : Natural; Year : Word_Unsigned; Month : Word_Unsigned; Day : Word_Unsigned; Hour : Natural; Minute : Minute_Number; Second : Second_Number; Sub_Second : Second_Duration; Leap_Second : Boolean; Error : Boolean; begin System.Formatting.Value ( Date, Last, Year, Error => Error); if Error or else Year not in Word_Unsigned (Year_Number'First) .. Word_Unsigned (Year_Number'Last) or else Last >= Date'Last or else Date (Last + 1) /= '-' then raise Constraint_Error; end if; Last := Last + 1; System.Formatting.Value ( Date (Last + 1 .. Date'Last), Last, Month, Error => Error); if Error or else Month not in Word_Unsigned (Month_Number'First) .. Word_Unsigned (Month_Number'Last) or else Last >= Date'Last or else Date (Last + 1) /= '-' then raise Constraint_Error; end if; Last := Last + 1; System.Formatting.Value ( Date (Last + 1 .. Date'Last), Last, Day, Error => Error); if Error or else Day not in Word_Unsigned (Day_Number'First) .. Word_Unsigned (Day_Number'Last) or else Last >= Date'Last or else Date (Last + 1) /= ' ' then raise Constraint_Error; end if; Last := Last + 1; Value ( Date (Last + 1 .. Date'Last), Hour => Hour, Minute => Minute, Second => Second, Sub_Second => Sub_Second, Leap_Second => Leap_Second); if Hour not in Hour_Number then raise Constraint_Error; end if; return Time_Of ( Year => Year_Number (Year), Month => Month_Number (Month), Day => Day_Number (Day), Hour => Hour, Minute => Minute, Second => Second, Sub_Second => Sub_Second, Leap_Second => Leap_Second, Time_Zone => Time_Zone); end Value; function Image ( Elapsed_Time : Duration; Include_Time_Fraction : Boolean := False) return String is Abs_Elapsed_Time : Duration := Elapsed_Time; Hour : Natural; Minute : Minute_Number; Second : Second_Number; Sub_Second : Second_Duration; Result : String (1 .. 12 + Integer'Width); -- [-]hh:mm:ss.ss Last : Natural := 0; begin if Abs_Elapsed_Time < 0.0 then Result (1) := '-'; Last := 1; Abs_Elapsed_Time := -Abs_Elapsed_Time; end if; Split_Base ( Abs_Elapsed_Time, Hour => Hour, Minute => Minute, Second => Second, Sub_Second => Sub_Second); Image ( Hour rem 100, Minute, Second, Sub_Second, False, Include_Time_Fraction, Result (Last + 1 .. Result'Last), Last); return Result (1 .. Last); end Image; function Value (Elapsed_Time : String) return Duration is Last : Natural := Elapsed_Time'First - 1; Minus : Boolean := False; Hour : Natural; Minute : Minute_Number; Second : Second_Number; Sub_Second : Second_Duration; Leap_Second : Boolean; Result : Duration; begin if Elapsed_Time'First <= Elapsed_Time'Last and then Elapsed_Time (Elapsed_Time'First) = '-' then Minus := True; Last := Elapsed_Time'First; end if; Value ( Elapsed_Time (Last + 1 .. Elapsed_Time'Last), Hour => Hour, Minute => Minute, Second => Second, Sub_Second => Sub_Second, Leap_Second => Leap_Second); if Leap_Second then raise Constraint_Error; end if; Result := Seconds_Of ( Hour_Number (Hour), Minute, Second, Sub_Second); if Minus then Result := -Result; end if; return Result; end Value; function Image (Time_Zone : Time_Zones.Time_Offset) return String is U_Time_Zone : constant Natural := Natural (abs Time_Zone); Hour : constant Hour_Number := U_Time_Zone / 60; Minute : constant Minute_Number := U_Time_Zone mod 60; Last : Natural; Error : Boolean; begin return Result : String (1 .. 6) do if Time_Zone < 0 then Result (1) := '-'; else Result (1) := '+'; end if; System.Formatting.Image ( Word_Unsigned (Hour), Result (2 .. 3), Last, Width => 2, Error => Error); pragma Assert (not Error and then Last = 3); Result (4) := ':'; System.Formatting.Image ( Word_Unsigned (Minute), Result (5 .. 6), Last, Width => 2, Error => Error); pragma Assert (not Error and then Last = 6); end return; end Image; function Value (Time_Zone : String) return Time_Zones.Time_Offset is Minus : Boolean; Hour : Word_Unsigned; Minute : Word_Unsigned; Last : Natural; Error : Boolean; Result : Time_Zones.Time_Offset; begin Last := Time_Zone'First - 1; if Last < Time_Zone'Last and then Time_Zone (Last + 1) = '-' then Minus := True; Last := Last + 1; else Minus := False; if Last < Time_Zone'Last and then Time_Zone (Last + 1) = '+' then Last := Last + 1; end if; end if; System.Formatting.Value ( Time_Zone (Last + 1 .. Time_Zone'Last), Last, Hour, Error => Error); if Error or else Hour > Word_Unsigned (Hour_Number'Last) or else Last >= Time_Zone'Last or else Time_Zone (Last + 1) /= ':' then raise Constraint_Error; end if; Last := Last + 1; System.Formatting.Value ( Time_Zone (Last + 1 .. Time_Zone'Last), Last, Minute, Error => Error); if Error or else Minute > Word_Unsigned (Minute_Number'Last) or else Last /= Time_Zone'Last then raise Constraint_Error; end if; Result := Time_Zones.Time_Offset'Base (Hour) * 60 + Time_Zones.Time_Offset'Base (Minute); if Minus then Result := -Result; end if; return Result; end Value; end Ada.Calendar.Formatting;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- E X P _ S T R M -- -- -- -- S p e c -- -- -- -- $Revision$ -- -- -- Copyright (C) 1992-1999 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, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- Routines to build stream subprograms for composite types with Types; use Types; package Exp_Strm is function Build_Elementary_Input_Call (N : Node_Id) return Node_Id; -- Build call to Read attribute function for elementary type. Also used -- for Input attributes for elementary types with an appropriate extra -- assignment statement. N is the attribute reference node. function Build_Elementary_Write_Call (N : Node_Id) return Node_Id; -- Build call to Write attribute function for elementary type. Also used -- for Output attributes for elementary types (since the effect of the -- two attributes is identical for elementary types). N is the attribute -- reference node. function Build_Stream_Attr_Profile (Loc : Source_Ptr; Typ : Entity_Id; Nam : Name_Id) return List_Id; -- Builds the parameter profile for the stream attribute identified by -- the given name (which is the underscore version, e.g. Name_uWrite to -- identify the Write attribute). This is used for the tagged case to -- build the spec for the primitive operation. -- The following routines build procedures and functions for stream -- attributes applied to composite types. For each of these routines, -- Loc is used to provide the location for the constructed subprogram -- declaration. Typ is the base type to which the subprogram applies -- (i.e. the base type of the stream attribute prefix). The returned -- results are the declaration and name (entity) of the subprogram. procedure Build_Array_Input_Function (Loc : Source_Ptr; Typ : Entity_Id; Decl : out Node_Id; Fnam : out Entity_Id); -- Build function for Input attribute for array type procedure Build_Array_Output_Procedure (Loc : Source_Ptr; Typ : Entity_Id; Decl : out Node_Id; Pnam : out Entity_Id); -- Build procedure for Output attribute for array type procedure Build_Array_Read_Procedure (Nod : Node_Id; Typ : Entity_Id; Decl : out Node_Id; Pnam : out Entity_Id); -- Build procedure for Read attribute for array type. Nod provides the -- Sloc value for generated code. procedure Build_Array_Write_Procedure (Nod : Node_Id; Typ : Entity_Id; Decl : out Node_Id; Pnam : out Entity_Id); -- Build procedure for Write attribute for array type. Nod provides the -- Sloc value for generated code. procedure Build_Mutable_Record_Read_Procedure (Loc : Source_Ptr; Typ : Entity_Id; Decl : out Node_Id; Pnam : out Entity_Id); -- Build procedure to Read a record with default discriminants. -- Discriminants must be read explicitly (RM 13.13.2(9)) in the -- same manner as is done for 'Input. procedure Build_Mutable_Record_Write_Procedure (Loc : Source_Ptr; Typ : Entity_Id; Decl : out Node_Id; Pnam : out Entity_Id); -- Build procedure to write a record with default discriminants. -- Discriminants must be written explicitly (RM 13.13.2(9)) in -- the same manner as is done for 'Output. procedure Build_Record_Or_Elementary_Input_Function (Loc : Source_Ptr; Typ : Entity_Id; Decl : out Node_Id; Fnam : out Entity_Id); -- Build function for Input attribute for record type or for an -- elementary type (the latter is used only in the case where a -- user defined Read routine is defined, since in other cases, -- Input calls the appropriate runtime library routine directly. procedure Build_Record_Or_Elementary_Output_Procedure (Loc : Source_Ptr; Typ : Entity_Id; Decl : out Node_Id; Pnam : out Entity_Id); -- Build procedure for Output attribute for record type or for an -- elementary type (the latter is used only in the case where a -- user defined Write routine is defined, since in other cases, -- Output calls the appropriate runtime library routine directly. procedure Build_Record_Read_Procedure (Loc : Source_Ptr; Typ : Entity_Id; Decl : out Node_Id; Pnam : out Entity_Id); -- Build procedure for Read attribute for record type procedure Build_Record_Write_Procedure (Loc : Source_Ptr; Typ : Entity_Id; Decl : out Node_Id; Pnam : out Entity_Id); -- Build procedure for Write attribute for record type end Exp_Strm;
-- Copyright 2016-2019 NXP -- All rights reserved.SPDX-License-Identifier: BSD-3-Clause -- This spec has been automatically generated from LPC55S6x.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package NXP_SVD.I2S is pragma Preelaborate; --------------- -- Registers -- --------------- -- Main enable for I 2S function in this Flexcomm type CFG1_MAINENABLE_Field is ( -- All I 2S channel pairs in this Flexcomm are disabled and the internal -- state machines, counters, and flags are reset. No other channel pairs -- can be enabled. Disabled, -- This I 2S channel pair is enabled. Other channel pairs in this -- Flexcomm may be enabled in their individual PAIRENABLE bits. Enabled) with Size => 1; for CFG1_MAINENABLE_Field use (Disabled => 0, Enabled => 1); -- Data flow Pause. Allows pausing data flow between the I2S -- serializer/deserializer and the FIFO. This could be done in order to -- change streams, or while restarting after a data underflow or overflow. -- When paused, FIFO operations can be done without corrupting data that is -- in the process of being sent or received. Once a data pause has been -- requested, the interface may need to complete sending data that was in -- progress before interrupting the flow of data. Software must check that -- the pause is actually in effect before taking action. This is done by -- monitoring the DATAPAUSED flag in the STAT register. When DATAPAUSE is -- cleared, data transfer will resume at the beginning of the next frame. type CFG1_DATAPAUSE_Field is ( -- Normal operation, or resuming normal operation at the next frame if -- the I2S has already been paused. Normal, -- A pause in the data flow is being requested. It is in effect when -- DATAPAUSED in STAT = 1. Pause) with Size => 1; for CFG1_DATAPAUSE_Field use (Normal => 0, Pause => 1); -- Provides the number of I2S channel pairs in this Flexcomm This is a -- read-only field whose value may be different in other Flexcomms. 00 = -- there is 1 I2S channel pair in this Flexcomm. 01 = there are 2 I2S -- channel pairs in this Flexcomm. 10 = there are 3 I2S channel pairs in -- this Flexcomm. 11 = there are 4 I2S channel pairs in this Flexcomm. type CFG1_PAIRCOUNT_Field is ( -- 1 I2S channel pairs in this flexcomm Pairs_1, -- 2 I2S channel pairs in this flexcomm Pairs_2, -- 3 I2S channel pairs in this flexcomm Pairs_3, -- 4 I2S channel pairs in this flexcomm Pairs_4) with Size => 2; for CFG1_PAIRCOUNT_Field use (Pairs_1 => 0, Pairs_2 => 1, Pairs_3 => 2, Pairs_4 => 3); -- Master / slave configuration selection, determining how SCK and WS are -- used by all channel pairs in this Flexcomm. type CFG1_MSTSLVCFG_Field is ( -- Normal slave mode, the default mode. SCK and WS are received from a -- master and used to transmit or receive data. Normal_Slave_Mode, -- WS synchronized master. WS is received from another master and used -- to synchronize the generation of SCK, when divided from the Flexcomm -- function clock. Ws_Sync_Master, -- Master using an existing SCK. SCK is received and used directly to -- generate WS, as well as transmitting or receiving data. Master_Using_Sck, -- Normal master mode. SCK and WS are generated so they can be sent to -- one or more slave devices. Normal_Master) with Size => 2; for CFG1_MSTSLVCFG_Field use (Normal_Slave_Mode => 0, Ws_Sync_Master => 1, Master_Using_Sck => 2, Normal_Master => 3); -- Selects the basic I2S operating mode. Other configurations modify this -- to obtain all supported cases. See Formats and modes for examples. type CFG1_MODE_Field is ( -- I2S mode a.k.a. 'classic' mode. WS has a 50% duty cycle, with (for -- each enabled channel pair) one piece of left channel data occurring -- during the first phase, and one pieces of right channel data -- occurring during the second phase. In this mode, the data region -- begins one clock after the leading WS edge for the frame. For a 50% -- WS duty cycle, FRAMELEN must define an even number of I2S clocks for -- the frame. If FRAMELEN defines an odd number of clocks per frame, the -- extra clock will occur on the right. Classic_Mode, -- DSP mode where WS has a 50% duty cycle. See remark for mode 0. Dsp_Mode_Ws_50_Dutycycle, -- DSP mode where WS has a one clock long pulse at the beginning of each -- data frame. Dsp_Mode_Ws_1_Clock, -- DSP mode where WS has a one data slot long pulse at the beginning of -- each data frame. Dsp_Mode_Ws_1_Data) with Size => 2; for CFG1_MODE_Field use (Classic_Mode => 0, Dsp_Mode_Ws_50_Dutycycle => 1, Dsp_Mode_Ws_1_Clock => 2, Dsp_Mode_Ws_1_Data => 3); -- Right channel data is in the Low portion of FIFO data. Essentially, this -- swaps left and right channel data as it is transferred to or from the -- FIFO. This bit is not used if the data width is greater than 24 bits or -- if PDMDATA = 1. Note that if the ONECHANNEL field (bit 10 of this -- register) = 1, the one channel to be used is the nominally the left -- channel. POSITION can still place that data in the frame where right -- channel data is normally located. if all enabled channel pairs have -- ONECHANNEL = 1, then RIGHTLOW = 1 is not allowed. type CFG1_RIGHTLOW_Field is ( -- The right channel is taken from the high part of the FIFO data. For -- example, when data is 16 bits, FIFO bits 31:16 are used for the right -- channel. Right_High, -- The right channel is taken from the low part of the FIFO data. For -- example, when data is 16 bits, FIFO bits 15:0 are used for the right -- channel. Right_Low) with Size => 1; for CFG1_RIGHTLOW_Field use (Right_High => 0, Right_Low => 1); -- Left Justify data. type CFG1_LEFTJUST_Field is ( -- Data is transferred between the FIFO and the I2S -- serializer/deserializer right justified, i.e. starting from bit 0 and -- continuing to the position defined by DATALEN. This would correspond -- to right justified data in the stream on the data bus. Right_Justified, -- Data is transferred between the FIFO and the I2S -- serializer/deserializer left justified, i.e. starting from the MSB of -- the FIFO entry and continuing for the number of bits defined by -- DATALEN. This would correspond to left justified data in the stream -- on the data bus. Left_Justified) with Size => 1; for CFG1_LEFTJUST_Field use (Right_Justified => 0, Left_Justified => 1); -- Single channel mode. Applies to both transmit and receive. This -- configuration bit applies only to the first I2S channel pair. Other -- channel pairs may select this mode independently in their separate CFG1 -- registers. type CFG1_ONECHANNEL_Field is ( -- I2S data for this channel pair is treated as left and right channels. Dual_Channel, -- I2S data for this channel pair is treated as a single channel, -- functionally the left channel for this pair. In mode 0 only, the -- right side of the frame begins at POSITION = 0x100. This is because -- mode 0 makes a clear distinction between the left and right sides of -- the frame. When ONECHANNEL = 1, the single channel of data may be -- placed on the right by setting POSITION to 0x100 + the data position -- within the right side (e.g. 0x108 would place data starting at the -- 8th clock after the middle of the frame). In other modes, data for -- the single channel of data is placed at the clock defined by -- POSITION. Single_Channel) with Size => 1; for CFG1_ONECHANNEL_Field use (Dual_Channel => 0, Single_Channel => 1); -- SCK polarity. type CFG1_SCK_POL_Field is ( -- Data is launched on SCK falling edges and sampled on SCK rising edges -- (standard for I2S). Falling_Edge, -- Data is launched on SCK rising edges and sampled on SCK falling -- edges. Rising_Edge) with Size => 1; for CFG1_SCK_POL_Field use (Falling_Edge => 0, Rising_Edge => 1); -- WS polarity. type CFG1_WS_POL_Field is ( -- Data frames begin at a falling edge of WS (standard for classic I2S). Not_Inverted, -- WS is inverted, resulting in a data frame beginning at a rising edge -- of WS (standard for most 'non-classic' variations of I2S). Inverted) with Size => 1; for CFG1_WS_POL_Field use (Not_Inverted => 0, Inverted => 1); subtype CFG1_DATALEN_Field is HAL.UInt5; -- Configuration register 1 for the primary channel pair. type CFG1_Register is record -- Main enable for I 2S function in this Flexcomm MAINENABLE : CFG1_MAINENABLE_Field := NXP_SVD.I2S.Disabled; -- Data flow Pause. Allows pausing data flow between the I2S -- serializer/deserializer and the FIFO. This could be done in order to -- change streams, or while restarting after a data underflow or -- overflow. When paused, FIFO operations can be done without corrupting -- data that is in the process of being sent or received. Once a data -- pause has been requested, the interface may need to complete sending -- data that was in progress before interrupting the flow of data. -- Software must check that the pause is actually in effect before -- taking action. This is done by monitoring the DATAPAUSED flag in the -- STAT register. When DATAPAUSE is cleared, data transfer will resume -- at the beginning of the next frame. DATAPAUSE : CFG1_DATAPAUSE_Field := NXP_SVD.I2S.Normal; -- Provides the number of I2S channel pairs in this Flexcomm This is a -- read-only field whose value may be different in other Flexcomms. 00 = -- there is 1 I2S channel pair in this Flexcomm. 01 = there are 2 I2S -- channel pairs in this Flexcomm. 10 = there are 3 I2S channel pairs in -- this Flexcomm. 11 = there are 4 I2S channel pairs in this Flexcomm. PAIRCOUNT : CFG1_PAIRCOUNT_Field := NXP_SVD.I2S.Pairs_1; -- Master / slave configuration selection, determining how SCK and WS -- are used by all channel pairs in this Flexcomm. MSTSLVCFG : CFG1_MSTSLVCFG_Field := NXP_SVD.I2S.Normal_Slave_Mode; -- Selects the basic I2S operating mode. Other configurations modify -- this to obtain all supported cases. See Formats and modes for -- examples. MODE : CFG1_MODE_Field := NXP_SVD.I2S.Classic_Mode; -- Right channel data is in the Low portion of FIFO data. Essentially, -- this swaps left and right channel data as it is transferred to or -- from the FIFO. This bit is not used if the data width is greater than -- 24 bits or if PDMDATA = 1. Note that if the ONECHANNEL field (bit 10 -- of this register) = 1, the one channel to be used is the nominally -- the left channel. POSITION can still place that data in the frame -- where right channel data is normally located. if all enabled channel -- pairs have ONECHANNEL = 1, then RIGHTLOW = 1 is not allowed. RIGHTLOW : CFG1_RIGHTLOW_Field := NXP_SVD.I2S.Right_High; -- Left Justify data. LEFTJUST : CFG1_LEFTJUST_Field := NXP_SVD.I2S.Right_Justified; -- Single channel mode. Applies to both transmit and receive. This -- configuration bit applies only to the first I2S channel pair. Other -- channel pairs may select this mode independently in their separate -- CFG1 registers. ONECHANNEL : CFG1_ONECHANNEL_Field := NXP_SVD.I2S.Dual_Channel; -- unspecified Reserved_11_11 : HAL.Bit := 16#0#; -- SCK polarity. SCK_POL : CFG1_SCK_POL_Field := NXP_SVD.I2S.Falling_Edge; -- WS polarity. WS_POL : CFG1_WS_POL_Field := NXP_SVD.I2S.Not_Inverted; -- unspecified Reserved_14_15 : HAL.UInt2 := 16#0#; -- Data Length, minus 1 encoded, defines the number of data bits to be -- transmitted or received for all I2S channel pairs in this Flexcomm. -- Note that data is only driven to or received from SDA for the number -- of bits defined by DATALEN. DATALEN is also used in these ways by the -- I2S: Determines the size of data transfers between the FIFO and the -- I2S serializer/deserializer. See FIFO buffer configurations and usage -- In mode 1, 2, and 3, determines the location of right data following -- left data in the frame. In mode 3 (where WS has a one data slot long -- pulse at the beginning of each data frame) determines the duration of -- the WS pulse. Values: 0x00 to 0x02 = not supported 0x03 = data is 4 -- bits in length 0x04 = data is 5 bits in length 0x1F = data is 32 bits -- in length DATALEN : CFG1_DATALEN_Field := 16#0#; -- unspecified Reserved_21_31 : HAL.UInt11 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CFG1_Register use record MAINENABLE at 0 range 0 .. 0; DATAPAUSE at 0 range 1 .. 1; PAIRCOUNT at 0 range 2 .. 3; MSTSLVCFG at 0 range 4 .. 5; MODE at 0 range 6 .. 7; RIGHTLOW at 0 range 8 .. 8; LEFTJUST at 0 range 9 .. 9; ONECHANNEL at 0 range 10 .. 10; Reserved_11_11 at 0 range 11 .. 11; SCK_POL at 0 range 12 .. 12; WS_POL at 0 range 13 .. 13; Reserved_14_15 at 0 range 14 .. 15; DATALEN at 0 range 16 .. 20; Reserved_21_31 at 0 range 21 .. 31; end record; subtype CFG2_FRAMELEN_Field is HAL.UInt9; subtype CFG2_POSITION_Field is HAL.UInt9; -- Configuration register 2 for the primary channel pair. type CFG2_Register is record -- Frame Length, minus 1 encoded, defines the number of clocks and data -- bits in the frames that this channel pair participates in. See Frame -- format. 0x000 to 0x002 = not supported 0x003 = frame is 4 bits in -- total length 0x004 = frame is 5 bits in total length 0x1FF = frame is -- 512 bits in total length if FRAMELEN is an defines an odd length -- frame (e.g. 33 clocks) in mode 0 or 1, the extra clock appears in the -- right half. When MODE = 3, FRAMELEN must be larger than DATALEN in -- order for the WS pulse to be generated correctly. FRAMELEN : CFG2_FRAMELEN_Field := 16#0#; -- unspecified Reserved_9_15 : HAL.UInt7 := 16#0#; -- Data Position. Defines the location within the frame of the data for -- this channel pair. POSITION + DATALEN must be less than FRAMELEN. See -- Frame format. When MODE = 0, POSITION defines the location of data in -- both the left phase and right phase, starting one clock after the WS -- edge. In other modes, POSITION defines the location of data within -- the entire frame. ONECHANNEL = 1 while MODE = 0 is a special case, -- see the description of ONECHANNEL. The combination of DATALEN and the -- POSITION fields of all channel pairs must be made such that the -- channels do not overlap within the frame. 0x000 = data begins at bit -- position 0 (the first bit position) within the frame or WS phase. -- 0x001 = data begins at bit position 1 within the frame or WS phase. -- 0x002 = data begins at bit position 2 within the frame or WS phase. POSITION : CFG2_POSITION_Field := 16#0#; -- unspecified Reserved_25_31 : HAL.UInt7 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CFG2_Register use record FRAMELEN at 0 range 0 .. 8; Reserved_9_15 at 0 range 9 .. 15; POSITION at 0 range 16 .. 24; Reserved_25_31 at 0 range 25 .. 31; end record; -- Busy status for the primary channel pair. Other BUSY flags may be found -- in the STAT register for each channel pair. type STAT_BUSY_Field is ( -- The transmitter/receiver for channel pair is currently idle. Idle, -- The transmitter/receiver for channel pair is currently processing -- data. Busy) with Size => 1; for STAT_BUSY_Field use (Idle => 0, Busy => 1); -- Slave Frame Error flag. This applies when at least one channel pair is -- operating as a slave. An error indicates that the incoming WS signal did -- not transition as expected due to a mismatch between FRAMELEN and the -- actual incoming I2S stream. type STAT_SLVFRMERR_Field is ( -- No error has been recorded. No_Error, -- An error has been recorded for some channel pair that is operating in -- slave mode. ERROR is cleared by writing a 1 to this bit position. Error) with Size => 1; for STAT_SLVFRMERR_Field use (No_Error => 0, Error => 1); -- Left/Right indication. This flag is considered to be a debugging aid and -- is not expected to be used by an I2S driver. Valid when one channel pair -- is busy. Indicates left or right data being processed for the currently -- busy channel pair. type STAT_LR_Field is ( -- Left channel. Left_Channel, -- Right channel. Right_Channel) with Size => 1; for STAT_LR_Field use (Left_Channel => 0, Right_Channel => 1); -- Data Paused status flag. Applies to all I2S channels type STAT_DATAPAUSED_Field is ( -- Data is not currently paused. A data pause may have been requested -- but is not yet in force, waiting for an allowed pause point. Refer to -- the description of the DATAPAUSE control bit in the CFG1 register. Not_Paused, -- A data pause has been requested and is now in force. Paused) with Size => 1; for STAT_DATAPAUSED_Field use (Not_Paused => 0, Paused => 1); -- Status register for the primary channel pair. type STAT_Register is record -- Read-only. Busy status for the primary channel pair. Other BUSY flags -- may be found in the STAT register for each channel pair. BUSY : STAT_BUSY_Field := NXP_SVD.I2S.Idle; -- Write-only. Slave Frame Error flag. This applies when at least one -- channel pair is operating as a slave. An error indicates that the -- incoming WS signal did not transition as expected due to a mismatch -- between FRAMELEN and the actual incoming I2S stream. SLVFRMERR : STAT_SLVFRMERR_Field := NXP_SVD.I2S.No_Error; -- Read-only. Left/Right indication. This flag is considered to be a -- debugging aid and is not expected to be used by an I2S driver. Valid -- when one channel pair is busy. Indicates left or right data being -- processed for the currently busy channel pair. LR : STAT_LR_Field := NXP_SVD.I2S.Left_Channel; -- Read-only. Data Paused status flag. Applies to all I2S channels DATAPAUSED : STAT_DATAPAUSED_Field := NXP_SVD.I2S.Not_Paused; -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for STAT_Register use record BUSY at 0 range 0 .. 0; SLVFRMERR at 0 range 1 .. 1; LR at 0 range 2 .. 2; DATAPAUSED at 0 range 3 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; subtype DIV_DIV_Field is HAL.UInt12; -- Clock divider, used by all channel pairs. type DIV_Register is record -- This field controls how this I2S block uses the Flexcomm function -- clock. 0x000 = The Flexcomm function clock is used directly. 0x001 = -- The Flexcomm function clock is divided by 2. 0x002 = The Flexcomm -- function clock is divided by 3. 0xFFF = The Flexcomm function clock -- is divided by 4,096. DIV : DIV_DIV_Field := 16#0#; -- unspecified Reserved_12_31 : HAL.UInt20 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for DIV_Register use record DIV at 0 range 0 .. 11; Reserved_12_31 at 0 range 12 .. 31; end record; -- Enable the transmit FIFO. type FIFOCFG_ENABLETX_Field is ( -- The transmit FIFO is not enabled. Disabled, -- The transmit FIFO is enabled. Enabled) with Size => 1; for FIFOCFG_ENABLETX_Field use (Disabled => 0, Enabled => 1); -- Enable the receive FIFO. type FIFOCFG_ENABLERX_Field is ( -- The receive FIFO is not enabled. Disabled, -- The receive FIFO is enabled. Enabled) with Size => 1; for FIFOCFG_ENABLERX_Field use (Disabled => 0, Enabled => 1); -- Transmit I2S empty 0. Determines the value sent by the I2S in transmit -- mode if the TX FIFO becomes empty. This value is sent repeatedly until -- the I2S is paused, the error is cleared, new data is provided, and the -- I2S is un-paused. type FIFOCFG_TXI2SE0_Field is ( -- If the TX FIFO becomes empty, the last value is sent. This setting -- may be used when the data length is 24 bits or less, or when MONO = 1 -- for this channel pair. Last_Value, -- If the TX FIFO becomes empty, 0 is sent. Use if the data length is -- greater than 24 bits or if zero fill is preferred. Zero) with Size => 1; for FIFOCFG_TXI2SE0_Field use (Last_Value => 0, Zero => 1); -- Packing format for 48-bit data. This relates to how data is entered into -- or taken from the FIFO by software or DMA. type FIFOCFG_PACK48_Field is ( -- 48-bit I2S FIFO entries are handled as all 24-bit values. Bit_24, -- 48-bit I2S FIFO entries are handled as alternating 32-bit and 16-bit -- values. Bit_32_16) with Size => 1; for FIFOCFG_PACK48_Field use (Bit_24 => 0, Bit_32_16 => 1); subtype FIFOCFG_SIZE_Field is HAL.UInt2; -- DMA configuration for transmit. type FIFOCFG_DMATX_Field is ( -- DMA is not used for the transmit function. Disabled, -- Trigger DMA for the transmit function if the FIFO is not full. -- Generally, data interrupts would be disabled if DMA is enabled. Enabled) with Size => 1; for FIFOCFG_DMATX_Field use (Disabled => 0, Enabled => 1); -- DMA configuration for receive. type FIFOCFG_DMARX_Field is ( -- DMA is not used for the receive function. Disabled, -- Trigger DMA for the receive function if the FIFO is not empty. -- Generally, data interrupts would be disabled if DMA is enabled. Enabled) with Size => 1; for FIFOCFG_DMARX_Field use (Disabled => 0, Enabled => 1); -- Wake-up for transmit FIFO level. This allows the device to be woken from -- reduced power modes (up to power-down, as long as the peripheral -- function works in that power mode) without enabling the TXLVL interrupt. -- Only DMA wakes up, processes data, and goes back to sleep. The CPU will -- remain stopped until woken by another cause, such as DMA completion. See -- Hardware Wake-up control register. type FIFOCFG_WAKETX_Field is ( -- Only enabled interrupts will wake up the device form reduced power -- modes. Disabled, -- A device wake-up for DMA will occur if the transmit FIFO level -- reaches the value specified by TXLVL in FIFOTRIG, even when the TXLVL -- interrupt is not enabled. Enabled) with Size => 1; for FIFOCFG_WAKETX_Field use (Disabled => 0, Enabled => 1); -- Wake-up for receive FIFO level. This allows the device to be woken from -- reduced power modes (up to power-down, as long as the peripheral -- function works in that power mode) without enabling the TXLVL interrupt. -- Only DMA wakes up, processes data, and goes back to sleep. The CPU will -- remain stopped until woken by another cause, such as DMA completion. See -- Hardware Wake-up control register. type FIFOCFG_WAKERX_Field is ( -- Only enabled interrupts will wake up the device form reduced power -- modes. Disabled, -- A device wake-up for DMA will occur if the receive FIFO level reaches -- the value specified by RXLVL in FIFOTRIG, even when the RXLVL -- interrupt is not enabled. Enabled) with Size => 1; for FIFOCFG_WAKERX_Field use (Disabled => 0, Enabled => 1); -- FIFO configuration and enable register. type FIFOCFG_Register is record -- Enable the transmit FIFO. ENABLETX : FIFOCFG_ENABLETX_Field := NXP_SVD.I2S.Disabled; -- Enable the receive FIFO. ENABLERX : FIFOCFG_ENABLERX_Field := NXP_SVD.I2S.Disabled; -- Transmit I2S empty 0. Determines the value sent by the I2S in -- transmit mode if the TX FIFO becomes empty. This value is sent -- repeatedly until the I2S is paused, the error is cleared, new data is -- provided, and the I2S is un-paused. TXI2SE0 : FIFOCFG_TXI2SE0_Field := NXP_SVD.I2S.Last_Value; -- Packing format for 48-bit data. This relates to how data is entered -- into or taken from the FIFO by software or DMA. PACK48 : FIFOCFG_PACK48_Field := NXP_SVD.I2S.Bit_24; -- Read-only. FIFO size configuration. This is a read-only field. 0x0 = -- FIFO is configured as 16 entries of 8 bits. 0x1, 0x2, 0x3 = not -- applicable to USART. SIZE : FIFOCFG_SIZE_Field := 16#0#; -- unspecified Reserved_6_11 : HAL.UInt6 := 16#0#; -- DMA configuration for transmit. DMATX : FIFOCFG_DMATX_Field := NXP_SVD.I2S.Disabled; -- DMA configuration for receive. DMARX : FIFOCFG_DMARX_Field := NXP_SVD.I2S.Disabled; -- Wake-up for transmit FIFO level. This allows the device to be woken -- from reduced power modes (up to power-down, as long as the peripheral -- function works in that power mode) without enabling the TXLVL -- interrupt. Only DMA wakes up, processes data, and goes back to sleep. -- The CPU will remain stopped until woken by another cause, such as DMA -- completion. See Hardware Wake-up control register. WAKETX : FIFOCFG_WAKETX_Field := NXP_SVD.I2S.Disabled; -- Wake-up for receive FIFO level. This allows the device to be woken -- from reduced power modes (up to power-down, as long as the peripheral -- function works in that power mode) without enabling the TXLVL -- interrupt. Only DMA wakes up, processes data, and goes back to sleep. -- The CPU will remain stopped until woken by another cause, such as DMA -- completion. See Hardware Wake-up control register. WAKERX : FIFOCFG_WAKERX_Field := NXP_SVD.I2S.Disabled; -- Empty command for the transmit FIFO. When a 1 is written to this bit, -- the TX FIFO is emptied. EMPTYTX : Boolean := False; -- Empty command for the receive FIFO. When a 1 is written to this bit, -- the RX FIFO is emptied. EMPTYRX : Boolean := False; -- unspecified Reserved_18_31 : HAL.UInt14 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FIFOCFG_Register use record ENABLETX at 0 range 0 .. 0; ENABLERX at 0 range 1 .. 1; TXI2SE0 at 0 range 2 .. 2; PACK48 at 0 range 3 .. 3; SIZE at 0 range 4 .. 5; Reserved_6_11 at 0 range 6 .. 11; DMATX at 0 range 12 .. 12; DMARX at 0 range 13 .. 13; WAKETX at 0 range 14 .. 14; WAKERX at 0 range 15 .. 15; EMPTYTX at 0 range 16 .. 16; EMPTYRX at 0 range 17 .. 17; Reserved_18_31 at 0 range 18 .. 31; end record; subtype FIFOSTAT_TXLVL_Field is HAL.UInt5; subtype FIFOSTAT_RXLVL_Field is HAL.UInt5; -- FIFO status register. type FIFOSTAT_Register is record -- TX FIFO error. Will be set if a transmit FIFO error occurs. This -- could be an overflow caused by pushing data into a full FIFO, or by -- an underflow if the FIFO is empty when data is needed. Cleared by -- writing a 1 to this bit. TXERR : Boolean := False; -- RX FIFO error. Will be set if a receive FIFO overflow occurs, caused -- by software or DMA not emptying the FIFO fast enough. Cleared by -- writing a 1 to this bit. RXERR : Boolean := False; -- unspecified Reserved_2_2 : HAL.Bit := 16#0#; -- Read-only. Peripheral interrupt. When 1, this indicates that the -- peripheral function has asserted an interrupt. The details can be -- found by reading the peripheral's STAT register. PERINT : Boolean := False; -- Read-only. Transmit FIFO empty. When 1, the transmit FIFO is empty. -- The peripheral may still be processing the last piece of data. TXEMPTY : Boolean := True; -- Read-only. Transmit FIFO not full. When 1, the transmit FIFO is not -- full, so more data can be written. When 0, the transmit FIFO is full -- and another write would cause it to overflow. TXNOTFULL : Boolean := True; -- Read-only. Receive FIFO not empty. When 1, the receive FIFO is not -- empty, so data can be read. When 0, the receive FIFO is empty. RXNOTEMPTY : Boolean := False; -- Read-only. Receive FIFO full. When 1, the receive FIFO is full. Data -- needs to be read out to prevent the peripheral from causing an -- overflow. RXFULL : Boolean := False; -- Read-only. Transmit FIFO current level. A 0 means the TX FIFO is -- currently empty, and the TXEMPTY and TXNOTFULL flags will be 1. Other -- values tell how much data is actually in the TX FIFO at the point -- where the read occurs. If the TX FIFO is full, the TXEMPTY and -- TXNOTFULL flags will be 0. TXLVL : FIFOSTAT_TXLVL_Field := 16#0#; -- unspecified Reserved_13_15 : HAL.UInt3 := 16#0#; -- Read-only. Receive FIFO current level. A 0 means the RX FIFO is -- currently empty, and the RXFULL and RXNOTEMPTY flags will be 0. Other -- values tell how much data is actually in the RX FIFO at the point -- where the read occurs. If the RX FIFO is full, the RXFULL and -- RXNOTEMPTY flags will be 1. RXLVL : FIFOSTAT_RXLVL_Field := 16#0#; -- unspecified Reserved_21_31 : HAL.UInt11 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FIFOSTAT_Register use record TXERR at 0 range 0 .. 0; RXERR at 0 range 1 .. 1; Reserved_2_2 at 0 range 2 .. 2; PERINT at 0 range 3 .. 3; TXEMPTY at 0 range 4 .. 4; TXNOTFULL at 0 range 5 .. 5; RXNOTEMPTY at 0 range 6 .. 6; RXFULL at 0 range 7 .. 7; TXLVL at 0 range 8 .. 12; Reserved_13_15 at 0 range 13 .. 15; RXLVL at 0 range 16 .. 20; Reserved_21_31 at 0 range 21 .. 31; end record; -- Transmit FIFO level trigger enable. This trigger will become an -- interrupt if enabled in FIFOINTENSET, or a DMA trigger if DMATX in -- FIFOCFG is set. type FIFOTRIG_TXLVLENA_Field is ( -- Transmit FIFO level does not generate a FIFO level trigger. Disabled, -- An trigger will be generated if the transmit FIFO level reaches the -- value specified by the TXLVL field in this register. Enabled) with Size => 1; for FIFOTRIG_TXLVLENA_Field use (Disabled => 0, Enabled => 1); -- Receive FIFO level trigger enable. This trigger will become an interrupt -- if enabled in FIFOINTENSET, or a DMA trigger if DMARX in FIFOCFG is set. type FIFOTRIG_RXLVLENA_Field is ( -- Receive FIFO level does not generate a FIFO level trigger. Disabled, -- An trigger will be generated if the receive FIFO level reaches the -- value specified by the RXLVL field in this register. Enabled) with Size => 1; for FIFOTRIG_RXLVLENA_Field use (Disabled => 0, Enabled => 1); subtype FIFOTRIG_TXLVL_Field is HAL.UInt4; subtype FIFOTRIG_RXLVL_Field is HAL.UInt4; -- FIFO trigger settings for interrupt and DMA request. type FIFOTRIG_Register is record -- Transmit FIFO level trigger enable. This trigger will become an -- interrupt if enabled in FIFOINTENSET, or a DMA trigger if DMATX in -- FIFOCFG is set. TXLVLENA : FIFOTRIG_TXLVLENA_Field := NXP_SVD.I2S.Disabled; -- Receive FIFO level trigger enable. This trigger will become an -- interrupt if enabled in FIFOINTENSET, or a DMA trigger if DMARX in -- FIFOCFG is set. RXLVLENA : FIFOTRIG_RXLVLENA_Field := NXP_SVD.I2S.Disabled; -- unspecified Reserved_2_7 : HAL.UInt6 := 16#0#; -- Transmit FIFO level trigger point. This field is used only when -- TXLVLENA = 1. If enabled to do so, the FIFO level can wake up the -- device just enough to perform DMA, then return to the reduced power -- mode. See Hardware Wake-up control register. 0 = trigger when the TX -- FIFO becomes empty. 1 = trigger when the TX FIFO level decreases to -- one entry. 15 = trigger when the TX FIFO level decreases to 15 -- entries (is no longer full). TXLVL : FIFOTRIG_TXLVL_Field := 16#0#; -- unspecified Reserved_12_15 : HAL.UInt4 := 16#0#; -- Receive FIFO level trigger point. The RX FIFO level is checked when a -- new piece of data is received. This field is used only when RXLVLENA -- = 1. If enabled to do so, the FIFO level can wake up the device just -- enough to perform DMA, then return to the reduced power mode. See -- Hardware Wake-up control register. 0 = trigger when the RX FIFO has -- received one entry (is no longer empty). 1 = trigger when the RX FIFO -- has received two entries. 15 = trigger when the RX FIFO has received -- 16 entries (has become full). RXLVL : FIFOTRIG_RXLVL_Field := 16#0#; -- unspecified Reserved_20_31 : HAL.UInt12 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FIFOTRIG_Register use record TXLVLENA at 0 range 0 .. 0; RXLVLENA at 0 range 1 .. 1; Reserved_2_7 at 0 range 2 .. 7; TXLVL at 0 range 8 .. 11; Reserved_12_15 at 0 range 12 .. 15; RXLVL at 0 range 16 .. 19; Reserved_20_31 at 0 range 20 .. 31; end record; -- Determines whether an interrupt occurs when a transmit error occurs, -- based on the TXERR flag in the FIFOSTAT register. type FIFOINTENSET_TXERR_Field is ( -- No interrupt will be generated for a transmit error. Disabled, -- An interrupt will be generated when a transmit error occurs. Enabled) with Size => 1; for FIFOINTENSET_TXERR_Field use (Disabled => 0, Enabled => 1); -- Determines whether an interrupt occurs when a receive error occurs, -- based on the RXERR flag in the FIFOSTAT register. type FIFOINTENSET_RXERR_Field is ( -- No interrupt will be generated for a receive error. Disabled, -- An interrupt will be generated when a receive error occurs. Enabled) with Size => 1; for FIFOINTENSET_RXERR_Field use (Disabled => 0, Enabled => 1); -- Determines whether an interrupt occurs when a the transmit FIFO reaches -- the level specified by the TXLVL field in the FIFOTRIG register. type FIFOINTENSET_TXLVL_Field is ( -- No interrupt will be generated based on the TX FIFO level. Disabled, -- If TXLVLENA in the FIFOTRIG register = 1, an interrupt will be -- generated when the TX FIFO level decreases to the level specified by -- TXLVL in the FIFOTRIG register. Enabled) with Size => 1; for FIFOINTENSET_TXLVL_Field use (Disabled => 0, Enabled => 1); -- Determines whether an interrupt occurs when a the receive FIFO reaches -- the level specified by the TXLVL field in the FIFOTRIG register. type FIFOINTENSET_RXLVL_Field is ( -- No interrupt will be generated based on the RX FIFO level. Disabled, -- If RXLVLENA in the FIFOTRIG register = 1, an interrupt will be -- generated when the when the RX FIFO level increases to the level -- specified by RXLVL in the FIFOTRIG register. Enabled) with Size => 1; for FIFOINTENSET_RXLVL_Field use (Disabled => 0, Enabled => 1); -- FIFO interrupt enable set (enable) and read register. type FIFOINTENSET_Register is record -- Determines whether an interrupt occurs when a transmit error occurs, -- based on the TXERR flag in the FIFOSTAT register. TXERR : FIFOINTENSET_TXERR_Field := NXP_SVD.I2S.Disabled; -- Determines whether an interrupt occurs when a receive error occurs, -- based on the RXERR flag in the FIFOSTAT register. RXERR : FIFOINTENSET_RXERR_Field := NXP_SVD.I2S.Disabled; -- Determines whether an interrupt occurs when a the transmit FIFO -- reaches the level specified by the TXLVL field in the FIFOTRIG -- register. TXLVL : FIFOINTENSET_TXLVL_Field := NXP_SVD.I2S.Disabled; -- Determines whether an interrupt occurs when a the receive FIFO -- reaches the level specified by the TXLVL field in the FIFOTRIG -- register. RXLVL : FIFOINTENSET_RXLVL_Field := NXP_SVD.I2S.Disabled; -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FIFOINTENSET_Register use record TXERR at 0 range 0 .. 0; RXERR at 0 range 1 .. 1; TXLVL at 0 range 2 .. 2; RXLVL at 0 range 3 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; -- FIFO interrupt enable clear (disable) and read register. type FIFOINTENCLR_Register is record -- Writing one clears the corresponding bits in the FIFOINTENSET -- register. TXERR : Boolean := False; -- Writing one clears the corresponding bits in the FIFOINTENSET -- register. RXERR : Boolean := False; -- Writing one clears the corresponding bits in the FIFOINTENSET -- register. TXLVL : Boolean := False; -- Writing one clears the corresponding bits in the FIFOINTENSET -- register. RXLVL : Boolean := False; -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FIFOINTENCLR_Register use record TXERR at 0 range 0 .. 0; RXERR at 0 range 1 .. 1; TXLVL at 0 range 2 .. 2; RXLVL at 0 range 3 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; -- FIFO interrupt status register. type FIFOINTSTAT_Register is record -- Read-only. TX FIFO error. TXERR : Boolean; -- Read-only. RX FIFO error. RXERR : Boolean; -- Read-only. Transmit FIFO level interrupt. TXLVL : Boolean; -- Read-only. Receive FIFO level interrupt. RXLVL : Boolean; -- Read-only. Peripheral interrupt. PERINT : Boolean; -- unspecified Reserved_5_31 : HAL.UInt27; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FIFOINTSTAT_Register use record TXERR at 0 range 0 .. 0; RXERR at 0 range 1 .. 1; TXLVL at 0 range 2 .. 2; RXLVL at 0 range 3 .. 3; PERINT at 0 range 4 .. 4; Reserved_5_31 at 0 range 5 .. 31; end record; subtype FIFOWR48H_TXDATA_Field is HAL.UInt24; -- FIFO write data for upper data bits. May only be used if the I2S is -- configured for 2x 24-bit data and not using DMA. type FIFOWR48H_Register is record -- Write-only. Transmit data to the FIFO. Whether this register is used -- and the number of bits used depends on configuration details. TXDATA : FIFOWR48H_TXDATA_Field := 16#0#; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FIFOWR48H_Register use record TXDATA at 0 range 0 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype FIFORD48H_RXDATA_Field is HAL.UInt24; -- FIFO read data for upper data bits. May only be used if the I2S is -- configured for 2x 24-bit data and not using DMA. type FIFORD48H_Register is record -- Read-only. Received data from the FIFO. Whether this register is used -- and the number of bits used depends on configuration details. RXDATA : FIFORD48H_RXDATA_Field; -- unspecified Reserved_24_31 : HAL.UInt8; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FIFORD48H_Register use record RXDATA at 0 range 0 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype FIFORD48HNOPOP_RXDATA_Field is HAL.UInt24; -- FIFO data read for upper data bits with no FIFO pop. May only be used if -- the I2S is configured for 2x 24-bit data and not using DMA. type FIFORD48HNOPOP_Register is record -- Read-only. Received data from the FIFO. Whether this register is used -- and the number of bits used depends on configuration details. RXDATA : FIFORD48HNOPOP_RXDATA_Field; -- unspecified Reserved_24_31 : HAL.UInt8; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FIFORD48HNOPOP_Register use record RXDATA at 0 range 0 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype ID_APERTURE_Field is HAL.UInt8; subtype ID_MINOR_REV_Field is HAL.UInt4; subtype ID_MAJOR_REV_Field is HAL.UInt4; subtype ID_ID_Field is HAL.UInt16; -- I2S Module identification type ID_Register is record -- Read-only. Aperture: encoded as (aperture size/4K) -1, so 0x00 means -- a 4K aperture. APERTURE : ID_APERTURE_Field; -- Read-only. Minor revision of module implementation, starting at 0. MINOR_REV : ID_MINOR_REV_Field; -- Read-only. Major revision of module implementation, starting at 0. MAJOR_REV : ID_MAJOR_REV_Field; -- Read-only. Unique module identifier for this IP block. ID : ID_ID_Field; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for ID_Register use record APERTURE at 0 range 0 .. 7; MINOR_REV at 0 range 8 .. 11; MAJOR_REV at 0 range 12 .. 15; ID at 0 range 16 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- I2S interface type I2S_Peripheral is record -- Configuration register 1 for the primary channel pair. CFG1 : aliased CFG1_Register; -- Configuration register 2 for the primary channel pair. CFG2 : aliased CFG2_Register; -- Status register for the primary channel pair. STAT : aliased STAT_Register; -- Clock divider, used by all channel pairs. DIV : aliased DIV_Register; -- FIFO configuration and enable register. FIFOCFG : aliased FIFOCFG_Register; -- FIFO status register. FIFOSTAT : aliased FIFOSTAT_Register; -- FIFO trigger settings for interrupt and DMA request. FIFOTRIG : aliased FIFOTRIG_Register; -- FIFO interrupt enable set (enable) and read register. FIFOINTENSET : aliased FIFOINTENSET_Register; -- FIFO interrupt enable clear (disable) and read register. FIFOINTENCLR : aliased FIFOINTENCLR_Register; -- FIFO interrupt status register. FIFOINTSTAT : aliased FIFOINTSTAT_Register; -- FIFO write data. FIFOWR : aliased HAL.UInt32; -- FIFO write data for upper data bits. May only be used if the I2S is -- configured for 2x 24-bit data and not using DMA. FIFOWR48H : aliased FIFOWR48H_Register; -- FIFO read data. FIFORD : aliased HAL.UInt32; -- FIFO read data for upper data bits. May only be used if the I2S is -- configured for 2x 24-bit data and not using DMA. FIFORD48H : aliased FIFORD48H_Register; -- FIFO data read with no FIFO pop. FIFORDNOPOP : aliased HAL.UInt32; -- FIFO data read for upper data bits with no FIFO pop. May only be used -- if the I2S is configured for 2x 24-bit data and not using DMA. FIFORD48HNOPOP : aliased FIFORD48HNOPOP_Register; -- I2S Module identification ID : aliased ID_Register; end record with Volatile; for I2S_Peripheral use record CFG1 at 16#C00# range 0 .. 31; CFG2 at 16#C04# range 0 .. 31; STAT at 16#C08# range 0 .. 31; DIV at 16#C1C# range 0 .. 31; FIFOCFG at 16#E00# range 0 .. 31; FIFOSTAT at 16#E04# range 0 .. 31; FIFOTRIG at 16#E08# range 0 .. 31; FIFOINTENSET at 16#E10# range 0 .. 31; FIFOINTENCLR at 16#E14# range 0 .. 31; FIFOINTSTAT at 16#E18# range 0 .. 31; FIFOWR at 16#E20# range 0 .. 31; FIFOWR48H at 16#E24# range 0 .. 31; FIFORD at 16#E30# range 0 .. 31; FIFORD48H at 16#E34# range 0 .. 31; FIFORDNOPOP at 16#E40# range 0 .. 31; FIFORD48HNOPOP at 16#E44# range 0 .. 31; ID at 16#FFC# range 0 .. 31; end record; -- I2S interface I2S0_Periph : aliased I2S_Peripheral with Import, Address => System'To_Address (16#40086000#); -- I2S interface I2S1_Periph : aliased I2S_Peripheral with Import, Address => System'To_Address (16#40087000#); -- I2S interface I2S2_Periph : aliased I2S_Peripheral with Import, Address => System'To_Address (16#40088000#); -- I2S interface I2S3_Periph : aliased I2S_Peripheral with Import, Address => System'To_Address (16#40089000#); -- I2S interface I2S4_Periph : aliased I2S_Peripheral with Import, Address => System'To_Address (16#4008A000#); -- I2S interface I2S5_Periph : aliased I2S_Peripheral with Import, Address => System'To_Address (16#40096000#); -- I2S interface I2S6_Periph : aliased I2S_Peripheral with Import, Address => System'To_Address (16#40097000#); -- I2S interface I2S7_Periph : aliased I2S_Peripheral with Import, Address => System'To_Address (16#40098000#); end NXP_SVD.I2S;
package Ada_Code is procedure Ada_Proc; pragma Export (C, Ada_Proc, "Ada_Proc"); procedure Ada_C_Caller; pragma Export (C, Ada_C_Caller, "Ada_C_Caller"); end Ada_Code;
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 euler05 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; function max2_0(a : in Integer; b : in Integer) return Integer is begin if a > b then return a; else return b; end if; end; type e is Array (Integer range <>) of Integer; type e_PTR is access e; function primesfactors(c : in Integer) return e_PTR is tab : e_PTR; n : Integer; d : Integer; begin n := c; tab := new e (0..n); for i in integer range 0..n loop tab(i) := 0; end loop; d := 2; while n /= 1 and then d * d <= n loop if n rem d = 0 then tab(d) := tab(d) + 1; n := n / d; else d := d + 1; end if; end loop; tab(n) := tab(n) + 1; return tab; end; t : e_PTR; product : Integer; o : e_PTR; lim : Integer; begin lim := 20; o := new e (0..lim); for m in integer range 0..lim loop o(m) := 0; end loop; for i in integer range 1..lim loop t := primesfactors(i); for j in integer range 1..i loop o(j) := max2_0(o(j), t(j)); end loop; end loop; product := 1; for k in integer range 1..lim loop for l in integer range 1..o(k) loop product := product * k; end loop; end loop; PInt(product); PString(new char_array'( To_C("" & Character'Val(10)))); end;
with RP.Device; with RP.I2C_Master; with RP.GPIO; with Pico; package body BB_Pico_Bsp.I2C is I2C_Port : RP.I2C_Master.I2C_Master_Port renames RP.Device.I2C_0; I2C_SDA : RP.GPIO.GPIO_Point renames Pico.GP4; I2C_SCL : RP.GPIO.GPIO_Point renames Pico.GP5; procedure Initialize; ---------------- -- Initialize -- ---------------- procedure Initialize is begin I2C_SDA.Configure (RP.GPIO.Output, RP.GPIO.Pull_Up, RP.GPIO.I2C); I2C_SCL.Configure (RP.GPIO.Output, RP.GPIO.Pull_Up, RP.GPIO.I2C); I2C_Port.Configure (400_000); end Initialize; ---------- -- Port -- ---------- function Port return not null HAL.I2C.Any_I2C_Port is begin return I2C_Port'Access; end Port; begin Initialize; end BB_Pico_Bsp.I2C;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- B I N D O . U N I T S -- -- -- -- S p e c -- -- -- -- Copyright (C) 2019-2020, 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 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. 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 COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- For full architecture, see unit Bindo. -- The following unit contains facilities to collect all elaborable units in -- the bind and inspect their properties. with GNAT; use GNAT; with GNAT.Sets; use GNAT.Sets; package Bindo.Units is --------------- -- Unit sets -- --------------- function Hash_Unit (U_Id : Unit_Id) return Bucket_Range_Type; pragma Inline (Hash_Unit); -- Obtain the hash value of key U_Id package Unit_Sets is new Membership_Sets (Element_Type => Unit_Id, "=" => "=", Hash => Hash_Unit); procedure Collect_Elaborable_Units; pragma Inline (Collect_Elaborable_Units); -- Gather all units in the bind that require elaboration. The units are -- accessible via iterator Elaborable_Units_Iterator. function Corresponding_Body (U_Id : Unit_Id) return Unit_Id; pragma Inline (Corresponding_Body); -- Return the body of a spec unit U_Id function Corresponding_Spec (U_Id : Unit_Id) return Unit_Id; pragma Inline (Corresponding_Spec); -- Return the spec of a body unit U_Id function Corresponding_Unit (FNam : File_Name_Type) return Unit_Id; pragma Inline (Corresponding_Unit); -- Obtain the unit which corresponds to name FNam function Corresponding_Unit (UNam : Unit_Name_Type) return Unit_Id; pragma Inline (Corresponding_Unit); -- Obtain the unit which corresponds to name FNam function File_Name (U_Id : Unit_Id) return File_Name_Type; pragma Inline (File_Name); -- Obtain the file name of unit U_Id type Unit_Processor_Ptr is access procedure (U_Id : Unit_Id); procedure For_Each_Elaborable_Unit (Processor : Unit_Processor_Ptr); pragma Inline (For_Each_Elaborable_Unit); -- Invoke Processor on each elaborable unit in the bind procedure For_Each_Unit (Processor : Unit_Processor_Ptr); pragma Inline (For_Each_Unit); -- Invoke Processor on each unit in the bind function Has_No_Elaboration_Code (U_Id : Unit_Id) return Boolean; pragma Inline (Has_No_Elaboration_Code); -- Determine whether unit U_Id lacks elaboration code function Hash_Invocation_Signature (IS_Id : Invocation_Signature_Id) return Bucket_Range_Type; pragma Inline (Hash_Invocation_Signature); -- Obtain the hash value of key IS_Id function Invocation_Graph_Encoding (U_Id : Unit_Id) return Invocation_Graph_Encoding_Kind; pragma Inline (Invocation_Graph_Encoding); -- Obtain the encoding format used to capture invocation constructs and -- relations in the ALI file of unit U_Id. function Is_Dynamically_Elaborated (U_Id : Unit_Id) return Boolean; pragma Inline (Is_Dynamically_Elaborated); -- Determine whether unit U_Id was compiled using the dynamic elaboration -- model. function Is_Internal_Unit (U_Id : Unit_Id) return Boolean; pragma Inline (Is_Internal_Unit); -- Determine whether unit U_Id is internal function Is_Predefined_Unit (U_Id : Unit_Id) return Boolean; pragma Inline (Is_Predefined_Unit); -- Determine whether unit U_Id is predefined function Name (U_Id : Unit_Id) return Unit_Name_Type; pragma Inline (Name); -- Obtain the name of unit U_Id function Needs_Elaboration (IS_Id : Invocation_Signature_Id) return Boolean; pragma Inline (Needs_Elaboration); -- Determine whether invocation signature IS_Id belongs to a construct that -- appears in a unit which needs to be elaborated. function Needs_Elaboration (U_Id : Unit_Id) return Boolean; pragma Inline (Needs_Elaboration); -- Determine whether unit U_Id needs to be elaborated function Number_Of_Elaborable_Units return Natural; pragma Inline (Number_Of_Elaborable_Units); -- Obtain the number of units in the bind that need to be elaborated function Number_Of_Units return Natural; pragma Inline (Number_Of_Units); -- Obtain the number of units in the bind --------------- -- Iterators -- --------------- -- The following type represents an iterator over all units that need to be -- elaborated. type Elaborable_Units_Iterator is private; function Has_Next (Iter : Elaborable_Units_Iterator) return Boolean; pragma Inline (Has_Next); -- Determine whether iterator Iter has more units to examine function Iterate_Elaborable_Units return Elaborable_Units_Iterator; pragma Inline (Iterate_Elaborable_Units); -- Obtain an iterator over all units that need to be elaborated procedure Next (Iter : in out Elaborable_Units_Iterator; U_Id : out Unit_Id); pragma Inline (Next); -- Return the current unit referenced by iterator Iter and advance to the -- next available unit. ----------------- -- Maintenance -- ----------------- procedure Finalize_Units; pragma Inline (Finalize_Units); -- Destroy the internal structures of this unit procedure Initialize_Units; pragma Inline (Initialize_Units); -- Initialize the internal structures of this unit private type Elaborable_Units_Iterator is new Unit_Sets.Iterator; end Bindo.Units;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2020 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 Interfaces.C.Strings; with Ada.Unchecked_Conversion; with EGL.API; with EGL.Errors; package body EGL.Objects.Displays is function Client_Extensions return String_List is No_Display : constant ID_Type := ID_Type (System.Null_Address); Result : constant C.Strings.chars_ptr := API.Query_String (No_Display, Extensions); use all type C.Strings.chars_ptr; begin if Result = C.Strings.Null_Ptr then Errors.Raise_Exception_On_EGL_Error; return (1 .. 0 => SU.To_Unbounded_String ("")); else return EGL.Extensions (Result); end if; exception when Errors.Invalid_Operation_Error => raise Feature_Not_Supported with "EGL_EXT_client_extensions not supported"; end Client_Extensions; function Extensions (Object : Display) return String_List is Result : constant C.Strings.chars_ptr := API.Query_String (Object.ID, Extensions); use all type C.Strings.chars_ptr; begin if Result = C.Strings.Null_Ptr then Errors.Raise_Exception_On_EGL_Error; return (1 .. 0 => SU.To_Unbounded_String ("")); else return EGL.Extensions (Result); end if; end Extensions; function Vendor (Object : Display) return String is Result : constant C.Strings.chars_ptr := API.Query_String (Object.ID, Vendor); use all type C.Strings.chars_ptr; begin if Result = C.Strings.Null_Ptr then Errors.Raise_Exception_On_EGL_Error; return ""; else return C.Strings.Value (Result); end if; end Vendor; function Version (Object : Display) return String is Result : constant C.Strings.chars_ptr := API.Query_String (Object.ID, Version); use all type C.Strings.chars_ptr; begin if Result = C.Strings.Null_Ptr then Errors.Raise_Exception_On_EGL_Error; return ""; else return C.Strings.Value (Result); end if; end Version; ----------------------------------------------------------------------------- function Create_Display (Platform : Platform_Kind; Native_Display : Void_Ptr; Device : Devices.Device) return Display is No_Display : constant ID_Type := ID_Type (System.Null_Address); Attributes : constant Int_Array := (1 => None); Major, Minor : Int; begin Check_Extension (Client_Extensions, (case Platform is when GBM => "EGL_MESA_platform_gbm", when Displays.Device => "EGL_EXT_platform_device", when Wayland => "EGL_EXT_platform_wayland")); return Result : Display (Platform) do Result.Reference.ID := API.Get_Platform_Display.Ref (Platform, Native_Display, Attributes); if Result.ID = No_Display or else not Boolean (API.Initialize_Display (Result.ID, Major, Minor)) then Errors.Raise_Exception_On_EGL_Error; end if; Result.Device := Device; end return; end Create_Display; function Create_Display (Device : Devices.Device) return Display is function Convert is new Ada.Unchecked_Conversion (ID_Type, Void_Ptr); begin return Create_Display (Displays.Device, Convert (Device.ID), Device); end Create_Display; function Create_Display (Wayland_Display : Native_Display_Ptr) return Display is function Convert is new Ada.Unchecked_Conversion (Native_Display_Ptr, Void_Ptr); begin return Create_Display (Displays.Wayland, Convert (Wayland_Display), Devices.No_Device); end Create_Display; function Create_Display (Platform : Platform_Kind) return Display is function Convert is new Ada.Unchecked_Conversion (ID_Type, Void_Ptr); function Get_First_Device return Devices.Device is All_Devices : constant EGL.Objects.Devices.Device_List := EGL.Objects.Devices.Devices; begin return All_Devices (All_Devices'First); end Get_First_Device; Native_Display : constant Void_Ptr := (case Platform is when GBM | Wayland => Void_Ptr (System.Null_Address), when Displays.Device => Convert (Get_First_Device.ID)); begin return Create_Display (Platform, Native_Display, Devices.No_Device); end Create_Display; overriding procedure Pre_Finalize (Object : in out Display) is No_Display : constant ID_Type := ID_Type (System.Null_Address); begin pragma Assert (Object.ID /= No_Display); if not Boolean (API.Terminate_Display (Object.ID)) then Errors.Raise_Exception_On_EGL_Error; end if; Object.Reference.ID := No_Display; end Pre_Finalize; function Device (Object : Display) return Devices.Device is use type EGL.Objects.Devices.Device; begin return Result : constant Devices.Device := Devices.Get_Device (Object) do if Object.Device /= Devices.No_Device then pragma Assert (Object.Device.ID = Result.ID); end if; end return; end Device; end EGL.Objects.Displays;
with Ada.Text_IO; with CryptAda.Digests.Message_Digests.MD4; with CryptAda.Digests.Hashes; with CryptAda.Pragmatics; with CryptAda.Utils.Format; procedure RC_MD4 is use CryptAda.Digests.Message_Digests; use CryptAda.Digests; use CryptAda.Pragmatics; function To_Byte_Array (Item : String) return Byte_Array is Result : Byte_Array (Item'Range); begin for I in Result'Range loop Result (I) := Byte (Character'Pos (Item (I))); end loop; return Result; end To_Byte_Array; Text : constant String := "Rosetta Code"; Bytes : constant Byte_Array := To_Byte_Array (Text); Handle : constant Message_Digest_Handle := MD4.Get_Message_Digest_Handle; Pointer : constant Message_Digest_Ptr := Get_Message_Digest_Ptr (Handle); Hash : Hashes.Hash; begin Digest_Start (Pointer); Digest_Update (Pointer, Bytes); Digest_End (Pointer, Hash); Ada.Text_IO.Put_Line ("""" & Text & """: " & CryptAda.Utils.Format.To_Hex_String (Hashes.Get_Bytes (Hash))); end RC_MD4;
-- RUN: %llvmgcc -c %s with System; procedure Negative_Field_Offset (N : Integer) is type String_Pointer is access String; -- Force use of a thin pointer. for String_Pointer'Size use System.Word_Size; P : String_Pointer; procedure Q (P : String_Pointer) is begin P (1) := 'Z'; end; begin P := new String (1 .. N); Q (P); end;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2012 Felix Krause <contact@flyx.org> -- -- 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 Interfaces.C.Strings; with GL.API; with GL.Enums; package body GL.Objects.Shaders is procedure Set_Source (Subject : Shader; Source : String) is C_Shader_Source : C.Strings.chars_ptr := C.Strings.New_String (Source); C_Source : constant Low_Level.CharPtr_Array := (1 => C_Shader_Source); Lengths : constant Low_Level.Int_Array := (1 => Source'Length); begin API.Shader_Source.Ref (Subject.Reference.GL_Id, 1, C_Source, Lengths); C.Strings.Free (C_Shader_Source); end Set_Source; function Source (Subject : Shader) return String is Source_Length : Size := 0; begin API.Get_Shader_Param.Ref (Subject.Reference.GL_Id, Enums.Shader_Source_Length, Source_Length); if Source_Length = 0 then return ""; end if; declare Shader_Source : String (1 .. Integer (Source_Length)); begin API.Get_Shader_Source.Ref (Subject.Reference.GL_Id, Source_Length, Source_Length, Shader_Source); return Shader_Source (1 .. Integer (Source_Length)); end; end Source; procedure Compile (Subject : Shader) is begin API.Compile_Shader.Ref (Subject.Reference.GL_Id); end Compile; function Compile_Status (Subject : Shader) return Boolean is Value : Int := 0; begin API.Get_Shader_Param.Ref (Subject.Reference.GL_Id, Enums.Compile_Status, Value); return Value /= 0; end Compile_Status; function Info_Log (Subject : Shader) return String is Log_Length : Size := 0; begin API.Get_Shader_Param.Ref (Subject.Reference.GL_Id, Enums.Info_Log_Length, Log_Length); if Log_Length = 0 then return ""; end if; declare Info_Log : String (1 .. Integer (Log_Length)); begin API.Get_Shader_Info_Log.Ref (Subject.Reference.GL_Id, Log_Length, Log_Length, Info_Log); return Info_Log (1 .. Integer (Log_Length)); end; end Info_Log; overriding procedure Initialize_Id (Object : in out Shader) is begin Object.Reference.GL_Id := API.Create_Shader.Ref (Object.Kind); end Initialize_Id; overriding procedure Delete_Id (Object : in out Shader) is begin API.Delete_Shader.Ref (Object.Reference.GL_Id); Object.Reference.GL_Id := 0; end Delete_Id; end GL.Objects.Shaders;
-- -- Copyright (C) 2015-2016 secunet Security Networks AG -- -- 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 HW.Time; with HW.MMIO_Range; pragma Elaborate_All (HW.MMIO_Range); with HW.GFX.GMA.Config; with HW.Debug; with GNAT.Source_Info; use type HW.Word64; package body HW.GFX.GMA.Registers with Refined_State => (Address_State => (Regs.Base_Address, GTT.Base_Address), Register_State => Regs.State, GTT_State => GTT.State) is pragma Disable_Atomic_Synchronization; type Registers_Range is new Natural range 0 .. 16#0020_0000# / Register_Width - 1; type Registers_Type is array (Registers_Range) of Word32 with Atomic_Components, Size => 16#20_0000# * 8; package Regs is new MMIO_Range (Base_Addr => Config.Default_MMIO_Base, Element_T => Word32, Index_T => Registers_Range, Array_T => Registers_Type); ---------------------------------------------------------------------------- type GTT_PTE_Type is mod 2 ** (Config.GTT_PTE_Size * 8); type GTT_Registers_Type is array (GTT_Range) of GTT_PTE_Type with Volatile_Components, Size => Config.GTT_Size * 8; package GTT is new MMIO_Range (Base_Addr => Config.Default_MMIO_Base + Config.GTT_Offset, Element_T => GTT_PTE_Type, Index_T => GTT_Range, Array_T => GTT_Registers_Type); GTT_PTE_Valid : constant Word32 := 1; ---------------------------------------------------------------------------- subtype Fence_Range is Registers_Range range 0 .. Config.Fence_Count - 1; FENCE_PAGE_SHIFT : constant := 12; FENCE_PAGE_MASK : constant := 16#ffff_f000#; FENCE_TILE_WALK_YMAJOR : constant := 1 * 2 ** 1; FENCE_VALID : constant := 1 * 2 ** 0; function Fence_Lower_Idx (Fence : Fence_Range) return Registers_Range is (Config.Fence_Base / Register_Width + 2 * Fence); function Fence_Upper_Idx (Fence : Fence_Range) return Registers_Range is (Fence_Lower_Idx (Fence) + 1); procedure Clear_Fences is begin for Fence in Fence_Range loop Regs.Write (Fence_Lower_Idx (Fence), 0); end loop; end Clear_Fences; procedure Add_Fence (First_Page : in GTT_Range; Last_Page : in GTT_Range; Tiling : in XY_Tiling; Pitch : in Natural; Success : out Boolean) is Y_Tiles : constant Boolean := Tiling = Y_Tiled; Reg32 : Word32; begin pragma Debug (Debug.Put (GNAT.Source_Info.Enclosing_Entity & ": ")); pragma Debug (Debug.Put_Word32 (Shift_Left (Word32 (First_Page), 12))); pragma Debug (Debug.Put (":")); pragma Debug (Debug.Put_Word32 (Shift_Left (Word32 (Last_Page), 12))); pragma Debug (not Y_Tiles, Debug.Put (" X tiled in ")); pragma Debug ( Y_Tiles, Debug.Put (" Y tiled in ")); pragma Debug (Debug.Put_Int32 (Int32 (Pitch))); pragma Debug (Debug.Put_Line (" tiles per row.")); Success := False; for Fence in Fence_Range loop Regs.Read (Reg32, Fence_Lower_Idx (Fence)); if (Reg32 and FENCE_VALID) = 0 then Regs.Write (Index => Fence_Lower_Idx (Fence), Value => Shift_Left (Word32 (First_Page), FENCE_PAGE_SHIFT) or (if Y_Tiles then FENCE_TILE_WALK_YMAJOR else 0) or FENCE_VALID); Regs.Write (Index => Fence_Upper_Idx (Fence), Value => Shift_Left (Word32 (Last_Page), FENCE_PAGE_SHIFT) or Word32 (Pitch) * (if Y_Tiles then 1 else 4) - 1); Success := True; exit; end if; end loop; end Add_Fence; procedure Remove_Fence (First_Page, Last_Page : GTT_Range) is Page_Lower : constant Word32 := Shift_Left (Word32 (First_Page), FENCE_PAGE_SHIFT); Page_Upper : constant Word32 := Shift_Left (Word32 (Last_Page), FENCE_PAGE_SHIFT); Fence_Upper, Fence_Lower : Word32; begin for Fence in Fence_Range loop Regs.Read (Fence_Lower, Fence_Lower_Idx (Fence)); Regs.Read (Fence_Upper, Fence_Upper_Idx (Fence)); if (Fence_Lower and FENCE_PAGE_MASK) = Page_Lower and (Fence_Upper and FENCE_PAGE_MASK) = Page_Upper then Regs.Write (Fence_Lower_Idx (Fence), 0); exit; end if; end loop; end Remove_Fence; ---------------------------------------------------------------------------- procedure Write_GTT (GTT_Page : GTT_Range; Device_Address : GTT_Address_Type; Valid : Boolean) is begin if Config.Fold_39Bit_GTT_PTE then GTT.Write (Index => GTT_Page, Value => GTT_PTE_Type (Device_Address and 16#ffff_f000#) or GTT_PTE_Type (Shift_Right (Word64 (Device_Address), 32 - 4) and 16#0000_07f0#) or Boolean'Pos (Valid)); else GTT.Write (Index => GTT_Page, Value => GTT_PTE_Type (Device_Address and 16#7f_ffff_f000#) or Boolean'Pos (Valid)); end if; end Write_GTT; ---------------------------------------------------------------------------- package Rep is function Index (Reg : Registers_Index) return Registers_Range; end Rep; package body Rep is function Index (Reg : Registers_Index) return Registers_Range with SPARK_Mode => Off is begin return Reg'Enum_Rep; end Index; end Rep; -- Read a specific register procedure Read (Register : in Registers_Index; Value : out Word32; Verbose : in Boolean := True) is begin Regs.Read (Value, Rep.Index (Register)); pragma Debug (Verbose, Debug.Put (GNAT.Source_Info.Enclosing_Entity & ": ")); pragma Debug (Verbose, Debug.Put_Word32 (Value)); pragma Debug (Verbose, Debug.Put (" <- ")); pragma Debug (Verbose, Debug.Put_Word32 (Register'Enum_Rep * Register_Width)); pragma Debug (Verbose, Debug.Put (":")); pragma Debug (Verbose, Debug.Put_Line (Registers_Index'Image (Register))); end Read; ---------------------------------------------------------------------------- -- Read a specific register to post a previous write procedure Posting_Read (Register : Registers_Index) is Discard_Value : Word32; begin pragma Warnings (Off, "unused assignment to ""Discard_Value""", Reason => "Intentional dummy read to affect hardware."); Read (Register, Discard_Value); pragma Warnings (On, "unused assignment to ""Discard_Value"""); end Posting_Read; ---------------------------------------------------------------------------- -- Write a specific register procedure Write (Register : Registers_Index; Value : Word32) is begin pragma Debug (Debug.Put (GNAT.Source_Info.Enclosing_Entity & ": ")); pragma Debug (Debug.Put_Word32 (Value)); pragma Debug (Debug.Put (" -> ")); pragma Debug (Debug.Put_Word32 (Register'Enum_Rep * Register_Width)); pragma Debug (Debug.Put (":")); pragma Debug (Debug.Put_Line (Registers_Index'Image (Register))); Regs.Write (Rep.Index (Register), Value); pragma Debug (Debug.Register_Write_Wait); end Write; ---------------------------------------------------------------------------- -- Check whether all bits in @Register@ indicated by @Mask@ are set procedure Is_Set_Mask (Register : in Registers_Index; Mask : in Word32; Result : out Boolean) is Value : Word32; begin pragma Debug (Debug.Put (GNAT.Source_Info.Enclosing_Entity & ": ")); pragma Debug (Debug.Put_Line (Registers_Index'Image (Register))); Read (Register, Value); Result := (Value and Mask) = Mask; end Is_Set_Mask; ---------------------------------------------------------------------------- -- TODO: Should have Success parameter -- Wait for the bits in @Register@ indicated by @Mask@ to be of @Value@ procedure Wait (Register : Registers_Index; Mask : Word32; Value : Word32; TOut_MS : Natural := Default_Timeout_MS; Verbose : Boolean := False) is Current : Word32; Timeout : Time.T; Timed_Out : Boolean; begin pragma Debug (Debug.Put (GNAT.Source_Info.Enclosing_Entity & ": ")); pragma Debug (Debug.Put_Word32 (Value)); pragma Debug (Debug.Put (" <- ")); pragma Debug (Debug.Put_Word32 (Mask)); pragma Debug (Debug.Put (" & ")); pragma Debug (Debug.Put_Word32 (Register'Enum_Rep * Register_Width)); pragma Debug (Debug.Put (":")); pragma Debug (Debug.Put_Line (Registers_Index'Image (Register))); Timeout := Time.MS_From_Now (TOut_MS); loop Timed_Out := Time.Timed_Out (Timeout); Read (Register, Current, Verbose); if (Current and Mask) = Value then exit; end if; pragma Debug (Timed_Out, Debug.Put (GNAT.Source_Info.Enclosing_Entity)); pragma Debug (Timed_Out, Debug.Put_Line (": Timed Out!")); exit when Timed_Out; end loop; end Wait; ---------------------------------------------------------------------------- -- TODO: Should have Success parameter -- Wait for all bits in @Register@ indicated by @Mask@ to be set procedure Wait_Set_Mask (Register : in Registers_Index; Mask : in Word32; TOut_MS : in Natural := Default_Timeout_MS; Verbose : in Boolean := False) is begin Wait (Register, Mask, Mask, TOut_MS, Verbose); end Wait_Set_Mask; ---------------------------------------------------------------------------- -- TODO: Should have Success parameter -- Wait for bits in @Register@ indicated by @Mask@ to be clear procedure Wait_Unset_Mask (Register : Registers_Index; Mask : Word32; TOut_MS : in Natural := Default_Timeout_MS; Verbose : in Boolean := False) is begin Wait (Register, Mask, 0, TOut_MS, Verbose); end Wait_Unset_Mask; ---------------------------------------------------------------------------- -- Set bits from @Mask@ in @Register@ procedure Set_Mask (Register : Registers_Index; Mask : Word32) is Value : Word32; begin pragma Debug (Debug.Put (GNAT.Source_Info.Enclosing_Entity & ": ")); pragma Debug (Debug.Put_Word32 (Mask)); pragma Debug (Debug.Put (" .S ")); pragma Debug (Debug.Put_Line (Registers_Index'Image (Register))); Read (Register, Value); Value := Value or Mask; Write (Register, Value); end Set_Mask; ---------------------------------------------------------------------------- -- Mask out @Mask@ in @Register@ procedure Unset_Mask (Register : Registers_Index; Mask : Word32) is Value : Word32; begin pragma Debug (Debug.Put (GNAT.Source_Info.Enclosing_Entity & ": ")); pragma Debug (Debug.Put_Word32 (Mask)); pragma Debug (Debug.Put (" !S ")); pragma Debug (Debug.Put_Line (Registers_Index'Image (Register))); Read (Register, Value); Value := Value and not Mask; Write (Register, Value); end Unset_Mask; ---------------------------------------------------------------------------- -- Mask out @Unset_Mask@ and set @Set_Mask@ in @Register@ procedure Unset_And_Set_Mask (Register : Registers_Index; Mask_Unset : Word32; Mask_Set : Word32) is Value : Word32; begin pragma Debug (Debug.Put (GNAT.Source_Info.Enclosing_Entity & ": ")); pragma Debug (Debug.Put_Line (Registers_Index'Image (Register))); Read (Register, Value); Value := (Value and not Mask_Unset) or Mask_Set; Write (Register, Value); end Unset_And_Set_Mask; ---------------------------------------------------------------------------- procedure Set_Register_Base (Base : Word64; GTT_Base : Word64 := 0) is begin Regs.Set_Base_Address (Base); if GTT_Base = 0 then GTT.Set_Base_Address (Base + Config.GTT_Offset); else GTT.Set_Base_Address (GTT_Base); end if; end Set_Register_Base; end HW.GFX.GMA.Registers;
with Ada.Calendar; private with Ada.Finalization; package taglib is type File (<>) is tagged limited private; type Tag (<>) is tagged limited private; type AudioProperties (<>) is tagged limited private; procedure set_strings_unicode (unicode : Boolean); procedure set_string_management_enabled (management : Boolean); type File_Type is (MPEG, OggVorbis, FLAC, MPC, OggFlac, WavPack, Speex, TrueAudio, MP4, ASF); function file_new (filename : String) return File; function file_new (filename : String; c_type : File_Type) return File; function is_valid (F : File) return Boolean; function Get_Tag (F : File'Class) return Tag; function Get_AudioProperties (F : File'Class) return AudioProperties; procedure save (F : File); function title (T : Tag) return String; function artist (T : Tag) return String; function album (T : Tag) return String; function comment (T : Tag) return String; function genre (T : Tag) return String; function year (T : Tag) return Ada.Calendar.Year_Number; function Track (T : Tag) return Natural; procedure set_title (T : in out Tag; title : String); procedure set_artist (T : in out Tag; artist : String); procedure set_album (T : in out Tag; album : String); procedure set_comment (T : in out Tag; comment : String); procedure set_genre (T : in out Tag; genre : String); procedure set_year (T : in out Tag; year : Ada.Calendar.Year_Number); procedure set_track (T : in out Tag; Track : Positive); procedure tag_free_strings; function length (Properties : AudioProperties) return Natural; function bitrate (Properties : AudioProperties) return Natural; function samplerate (Properties : AudioProperties) return Natural; function channels (Properties : AudioProperties) return Natural; type ID3v2_Encoding is (Latin1, UTF16, UTF16BE, UTF8); procedure set_default_text_encoding (encoding : ID3v2_Encoding); private type TagLib_File; type TagLib_File_Access is access all TagLib_File with Storage_Size => 0; type File is new Ada.Finalization.Limited_Controlled with record Dummy : TagLib_File_Access; end record; procedure Finalize (Object : in out File); type Taglib_Tag; type Taglib_Tag_Access is access all Taglib_Tag with Storage_Size => 0; type Tag is new Ada.Finalization.Limited_Controlled with record dummy : Taglib_Tag_Access; end record; type TagLib_AudioProperties; type TagLib_AudioProperties_Access is access all TagLib_AudioProperties with Storage_Size => 0; type AudioProperties is new Ada.Finalization.Limited_Controlled with record dummy : TagLib_AudioProperties_Access; end record; type Package_Controler is new Ada.Finalization.Limited_Controlled with null record; end taglib;
with Ada.Text_IO; use Ada.Text_IO; procedure Calc is procedure Add (X, Y : Integer) is Sum : Integer; begin Sum := X + Y; Put_Line (Integer'Image (Sum)); end Add; procedure Sub (X, Y : Integer) is Diff : Integer; begin Diff := X - Y; Put_Line (Integer'Image (Diff)); end Sub; procedure Mul (X, Y : Integer) is Prod : Integer; begin Prod := X * Y; Put_Line (Integer'Image (Prod)); end Mul; procedure Div (X, Y : Float) is Quot : Float; begin Quot := X / Y; Put_Line (Float'Image (Quot)); end Div; begin Add (10, 3); Sub (10, 3); Mul (10, 3); Div (10.0, 5.0); end Calc;
pragma License (Unrestricted); -- implementation unit specialized for Windows with Ada.IO_Exceptions; with Ada.IO_Modes; with Ada.Streams; with System.Native_IO; with C.wincon; with C.windef; package System.Native_Text_IO is pragma Preelaborate; subtype Handle_Type is Native_IO.Handle_Type; -- file management Default_External : constant Ada.IO_Modes.File_External := Ada.IO_Modes.Locale; Default_New_Line : constant Ada.IO_Modes.File_New_Line := Ada.IO_Modes.CR_LF; type Packed_Form is record Stream_Form : Native_IO.Packed_Form; External : Ada.IO_Modes.File_External_Spec; New_Line : Ada.IO_Modes.File_New_Line_Spec; end record; pragma Suppress_Initialization (Packed_Form); pragma Pack (Packed_Form); -- read / write subtype Buffer_Type is String (1 .. 12); -- 2 code-points of UTF-8 subtype DBCS_Buffer_Type is String (1 .. 2); procedure To_UTF_8 ( Buffer : aliased DBCS_Buffer_Type; Last : Natural; Out_Buffer : out Buffer_Type; Out_Last : out Natural); procedure To_DBCS ( Buffer : Buffer_Type; Last : Natural; Out_Buffer : aliased out DBCS_Buffer_Type; Out_Last : out Natural); -- terminal procedure Terminal_Get ( Handle : Handle_Type; Item : Address; -- requires 6 bytes at least Length : Ada.Streams.Stream_Element_Offset; Out_Length : out Ada.Streams.Stream_Element_Offset); -- -1 when error procedure Terminal_Get_Immediate ( Handle : Handle_Type; Item : Address; -- requires 6 bytes at least Length : Ada.Streams.Stream_Element_Offset; Out_Length : out Ada.Streams.Stream_Element_Offset); -- -1 when error procedure Terminal_Put ( Handle : Handle_Type; Item : Address; Length : Ada.Streams.Stream_Element_Offset; Out_Length : out Ada.Streams.Stream_Element_Offset); -- -1 when error procedure Terminal_Size ( Handle : Handle_Type; Line_Length, Page_Length : out Natural); procedure Set_Terminal_Size ( Handle : Handle_Type; Line_Length, Page_Length : Natural); procedure Terminal_View ( Handle : Handle_Type; Left, Top : out Positive; Right, Bottom : out Natural); function Use_Terminal_Position (Handle : Handle_Type) return Boolean is (True); procedure Terminal_Position ( Handle : Handle_Type; Col, Line : out Positive); procedure Set_Terminal_Position ( Handle : Handle_Type; Col, Line : Positive); procedure Set_Terminal_Col ( Handle : Handle_Type; To : Positive); procedure Terminal_Clear ( Handle : Handle_Type); subtype Setting is C.windef.DWORD; procedure Set_Non_Canonical_Mode ( Handle : Handle_Type; Wait : Boolean; -- unreferenced Saved_Settings : aliased out Setting); procedure Restore ( Handle : Handle_Type; Settings : aliased Setting); procedure Set_Terminal_Attributes ( Handle : Handle_Type; Attributes : C.windef.WORD); type Output_State is record Position : C.wincon.COORD; Attributes : C.windef.WORD; end record; pragma Suppress_Initialization (Output_State); procedure Save_State (Handle : Handle_Type; To_State : out Output_State); procedure Reset_State (Handle : Handle_Type; From_State : Output_State); -- exceptions Device_Error : exception renames Ada.IO_Exceptions.Device_Error; Data_Error : exception renames Ada.IO_Exceptions.Data_Error; Layout_Error : exception renames Ada.IO_Exceptions.Layout_Error; end System.Native_Text_IO;
with Interfaces; use Interfaces; package Flash is pragma Preelaborate; procedure Init with Inline_Always; procedure Unlock with Inline_Always; procedure Lock with Inline_Always; procedure Enable_Erase with Inline_Always; procedure Enable_Write with Inline_Always; procedure Write (Addr : Unsigned_16; Value : Unsigned_16) with Inline_Always; function Read (Addr : Unsigned_16) return Unsigned_16 with Inline_Always; procedure Erase (Addr : Unsigned_16) with Inline_Always; procedure Wait_Until_Ready with Inline_Always; end Flash;
------------------------------------------------------------------------------ -- -- -- ASIS-for-GNAT INTERFACE COMPONENTS -- -- -- -- A S I S . D A T A _ D E C O M P O S I T I O N -- -- -- -- S p e c -- -- -- -- Copyright (c) 1995-2006, Free Software Foundation, Inc. -- -- -- -- This specification is derived from the Ada Semantic Interface -- -- Specification Standard (ISO/IEC 15291) for use with GNAT. The copyright -- -- notice above, and the license provisions that follow apply solely to the -- -- contents of the part following the private keyword. -- -- -- -- 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). -- -- -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- 22 package Asis.Data_Decomposition (optional) ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ with Repinfo; use Repinfo; package Asis.Data_Decomposition is ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Asis.Data_Decomposition -- -- This package is optional. -- -- Operations to decompose data values using the ASIS type information and a -- Portable_Data stream, representing a data value of that type. -- -- An application can write data, using the -- Asis.Data_Decomposition.Portable_Transfer package to an external medium -- for later retrieval by another application. The second application reads -- that data and then uses this package to convert that data into useful -- information. Simple discrete scalar types can be converted directly into -- useful information. Composite types, such as records and arrays, -- shall first be broken into their various discriminants and components. -- -- A data stream representing a record value can be decomposed into a group -- of discriminant and component data streams by extracting those streams -- from the record's data stream. This extraction is performed by applying -- any of the Record_Components which describe the discriminants and -- components of the record type. Each discriminant and each component of a -- record type is described by a Record_Component value. Each value -- encapsulates the information needed, by the implementation, to efficiently -- extract the associated field from a data stream representing a record -- value of the correct type. -- -- A data stream representing an array value can be decomposed into a group -- of component data streams by extracting those streams from the array's -- data stream. This extraction is performed by applying the single -- Array_Component which describes the components of the array type. One -- Array_Component value is used to describe all array components. The value -- encapsulates the information needed, by the implementation, to efficiently -- extract any of the array components. -- -- Assumptions and Limitations of this Interface: -- -- a) The data stream is appropriate for the ASIS host machine. For example, -- the implementation of this interface will not need to worry about -- byte flipping or reordering of bits caused by movement of data between -- machine architectures. -- -- b) Records, arrays, and their components may be packed. -- -- c) Records, array components, enumerations, and scalar types may have -- representation and length clauses applied to them. This includes scalar -- types used as record discriminants and array indices. -- -- d) This specification supports two of the three type models discussed -- below. Models A and B are supported. Model C is not supported. -- -- 1) Simple "static" types contain no variants, have a single fixed 'Size, -- and all components and attributes are themselves static and/or fully -- constrained. The size and position for any component of the type -- can be determined without regard to constraints. For example: -- -- type Static_Record is -- record -- F1, F2 : Natural; -- C1 : Wide_Character; -- A1 : Wide_String (1..5); -- end record; -- -- type Static_Discriminated (X : Boolean) is -- record -- F1, F2 : Natural; -- C1 : Wide_Character; -- end record; -- -- type Static_Array is array (Integer range 1 .. 100) of Boolean; -- type Static_Enum is (One, Two, Three); -- type Static_Integer is range 1 .. 512; -- type Static_Float is digits 15 range -100.0 .. 100.0; -- type Static_Fixed is delta 0.1 range -100.0 .. 100.0; -- -- 2) Simple "dynamic" types contain one or more components or attributes -- whose size, position, or value depends on the value of one or more -- constraints computed at execution time. This means that the size, -- position, or number of components within the data type cannot be -- determined without reference to constraint values. -- -- Records containing components, whose size depends on discriminants -- of the record, can be handled because the discriminants for a record -- value are fully specified by the data stream form of the record -- value. For example: -- -- type Dynamic_Length (Length : Natural) is -- record -- S1 : Wide_String (1 .. Length); -- end record; -- -- type Dynamic_Variant (When : Boolean) is -- record -- case When is -- when True => -- C1 : Wide_Character; -- when False => -- null; -- end case; -- end record; -- -- Arrays with an unconstrained subtype, whose 'Length, 'First, and -- 'Last depend on dynamic index constraints, can be handled because -- these attributes can be queried and stored when the data stream is -- written. For example: -- -- I : Integer := Some_Function; -- type Dynamic_Array is -- array (Integer range I .. I + 10) of Boolean; -- -- type Heap_Array is array (Integer range <>) of Boolean; -- type Access_Array is access Heap_Array; -- X : Access_Array := new Heap_Array (1 .. 100); -- -- 3) Complex, externally "discriminated" records, contain one or more -- components whose size or position depends on the value of one or -- more non-static external values (values not stored within instances -- of the type) at execution time. The size for a value of the type -- cannot be determined without reference to these external values, -- whose runtime values are not known to the ASIS Context and cannot be -- automatically recorded by the -- Asis.Data_Decomposition.Portable_Transfer generics. For example: -- -- N : Natural := Function_Call(); -- .... -- declare -- type Complex is -- record -- S1 : Wide_String (1 .. N); -- end record; -- begin -- .... -- end; -- -- -- General Usage Rules: -- -- All operations in this package will attempt to detect the use of invalid -- data streams. A data stream is "invalid" if an operation determines that -- the stream could not possibly represent a value of the expected variety. -- Possible errors are: stream is of incorrect length, stream contains bit -- patterns which are illegal, etc. The exception ASIS_Inappropriate_Element -- is raised in these cases. The Status value is Data_Error. The -- Diagnosis string will indicate the kind of error detected. -- -- All implementations will handle arrays with a minimum of 16 dimensions, -- or the number of dimensions allowed by their compiler, whichever is -- smaller. ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- 22.1 type Record_Component ------------------------------------------------------------------------------ -- Record_Component -- -- Describes one discriminant or component of a record type. Implementation -- is highly implementation dependent. The "=" operator is not meaningful -- between Record_Component values unless one of them is the -- Nil_Record_Component value. -- -- A record type describes composite values which contain zero or more -- discriminant and component fields. A_Record_Type_Definition can be -- queried to obtain a list of Record_Components. Each Record_Component -- contains the information necessary to extract one discriminant or -- component field of the record. -- -- Record_Components are intended for use with data stream extraction -- operations. An extraction operation is performed using a Record_Component, -- in conjunction with a data stream representing a value of the record type. -- The record data stream contains data for all fields of the record. The -- result is an extracted data stream representing just the value of the one -- field. Record_Components are implemented so as to allow for efficient -- extraction of field values. -- -- An extracted field data stream is suitable for all uses. If the field is a -- scalar type, it can be converted directly into useful information. If the -- field is, in turn, another composite value, it can be further decomposed -- into its own component values. -- -- There are two ways to obtain the Record_Components or the Array_Component -- needed to further decompose an embedded composite field. First, if the -- type of the field is known, the type definition can be directly queried to -- obtain the Record_Components or the Array_Component that describe its -- internal structure. Second, the Record_Component used to extract the field -- can be queried to obtain the same Record_Components or the same -- Array_Component. Both methods return identical information. -- -- This kind of nested decomposition can be carried to any required level. -- -- Record_Components become invalid when the Context, from which they -- originate, is closed. All Record_Components are obtained by referencing a) -- an Element, which has an associated Context, b) another Record_Component, -- or c) an Array_Component. Ultimately, all component values originate from -- a A_Type_Definition Element; that Element determines their Context of -- origin. ------------------------------------------------------------------------------ type Record_Component is private; Nil_Record_Component : constant Record_Component; function "=" (Left : Record_Component; Right : Record_Component) return Boolean is abstract; ------------------------------------------------------------------------------ -- 22.2 type Record_Component_List ------------------------------------------------------------------------------ type Record_Component_List is array (Asis.List_Index range <>) of Record_Component; ------------------------------------------------------------------------------ -- 22.3 type Array_Component ------------------------------------------------------------------------------ -- Array_Component -- -- Describes the components of an array valued field for a record type. -- Implementation is highly implementor dependent. The "=" operator is not -- meaningful between Array_Component values unless one of them is the -- Nil_Array_Component value. -- -- An array type describes composite values which contain zero or more indexed -- components. Both An_Unconstrained_Array_Definition or -- A_Constrained_Array_Definition can be queried to obtain a single -- Array_Component. The Array_Component contains the information necessary to -- extract any arbitrary component of the array. -- -- Array_Components are intended for use with data stream extraction -- operations. An extraction operation is performed using an Array_Component, -- in conjunction with a data stream representing a value of the array type. -- The array data stream contains data for all components of the array. The -- result is an extracted data stream representing just the value of the one -- component. Array_Components are implemented so as to allow for efficient -- extraction of array component values. -- -- An extracted component data stream is suitable for all uses. If the -- component is a scalar type, it can be converted directly into useful -- information. If the component is, in turn, another composite value, it can -- be further decomposed into its own component values. -- -- There are two ways to obtain the Record_Components or the Array_Component -- needed to further decompose an embedded composite component. First, if the -- type of the component is known, the type definition can be directly queried -- to obtain the Record_Components or the Array_Component that describe its -- internal structure. Second, the Array_Component used to extract the -- component can be queried to obtain the same Record_Components or the same -- Array_Component. Both methods return identical information. -- -- This kind of nested decomposition can be carried to any required level. -- -- Array_Components become invalid when the Context, from which they -- originate, is closed. All Record_Components are obtained by referencing a) -- an Element, which has an associated Context, b) a Record_Component, or c) -- another Array_Component. Ultimately, all component values originate from a -- A_Type_Definition Element; that Element determines their Context of origin. ------------------------------------------------------------------------------ type Array_Component is private; Nil_Array_Component : constant Array_Component; function "=" (Left : Array_Component; Right : Array_Component) return Boolean is abstract; ------------------------------------------------------------------------------ -- 22.4 type Array_Component_List ------------------------------------------------------------------------------ type Array_Component_List is array (Asis.List_Index range <>) of Array_Component; ------------------------------------------------------------------------------ -- 22.5 type Dimension_Indexes ------------------------------------------------------------------------------ -- Dimension_Indexes - an array of index values used to access an array stream ------------------------------------------------------------------------------ type Dimension_Indexes is array (Asis.ASIS_Positive range <>) of Asis.ASIS_Positive; ------------------------------------------------------------------------------ -- 22.6 type Array_Component_Iterator ------------------------------------------------------------------------------ -- Array_Component_Iterator - Used to iterate over successive components of an -- array. This can be more efficient than using individual index values when -- extracting array components from a data stream because it substitutes two -- subroutine calls (Next and Done) for the multiplications and divisions -- implicit in indexing an N dimensional array with a single index value. -- -- Iterators can be copied. The copies operate independently (have separate -- state). -- -- An example: -- -- declare -- Component : Array_Component := ...; -- Iter : Array_Component_Iterator; -- Array_Stream : Portable_Data (...) := ...; -- Component_Stream : Portable_Data (...); -- begin -- Iter := Array_Iterator (Component); -- while not Done (Iter) loop -- Component_Stream := Component_Data_Stream (Iter, Array_Stream); -- Next (Iter); -- end loop; -- end; ------------------------------------------------------------------------------ type Array_Component_Iterator is private; Nil_Array_Component_Iterator : constant Array_Component_Iterator; ------------------------------------------------------------------------------ -- 22.7 type Portable_Data ------------------------------------------------------------------------------ -- -- Portable Data Representation - an ordered "stream" of data values -- -- The portable representation for application data is an array of data -- values. This portable data representation is guaranteed to be valid when -- written, and later read, on the same machine architecture, using the same -- implementor's compiler and runtime system. Portability of the data -- values, across implementations and architectures, is not guaranteed. -- Some implementors may be able to provide data values which are portable -- across a larger subset of their supported machine architectures. -- -- Some of the problems encountered when changing architectures are: bit -- order, byte order, floating point representation, and alignment -- constraints. Some of the problems encountered when changing runtime -- systems or implementations are: type representation, optimization, -- record padding, and other I/O subsystem implementation variations. -- -- The nature of these data values is deliberately unspecified. An -- implementor will choose a data value type that is suitable for the -- expected uses of these arrays and data values. Arrays and data -- values have these uses: -- -- a) Array values are used in conjunction with the -- Asis.Data_Decomposition interface. The data value type should be -- readily decomposable, by that package, so that array and record -- components can be efficiently extracted from a data stream represented -- by this array type. The efficiency of that interface is a priority. -- -- b) The data value type is read and written by applications. It -- should have a size that makes efficient I/O possible. Applications can -- be expected to perform I/O in any or all of these ways: -- -- 1) Ada.Sequential_Io or Ada.Direct_Io could be used to read or write -- these values. -- -- 2) Individual values may be placed inside other types and those types -- may be read or written. -- -- 3) The 'Address of a data value, plus the 'Size of the data value -- type, may be used to perform low level system I/O. Note: This -- requires the 'Size of the type and the 'Size of a variable of that -- type to be the same for some implementations. -- -- 4) Individual values may be passed through Unchecked_Conversion in -- order to obtain a different value type, of the same 'Size, suitable -- for use with some user I/O facility. This usage is non-portable -- across implementations. -- -- c) Array values are read and written by applications. The data value -- type should have a size that makes efficient I/O possible. -- Applications can be expected to perform I/O in any or all of these -- ways: -- -- 1) Ada.Sequential_Io or Ada.Direct_Io could be used to read or write a -- constrained array subtype. -- -- 2) Array values may be placed inside other types and those types may -- be read and written. -- -- 3) The 'Address of the first array value, plus the 'Length of the -- array times the 'Size of the values, may be used to perform low -- level system I/O. Note: This implies that the array type is -- unpacked, or, that the packed array type has no "padding" (e.g., -- groups of five 6-bit values packed into 32-bit words with 2 bits -- of padding every 5 elements). -- -- 4) Array values may be passed through Unchecked_Conversion in order to -- obtain an array value, with a different value type, suitable for -- use with some user I/O facility. This usage is non-portable across -- implementations. -- -- The data value type should be chosen so that the 'Address of the first -- array data value is also the 'Address of the first storage unit containing -- array data. This is especially necessary for target architectures where -- the "bit" instructions address bits in the opposite direction as that used -- by normal machine memory (or array component) indexing. A recommended -- 'Size is System.Storage_Unit (or a multiple of that size). -- -- Implementations that do not support Unchecked_Conversion of array values, -- or which do not guarantee that Unchecked_Conversion of array values will -- always "do the right thing" (convert only the data, and not the dope vector -- information), should provide warnings in their ASIS documentation that -- detail possible consequences and work-arounds. -- -- The index range for the Portable_Data type shall be a numeric type whose -- range is large enough to encompass the Portable_Data representation for all -- possible runtime data values. -- -- All conversion interfaces always return Portable_Data array values with a -- 'First of one (1). -- -- The Portable_Value type may be implemented in any way -- whatsoever. It need not be a numeric type. ------------------------------------------------------------------------------ type Portable_Value is mod 2 ** 8; subtype Portable_Positive is Asis.ASIS_Positive range 1 .. Implementation_Defined_Integer_Constant; type Portable_Data is array (Portable_Positive range <>) of Portable_Value; Nil_Portable_Data : Portable_Data (1 .. 0); ------------------------------------------------------------------------------ -- 22.8 type Type_Model_Kinds ------------------------------------------------------------------------------ -- Type_Model_Kinds -- -- Each Type_Definition fits into one of three type models. ------------------------------------------------------------------------------ type Type_Model_Kinds is (A_Simple_Static_Model, A_Simple_Dynamic_Model, A_Complex_Dynamic_Model, Not_A_Type_Model); -- Nil arguments ------------------------------------------------------------------------------ -- 22.9 function Type_Model_Kind ------------------------------------------------------------------------------ function Type_Model_Kind (Type_Definition : Asis.Type_Definition) return Type_Model_Kinds; function Type_Model_Kind (Component : Record_Component) return Type_Model_Kinds; function Type_Model_Kind (Component : Array_Component) return Type_Model_Kinds; ------------------------------------------------------------------------------ -- Type_Definition - Specifies the type definition to query -- Component - Specifies a record field with a record or array type -- -- Returns the model that best describes the type indicated by the argument. -- Returns Not_A_Type_Model for any unexpected argument such as a Nil value. -- -- Expected Element_Kinds: -- A_Type_Definition -- -- --|A4G Type_Model_Kind is extended to operate on A_Subtype_Indication -- --|A4G Elements ------------------------------------------------------------------------------ -- 22.10 function Is_Nil ------------------------------------------------------------------------------ function Is_Nil (Right : Record_Component) return Boolean; function Is_Nil (Right : Array_Component) return Boolean; ------------------------------------------------------------------------------ -- Right - Specifies the component to check -- -- Returns True if Right is a Nil (or uninitialized) component value. -- -- Returns False for all other values. -- -- All component values are appropriate. -- ------------------------------------------------------------------------------ -- 22.11 function Is_Equal ------------------------------------------------------------------------------ function Is_Equal (Left : Record_Component; Right : Record_Component) return Boolean; function Is_Equal (Left : Array_Component; Right : Array_Component) return Boolean; ------------------------------------------------------------------------------ -- Left - Specifies the left component to compare -- Right - Specifies the right component to compare -- -- Returns True if Left and Right represent the same physical component of the -- same record or array type, from the same physical compilation unit. The -- two components may or may not be from the same open ASIS Context variable. -- -- Implies: -- Is_Equal (Enclosing_Compilation_Unit (Component_Declaration (Left)), -- Enclosing_Compilation_Unit (Component_Declaration (Right))) -- = True -- -- All component values are appropriate. -- ------------------------------------------------------------------------------ -- 22.12 function Is_Identical ------------------------------------------------------------------------------ function Is_Identical (Left : Record_Component; Right : Record_Component) return Boolean; function Is_Identical (Left : Array_Component; Right : Array_Component) return Boolean; ------------------------------------------------------------------------------ -- Left - Specifies the left component to compare -- Right - Specifies the right component to compare -- -- Returns True if Left and Right represent the same physical component of the -- same record or array type, from the same physical compilation unit and the -- same open ASIS Context variable. -- -- Implies: -- Is_Identical (Enclosing_Compilation_Unit (Component_Declaration (Left)), -- Enclosing_Compilation_Unit (Component_Declaration (Right))) -- = True -- -- All component values are appropriate. -- ------------------------------------------------------------------------------ -- 22.13 function Is_Array ------------------------------------------------------------------------------ function Is_Array (Component : Record_Component) return Boolean; function Is_Array (Component : Array_Component) return Boolean; ------------------------------------------------------------------------------ -- Component - Specifies any component -- -- Returns True if the component has an array subtype (contains an array -- value). -- -- Returns False for Nil components and any component that is not an embedded -- array. -- ------------------------------------------------------------------------------ -- 22.14 function Is_Record ------------------------------------------------------------------------------ function Is_Record (Component : Record_Component) return Boolean; function Is_Record (Component : Array_Component) return Boolean; ------------------------------------------------------------------------------ -- Component - Specifies any component -- -- Returns True if the component has a record subtype. -- Returns False for Nil components and any component that is not an embedded -- record. -- ------------------------------------------------------------------------------ -- 22.15 function Done ------------------------------------------------------------------------------ function Done (Iterator : Array_Component_Iterator) return Boolean; ------------------------------------------------------------------------------ -- Iterator - Specifies the iterator to query -- -- Returns True if the iterator has been advanced past the last array -- component. Returns True for a Nil_Array_Component_Iterator. -- ------------------------------------------------------------------------------ -- 22.16 procedure Next ------------------------------------------------------------------------------ procedure Next (Iterator : in out Array_Component_Iterator); ------------------------------------------------------------------------------ -- Iterator - Specifies the iterator to advance -- -- Advances the iterator to the next array component. Use Done to test the -- iterator to see if it has passed the last component. Does nothing if the -- iterator is already past the last component. -- ------------------------------------------------------------------------------ -- 22.17 procedure Reset ------------------------------------------------------------------------------ procedure Reset (Iterator : in out Array_Component_Iterator); ------------------------------------------------------------------------------ -- Iterator - Specifies the iterator to reset -- -- Resets the iterator to the first array component. -- ------------------------------------------------------------------------------ -- 22.18 function Array_Index ------------------------------------------------------------------------------ function Array_Index (Iterator : Array_Component_Iterator) return Asis.ASIS_Natural; ------------------------------------------------------------------------------ -- Iterator - Specifies the iterator to query -- -- Returns the Index value which, when used in conjunction with the -- Array_Component value used to create the Iterator, indexes the same array -- component as that presently addressed by the Iterator. -- -- Raises ASIS_Inappropriate_Element if given a Nil_Array_Component_Iterator -- or one where Done(Iterator) = True. The Status value is Data_Error. -- The Diagnosis string will indicate the kind of error detected. -- ------------------------------------------------------------------------------ -- 22.19 function Array_Indexes ------------------------------------------------------------------------------ function Array_Indexes (Iterator : Array_Component_Iterator) return Dimension_Indexes; ------------------------------------------------------------------------------ -- Iterator - Specifies the iterator to query -- -- Returns the index values which, when used in conjunction with the -- Array_Component value used to create the Iterator, indexes the same array -- component as that presently addressed by the Iterator. -- -- Raises ASIS_Inappropriate_Element if given a Nil_Array_Component_Iterator -- or one where Done(Iterator) = True. The Status value is Data_Error. -- The Diagnosis string will indicate the kind of error detected. -- ------------------------------------------------------------------------------ -- 22.20 function Discriminant_Components ------------------------------------------------------------------------------ function Discriminant_Components (Type_Definition : Asis.Type_Definition) return Record_Component_List; function Discriminant_Components (Component : Record_Component) return Record_Component_List; function Discriminant_Components (Component : Array_Component) return Record_Component_List; ------------------------------------------------------------------------------ -- Type_Definition - Specifies the record type definition to query -- Component - Specifies a component which has a record subtype, -- Is_Record(Component) = True -- -- Returns a list of the discriminant components for records of the indicated -- record type. -- -- The result describes the locations of the record type's discriminants, -- regardless of the static or dynamic nature of the record type. -- All return components are intended for use with a data stream representing -- a value of the indicated record type. -- -- All Is_Record(Component) = True arguments are appropriate. All return -- values are valid parameters for all query operations. -- -- Appropriate Element_Kinds: -- A_Type_Definition -- -- Appropriate Type_Kinds: -- A_Derived_Type_Definition (derived from a record type) -- A_Record_Type_Definition -- -- ??? Should be extended for A_Subtype_Indication -- -- Appropriate Asis.Data_Decomposition.Type_Model_Kinds: -- A_Simple_Static_Model -- A_Simple_Dynamic_Model -- A_Complex_Dynamic_Model -- ------------------------------------------------------------------------------ -- 22.21 function Record_Components ------------------------------------------------------------------------------ function Record_Components (Type_Definition : Asis.Type_Definition) return Record_Component_List; function Record_Components (Component : Record_Component) return Record_Component_List; function Record_Components (Component : Array_Component) return Record_Component_List; ------------------------------------------------------------------------------ -- Type_Definition - Specifies the record type definition to query -- Component - Specifies a component which has a record subtype, -- Is_Record(Component) = True -- -- Returns a list of the discriminants and components for the indicated simple -- static record type. (See rule 6.A above.) -- -- The result describes the locations of the record type's discriminants and -- components. All return components are intended for use with a data stream -- representing a value of the indicated record type. -- -- All Is_Record (Component) = True values, having simple static types, are -- appropriate. All return values are valid parameters for all query -- operations. -- -- Note: If an Ada implementation uses implementation-dependent record -- components (Reference Manual 13.5.1 (15)), then each such component of -- the record type is included in the result. -- -- Appropriate Element_Kinds: -- A_Type_Definition -- -- Appropriate Type_Kinds: -- A_Derived_Type_Definition (derived from a record type) -- A_Record_Type_Definition -- -- -- ??? Should be extended for A_Subtype_Indication -- -- Appropriate Asis.Data_Decomposition.Type_Model_Kinds: -- A_Simple_Static_Model -- ------------------------------------------------------------------------------ -- 22.22 function Record_Components ------------------------------------------------------------------------------ function Record_Components (Type_Definition : Asis.Type_Definition; Data_Stream : Portable_Data) return Record_Component_List; function Record_Components (Component : Record_Component; Data_Stream : Portable_Data) return Record_Component_List; function Record_Components (Component : Array_Component; Data_Stream : Portable_Data) return Record_Component_List; ------------------------------------------------------------------------------ -- Type_Definition - Specifies the record type definition to query -- Component - Specifies a component which has a record subtype, -- Is_Record(Component) = True -- Data_Stream - Specifies a data stream containing, at least, the -- complete set of discriminant or index constraints for -- the type -- -- Returns a list of the discriminants and components for the indicated record -- type, using the data stream argument as a guide. The record type shall be -- either a simple static, or a simple dynamic, record type. (See rules 6.A -- and 6.B above.) -- -- The result describes the locations of the record type's discriminants and -- all components of the appropriate variant parts. The contents of the list -- are determined by the discriminant values present in the data stream. -- -- A simple static type will always return the same component list (Is_Equal -- parts) regardless of the Data_Stream, because the layout of a simple static -- type does not change with changes in discriminant values. A simple dynamic -- type returns different component lists (non-Is_Equal parts) depending on -- the contents of the Data_Stream, because the contents and layout of a -- simple dynamic type changes with changes in discriminant values. All -- return components are intended for use with a data stream representing a -- value of the indicate record type. -- -- The Data_Stream shall represent a fully discriminated value of the -- indicated record type. The stream may have been read from a file, it may -- have been extracted from some enclosing data stream, or it may be an -- artificial value created by the Construct_Artificial_Data_Stream operation. -- Only the discriminant portion of the Data_Stream is checked for validity, -- and, only some discriminant fields may need to be checked, depending on the -- complexity of the record type. The best approach, for any application that -- is constructing artificial data streams, is to always provide appropriate -- values for all discriminant fields. It is not necessary to provide values -- for non-discriminant fields. -- -- All Is_Record(Component) = True values are appropriate. All return values -- are valid parameters for all query operations. -- -- Note: If an Ada implementation uses implementation-dependent record -- components (Reference Manual 13.5.1 (15)), then each such component of the -- record type is included in the result. -- -- Appropriate Element_Kinds: -- A_Type_Definition -- -- Appropriate Type_Kinds: -- A_Derived_Type_Definition (derived from a record type) -- A_Record_Type_Definition -- -- -- ??? Should be extended for A_Subtype_Indication -- -- Appropriate Asis.Data_Decomposition.Type_Model_Kinds: -- A_Simple_Static_Model -- A_Simple_Dynamic_Model -- ------------------------------------------------------------------------------ -- 22.23 function Array_Components ------------------------------------------------------------------------------ function Array_Components (Type_Definition : Asis.Type_Definition) return Array_Component; function Array_Components (Component : Record_Component) return Array_Component; function Array_Components (Component : Array_Component) return Array_Component; ------------------------------------------------------------------------------ -- Type_Definition - Specifies the array type definition to query -- Component - Specifies a component which has an array subtype, -- Is_Array(Component) = True -- -- Returns a single component, describing all components of the indicated -- array type. The array type shall be a simple static, or a simple dynamic -- array type. (See rules 6.A and 6.B above.) -- -- The result contains all information necessary to index and extract any -- component of a data stream representing a value of the indicated array -- type. -- -- All Is_Array (Component) = True values are appropriate. All return values -- are valid parameters for all query operations. -- -- Appropriate Element_Kinds: -- A_Type_Definition -- -- Appropriate Type_Kinds: -- A_Derived_Type_Definition (derived from an array type) -- An_Unconstrained_Array_Definition -- A_Constrained_Array_Definition -- -- -- ??? Should be extended for A_Subtype_Indication -- -- Appropriate Asis.Data_Decomposition.Type_Model_Kinds: -- A_Simple_Static_Model -- A_Simple_Dynamic_Model -- ------------------------------------------------------------------------------ -- 22.24 function Array_Iterator ------------------------------------------------------------------------------ function Array_Iterator (Component : Array_Component) return Array_Component_Iterator; ------------------------------------------------------------------------------ -- Component - Specifies an array component to be used for iteration -- -- Returns an iterator poised to fetch the 1st component of an array. -- ------------------------------------------------------------------------------ -- 22.25 function Component_Data_Stream ------------------------------------------------------------------------------ function Component_Data_Stream (Component : Record_Component; Data_Stream : Portable_Data) return Portable_Data; function Component_Data_Stream (Component : Array_Component; Index : Asis.ASIS_Positive; Data_Stream : Portable_Data) return Portable_Data; function Component_Data_Stream (Component : Array_Component; Indexes : Dimension_Indexes; Data_Stream : Portable_Data) return Portable_Data; function Component_Data_Stream (Iterator : Array_Component_Iterator; Data_Stream : Portable_Data) return Portable_Data; ------------------------------------------------------------------------------ -- Component - Specifies the component or discriminant to be extracted -- Index - Specifies an index, 1..Array_Length, within an array -- Indexes - Specifies a list of index values, there is one value for -- each dimension of the array type, each index N is in the -- range 1..Array_Length (Component, N); -- Iterator - Specifies the array component to extract -- Data_Stream - Specifies the data stream from which to extract the result -- -- Returns a data stream representing just the value of the chosen Component. -- The return value is sliced from the data stream. The Data_Stream shall -- represent a value of the appropriate type. It may have been obtained from -- a file, extracted from another data stream, or artificially constructed -- using the Construct_Artificial_Data_Stream operation. -- -- An artificial data stream may raise ASIS_Inappropriate_Element (the Status -- is Value_Error). Only the constraint values are valid, once they -- have been properly initialized, and can be safely extracted from an -- artificial data stream. -- -- Raises ASIS_Inappropriate_Element if given a Nil_Array_Component_Iterator -- or one where Done(Iterator) = True. The Status value is Data_Error. -- The Diagnosis string will indicate the kind of error detected. -- -- All non-Nil component values are appropriate. -- ------------------------------------------------------------------------------ -- 22.26 function Component_Declaration ------------------------------------------------------------------------------ function Component_Declaration (Component : Record_Component) return Asis.Declaration; ------------------------------------------------------------------------------ -- Component - Specifies the component to be queried -- -- Returns an Asis.Declaration, which is either A_Component_Declaration -- or A_Discriminant_Specification. These values can be used to determine the -- subtype, type, and base type of the record component. The result may be an -- explicit declaration made by the user, or, it may be an implicit -- component declaration for an implementation-defined component (Reference -- Manual 13.5.1(15)). -- -- All non-Nil component values are appropriate. -- -- Returns Element_Kinds: -- A_Declaration -- -- Returns Declaration_Kinds: -- A_Component_Declaration -- A_Discriminant_Specification -- ------------------------------------------------------------------------------ -- 22.27 function Component_Indication ------------------------------------------------------------------------------ function Component_Indication (Component : Array_Component) return Asis.Subtype_Indication; ------------------------------------------------------------------------------ -- Component - Specifies the component to be queried -- -- Returns an Asis.Subtype_Indication. These values can be used to determine -- the subtype, type, and base type of the array components. -- -- All non-Nil component values are appropriate. -- -- Returns Element_Kinds: -- A_Subtype_Indication -- ------------------------------------------------------------------------------ -- 22.28 function All_Named_Components ------------------------------------------------------------------------------ function All_Named_Components (Type_Definition : Asis.Type_Definition) return Asis.Defining_Name_List; ------------------------------------------------------------------------------ -- Type_Definition - Specifies the record type definition to query -- -- Returns a list of all discriminant and component entity names defined by -- the record type. All record type definitions are appropriate for this -- operation. This query provides a means for determining whether a field, -- with a particular name, exists for some possible instance of the record -- type. This list does not include the names of implementation-defined -- components (Reference Manual 13.5.1 (15)); those name have the form of -- An_Attribute_Reference expression. -- -- Appropriate Element_Kinds: -- A_Type_Definition -- -- Appropriate Type_Kinds: -- A_Derived_Type_Definition (derived from a record type) -- A_Record_Type_Definition -- -- -- ??? Should be extended for A_Subtype_Indication -- -- Appropriate Asis.Data_Decomposition.Type_Model_Kinds: -- A_Simple_Static_Model -- A_Simple_Dynamic_Model -- A_Complex_Dynamic_Model -- ------------------------------------------------------------------------------ -- 22.29 function Array_Length ------------------------------------------------------------------------------ function Array_Length (Component : Record_Component) return Asis.ASIS_Natural; function Array_Length (Component : Array_Component) return Asis.ASIS_Natural; ------------------------------------------------------------------------------ -- Component - Specifies the component to query -- -- Returns the number of components within an array valued component. The -- array subtype may be multidimensional. The result treats the array as if -- it were unidimensional. It is the product of the 'Lengths of the -- individual array dimensions. -- -- All Is_Array(Component) = True values are appropriate. -- ------------------------------------------------------------------------------ -- 22.30 function Array_Length ------------------------------------------------------------------------------ function Array_Length (Component : Record_Component; Dimension : Asis.ASIS_Natural) return Asis.ASIS_Natural; function Array_Length (Component : Array_Component; Dimension : Asis.ASIS_Natural) return Asis.ASIS_Natural; ------------------------------------------------------------------------------ -- Component - Specifies the component to query -- Dimension - Specifies the array dimension to query -- -- Returns the number of components within an array valued component. The -- array subtype may be unidimensional. The result is the 'Length(Dimension) -- of the array. -- -- All Is_Array(Component) = True values are appropriate. -- ------------------------------------------------------------------------------ -- 22.31 function Size ------------------------------------------------------------------------------ function Size (Type_Definition : Asis.Type_Definition) return Asis.ASIS_Natural; function Size (Component : Record_Component) return Asis.ASIS_Natural; function Size (Component : Array_Component) return Asis.ASIS_Natural; ------------------------------------------------------------------------------ -- Type_Definition - Specifies a type definition, whose 'Size is desired -- Component - Specifies a component, whose 'Size is desired -- -- Returns the minimum number of bits required to hold a simple static type, -- the number of bits allocated to hold a record field, or the number of bits -- allocated to hold each array component. -- -- --|AN Application Note: -- --|AN -- --|AN For components, this is the number of bits allocated -- --|AN within the composite value. It may be greater than the number -- --|AN of bits occupied by data values of this component type. -- --|AN Also, the data value, when occupying more space than is -- --|AN minimally required, may be preceded, followed, or surrounded by -- --|AN padding bits which are necessary to fully occupy the space allotted. -- --|AN -- All non-Nil component values are appropriate. -- -- Appropriate Element_Kinds: -- A_Type_Definition -- -- -- --|A4G Size is extended to operate on A_Subtype_Indication -- --|A4G Elements -- -- Appropriate Asis.Data_Decomposition.Type_Model_Kinds: -- A_Simple_Static_Model -- ------------------------------------------------------------------------------ -- 22.32 function Size ------------------------------------------------------------------------------ function Size (Type_Definition : Asis.Type_Definition; Data_Stream : Portable_Data) return Asis.ASIS_Natural; ------------------------------------------------------------------------------ -- Type_Definition - Specifies the type definition to query -- Data_Stream - Specifies a data stream containing, at least, the -- complete set of discriminant or index constraints for -- the type -- -- Returns the 'Size of a value of this type, with these constraints. This is -- the minimum number of bits that is needed to hold any possible value of the -- given fully constrained subtype. Only the constraint portion of the -- Data_Stream is checked. -- -- The Data_Stream may be a data stream or it may be an artificial -- data stream created by the Construct_Artificial_Data_Stream operation. -- -- Appropriate Element_Kinds: -- A_Type_Definition -- -- -- ??? Should be extended for A_Subtype_Indication -- -- Appropriate Asis.Data_Decomposition.Type_Model_Kinds: -- A_Simple_Static_Model -- A_Simple_Dynamic_Model -- ------------------------------------------------------------------------------ -- 22.33 function Position ------------------------------------------------------------------------------ function Position (Component : Record_Component) return Asis.ASIS_Natural; function Position (Component : Array_Component; Index : Asis.ASIS_Positive) return Asis.ASIS_Natural; function Position (Component : Array_Component; Indexes : Dimension_Indexes) return Asis.ASIS_Natural; function Position (Iterator : Array_Component_Iterator) return Asis.ASIS_Natural; ------------------------------------------------------------------------------ -- Component - Specifies the component to query -- Index - Specifies a value in the range 1..Array_Length (Component), -- the index of the component to query -- Indexes - Specifies a list of index values, there is one value for -- each dimension of the array type, each index N is in the -- range 1..Array_Length (Component, N); -- Iterator - Specifies a particular array component to query -- -- Returns the System.Storage_Unit offset, from the start of the first storage -- unit occupied by the enclosing composite type, of the first of the storage -- units occupied by the Component. The offset is measured in storage units. -- -- All non-Nil component values are appropriate. Raises -- ASIS_Inappropriate_Element with a Status of Data_Error if any index is not -- in the expected range or if Done (Iterator) = True. The Status value will -- be Data_Error. The Diagnosis string will indicate the kind of error -- detected. -- ------------------------------------------------------------------------------ -- 22.34 function First_Bit ------------------------------------------------------------------------------ function First_Bit (Component : Record_Component) return Asis.ASIS_Natural; function First_Bit (Component : Array_Component; Index : Asis.ASIS_Positive) return Asis.ASIS_Natural; function First_Bit (Component : Array_Component; Indexes : Dimension_Indexes) return Asis.ASIS_Natural; function First_Bit (Iterator : Array_Component_Iterator) return Asis.ASIS_Natural; ------------------------------------------------------------------------------ -- Component - Specifies the component to query -- Index - Specifies a value in the range 1..Array_Length (Component), -- the index of the component to query -- Indexes - Specifies a list of index values, there is one value for -- each dimension of the array type, each index N is in the -- range 1..Array_Length (Component, N); -- Iterator - Specifies a particular array component to query -- -- Returns the bit offset, from the start of the first of the storage units -- occupied by the Component, of the first bit occupied by the Component. The -- offset is measured in bits. -- -- All non-Nil component values are appropriate. Raises -- ASIS_Inappropriate_Element with a Status of Data_Error if any index is not -- in the expected range or if Done (Iterator) = True. The Status value will -- be Data_Error. The Diagnosis string will indicate the kind of error -- detected. -- ------------------------------------------------------------------------------ -- 22.35 function Last_Bit ------------------------------------------------------------------------------ function Last_Bit (Component : Record_Component) return Asis.ASIS_Integer; function Last_Bit (Component : Array_Component; Index : Asis.ASIS_Positive) return Asis.ASIS_Integer; function Last_Bit (Component : Array_Component; Indexes : Dimension_Indexes) return Asis.ASIS_Integer; function Last_Bit (Iterator : Array_Component_Iterator) return Asis.ASIS_Integer; ------------------------------------------------------------------------------ -- Component - Specifies the component to query -- Index - Specifies a value in the range 1..Array_Length (Component), -- the index of the component to query -- Indexes - Specifies a list of index values, there is one value for -- each dimension of the array type, each index N is in the -- range 1..Array_Length (Component, N); -- Iterator - Specifies a particular array component to query -- -- Returns the bit offset, from the start of the first of the storage units -- occupied by the Index'th Element, of the last bit occupied by the Element. -- The offset is measured in bits. -- -- Note, that Last_Bit may be equal to -1 for a component which is -- an empty array -- -- All non-Nil component values are appropriate. Raises -- ASIS_Inappropriate_Element with a Status of Data_Error if any index is not -- in the expected range or if Done (Iterator) = True. The Status value will -- be Data_Error. The Diagnosis string will indicate the kind of error -- detected. -- ------------------------------------------------------------------------------ -- 22.36 function Portable_Constrained_Subtype ------------------------------------------------------------------------------ -- Generic for Data Stream Conversions ------------------------------------------------------------------------------ generic -- Ada notation for a constrained subtype. -- type Constrained_Subtype (<>) is private; type Constrained_Subtype is private; function Portable_Constrained_Subtype (Data_Stream : Portable_Data) return Constrained_Subtype; ------------------------------------------------------------------------------ -- Data_Stream - Specifies an extracted component of a record -- -- Instantiated with an appropriate scalar type, (e.g., System.Integer, can be -- used to convert a data stream to a value that can be directly examined). -- -- Instantiated with a record type, can be used to convert a data stream to a -- value that can be directly examined. -- -- Instantiations with constrained array subtypes may not convert array values -- if they were created using the Portable_Array_Type_1, -- Portable_Array_Type_2, or Portable_Array_Type_3 interfaces. -- -- May raise Constraint_Error if the subtype is a scalar and the converted -- value is not in the subtype's range. -- ------------------------------------------------------------------------------ -- 22.37 function Construct_Artificial_Data_Stream ------------------------------------------------------------------------------ function Construct_Artificial_Data_Stream (Type_Definition : Asis.Type_Definition; Data_Stream : Portable_Data; Discriminant : Record_Component; Value : Portable_Data) return Portable_Data; ------------------------------------------------------------------------------ -- Type_Definition - Specifies the record type definition for the record -- valued data stream being constructed -- Data_Stream - Specifies the data stream constructed so far; initially -- specified as the Nil_Portable_Data value -- Discriminant - Specifies the discriminant of the record type that is -- being set or changed -- Value - Specifies a data stream representing a single -- discriminant value of the appropriate type -- -- Used to artificially construct a data stream which represents the -- discriminant portion of a fully constrained value of the indicated record -- type. This operation is called once with a value for each discriminant of -- the record type (the order in which the discriminants are specified is not -- important). The return value of each call is used as the input Data_Stream -- for the next. -- -- The resulting artificial data stream may be used solely for the purpose of -- creating Record_Component values. The values of any non-discriminant -- fields are arbitrary and quite possibly invalid. The resulting -- component values may then be used for any purpose. In particular, they may -- be used to determine First_Bit, Last_Bit, and Size values for all record -- discriminants and components. -- -- Appropriate Element_Kinds: -- A_Type_Definition -- -- Appropriate Type_Kinds: -- A_Derived_Type_Definition (derived from a record type) -- A_Record_Type_Definition -- -- -- ??? Should be extended for A_Subtype_Indication -- -- Raises ASIS_Inappropriate_Element, with a Status of Data_Error, if the -- discriminant Value is inappropriate for the specified Discriminant. -- ------------------------------------------------------------------------------ private type Portable_Data_Access is access all Portable_Data; -- ??? Do we have to keep the whole parent stream? Is not a list -- ??? of parent discriminants (in the form suitable for A4G.DDA_Aux) -- ??? enough? type Discrim_List_Access is access all Discrim_List; type Record_Component is record Parent_Record_Type : Asis.Definition := Nil_Element; -- The definition of the type from which this component was extracted -- ??? Do we really need this? Component_Name : Asis.Defining_Name := Nil_Element; -- The defining name corresponding to the component in -- Parent_Record_Type -- ??? Why not just keep the entity node? Is_Record_Comp : Boolean := False; -- Flag indcating if the component itself is of a record type Is_Array_Comp : Boolean := False; -- Flag indcating if the component itself is of an array type Position : ASIS_Natural := 0; -- Position of the component, as it is to be returned by -- Position query First_Bit : ASIS_Natural := 0; -- Component first bit, as it is to be returned by First_Bit query Last_Bit : ASIS_Integer := 0; -- Component last bit, as it is to be returned by Last_Bit query -- Note, that Last_Bit may be equal to -1 for a component which is -- an empty array Size : ASIS_Natural := 0; -- Component size, as it is to be returned by Size query Parent_Discrims : Discrim_List_Access := null; -- The reference to a list of discriminants from the enclosed record -- value (null if there is no discriminant) Parent_Context : Context_Id := Non_Associated; -- An ASIS Context from which a given component is originated Obtained : ASIS_OS_Time := Nil_ASIS_OS_Time; -- Time when a given component was created, needed for validity -- checks -- What else do we need??? -- ??? Do we need the reference to a tree file from which the -- ??? component is obtained (plus tree swapping mechanism similar -- ??? to what is used for Elements end record; Nil_Record_Component : constant Record_Component := (Parent_Record_Type => Nil_Element, Component_Name => Nil_Element, Is_Record_Comp => False, Is_Array_Comp => False, Position => 0, First_Bit => 0, Last_Bit => 0, Size => 0, Parent_Discrims => null, Parent_Context => Non_Associated, Obtained => Nil_ASIS_OS_Time); type Dimention_Length is array (1 .. 16) of Asis.ASIS_Natural; type Array_Component is record -- ??? Currently, the same structure as for Record_Component Parent_Array_Type : Asis.Definition := Nil_Element; -- The definition of the Array type to which this component -- belongs ??? Array_Type_Entity : Entity_Id := Empty; -- Entyty Id for the array type from which the array component was -- extracted. It may not correspond to Parent_Array_Type, and it may -- be the implicit type entity as well. Parent_Component_Name : Asis.Defining_Name := Nil_Element; -- The defining name corresponding to the record component (which is of -- array type) to which a given array componnets directly belonds -- (Nil_Element, if the array component is not directly extracted from -- some record component). It may contain index constraint, so we -- need it. We also need it to compare array components. Is_Record_Comp : Boolean := False; -- Flag indcating if the component itself is of a record type Is_Array_Comp : Boolean := False; -- Flag indcating if the component itself is of an array type Position : ASIS_Natural := 0; -- Position of the component, as it is to be returned by -- Position query First_Bit : ASIS_Natural := 0; -- Component first bit, as it is to be returned by First_Bit query Last_Bit : ASIS_Integer := 0; -- Component last bit, as it is to be returned by Last_Bit query -- Note, that Last_Bit may be equal to -1 for a component which is -- an empty array Size : ASIS_Natural := 0; -- Component size, as it is to be returned by Size query Parent_Discrims : Discrim_List_Access := null; -- The reference to a list of discriminants from the enclosed record -- value (null if there is no discriminant), needed in case when the -- array componnet is extracted from a record component which in turn -- depends on discriminant Parent_Context : Context_Id := Non_Associated; -- An ASIS Context from which a given component is originated Obtained : ASIS_OS_Time := Nil_ASIS_OS_Time; -- Time when a given component was created, needed for validity -- checks -- What else do we need??? Dimension : ASIS_Natural range 1 .. 16; -- Dimension of enclosing array value Length : Dimention_Length := (others => 0); end record; Nil_Array_Component : constant Array_Component := (Parent_Array_Type => Nil_Element, Array_Type_Entity => Empty, Parent_Component_Name => Nil_Element, Is_Record_Comp => False, Is_Array_Comp => False, Position => 0, First_Bit => 0, Last_Bit => 0, Size => 0, Parent_Discrims => null, Parent_Context => Non_Associated, Obtained => Nil_ASIS_OS_Time, Dimension => 1, Length => (others => 0)); type Array_Component_Iterator is record Component : Array_Component; Max_Len : Asis.ASIS_Natural := 0; Index : Asis.ASIS_Natural := 0; end record; Nil_Array_Component_Iterator : constant Array_Component_Iterator := (Component => Nil_Array_Component, Max_Len => 0, Index => 0); ------------------------------------------------------------------------------ end Asis.Data_Decomposition;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S T Y L E S W -- -- -- -- S p e c -- -- -- -- Copyright (C) 1992-2020, 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 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. 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 COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This package contains the style switches used for setting style options. -- The only clients of this package are the body of Style and the body of -- Switches. All other style checking issues are handled using the public -- interfaces in the spec of Style. with Types; use Types; package Stylesw is -------------------------- -- Style Check Switches -- -------------------------- -- These flags are used to control the details of the style checking -- options. The default values shown here correspond to no style checking. -- If any of these values is set to a non-default value, then -- Opt.Style_Check is set True to activate calls to this package. -- The actual mechanism for setting these switches to other than default -- values is via the Set_Style_Check_Options procedure or through a call to -- Set_Default_Style_Check_Options. They should not be set directly in any -- other manner. Style_Check_Array_Attribute_Index : Boolean := False; -- This can be set True by using the -gnatyA switch. If it is True then -- index numbers for array attributes (like Length) are required to be -- absent for one-dimensional arrays and present for multi-dimensional -- array attribute references. Style_Check_Attribute_Casing : Boolean := False; -- This can be set True by using the -gnatya switch. If it is True, then -- attribute names (including keywords such as digits used as attribute -- names) must be in mixed case. Style_Check_Blanks_At_End : Boolean := False; -- This can be set True by using the -gnatyb switch. If it is True, then -- spaces at the end of lines are not permitted. Style_Check_Blank_Lines : Boolean := False; -- This can be set True by using the -gnatyu switch. If it is True, then -- multiple blank lines are not permitted, and there may not be a blank -- line at the end of the file. Style_Check_Boolean_And_Or : Boolean := False; -- This can be set True by using the -gnatyB switch. If it is True, then -- the use of AND THEN/OR ELSE rather than AND/OR is required except for -- the following cases: -- -- a) Both operands are simple Boolean constants or variables -- b) Both operands are of a modular type -- c) Both operands are of an array type Style_Check_Comments : Boolean := False; -- This can be set True by using the -gnatyc switch. If it is True, then -- comments are style checked as follows: -- -- All comments must be at the start of the line, or the first minus must -- be preceded by at least one space. -- -- For a comment that is not at the start of a line, the only requirement -- is that a space follow the comment characters. -- -- For a comment that is at the start of the line, one of the following -- conditions must hold: -- -- The comment characters are the only non-blank characters on the line -- -- The comment characters are followed by an exclamation point (the -- sequence --! is used by gnatprep for marking deleted lines). -- -- The comment characters are followed by two space characters if -- Comment_Spacing = 2, else by one character if Comment_Spacing = 1. -- -- The line consists entirely of minus signs -- -- The comment characters are followed by a single space, and the last -- two characters on the line are also comment characters. -- -- Note: the reason for the last two conditions is to allow "boxed" -- comments where only a single space separates the comment characters. Style_Check_Comments_Spacing : Nat range 1 .. 2; -- Spacing required for comments, valid only if Style_Check_Comments true. Style_Check_DOS_Line_Terminator : Boolean := False; -- This can be set true by using the -gnatyd switch. If it is True, then -- the line terminator must be a single LF, without an associated CR (e.g. -- DOS line terminator sequence CR/LF not allowed). Style_Check_Mixed_Case_Decls : Boolean := False; -- This can be set True by using the -gnatyD switch. If it is True, then -- declared identifiers must be in Mixed_Case. Style_Check_End_Labels : Boolean := False; -- This can be set True by using the -gnatye switch. If it is True, then -- optional END labels must always be present. Style_Check_Form_Feeds : Boolean := False; -- This can be set True by using the -gnatyf switch. If it is True, then -- form feeds and vertical tabs are not allowed in the source text. Style_Check_Horizontal_Tabs : Boolean := False; -- This can be set True by using the -gnatyh switch. If it is True, then -- horizontal tabs are not allowed in source text. Style_Check_If_Then_Layout : Boolean := False; -- This can be set True by using the -gnatyi switch. If it is True, then a -- THEN keyword must either appear on the same line as the IF, or on a line -- all on its own. -- -- This permits one of two styles for IF-THEN layout. Either the IF and -- THEN keywords are on the same line, where the condition is short enough, -- or the conditions are continued over to the lines following the IF and -- the THEN stands on its own. For example: -- -- if X > Y then -- -- if X > Y -- and then Y < Z -- then -- -- if X > Y and then Z > 0 -- then -- -- are allowed, but -- -- if X > Y -- and then B > C then -- -- is not allowed. Style_Check_Indentation : Column_Number range 0 .. 9 := 0; -- This can be set non-zero by using the -gnaty? (? a digit) switch. If -- it is non-zero it activates indentation checking with the indicated -- indentation value. A value of zero turns off checking. The requirement -- is that any new statement, line comment, declaration or keyword such -- as END, start on a column that is a multiple of the indentation value. Style_Check_Keyword_Casing : Boolean := False; -- This can be set True by using the -gnatyk switch. If it is True, then -- keywords are required to be in all lower case. This rule does not apply -- to keywords such as digits appearing as an attribute name. Style_Check_Layout : Boolean := False; -- This can be set True by using the -gnatyl switch. If it is True, it -- activates checks that constructs are indented as suggested by the -- examples in the RM syntax, e.g. that the ELSE keyword must line up -- with the IF keyword. Style_Check_Max_Line_Length : Boolean := False; -- This can be set True by using the -gnatym/M switches. If it is True, it -- activates checking for a maximum line length of Style_Max_Line_Length -- characters. Style_Check_Max_Nesting_Level : Boolean := False; -- This can be set True by using -gnatyLnnn with a value other than zero -- (a value of zero resets it to False). If True, it activates checking -- the maximum nesting level against Style_Max_Nesting_Level. Style_Check_Missing_Overriding : Boolean := False; -- This can be set True by using the -gnatyO switch. If it is True, then -- "overriding" is required in subprogram declarations and bodies where -- appropriate. Note that "not overriding" is never required. Style_Check_Mode_In : Boolean := False; -- This can be set True by using -gnatyI. If True, it activates checking -- that mode IN is not used on its own (since it is the default). Style_Check_Order_Subprograms : Boolean := False; -- This can be set True by using the -gnatyo switch. If it is True, then -- names of subprogram bodies must be in alphabetical order (not taking -- casing into account). Style_Check_Pragma_Casing : Boolean := False; -- This can be set True by using the -gnatyp switch. If it is True, then -- pragma names must use mixed case. Style_Check_References : Boolean := False; -- This can be set True by using the -gnatyr switch. If it is True, then -- all references to declared identifiers are checked. The requirement -- is that casing of the reference be the same as the casing of the -- corresponding declaration. Style_Check_Separate_Stmt_Lines : Boolean := False; -- This can be set True by using the -gnatyS switch. If it is TRUE, -- then for the case of keywords THEN (not preceded by AND) or ELSE (not -- preceded by OR) which introduce a conditionally executed statement -- sequence, there must be no tokens on the same line as the keyword, so -- that coverage testing can clearly identify execution of the statement -- sequence. A comment is permitted, as is THEN ABORT or a PRAGMA keyword -- after ELSE (a common style to specify the condition for the ELSE). Style_Check_Specs : Boolean := False; -- This can be set True by using the -gnatys switches. If it is True, then -- separate specs are required to be present for all procedures except -- parameterless library level procedures. The exception means that typical -- main programs do not require separate specs. Style_Check_Standard : Boolean := False; -- This can be set True by using the -gnatyn switch. If it is True, then -- any references to names in Standard have to be cased in a manner that -- is consistent with the Ada RM (usually Mixed case, as in Long_Integer) -- but there are some exceptions (e.g. NUL, ASCII). Style_Check_Tokens : Boolean := False; -- This can be set True by using the -gnatyt switch. If it is True, then -- the style check that requires canonical spacing between various -- punctuation tokens as follows: -- -- ABS and NOT must be followed by a space -- -- => must be surrounded by spaces -- -- <> must be preceded by a space or left paren -- -- Binary operators other than ** must be surrounded by spaces. -- -- There is no restriction on the layout of the ** binary operator. -- -- Colon must be surrounded by spaces -- -- Colon-equal (assignment) must be surrounded by spaces -- -- Comma must be the first non-blank character on the line, or be -- immediately preceded by a non-blank character, and must be followed -- by a blank. -- -- A space must precede a left paren following a digit or letter, and a -- right paren must not be followed by a space (it can be at the end of -- the line). -- -- A right paren must either be the first non-blank character on a line, -- or it must be preceded by a non-blank character. -- -- A semicolon must not be preceded by a blank, and must not be followed -- by a non-blank character. -- -- A unary plus or minus may not be followed by a space -- -- There must be one blank (and no other white space) between NOT and IN -- -- A vertical bar must be surrounded by spaces -- -- Note that a requirement that a token be preceded by a space is met by -- placing the token at the start of the line, and similarly a requirement -- that a token be followed by a space is met by placing the token at -- the end of the line. Note that in the case where horizontal tabs are -- permitted, a horizontal tab is acceptable for meeting the requirement -- for a space. Style_Check_Xtra_Parens : Boolean := False; -- This can be set True by using the -gnatyx switch. If true, then it is -- not allowed to enclose entire expressions in tests in parentheses -- (C style), e.g. if (x = y) then ... is not allowed. Style_Max_Line_Length : Nat := 0; -- Value used to check maximum line length. Gets reset as a result of -- use of -gnatym or -gnatyMnnn switches. This value is only read if -- Style_Check_Max_Line_Length is True. Style_Max_Nesting_Level : Nat := 0; -- Value used to check maximum nesting level. Gets reset as a result -- of use of the -gnatyLnnn switch. This value is only read if -- Style_Check_Max_Nesting_Level is True. ----------------- -- Subprograms -- ----------------- function RM_Column_Check return Boolean; -- Determines whether style checking is active and the RM column check -- mode is set requiring checking of RM format layout. procedure Set_Default_Style_Check_Options; -- This procedure is called to set the default style checking options in -- response to a -gnaty switch with no suboptions or from -gnatyy. procedure Set_GNAT_Style_Check_Options; -- This procedure is called to set the default style checking options for -- GNAT units (as set by -gnatg or -gnatyg). Style_Msg_Buf : String (1 .. 80); Style_Msg_Len : Natural; -- Used to return procedure Set_Style_Check_Options (Options : String; OK : out Boolean; Err_Col : out Natural); -- This procedure is called to set the style check options that correspond -- to the characters in the given Options string. If all options are valid, -- they are set in an additive manner: any previous options are retained -- unless overridden, unless a minus is encountered, and then subsequent -- style switches are subtracted from the current set. -- -- If all options given are valid, then OK is True, Err_Col is set to -- Options'Last + 1, and Style_Msg_Buf/Style_Msg_Len are unchanged. -- -- If an invalid character is found, then OK is False on exit, and Err_Col -- is the index in options of the bad character. In this case Style_Msg_Len -- is set and Style_Msg_Buf (1 .. Style_Msg_Len) has a detailed message -- describing the error. procedure Set_Style_Check_Options (Options : String); -- Like the above procedure, but used when the Options string is known to -- be valid. This is for example appropriate for calls where the string was -- obtained by Save_Style_Check_Options. procedure Reset_Style_Check_Options; -- Sets all style check options to off subtype Style_Check_Options is String (1 .. 64); -- Long enough string to hold all options from Save call below procedure Save_Style_Check_Options (Options : out Style_Check_Options); -- Sets Options to represent current selection of options. This set can be -- restored by first calling Reset_Style_Check_Options, and then calling -- Set_Style_Check_Options with the Options string. end Stylesw;
-- Taken from https://en.wikibooks.org/wiki/Ada_Programming/Object_Orientation#Overriding_indicators package Input_3 is type Object is tagged null record; function Primitive return access Object; -- new in Ada 2005 type Derived_Object is new Object with null record; not overriding -- new optional keywords in Ada 2005 procedure Primitive (This : in Derived_Object); -- new primitive operation overriding function Primitive return access Derived_Object; end X;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015-2016, 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 Virtual_File_System; use Virtual_File_System; with HAL.Filesystem; use HAL.Filesystem; with Semihosting; with Semihosting.Filesystem; use Semihosting.Filesystem; with File_Block_Drivers; use File_Block_Drivers; with Partitions; use Partitions; procedure Main is procedure List_Dir (FS : in out FS_Driver'Class; Path : Pathname); -- List files in directory procedure List_Partitions (FS : in out FS_Driver'Class; Path_To_Disk_Image : Pathname); -- List partition in a disk file -------------- -- List_Dir -- -------------- procedure List_Dir (FS : in out FS_Driver'Class; Path : Pathname) is Status : Status_Kind; DH : Any_Directory_Handle; begin Status := FS.Open_Directory (Path, DH); if Status /= Status_Ok then Semihosting.Log_Line ("Open Directory '" & Path & "' Error: " & Status'Img); else declare Ent : Directory_Entry; Index : Positive := 1; begin Semihosting.Log_Line ("Listing '" & Path & "' content:"); loop Status := DH.Read_Entry (Index, Ent); if Status = Status_Ok then Semihosting.Log_Line (" - '" & DH.Entry_Name (Index) & "'"); Semihosting.Log_Line (" Kind: " & Ent.Entry_Type'Img); else exit; end if; Index := Index + 1; end loop; end; end if; end List_Dir; --------------------- -- List_Partitions -- --------------------- procedure List_Partitions (FS : in out FS_Driver'Class; Path_To_Disk_Image : Pathname) is File : Any_File_Handle; begin if FS.Open (Path_To_Disk_Image, Read_Only, File) /= Status_Ok then Semihosting.Log_Line ("Cannot open disk image '" & Path_To_Disk_Image & "'"); return; end if; declare Disk : aliased File_Block_Driver (File); Nbr : Natural; P_Entry : Partition_Entry; begin Nbr := Number_Of_Partitions (Disk'Unchecked_Access); Semihosting.Log_Line ("Disk '" & Path_To_Disk_Image & "' has " & Nbr'Img & " parition(s)"); for Id in 1 .. Nbr loop if Get_Partition_Entry (Disk'Unchecked_Access, Id, P_Entry) /= Status_Ok then Semihosting.Log_Line ("Cannot read partition :" & Id'Img); else Semihosting.Log_Line (" - partition :" & Id'Img); Semihosting.Log_Line (" Status:" & P_Entry.Status'Img); Semihosting.Log_Line (" Kind: " & P_Entry.Kind'Img); Semihosting.Log_Line (" LBA: " & P_Entry.First_Sector_LBA'Img); Semihosting.Log_Line (" Number of sectors: " & P_Entry.Number_Of_Sectors'Img); end if; end loop; end; end List_Partitions; My_VFS : VFS; My_VFS2 : aliased VFS; My_VFS3 : aliased VFS; My_SHFS : aliased SHFS; Status : Status_Kind; FH : Any_File_Handle; Data : UInt8_Array (1 .. 10); begin -- Mount My_VFS2 in My_VFS Status := My_VFS.Mount (Path => "vfs2", Filesystem => My_VFS2'Unchecked_Access); if Status /= Status_Ok then Semihosting.Log_Line ("Mount Error: " & Status'Img); end if; -- Mount My_VFS3 in My_VFS2 Status := My_VFS2.Mount (Path => "vfs3", Filesystem => My_VFS3'Unchecked_Access); if Status /= Status_Ok then Semihosting.Log_Line ("Mount Error: " & Status'Img); end if; -- Mount semi-hosting filesystem in My_VFS Status := My_VFS.Mount (Path => "host", Filesystem => My_SHFS'Unchecked_Access); if Status /= Status_Ok then Semihosting.Log_Line ("Mount Error: " & Status'Img); end if; -- List all partitions of a disk image on the host List_Partitions (My_VFS, "/host/tmp/disk_8_partitions.img"); -- Try to unlink a file that doesn't exist in My_VFS2 Status := My_VFS.Unlink ("/vfs2/no_file"); if Status /= Status_Ok then Semihosting.Log_Line ("Unlink Error: " & Status'Img); end if; -- Try to unlink a file that doesn't exist in My_VFS3 Status := My_VFS.Unlink ("/vfs2/vfs3/no_file"); if Status /= Status_Ok then Semihosting.Log_Line ("Unlink Error: " & Status'Img); end if; -- Open a file on the host Status := My_VFS.Open ("/host/tmp/test.shfs", Read_Only, FH); if Status /= Status_Ok then Semihosting.Log_Line ("Open Error: " & Status'Img); end if; -- Read the first 10 characters Status := FH.Read (Data); if Status /= Status_Ok then Semihosting.Log_Line ("Read Error: " & Status'Img); end if; for C of Data loop Semihosting.Log (Character'Val (Integer (C))); end loop; Semihosting.Log_New_Line; -- Move file cursor Status := FH.Seek (10); if Status /= Status_Ok then Semihosting.Log_Line ("Seek Error: " & Status'Img); end if; -- Read 10 characters again Status := FH.Read (Data); if Status /= Status_Ok then Semihosting.Log_Line ("Read Error: " & Status'Img); end if; for C of Data loop Semihosting.Log (Character'Val (Integer (C))); end loop; Semihosting.Log_New_Line; Status := FH.Close; if Status /= Status_Ok then Semihosting.Log_Line ("Close Error: " & Status'Img); end if; -- Test directory listing List_Dir (My_VFS, "/"); List_Dir (My_VFS, "/vfs2"); List_Dir (My_VFS, "/vfs2/"); end Main;
with Ada.Text_IO; use Ada.Text_IO; with Gtk; use Gtk; with Gtk.Main; with Gtk.Widget; use Gtk.Widget; with Life_Pkg; use Life_Pkg; with World; use World; procedure Main is WG : World_Grid (16); B : Boolean; begin WG := New_World (16); B := Get_Spot (WG, 1, 1); Put_Line ("World Size: " & Integer'Image(WG.Size)); Put_Line ("Hello Ada!"); --Gtk.Main.Init; --Gtk_New (Life_Value); --Gtk.Main.Main; end;
with Ada.Text_IO; procedure Stooge is type Integer_Array is array (Positive range <>) of Integer; procedure Swap (Left, Right : in out Integer) is Temp : Integer := Left; begin Left := Right; Right := Temp; end Swap; procedure Stooge_Sort (List : in out Integer_Array) is T : Natural := List'Length / 3; begin if List (List'Last) < List (List'First) then Swap (List (List'Last), List (List'First)); end if; if List'Length > 2 then Stooge_Sort (List (List'First .. List'Last - T)); Stooge_Sort (List (List'First + T .. List'Last)); Stooge_Sort (List (List'First .. List'Last - T)); end if; end Stooge_Sort; Test_Array : Integer_Array := (1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7); begin Stooge_Sort (Test_Array); for I in Test_Array'Range loop Ada.Text_IO.Put (Integer'Image (Test_Array (I))); if I /= Test_Array'Last then Ada.Text_IO.Put (", "); end if; end loop; Ada.Text_IO.New_Line; end Stooge;
-- -- Copyright (C) 2017, AdaCore -- -- This spec has been automatically generated from ATSAM4SD32C.svd -- This is a version for the Atmel ATSAM4SD32C device: Cortex-M4 -- Microcontroller with 2MB dual-bank Flash, 160KB SRAM, USB, 100 Pins (refer -- to http://www.atmel.com/devices/SAM4SD32C.aspx for more) MCU package Ada.Interrupts.Names is -- All identifiers in this unit are implementation defined pragma Implementation_Defined; ---------------- -- Interrupts -- ---------------- -- System tick Sys_Tick_Interrupt : constant Interrupt_ID := -1; SUPC_Interrupt : constant Interrupt_ID := 0; RSTC_Interrupt : constant Interrupt_ID := 1; RTC_Interrupt : constant Interrupt_ID := 2; RTT_Interrupt : constant Interrupt_ID := 3; WDT_Interrupt : constant Interrupt_ID := 4; PMC_Interrupt : constant Interrupt_ID := 5; EEFC0_Interrupt : constant Interrupt_ID := 6; EEFC1_Interrupt : constant Interrupt_ID := 7; UART0_Interrupt : constant Interrupt_ID := 8; UART1_Interrupt : constant Interrupt_ID := 9; SMC_Interrupt : constant Interrupt_ID := 10; PIOA_Interrupt : constant Interrupt_ID := 11; PIOB_Interrupt : constant Interrupt_ID := 12; PIOC_Interrupt : constant Interrupt_ID := 13; USART0_Interrupt : constant Interrupt_ID := 14; USART1_Interrupt : constant Interrupt_ID := 15; HSMCI_Interrupt : constant Interrupt_ID := 18; TWI0_Interrupt : constant Interrupt_ID := 19; TWI1_Interrupt : constant Interrupt_ID := 20; SPI_Interrupt : constant Interrupt_ID := 21; SSC_Interrupt : constant Interrupt_ID := 22; TC0_Interrupt : constant Interrupt_ID := 23; TC1_Interrupt : constant Interrupt_ID := 24; TC2_Interrupt : constant Interrupt_ID := 25; TC3_Interrupt : constant Interrupt_ID := 26; TC4_Interrupt : constant Interrupt_ID := 27; TC5_Interrupt : constant Interrupt_ID := 28; ADC_Interrupt : constant Interrupt_ID := 29; DACC_Interrupt : constant Interrupt_ID := 30; PWM_Interrupt : constant Interrupt_ID := 31; CRCCU_Interrupt : constant Interrupt_ID := 32; ACC_Interrupt : constant Interrupt_ID := 33; UDP_Interrupt : constant Interrupt_ID := 34; end Ada.Interrupts.Names;
generic type Component is private; type List_Index is range <>; type List is array (List_Index range <>) of Component; Default_Value : Component; with function "=" (Left, Right : List) return Boolean is <>; package Bounded_Dynamic_Arrays is pragma Pure; Maximum_Length : constant List_Index := List_Index'Last; -- The physical maximum for the upper bound of the wrapped List array -- values. Defined for readability in predicates. subtype Natural_Index is List_Index'Base range 0 .. Maximum_Length; subtype Index is List_Index range 1 .. Maximum_Length; -- The representation internally uses a one-based array, hence the -- predicate on the generic formal List_Index integer type. type Sequence (Capacity : Natural_Index) is private with Default_Initial_Condition => Empty (Sequence); -- A wrapper for List array values in which Capacity represents the -- physical upper bound. Capacity is, therefore, the maximum number of -- Component values possibly contained by the associated Sequence instance. -- However, not all of the physical capacity of a Sequence need be used at -- any moment, leading to the notion of a logical current length ranging -- from zero to Capacity. Null_List : constant List (List_Index'First .. List_Index'First - 1) := (others => Default_Value); function Null_Sequence return Sequence with Post => Null_Sequence'Result.Capacity = 0 and Length (Null_Sequence'Result) = 0 and Value (Null_Sequence'Result) = Null_List and Null_Sequence'Result = Null_List; function Instance (Content : List) return Sequence with Pre => Content'Length <= Maximum_Length, Post => Length (Instance'Result) = Content'Length and Value (Instance'Result) = Content and Instance'Result = Content and Instance'Result.Capacity = Content'Length and Contains (Instance'Result, Content), Global => null, Depends => (Instance'Result => Content); function Instance (Capacity : Natural_Index; Content : Component) return Sequence with Pre => Capacity >= 1, Post => Length (Instance'Result) = 1 and Value (Instance'Result) (1) = Content and Instance'Result.Capacity = Capacity and Instance'Result = Content and Contains (Instance'Result, Content), Global => null; -- Depends => (Instance'Result => (Capacity, Content)); function Instance (Capacity : Natural_Index; Content : List) return Sequence with Pre => Content'Length <= Capacity, Post => Instance'Result.Capacity = Capacity and Length (Instance'Result) = Content'Length and Value (Instance'Result) = Content and Instance'Result = Content and Contains (Instance'Result, Content), Global => null; -- Depends => (Instance'Result => (Capacity, Content)); function Value (This : Sequence) return List with Post => Value'Result'Length = Length (This) and Value'Result'First = 1 and Value'Result'Last = Length (This), Inline; -- Returns the content of this sequence. The value returned is the -- "logical" value in that only that slice which is currently assigned -- is returned, as opposed to the entire physical representation. function Value (This : Sequence; Position : Index) return Component with Pre => Position in 1 .. Length (This), Inline; function Length (This : Sequence) return Natural_Index with Inline; -- Returns the logical length of This, i.e., the length of the slice of -- This that is currently assigned a value. function Empty (This : Sequence) return Boolean with Post => Empty'Result = (Length (This) = 0), Inline; procedure Clear (This : out Sequence) with Post => Empty (This) and Length (This) = 0 and Value (This) = Null_List and This = Null_Sequence, Global => null, Depends => (This => This), Inline; procedure Copy (Source : Sequence; To : in out Sequence) with Pre => To.Capacity >= Length (Source), Post => Value (To) = Value (Source) and Length (To) = Length (Source) and To = Source and Contains_At (To, 1, Source), Global => null, Depends => (To =>+ Source); -- Copies the logical value of Source, the RHS, to the LHS sequence To. The -- prior value of To is lost. procedure Copy (Source : List; To : in out Sequence) with Pre => To.Capacity >= Source'Length, Post => Value (To) = Source and then Length (To) = Source'Length and then To = Source and then Contains_At (To, 1, Source), Global => null, Depends => (To =>+ Source); -- Copies the value of the array Source, the RHS, to the LHS sequence To. -- The prior value of To is lost. procedure Copy (Source : Component; To : in out Sequence) with Pre => To.Capacity > 0, Post => Value (To) (1) = Source and Length (To) = 1 and To = Source and Contains_At (To, 1, Source), Global => null, Depends => (To =>+ Source); -- Copies the value of the individual array component Source, the RHS, to -- the LHS sequence To. The prior value of To is lost. overriding function "=" (Left, Right : Sequence) return Boolean with Inline; function "=" (Left : Sequence; Right : List) return Boolean with Inline; function "=" (Left : List; Right : Sequence) return Boolean with Inline; function "=" (Left : Sequence; Right : Component) return Boolean with Inline; function "=" (Left : Component; Right : Sequence) return Boolean with Inline; function Normalized (L : List) return List with Pre => L'Length <= Maximum_Length, Post => Normalized'Result'First = 1 and Normalized'Result'Last = L'Length and Normalized'Result = L; -- Slides the input into a 1-based array function "&" (Left : Sequence; Right : Sequence) return Sequence with Pre => Length (Left) <= Maximum_Length - Length (Right), Post => Value ("&"'Result) = Value (Left) & Value (Right) and Value ("&"'Result)'First = 1 and Length ("&"'Result) = Length (Left) + Length (Right) and "&"'Result.Capacity = Length (Left) + Length (Right); function "&" (Left : Sequence; Right : List) return Sequence with Pre => Length (Left) <= Maximum_Length - Right'Length, Post => Value ("&"'Result) = Value (Left) & Right and Value ("&"'Result)'First = 1 and Length ("&"'Result) = Length (Left) + Right'Length and "&"'Result.Capacity = Length (Left) + Right'Length; function "&" (Left : List; Right : Sequence) return Sequence with Pre => Left'Length <= Maximum_Length - Length (Right), Post => Value ("&"'Result) = Normalized (Left) & Value (Right) and Value ("&"'Result)'First = 1 and Length ("&"'Result) = Left'Length + Length (Right) and "&"'Result.Capacity = Left'Length + Length (Right); function "&" (Left : Sequence; Right : Component) return Sequence with Pre => Length (Left) <= Maximum_Length - 1, Post => Value ("&"'Result) = Value (Left) & Right and Value ("&"'Result)'First = 1 and Length ("&"'Result) = Length (Left) + 1 and "&"'Result.Capacity = Length (Left) + 1; function "&" (Left : Component; Right : Sequence) return Sequence with Pre => Length (Right) <= Maximum_Length - 1, Post => Value ("&"'Result) = Left & Value (Right) and Value ("&"'Result)'First = 1 and Length ("&"'Result) = 1 + Length (Right) and "&"'Result.Capacity = 1 + Length (Right); procedure Append (Tail : Sequence; To : in out Sequence) with Pre => Length (Tail) <= To.Capacity - Length (To), Post => Value (To) = Value (To'Old) & Value (Tail) and Length (To) = Length (To'Old) + Length (Tail); -- and -- To = Value (To'Old) & Value (Tail); -- caused crash... procedure Append (Tail : List; To : in out Sequence) with Pre => Tail'Length <= To.Capacity - Length (To), Post => Value (To) = Value (To'Old) & Tail and Length (To) = Length (To'Old) + Tail'Length; procedure Append (Tail : Component; To : in out Sequence) with Pre => Length (To) <= To.Capacity - 1, Post => Value (To) = Value (To'Old) & Tail and Length (To) = Length (To'Old) + 1; procedure Amend (This : in out Sequence; By : Sequence; Start : Index) with Pre => Start <= Length (This) and Start - 1 in 1 .. This.Capacity - Length (By) and Start <= Maximum_Length - Length (By), Post => Value (This) (Start .. Start + Length (By) - 1) = Value (By) and (if Start + Length (By) - 1 > Length (This'Old) then Length (This) = Start + Length (By) - 1 else Length (This) = Length (This'Old)) and Contains_At (This, Start, By) and Unchanged (This'Old, This, Start, Length (By)), Global => null, Depends => (This =>+ (By, Start)); -- Overwrites the content of This, beginning at Start, with the logical -- value of the Sequence argument By procedure Amend (This : in out Sequence; By : List; Start : Index) with Pre => Start <= Length (This) and Start - 1 in 1 .. This.Capacity - By'Length and Start <= Maximum_Length - By'Length, Post => Value (This) (Start .. Start + By'Length - 1) = By and (if Start + By'Length - 1 > Length (This'Old) then Length (This) = Start + By'Length - 1 else Length (This) = Length (This'Old)) and Contains_At (This, Start, By) and Unchanged (This'Old, This, Start, By'Length), Global => null, Depends => (This =>+ (By, Start)); -- Overwrites the content of This, beginning at Start, with the value of -- List argument By procedure Amend (This : in out Sequence; By : Component; Start : Index) with Pre => Start <= Length (This) and Start <= Maximum_Length - 1, Post => Value (This) (Start) = By and Length (This) = Length (This)'Old and Contains_At (This, Start, By) and Unchanged (This'Old, This, Start, 1), Global => null, Depends => (This =>+ (By, Start)); -- Overwrites the content of This, at position Start, with the value of -- the single Component argument By function Location (Fragment : Sequence; Within : Sequence) return Natural_Index with Pre => Length (Fragment) > 0, Post => Location'Result in 0 .. Within.Capacity and (if Length (Fragment) > Within.Capacity then Location'Result = 0) and (if Length (Fragment) > Length (Within) then Location'Result = 0) and (if Location'Result > 0 then Contains_At (Within, Location'Result, Fragment)); -- Returns the starting index of the logical value of the sequence Fragment -- in the sequence Within, if any. Returns 0 when the fragment is not -- found. -- NB: The implementation is not the best algorithm... function Location (Fragment : List; Within : Sequence) return Natural_Index with Pre => Fragment'Length > 0, Post => Location'Result in 0 .. Length (Within) and (if Fragment'Length > Within.Capacity then Location'Result = 0) and (if Fragment'Length > Length (Within) then Location'Result = 0) and (if Location'Result > 0 then Contains_At (Within, Location'Result, Fragment)); -- Returns the starting index of the value of the array Fragment in the -- sequence Within, if any. Returns 0 when the fragment is not found. -- NB: The implementation is a simple linear search... function Location (Fragment : Component; Within : Sequence) return Natural_Index with Post => Location'Result in 0 .. Length (Within) and (if Location'Result > 0 then Contains_At (Within, Location'Result, Fragment)); -- Returns the index of the value of the component Fragment within the -- sequence Within, if any. Returns 0 when the fragment is not found. function Contains (Within : Sequence; Fragment : Component) return Boolean with Inline; function Contains (Within : Sequence; Fragment : List) return Boolean with Pre => Length (Within) - Fragment'Length <= Maximum_Length - 1, Post => (if Fragment'Length = 0 then Contains'Result) and (if Fragment'Length > Length (Within) then not Contains'Result), Inline; function Contains (Within : Sequence; Fragment : Sequence) return Boolean with Pre => Length (Within) - Length (Fragment) <= Maximum_Length - 1, Post => (if Length (Fragment) = 0 then Contains'Result) and (if Length (Fragment) > Length (Within) then not Contains'Result), Inline; function Contains_At (Within : Sequence; Start : Index; Fragment : Sequence) return Boolean with Inline; function Contains_At (Within : Sequence; Start : Index; Fragment : List) return Boolean; -- with Inline, -- Pre => Start <= Length (Within) and then -- Start - 1 <= Length (Within) - Fragment'Length; function Contains_At (Within : Sequence; Position : Index; Fragment : Component) return Boolean with Inline; function Unchanged (Original : Sequence; Current : Sequence; Slice_Start : Index; Slice_Length : Natural_Index) return Boolean -- Returns whether the Original content is the same as the Current content, -- except for the slice beginning at Slice_Start and having Slice_Length -- number of components. with Pre => Original.Capacity = Current.Capacity and Slice_Start <= Length (Original) and Slice_Start - 1 <= Original.Capacity - Slice_Length and Slice_Start <= Maximum_Length - Slice_Length, Ghost; private type Sequence (Capacity : Natural_Index) is record Current_Length : Natural_Index := 0; Content : List (1 .. Capacity) := (others => Default_Value); end record with Predicate => Current_Length in 0 .. Capacity; ------------ -- Length -- ------------ function Length (This : Sequence) return Natural_Index is (This.Current_Length); ----------- -- Value -- ----------- function Value (This : Sequence) return List is (This.Content (1 .. This.Current_Length)); ----------- -- Value -- ----------- function Value (This : Sequence; Position : Index) return Component is (This.Content (Position)); ----------- -- Empty -- ----------- function Empty (This : Sequence) return Boolean is (This.Current_Length = 0); -------------- -- Contains -- -------------- function Contains (Within : Sequence; Fragment : Component) return Boolean is (for some K in 1 .. Length (Within) => Within.Content (K) = Fragment); ----------------- -- Contains_At -- ----------------- function Contains_At (Within : Sequence; Start : Index; Fragment : List) return Boolean is ((Start - 1 <= Within.Current_Length - Fragment'Length) and then Within.Content (Start .. (Start + Fragment'Length - 1)) = Fragment); -- note that this includes the case of a null slice on each side, eg -- when Start = 1 and Fragment'Length = 0, which is intended to return -- True ----------------- -- Contains_At -- ----------------- function Contains_At (Within : Sequence; Start : Index; Fragment : Sequence) return Boolean is (Contains_At (Within, Start, Value (Fragment))); ----------------- -- Contains_At -- ----------------- function Contains_At (Within : Sequence; Position : Index; Fragment : Component) return Boolean is (Position in 1 .. Within.Current_Length and then Within.Content (Position) = Fragment); -------------- -- Contains -- -------------- function Contains (Within : Sequence; Fragment : List) return Boolean is -- We want to return True when the fragment is empty (eg "") because we -- want to use Contains in the postcondition to Instance, and we want to -- allow creating an instance that is empty (because "&" can work with -- empty fragments/instances). Therefore we must allow a zero length -- Fragment. -- -- Also, note that we need to explicitly check for the empty fragment -- (using the short-circuit form) because otherwise the expression -- "(Within.Current_Length - Fragment'Length + 1)" would go past the -- current length. (Fragment'Length = 0 or else -- But also, for Within to possibly contain the slice Fragment, -- the length of the fragment cannot be greater than the length -- of Within.Content. (Fragment'Length in 1 .. Within.Current_Length and then (for some K in Within.Content'First .. (Within.Current_Length - Fragment'Length + 1) => Contains_At (Within, K, Fragment)))); -------------- -- Contains -- -------------- function Contains (Within : Sequence; Fragment : Sequence) return Boolean is (Contains (Within, Value (Fragment))); --------------- -- Unchanged -- --------------- function Unchanged (Original : Sequence; Current : Sequence; Slice_Start : Index; Slice_Length : Natural_Index) return Boolean is -- First we verify the part before the ammended slice, if any. If there -- is none before, this will compare against a null slice and so will -- return True. (Current.Content (1 .. Slice_Start - 1) = Original.Content (1 .. Slice_Start - 1) and then -- Now we verify the part after the ammended slice, if any, but also -- noting that the ammended part might extend past the end of the -- original. In other words, ammending a sequence can extend the -- length of the original. Current.Content (Slice_Start + Slice_Length .. Original.Current_Length) = Original.Content (Slice_Start + Slice_Length .. Original.Current_Length)); --------- -- "=" -- --------- overriding function "=" (Left, Right : Sequence) return Boolean is (Value (Left) = Value (Right)); --------- -- "=" -- --------- function "=" (Left : Sequence; Right : List) return Boolean is (Value (Left) = Right); --------- -- "=" -- --------- function "=" (Left : List; Right : Sequence) return Boolean is (Right = Left); --------- -- "=" -- --------- function "=" (Left : Sequence; Right : Component) return Boolean is (Left.Current_Length = 1 and then Left.Content (1) = Right); --------- -- "=" -- --------- function "=" (Left : Component; Right : Sequence) return Boolean is (Right = Left); end Bounded_Dynamic_Arrays;
-- SPDX-FileCopyrightText: 2020 Max Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT ---------------------------------------------------------------- with Ada.Wide_Wide_Text_IO; with Jupyter.Kernels; procedure Magics.Write_File (IO_Pub : not null Jupyter.Kernels.IO_Pub_Access; Name : League.Strings.Universal_String; Text : League.Strings.Universal_String; Silent : Boolean) is pragma Unreferenced (Silent, IO_Pub); Output : Ada.Wide_Wide_Text_IO.File_Type; begin Ada.Wide_Wide_Text_IO.Create (Output, Name => Name.To_UTF_8_String, Form => "WCEM=8"); Ada.Wide_Wide_Text_IO.Put_Line (Output, Text.To_Wide_Wide_String); Ada.Wide_Wide_Text_IO.Close (Output); end Magics.Write_File;
with Ada.Integer_Text_IO; procedure Euler2 is A, B: Integer := 1; Sum : Integer := 0; Tmp: Integer; begin while A < 4_000_000 loop if A mod 2 = 0 then Sum := Sum + A; end if; Tmp := A; A := A + B; B := Tmp; end loop; Ada.Integer_Text_IO.Put(Sum); end Euler2;
with Ada.Finalization; generic type T is private; package Controlled6_Pkg is type Node_Type is record Item : T; end record; type Node_Access_Type is access Node_Type; end Controlled6_Pkg;
with STM32_SVD; use STM32_SVD; with HAL; generic with package Chip_Select is new HAL.Pin (<>); with package IRQ is new HAL.Pin (<>); with package SPI is new HAL.SPI (<>); package Drivers.CC1101 is type Raw_Register_Array is array (0 .. 16#3D#) of Byte; type Packet_Type is array (Positive range <>) of Byte; procedure Init; procedure TX_Mode; procedure RX_Mode; procedure Set_Sync_Word (Word : Unsigned_16); function Get_Sync_Word return Unsigned_16; procedure TX (Packet: Packet_Type); function Wait_For_RX return Boolean; procedure RX (Packet : out Packet_Type; Length : out Natural); function RX_Available return Boolean; procedure Clear_IRQ; procedure Power_Down; procedure Cancel; procedure Read_Registers (Registers : out Raw_Register_Array); generic with procedure Put_Line (Line: in string); procedure Print_Registers; end Drivers.CC1101;
-- This spec has been automatically generated from STM32F0xx.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with System; package STM32_SVD.SYSCFG is pragma Preelaborate; --------------- -- Registers -- --------------- subtype CFGR1_MEM_MODE_Field is STM32_SVD.UInt2; subtype CFGR1_ADC_DMA_RMP_Field is STM32_SVD.Bit; subtype CFGR1_USART1_TX_DMA_RMP_Field is STM32_SVD.Bit; subtype CFGR1_USART1_RX_DMA_RMP_Field is STM32_SVD.Bit; subtype CFGR1_TIM16_DMA_RMP_Field is STM32_SVD.Bit; subtype CFGR1_TIM17_DMA_RMP_Field is STM32_SVD.Bit; subtype CFGR1_I2C_PB6_FM_Field is STM32_SVD.Bit; subtype CFGR1_I2C_PB7_FM_Field is STM32_SVD.Bit; subtype CFGR1_I2C_PB8_FM_Field is STM32_SVD.Bit; subtype CFGR1_I2C_PB9_FM_Field is STM32_SVD.Bit; -- configuration register 1 type CFGR1_Register is record -- Memory mapping selection bits MEM_MODE : CFGR1_MEM_MODE_Field := 16#0#; -- unspecified Reserved_2_7 : STM32_SVD.UInt6 := 16#0#; -- ADC DMA remapping bit ADC_DMA_RMP : CFGR1_ADC_DMA_RMP_Field := 16#0#; -- USART1_TX DMA remapping bit USART1_TX_DMA_RMP : CFGR1_USART1_TX_DMA_RMP_Field := 16#0#; -- USART1_RX DMA request remapping bit USART1_RX_DMA_RMP : CFGR1_USART1_RX_DMA_RMP_Field := 16#0#; -- TIM16 DMA request remapping bit TIM16_DMA_RMP : CFGR1_TIM16_DMA_RMP_Field := 16#0#; -- TIM17 DMA request remapping bit TIM17_DMA_RMP : CFGR1_TIM17_DMA_RMP_Field := 16#0#; -- unspecified Reserved_13_15 : STM32_SVD.UInt3 := 16#0#; -- Fast Mode Plus (FM+) driving capability activation bits. I2C_PB6_FM : CFGR1_I2C_PB6_FM_Field := 16#0#; -- Fast Mode Plus (FM+) driving capability activation bits. I2C_PB7_FM : CFGR1_I2C_PB7_FM_Field := 16#0#; -- Fast Mode Plus (FM+) driving capability activation bits. I2C_PB8_FM : CFGR1_I2C_PB8_FM_Field := 16#0#; -- Fast Mode Plus (FM+) driving capability activation bits. I2C_PB9_FM : CFGR1_I2C_PB9_FM_Field := 16#0#; -- unspecified Reserved_20_31 : STM32_SVD.UInt12 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CFGR1_Register use record MEM_MODE at 0 range 0 .. 1; Reserved_2_7 at 0 range 2 .. 7; ADC_DMA_RMP at 0 range 8 .. 8; USART1_TX_DMA_RMP at 0 range 9 .. 9; USART1_RX_DMA_RMP at 0 range 10 .. 10; TIM16_DMA_RMP at 0 range 11 .. 11; TIM17_DMA_RMP at 0 range 12 .. 12; Reserved_13_15 at 0 range 13 .. 15; I2C_PB6_FM at 0 range 16 .. 16; I2C_PB7_FM at 0 range 17 .. 17; I2C_PB8_FM at 0 range 18 .. 18; I2C_PB9_FM at 0 range 19 .. 19; Reserved_20_31 at 0 range 20 .. 31; end record; -- EXTICR1_EXTI array element subtype EXTICR1_EXTI_Element is STM32_SVD.UInt4; -- EXTICR1_EXTI array type EXTICR1_EXTI_Field_Array is array (0 .. 3) of EXTICR1_EXTI_Element with Component_Size => 4, Size => 16; -- Type definition for EXTICR1_EXTI type EXTICR1_EXTI_Field (As_Array : Boolean := False) is record case As_Array is when False => -- EXTI as a value Val : STM32_SVD.UInt16; when True => -- EXTI as an array Arr : EXTICR1_EXTI_Field_Array; end case; end record with Unchecked_Union, Size => 16; for EXTICR1_EXTI_Field use record Val at 0 range 0 .. 15; Arr at 0 range 0 .. 15; end record; -- external interrupt configuration register 1 type EXTICR1_Register is record -- EXTI 0 configuration bits EXTI : EXTICR1_EXTI_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_16_31 : STM32_SVD.UInt16 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for EXTICR1_Register use record EXTI at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- EXTICR2_EXTI array element subtype EXTICR2_EXTI_Element is STM32_SVD.UInt4; -- EXTICR2_EXTI array type EXTICR2_EXTI_Field_Array is array (4 .. 7) of EXTICR2_EXTI_Element with Component_Size => 4, Size => 16; -- Type definition for EXTICR2_EXTI type EXTICR2_EXTI_Field (As_Array : Boolean := False) is record case As_Array is when False => -- EXTI as a value Val : STM32_SVD.UInt16; when True => -- EXTI as an array Arr : EXTICR2_EXTI_Field_Array; end case; end record with Unchecked_Union, Size => 16; for EXTICR2_EXTI_Field use record Val at 0 range 0 .. 15; Arr at 0 range 0 .. 15; end record; -- external interrupt configuration register 2 type EXTICR2_Register is record -- EXTI 4 configuration bits EXTI : EXTICR2_EXTI_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_16_31 : STM32_SVD.UInt16 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for EXTICR2_Register use record EXTI at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- EXTICR3_EXTI array element subtype EXTICR3_EXTI_Element is STM32_SVD.UInt4; -- EXTICR3_EXTI array type EXTICR3_EXTI_Field_Array is array (8 .. 11) of EXTICR3_EXTI_Element with Component_Size => 4, Size => 16; -- Type definition for EXTICR3_EXTI type EXTICR3_EXTI_Field (As_Array : Boolean := False) is record case As_Array is when False => -- EXTI as a value Val : STM32_SVD.UInt16; when True => -- EXTI as an array Arr : EXTICR3_EXTI_Field_Array; end case; end record with Unchecked_Union, Size => 16; for EXTICR3_EXTI_Field use record Val at 0 range 0 .. 15; Arr at 0 range 0 .. 15; end record; -- external interrupt configuration register 3 type EXTICR3_Register is record -- EXTI 8 configuration bits EXTI : EXTICR3_EXTI_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_16_31 : STM32_SVD.UInt16 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for EXTICR3_Register use record EXTI at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- EXTICR4_EXTI array element subtype EXTICR4_EXTI_Element is STM32_SVD.UInt4; -- EXTICR4_EXTI array type EXTICR4_EXTI_Field_Array is array (12 .. 15) of EXTICR4_EXTI_Element with Component_Size => 4, Size => 16; -- Type definition for EXTICR4_EXTI type EXTICR4_EXTI_Field (As_Array : Boolean := False) is record case As_Array is when False => -- EXTI as a value Val : STM32_SVD.UInt16; when True => -- EXTI as an array Arr : EXTICR4_EXTI_Field_Array; end case; end record with Unchecked_Union, Size => 16; for EXTICR4_EXTI_Field use record Val at 0 range 0 .. 15; Arr at 0 range 0 .. 15; end record; -- external interrupt configuration register 4 type EXTICR4_Register is record -- EXTI 12 configuration bits EXTI : EXTICR4_EXTI_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_16_31 : STM32_SVD.UInt16 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for EXTICR4_Register use record EXTI at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype CFGR2_LOCUP_LOCK_Field is STM32_SVD.Bit; subtype CFGR2_SRAM_PARITY_LOCK_Field is STM32_SVD.Bit; subtype CFGR2_PVD_LOCK_Field is STM32_SVD.Bit; subtype CFGR2_SRAM_PEF_Field is STM32_SVD.Bit; -- configuration register 2 type CFGR2_Register is record -- Cortex-M0 LOCKUP bit enable bit LOCUP_LOCK : CFGR2_LOCUP_LOCK_Field := 16#0#; -- SRAM parity lock bit SRAM_PARITY_LOCK : CFGR2_SRAM_PARITY_LOCK_Field := 16#0#; -- PVD lock enable bit PVD_LOCK : CFGR2_PVD_LOCK_Field := 16#0#; -- unspecified Reserved_3_7 : STM32_SVD.UInt5 := 16#0#; -- SRAM parity flag SRAM_PEF : CFGR2_SRAM_PEF_Field := 16#0#; -- unspecified Reserved_9_31 : STM32_SVD.UInt23 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CFGR2_Register use record LOCUP_LOCK at 0 range 0 .. 0; SRAM_PARITY_LOCK at 0 range 1 .. 1; PVD_LOCK at 0 range 2 .. 2; Reserved_3_7 at 0 range 3 .. 7; SRAM_PEF at 0 range 8 .. 8; Reserved_9_31 at 0 range 9 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- System configuration controller type SYSCFG_Peripheral is record -- configuration register 1 CFGR1 : aliased CFGR1_Register; -- external interrupt configuration register 1 EXTICR1 : aliased EXTICR1_Register; -- external interrupt configuration register 2 EXTICR2 : aliased EXTICR2_Register; -- external interrupt configuration register 3 EXTICR3 : aliased EXTICR3_Register; -- external interrupt configuration register 4 EXTICR4 : aliased EXTICR4_Register; -- configuration register 2 CFGR2 : aliased CFGR2_Register; end record with Volatile; for SYSCFG_Peripheral use record CFGR1 at 16#0# range 0 .. 31; EXTICR1 at 16#8# range 0 .. 31; EXTICR2 at 16#C# range 0 .. 31; EXTICR3 at 16#10# range 0 .. 31; EXTICR4 at 16#14# range 0 .. 31; CFGR2 at 16#18# range 0 .. 31; end record; -- System configuration controller SYSCFG_Periph : aliased SYSCFG_Peripheral with Import, Address => System'To_Address (16#40010000#); end STM32_SVD.SYSCFG;
------------------------------------------------------------------------------- -- Copyright (c) 2019 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 Ada.Unchecked_Conversion; with DW1000.Types; use DW1000.Types; with Interfaces; use Interfaces; package IEEE802154.MAC with SPARK_Mode => On is -- Min/Max length of the MAC header (excluding Header IEs). Min_MHR_Length : constant := 2; Max_MHR_Length : constant := 37; -- Min/Max length of the Auxiliary Security Header Min_Aux_Security_Header_Length : constant := 0; Max_Aux_Security_Header_Length : constant := 14; ------------------------ -- Frame Type Field -- ------------------------ -- Ref. 7.2.1.1 of IEEE 802.15.4-2015 type Frame_Type_Field is (Beacon, Data, Ack, MAC_Command, Reserved, Multipurpose, Frak, Extended) with Size => 3; for Frame_Type_Field use (Beacon => 2#000#, Data => 2#001#, Ack => 2#010#, MAC_Command => 2#011#, Reserved => 2#100#, Multipurpose => 2#101#, Frak => 2#110#, Extended => 2#111#); ------------------------------ -- Security Enabled Field -- ------------------------------ -- Ref. 7.2.1.2 of IEEE 802.15.4-2015 type Security_Enabled_Field is (Disabled, Enabled) with Size => 1; for Security_Enabled_Field use (Disabled => 0, Enabled => 1); --------------------------- -- Frame Pending Field -- --------------------------- -- Ref. 7.2.1.3 of IEEE 802.15.4-2015 type Frame_Pending_Field is (Not_Pending, Pending) with Size => 1; for Frame_Pending_Field use (Not_Pending => 0, Pending => 1); -------------------------- -- Ack Required Field -- -------------------------- -- Ref. 7.2.1.4 of IEEE 802.15.4-2015 type Ack_Required_Field is (Not_Required, Required) with Size => 1; for Ack_Required_Field use (Not_Required => 0, Required => 1); -------------------------- -- PAN ID Compression -- -------------------------- -- Ref. 7.2.1.5 of IEEE 802.15.4-2015 type PAN_ID_Compression_Field is (Not_Compressed, Compressed) with Size => 1; for PAN_ID_Compression_Field use (Not_Compressed => 0, Compressed => 1); ----------------------------------- -- Sequence Number Suppression -- ----------------------------------- -- Ref. 7.2.1.6 of IEEE 802.15.4-2015 type Seq_Number_Suppression_Field is (Not_Suppressed, Suppressed) with Size => 1; for Seq_Number_Suppression_Field use (Not_Suppressed => 0, Suppressed => 1); ------------------------------------------ -- Information Elements Present Field -- ------------------------------------------ -- Ref. 7.2.1.7 of IEEE 802.15.4-2015 type IE_Present_Field is (Not_Present, Present) with Size => 1; for IE_Present_Field use (Not_Present => 0, Present => 1); ------------------------------------------------ -- Destination/Source Addressing Mode Field -- ------------------------------------------------ -- Ref. 7.2.1.8 of IEEE 802.15.4-2015 type Address_Mode_Field is (Not_Present, Reserved, Short, Extended) with Size => 2; for Address_Mode_Field use (Not_Present => 2#00#, Reserved => 2#01#, Short => 2#10#, Extended => 2#11#); ---------------------------------------- -- Destination/Source Address Field -- ---------------------------------------- -- Ref. 7.2.4 of IEEE 802.15.4-2015 type Extended_Address_Field is new Interfaces.Unsigned_64; type Short_Address_Field is new Interfaces.Unsigned_16; type Variant_Address (Mode : Address_Mode_Field := Not_Present) is record case Mode is when Not_Present | Reserved => null; when Short => Short_Address : Short_Address_Field; when Extended => Extended_Address : Extended_Address_Field; end case; end record; --------------------------- -- Frame Version Field -- --------------------------- -- Ref. 7.2.1.9 of IEEE 802.15.4-2015 type Frame_Version_Field is (IEEE_802_15_4_2003, IEEE_802_15_4_2006, IEEE_802_15_4, Reserved) with Size => 2; for Frame_Version_Field use (IEEE_802_15_4_2003 => 2#00#, IEEE_802_15_4_2006 => 2#01#, IEEE_802_15_4 => 2#10#, Reserved => 2#11#); ----------------------------- -- Sequence Number Field -- ----------------------------- -- Ref. 7.2.2 of IEEE 802.15.4-2015 type Sequence_Number_Field is new Interfaces.Unsigned_8; type Variant_Sequence_Number (Suppression : Seq_Number_Suppression_Field := Suppressed) is record case Suppression is when Suppressed => null; when Not_Suppressed => Number : Sequence_Number_Field; end case; end record; -------------------- -- PAN ID Field -- -------------------- -- Ref. 7.2.3 of IEEE 802.15.4-2015 type PAN_ID_Field is new Interfaces.Unsigned_16; type Variant_PAN_ID (Present : Boolean := False) is record case Present is when False => null; when True => PAN_ID : PAN_ID_Field; end case; end record; --------------------------- -- Frame Control Field -- --------------------------- -- Ref. 7.2.1 of IEEE 802.15.4-2015 -- Note that Multipurpose and Extended frame control field formats -- are NOT supported in this implementation. type Frame_Control_Field is record Frame_Type : Frame_Type_Field; Security_Enabled : Security_Enabled_Field; Frame_Pending : Frame_Pending_Field; AR : Ack_Required_Field; PAN_ID_Compression : PAN_ID_Compression_Field; Reserved : DW1000.Types.Bits_1; SN_Suppression : Seq_Number_Suppression_Field; IE_Present : IE_Present_Field; Dest_Address_Mode : Address_Mode_Field; Frame_Version : Frame_Version_Field; Src_Address_Mode : Address_Mode_Field; end record with Size => 16; for Frame_Control_Field use record Frame_Type at 0 range 0 .. 2; Security_Enabled at 0 range 3 .. 3; Frame_Pending at 0 range 4 .. 4; AR at 0 range 5 .. 5; PAN_ID_Compression at 0 range 6 .. 6; Reserved at 0 range 7 .. 7; SN_Suppression at 0 range 8 .. 8; IE_Present at 0 range 9 .. 9; Dest_Address_Mode at 0 range 10 .. 11; Frame_Version at 0 range 12 .. 13; Src_Address_Mode at 0 range 14 .. 15; end record; ---------------------------- -- Security Level Field -- ---------------------------- -- Ref. 9.4.1.1 of IEEE 802.15.4-2015 type Security_Level_Field is range 0 .. 7 with Size => 3; --------------------------------- -- Key Identifier Mode Field -- --------------------------------- -- Ref. 9.4.1.2 of IEEE 802.15.4-2015 type Key_ID_Mode_Field is range 0 .. 3 with Size => 2; --------------------------------------- -- Frame Counter Suppression Field -- --------------------------------------- -- Ref. 9.4.1.3 of IEEE 802.15.4-2015 type Frame_Counter_Suppression_Field is (Not_Suppressed, Suppressed) with Size => 1; for Frame_Counter_Suppression_Field use (Not_Suppressed => 0, Suppressed => 1); -------------------------- -- ASN In Nonce Field -- -------------------------- -- Ref. 9.4.1.4 of IEEE 802.15.4-2015 type Nonce_Source_Field is (From_Frame_Counter, From_ASN) with Size => 1; for Nonce_Source_Field use (From_Frame_Counter => 0, From_ASN => 1); ------------------------------ -- Security Control Field -- ------------------------------ -- Ref. 9.4.1 of IEEE 802.15.4-2015 type Security_Control_Field is record Security_Level : Security_Level_Field; Key_ID_Mode : Key_ID_Mode_Field; FC_Suppression : Frame_Counter_Suppression_Field; Nonce_Source : Nonce_Source_Field; Reserved : DW1000.Types.Bits_1; end record with Size => 8; for Security_Control_Field use record Security_Level at 0 range 0 .. 2; Key_ID_Mode at 0 range 3 .. 4; FC_Suppression at 0 range 5 .. 5; Nonce_Source at 0 range 6 .. 6; Reserved at 0 range 7 .. 7; end record; --------------------------- -- Frame Counter Field -- --------------------------- -- Ref. 9.4.2 of IEEE 802.15.4-2015 type Frame_Counter_Field is new Interfaces.Unsigned_32; type Variant_Frame_Counter (Suppression : Frame_Counter_Suppression_Field := Suppressed) is record case Suppression is when Suppressed => null; when Not_Suppressed => Frame_Counter : Frame_Counter_Field; end case; end record; ---------------------------- -- Key Identifier Field -- ---------------------------- -- Ref. 9.4.3 of IEEE 802.15.4-2015 type Key_Source_Field is new DW1000.Types.Byte_Array with Dynamic_Predicate => Key_Source_Field'Length in 0 | 4 | 8; type Key_Index_Field is range 0 .. 255 with Size => 8; -- Presence of Key Index and Key Source fields depends on the Key ID Mode. -- Refer to Table 9-7 of IEEE 802.15.4-2015. type Variant_Key_ID (Mode : Key_ID_Mode_Field := 0) is record case Mode is when 0 => null; when 1 .. 3 => Key_Index : Key_Index_Field; case Mode is when 0 | 1 => null; when 2 => Key_Source_4 : Key_Source_Field (1 .. 4); when 3 => Key_Source_8 : Key_Source_Field (1 .. 8); end case; end case; end record; --------------------------------- -- Auxiliary Security Header -- --------------------------------- -- Ref 9.4 of IEEE 802.15.4-2015 type Variant_Aux_Security_Header (Security_Enabled : Security_Enabled_Field := Disabled) is record case Security_Enabled is when Disabled => null; when Enabled => Security_Level : Security_Level_Field; ASN_In_Nonce : Nonce_Source_Field; Frame_Counter : Variant_Frame_Counter; Key_ID : Variant_Key_ID; end case; end record; ------------------ -- MAC Header -- ------------------ -- Ref. 7.2 of IEEE 802.15.4-2015 type MAC_Header is record -- Frame Control Fields. -- Note that some fields are in the variant part of other fields. Frame_Type : Frame_Type_Field; Frame_Pending : Frame_Pending_Field; AR : Ack_Required_Field; PAN_ID_Compression : PAN_ID_Compression_Field; IE_Present : IE_Present_Field; Frame_Version : Frame_Version_Field; -- Other fields Sequence_Number : Variant_Sequence_Number; Destination_PAN_ID : Variant_PAN_ID; Destination_Address : Variant_Address; Source_PAN_ID : Variant_PAN_ID; Source_Address : Variant_Address; Aux_Security_Header : Variant_Aux_Security_Header; end record; ------------------------------ -- Is_Valid_Configuration -- ------------------------------ function Is_Valid_Configuration (Destination_Address_Mode : in Address_Mode_Field; Source_Address_Mode : in Address_Mode_Field; Destination_PAN_ID_Present : in Boolean; Source_PAN_ID_Present : in Boolean) return Boolean with Global => null; -- Checks if the given source/destination address and PAN IDs are a -- valid configuration according to Table 7-2 of IEEE 802.15.4-2015. ------------------------------ -- Get_PAN_ID_Compression -- ------------------------------ function Get_PAN_ID_Compression (Destination_Address_Mode : in Address_Mode_Field; Source_Address_Mode : in Address_Mode_Field; Destination_PAN_ID_Present : in Boolean; Source_PAN_ID_Present : in Boolean) return PAN_ID_Compression_Field with Global => null, Pre => Is_Valid_Configuration (Destination_Address_Mode, Source_Address_Mode, Destination_PAN_ID_Present, Source_PAN_ID_Present); -- Get the value of the PAN ID Compression field for the specified -- source/destination address and PAN ID presence configuration. -- -- Note that this function follows the rules for frame version 2#10# -- (i.e. IEEE_802_15_4) as specified in Table 7-2 of IEEE 802.15.4-2015 -------------------------------- -- Is_Source_PAN_ID_Present -- -------------------------------- function Is_Source_PAN_ID_Present (Destination_Address_Mode : in Address_Mode_Field; Source_Address_Mode : in Address_Mode_Field; PAN_ID_Compression : in PAN_ID_Compression_Field) return Boolean with Global => null; ------------------------------------- -- Is_Destination_PAN_ID_Present -- ------------------------------------- function Is_Destination_PAN_ID_Present (Destination_Address_Mode : in Address_Mode_Field; Source_Address_Mode : in Address_Mode_Field; PAN_ID_Compression : in PAN_ID_Compression_Field) return Boolean with Global => null; -------------- -- Encode -- -------------- procedure Encode (MHR : in MAC_Header; Buffer : in out DW1000.Types.Byte_Array; Length : out Natural) with Global => null, Depends => (Buffer =>+ MHR, Length => MHR), Pre => (Buffer'Length >= Max_MHR_Length and MHR.Frame_Version /= Reserved and Is_Valid_Configuration (Destination_Address_Mode => MHR.Destination_Address.Mode, Source_Address_Mode => MHR.Source_Address.Mode, Destination_PAN_ID_Present => MHR.Destination_PAN_ID.Present, Source_PAN_ID_Present => MHR.Source_PAN_ID.Present)), Post => (Length <= Buffer'Length and (Length in Min_MHR_Length .. Max_MHR_Length)); -- Encode a MAC header into a byte array. -------------- -- Decode -- -------------- type Decode_Result is (Success, -- Decode was successful End_Of_Buffer, -- Error: End of buffer was reached during decode Reserved_Field); -- Error: A reserved value was encountered. procedure Decode (Buffer : in DW1000.Types.Byte_Array; MHR : out MAC_Header; Length : out Natural; Result : out Decode_Result) with Global => null, Pre => Buffer'Length > 0, Post => (Length <= Buffer'Length and Length <= Max_MHR_Length and (if Result = Success then (MHR.Frame_Version /= Reserved and MHR.Destination_Address.Mode /= Reserved and MHR.Source_Address.Mode /= Reserved and Is_Valid_Configuration (Destination_Address_Mode => MHR.Destination_Address.Mode, Source_Address_Mode => MHR.Source_Address.Mode, Destination_PAN_ID_Present => MHR.Destination_PAN_ID.Present, Source_PAN_ID_Present => MHR.Source_PAN_ID.Present)))); -- Decode a MAC header from a byte array buffer. -- -- If the decode was successful then the source/destination addresses -- and PAN IDs are guaranteed to be a valid configuration. ------------------- -- Conversions -- ------------------- subtype Byte_Array_2 is DW1000.Types.Byte_Array (1 .. 2); subtype Byte_Array_4 is DW1000.Types.Byte_Array (1 .. 4); subtype Byte_Array_8 is DW1000.Types.Byte_Array (1 .. 8); -- These subprograms convert certain field types to and from their -- byte array representation. -- -- These are used for encoding and decoding operations. function Convert is new Ada.Unchecked_Conversion (Source => Frame_Control_Field, Target => Byte_Array_2); function Convert is new Ada.Unchecked_Conversion (Source => Byte_Array_2, Target => Frame_Control_Field); function Convert is new Ada.Unchecked_Conversion (Source => Security_Control_Field, Target => Bits_8); function Convert is new Ada.Unchecked_Conversion (Source => Bits_8, Target => Security_Control_Field); function Convert (PAN_ID : in PAN_ID_Field) return Byte_Array_2 with Inline, Global => null; function Convert (Bytes : in Byte_Array_2) return PAN_ID_Field with Inline, Global => null; function Convert (Address : in Short_Address_Field) return Byte_Array_2 with Inline, Global => null; function Convert (Bytes : in Byte_Array_2) return Short_Address_Field with Inline, Global => null; function Convert (FC : in Frame_Counter_Field) return Byte_Array_4 with Inline, Global => null; function Convert (Bytes : in Byte_Array_4) return Frame_Counter_Field with Inline, Global => null; function Convert (Address : in Extended_Address_Field) return Byte_Array_8 with Inline, Global => null; function Convert (Bytes : in Byte_Array_8) return Extended_Address_Field with Inline, Global => null; private ----------------------------------------- -- PAN ID Configuration Validity LUT -- ----------------------------------------- Valid_PAN_ID_Configurations : constant array (Address_Mode_Field, Address_Mode_Field, Boolean, Boolean) of Boolean := -- | |Destination| Source | -- Destination | Source | PAN ID | PAN ID | -- Address | Address | Present? |Present? | Valid? (Not_Present => (Not_Present => (False => (False => True, -- Row 1 True => False), True => (False => True, -- Row 2 True => False)), Reserved => (others => (others => False)), Short | Extended => (False => (False => True, -- Row 6 True => True), -- Row 5 True => (others => False))), Reserved => (others => (others => (others => False))), Short => (Not_Present => (False => (False => True, -- Row 4 True => False), True => (False => True, -- Row 3 True => False)), Reserved => (others => (others => False)), Short => (False => (others => False), True => (False => True, -- Row 14 True => True)), -- Row 9 Extended => (False => (False => False, True => False), True => (False => True, -- Row 12 True => True))), -- Row 10 Extended => (Not_Present => (False => (False => True, -- Row 4 True => False), True => (False => True, -- Row 3 True => False)), Reserved => (others => (others => False)), Short => (False => (others => False), True => (False => True, -- Row 13 True => True)), -- Row 11 Extended => (False => (False => True, -- Row 8 True => False), True => (False => True, -- Row 7 True => False)))); -- This look-up table captures the set of valid configurations -- for all possible Source/Destination Address and PAN ID combinations. -- -- Only the set of configurations listed in Table 7-2 of IEEE 802.15.4-2015 -- are permitted (marked as True in the last column of this table). -- All other combinations are not allowed. -- -- The entries in this table are annotated with the corresponding row -- number from Table 7-2. ---------------------------------- -- Source PAN ID Presence LUT -- ---------------------------------- Source_PAN_ID_Presence : constant array (Address_Mode_Field, Address_Mode_Field, PAN_ID_Compression_Field) of Boolean := -- | | | Source -- Destination | Source | PAN ID | PAN ID -- Address | Address | Compression | Present? (Not_Present => (Not_Present => (Not_Compressed => False, -- Row 1 Compressed => False), -- Row 2 Reserved => (others => False), Short => (Not_Compressed => True, -- Row 5 Compressed => False), -- Row 6 Extended => (Not_Compressed => True, -- Row 5 Compressed => False)), -- Row 6 Reserved => (others => (others => False)), Short => (Not_Present => (Not_Compressed => False, -- Row 3 Compressed => False), -- Row 4 Reserved => (others => False), Short => (Not_Compressed => True, -- Row 9 Compressed => False), -- Row 14 Extended => (Not_Compressed => True, -- Row 10 Compressed => False)), -- Row 12 Extended => (Not_Present => (Not_Compressed => False, -- Row 3 Compressed => False), -- Row 4 Reserved => (others => False), Short => (Not_Compressed => True, -- Row 11 Compressed => False), -- Row 13 Extended => (Not_Compressed => False, -- Row 7 Compressed => False))); -- Row 8 -- This look-up table determines when the source PAN ID field is present -- in the encoded MAC header. -- -- The circumstances when the source PAN ID is present is documented in -- Table 7-2 of IEEE 802.15.4-2015. --------------------------------------- -- Destination PAN ID Presence LUT -- --------------------------------------- Destination_PAN_ID_Presence : constant array (Address_Mode_Field, Address_Mode_Field, PAN_ID_Compression_Field) of Boolean := -- | | | Dest. -- Destination | Source | PAN ID | PAN ID -- Address | Address | Compression | Present? (Not_Present => (Not_Present => (Not_Compressed => False, -- Row 1 Compressed => True), -- Row 2 Reserved => (others => False), Short => (Not_Compressed => False, -- Row 5 Compressed => False), -- Row 6 Extended => (Not_Compressed => False, -- Row 5 Compressed => False)), -- Row 6 Reserved => (others => (others => False)), Short => (Not_Present => (Not_Compressed => True, -- Row 3 Compressed => False), -- Row 4 Reserved => (others => False), Short => (Not_Compressed => True, -- Row 9 Compressed => True), -- Row 14 Extended => (Not_Compressed => True, -- Row 10 Compressed => True)), -- Row 12 Extended => (Not_Present => (Not_Compressed => True, -- Row 3 Compressed => False), -- Row 4 Reserved => (others => False) , Short => (Not_Compressed => True, -- Row 11 Compressed => True), -- Row 13 Extended => (Not_Compressed => True, -- Row 7 Compressed => False))); -- Row 8 -- This look-up table determines when the destination PAN ID field is -- present in the encoded MAC header. -- -- The circumstances when the destination PAN ID is present is documented -- in Table 7-2 of IEEE 802.15.4-2015. ------------------------------ -- Is_Valid_Configuration -- ------------------------------ function Is_Valid_Configuration (Destination_Address_Mode : in Address_Mode_Field; Source_Address_Mode : in Address_Mode_Field; Destination_PAN_ID_Present : in Boolean; Source_PAN_ID_Present : in Boolean) return Boolean is (Valid_PAN_ID_Configurations (Destination_Address_Mode, Source_Address_Mode, Destination_PAN_ID_Present, Source_PAN_ID_Present)); ------------------------------ -- Get_PAN_ID_Compression -- ------------------------------ -- Refer to Table 7-2 of IEEE 802.15.4-2015 for the rules for when the -- PAN ID compression is set. function Get_PAN_ID_Compression (Destination_Address_Mode : in Address_Mode_Field; Source_Address_Mode : in Address_Mode_Field; Destination_PAN_ID_Present : in Boolean; Source_PAN_ID_Present : in Boolean) return PAN_ID_Compression_Field is (if Source_PAN_ID_Present then Not_Compressed elsif Destination_PAN_ID_Present then (if (Destination_Address_Mode = Extended and Source_Address_Mode = Extended) then Not_Compressed elsif (Destination_Address_Mode = Not_Present xor Source_Address_Mode = Not_Present) then Not_Compressed else Compressed) else (if (Destination_Address_Mode = Extended and Source_Address_Mode = Extended) then Compressed elsif (Destination_Address_Mode = Not_Present and Source_Address_Mode = Not_Present) then Not_Compressed else Compressed) ); -------------------------------- -- Is_Source_PAN_ID_Present -- -------------------------------- function Is_Source_PAN_ID_Present (Destination_Address_Mode : in Address_Mode_Field; Source_Address_Mode : in Address_Mode_Field; PAN_ID_Compression : in PAN_ID_Compression_Field) return Boolean is (Source_PAN_ID_Presence (Destination_Address_Mode, Source_Address_Mode, PAN_ID_Compression)); ------------------------------------- -- Is_Destination_PAN_ID_Present -- ------------------------------------- function Is_Destination_PAN_ID_Present (Destination_Address_Mode : in Address_Mode_Field; Source_Address_Mode : in Address_Mode_Field; PAN_ID_Compression : in PAN_ID_Compression_Field) return Boolean is (Destination_PAN_ID_Presence (Destination_Address_Mode, Source_Address_Mode, PAN_ID_Compression)); ------------------- -- Conversions -- ------------------- function Convert (PAN_ID : in PAN_ID_Field) return Byte_Array_2 is (Byte_Array_2'(Bits_8 (Unsigned_16 (PAN_ID) and 16#FF#), Bits_8 (Shift_Right (Unsigned_16 (PAN_ID), 8) and 16#FF#))); function Convert (Bytes : in Byte_Array_2) return PAN_ID_Field is (PAN_ID_Field (Bytes (1)) or PAN_ID_Field (Shift_Left (Unsigned_16 (Bytes (2)), 8))); function Convert (Address : in Short_Address_Field) return Byte_Array_2 is (Byte_Array_2'(Bits_8 (Unsigned_16 (Address) and 16#FF#), Bits_8 (Shift_Right (Unsigned_16 (Address), 8) and 16#FF#))); function Convert (Bytes : in Byte_Array_2) return Short_Address_Field is (Short_Address_Field (Bytes (1)) or Short_Address_Field (Shift_Left (Unsigned_16 (Bytes (2)), 8))); function Convert (FC : in Frame_Counter_Field) return Byte_Array_4 is (Byte_Array_4'(Bits_8 (Unsigned_32 (FC) and 16#FF#), Bits_8 (Shift_Right (Unsigned_32 (FC), 8) and 16#FF#), Bits_8 (Shift_Right (Unsigned_32 (FC), 16) and 16#FF#), Bits_8 (Shift_Right (Unsigned_32 (FC), 24) and 16#FF#))); function Convert (Bytes : in Byte_Array_4) return Frame_Counter_Field is (Frame_Counter_Field (Bytes (1)) or Frame_Counter_Field (Shift_Left (Unsigned_32 (Bytes (2)), 8)) or Frame_Counter_Field (Shift_Left (Unsigned_32 (Bytes (3)), 16)) or Frame_Counter_Field (Shift_Left (Unsigned_32 (Bytes (4)), 24))); function Convert (Address : in Extended_Address_Field) return Byte_Array_8 is (Byte_Array_8'(Bits_8 (Unsigned_64 (Address) and 16#FF#), Bits_8 (Shift_Right (Unsigned_64 (Address), 8) and 16#FF#), Bits_8 (Shift_Right (Unsigned_64 (Address), 16) and 16#FF#), Bits_8 (Shift_Right (Unsigned_64 (Address), 24) and 16#FF#), Bits_8 (Shift_Right (Unsigned_64 (Address), 32) and 16#FF#), Bits_8 (Shift_Right (Unsigned_64 (Address), 40) and 16#FF#), Bits_8 (Shift_Right (Unsigned_64 (Address), 48) and 16#FF#), Bits_8 (Shift_Right (Unsigned_64 (Address), 56) and 16#FF#))); function Convert (Bytes : in Byte_Array_8) return Extended_Address_Field is (Extended_Address_Field (Bytes (1)) or Extended_Address_Field (Shift_Left (Unsigned_64 (Bytes (2)), 8)) or Extended_Address_Field (Shift_Left (Unsigned_64 (Bytes (3)), 16)) or Extended_Address_Field (Shift_Left (Unsigned_64 (Bytes (4)), 24)) or Extended_Address_Field (Shift_Left (Unsigned_64 (Bytes (5)), 32)) or Extended_Address_Field (Shift_Left (Unsigned_64 (Bytes (6)), 40)) or Extended_Address_Field (Shift_Left (Unsigned_64 (Bytes (7)), 48)) or Extended_Address_Field (Shift_Left (Unsigned_64 (Bytes (8)), 56))); end IEEE802154.MAC;
package body Loop_Optimization17_Pkg is function F (V : Vector) return Vector is begin return V; end; end Loop_Optimization17_Pkg;
package Set_Puzzle is type Three is range 1..3; type Card is array(1 .. 4) of Three; type Cards is array(Positive range <>) of Card; type Set is array(Three) of Positive; procedure Deal_Cards(Dealt: out Cards); -- ouputs an array with disjoint cards function To_String(C: Card) return String; generic with procedure Do_something(C: Cards; S: Set); procedure Find_Sets(Given: Cards); -- calls Do_Something once for each set it finds. end Set_Puzzle;
generic type Real is digits <>; with function Sqrt(X: Real) return Real; with function "**"(X: Real; Y: Real) return Real; package Approximation is type Number is private; -- create an approximation function Approx(Value: Real; Sigma: Real) return Number; -- unary operations and conversion Real to Number function "+"(X: Real) return Number; function "-"(X: Real) return Number; function "+"(X: Number) return Number; function "-"(X: Number) return Number; -- addition / subtraction function "+"(X: Number; Y: Number) return Number; function "-"(X: Number; Y: Number) return Number; -- multiplication / division function "*"(X: Number; Y: Number) return Number; function "/"(X: Number; Y: Number) return Number; -- exponentiation function "**"(X: Number; Y: Positive) return Number; function "**"(X: Number; Y: Real) return Number; -- Output to Standard IO (wrapper for Ada.Text_IO and Ada.Text_IO.Float_IO) procedure Put_Line(Message: String; Item: Number; Value_Fore: Natural := 7; Sigma_Fore: Natural := 4; Aft: Natural := 2; Exp: Natural := 0); procedure Put(Item: Number; Value_Fore: Natural := 7; Sigma_Fore: Natural := 3; Aft: Natural := 2; Exp: Natural := 0); private type Number is record Value: Real; Sigma: Real; end record; end Approximation;
----------------------------------------------------------------------- -- servlet-servlets -- Servlet.Core -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016, 2017, 2018, 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. ----------------------------------------------------------------------- with Servlet.Requests; with Servlet.Responses; with Servlet.Sessions; with Servlet.Sessions.Factory; with Servlet.Routes; limited with Servlet.Filters; with Ada.Finalization; with Ada.Strings.Unbounded; with Ada.Strings.Hash; with Ada.Calendar; with Ada.Exceptions; with Util.Log; with Util.Properties; with Util.Strings.Vectors; with EL.Contexts; private with Ada.Containers.Indefinite_Hashed_Maps; -- The <b>Servlet.Core</b> package implements a subset of the -- Java Servlet Specification adapted for the Ada language. -- -- The rationale for this implementation is to provide a set of -- interfaces and ways of developing a Web application which -- benefit from the architecture expertise defined in Java applications. -- -- The <b>Servlet.Core</b>, <b>Servlet.Requests</b>, <b>Servlet.Responses</b> -- and <b>Servlet.Sessions</b> packages are independent of the web server -- which will be used (such as <b>AWS</b>, <b>Apache</b> or <b>Lighthttpd</b>). -- package Servlet.Core is Servlet_Error : exception; type Status_Type is (Ready, Disabled, Started, Suspended, Stopped); -- Filter chain as defined by JSR 315 6. Filtering type Filter_Chain is limited private; type Filter_Config is private; type Filter_Access is access all Servlet.Filters.Filter'Class; type Filter_List_Access is access all Servlet.Filters.Filter_List; -- Causes the next filter in the chain to be invoked, or if the calling -- filter is the last filter in the chain, causes the resource at the end -- of the chain to be invoked. procedure Do_Filter (Chain : in out Filter_Chain; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Get the filter name. function Get_Filter_Name (Config : in Filter_Config) return String; -- Returns a String containing the value of the named context-wide initialization -- parameter, or the default value if the parameter does not exist. -- -- The filter parameter name is automatically prefixed by the filter name followed by '.'. function Get_Init_Parameter (Config : in Filter_Config; Name : in String; Default : in String := "") return String; function Get_Init_Parameter (Config : in Filter_Config; Name : in String; Default : in String := "") return Ada.Strings.Unbounded.Unbounded_String; -- type Servlet_Registry; type Servlet_Registry is new Servlet.Sessions.Factory.Session_Factory with private; type Servlet_Registry_Access is access all Servlet_Registry'Class; -- Get the servlet context associated with the filter chain. function Get_Servlet_Context (Chain : in Filter_Chain) return Servlet_Registry_Access; -- Get the servlet context associated with the filter config. function Get_Servlet_Context (Config : in Filter_Config) return Servlet_Registry_Access; -- The <b>Servlet</b> represents the component that will handle -- an HTTP request received by the server. -- -- JSR 315 - 2. The Servlet Interface type Servlet is tagged limited private; type Servlet_Access is access all Servlet'Class; -- Get the servlet name. function Get_Name (Server : in Servlet) return String; -- Get the servlet context associated with this servlet. function Get_Servlet_Context (Server : in Servlet) return Servlet_Registry_Access; -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- not overriding procedure Initialize (Server : in out Servlet; Context : in Servlet_Registry'Class); -- Receives standard HTTP requests from the public service method and dispatches -- them to the Do_XXX methods defined in this class. This method is an HTTP-specific -- version of the Servlet.service(Request, Response) method. There's no need -- to override this method. procedure Service (Server : in Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Returns the time the Request object was last modified, in milliseconds since -- midnight January 1, 1970 GMT. If the time is unknown, this method returns -- a negative number (the default). -- -- Servlets that support HTTP GET requests and can quickly determine their -- last modification time should override this method. This makes browser and -- proxy caches work more effectively, reducing the load on server and network -- resources. function Get_Last_Modified (Server : in Servlet; Request : in Requests.Request'Class) return Ada.Calendar.Time; -- Called by the server (via the service method) to allow a servlet to handle -- a GET request. -- -- Overriding this method to support a GET request also automatically supports -- an HTTP HEAD request. A HEAD request is a GET request that returns no body -- in the response, only the request header fields. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. -- When using a PrintWriter object to return the response, set the content type -- before accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container -- to use a persistent connection to return its response to the client, -- improving performance. The content length is automatically set if the entire -- response fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- The GET method should be safe, that is, without any side effects for which -- users are held responsible. For example, most form queries have no side effects. -- If a client request is intended to change stored data, the request should use -- some other HTTP method. -- -- The GET method should also be idempotent, meaning that it can be safely repeated. -- Sometimes making a method safe also makes it idempotent. For example, repeating -- queries is both safe and idempotent, but buying a product online or modifying -- data is neither safe nor idempotent. -- -- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request" procedure Do_Get (Server : in Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Receives an HTTP HEAD request from the protected service method and handles -- the request. The client sends a HEAD request when it wants to see only the -- headers of a response, such as Content-Type or Content-Length. The HTTP HEAD -- method counts the output bytes in the response to set the Content-Length header -- accurately. -- -- If you override this method, you can avoid computing the response body and just -- set the response headers directly to improve performance. Make sure that the -- Do_Head method you write is both safe and idempotent (that is, protects itself -- from being called multiple times for one HTTP HEAD request). -- -- If the HTTP HEAD request is incorrectly formatted, doHead returns an HTTP -- "Bad Request" message. procedure Do_Head (Server : in Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Called by the server (via the service method) to allow a servlet to handle -- a POST request. The HTTP POST method allows the client to send data of unlimited -- length to the Web server a single time and is useful when posting information -- such as credit card numbers. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. When using -- a PrintWriter object to return the response, set the content type before -- accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container to use -- a persistent connection to return its response to the client, improving -- performance. The content length is automatically set if the entire response -- fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- This method does not need to be either safe or idempotent. Operations -- requested through POST can have side effects for which the user can be held -- accountable, for example, updating stored data or buying items online. -- -- If the HTTP POST request is incorrectly formatted, doPost returns -- an HTTP "Bad Request" message. procedure Do_Post (Server : in Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Called by the server (via the service method) to allow a servlet to handle -- a PUT request. The PUT operation allows a client to place a file on the server -- and is similar to sending a file by FTP. -- -- When overriding this method, leave intact any content headers sent with -- the request (including Content-Length, Content-Type, Content-Transfer-Encoding, -- Content-Encoding, Content-Base, Content-Language, Content-Location, -- Content-MD5, and Content-Range). If your method cannot handle a content -- header, it must issue an error message (HTTP 501 - Not Implemented) and -- discard the request. For more information on HTTP 1.1, see RFC 2616 . -- -- This method does not need to be either safe or idempotent. Operations that -- Do_Put performs can have side effects for which the user can be held accountable. -- When using this method, it may be useful to save a copy of the affected URL -- in temporary storage. -- -- If the HTTP PUT request is incorrectly formatted, Do_Put returns -- an HTTP "Bad Request" message. procedure Do_Put (Server : in Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Called by the server (via the service method) to allow a servlet to handle -- a DELETE request. The DELETE operation allows a client to remove a document -- or Web page from the server. -- -- This method does not need to be either safe or idempotent. Operations requested -- through DELETE can have side effects for which users can be held accountable. -- When using this method, it may be useful to save a copy of the affected URL in -- temporary storage. -- -- If the HTTP DELETE request is incorrectly formatted, Do_Delete returns an HTTP -- "Bad Request" message. procedure Do_Delete (Server : in Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Called by the server (via the service method) to allow a servlet to handle a -- OPTIONS request. The OPTIONS request determines which HTTP methods the server -- supports and returns an appropriate header. For example, if a servlet overrides -- Do_Get, this method returns the following header: -- -- Allow: GET, HEAD, TRACE, OPTIONS -- -- There's no need to override this method unless the servlet implements new -- HTTP methods, beyond those implemented by HTTP 1.1. procedure Do_Options (Server : in Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Called by the server (via the service method) to allow a servlet to handle -- a TRACE request. A TRACE returns the headers sent with the TRACE request to -- the client, so that they can be used in debugging. There's no need to override -- this method. procedure Do_Trace (Server : in Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Called by the server (via the service method) to allow a servlet to handle -- a PATCH request (RFC 5789). procedure Do_Patch (Server : in Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- JSR 315 9. Dispatching Requests type Request_Dispatcher is limited private; -- Forwards a request from a servlet to another resource -- (servlet, or HTML file) on the server. This method allows one servlet to do -- preliminary processing of a request and another resource to generate the response. -- -- For a Request_Dispatcher obtained via Get_Request_Dispatcher(), -- the ServletRequest object has its path elements and parameters adjusted -- to match the path of the target resource. -- -- forward should be called before the response has been committed to the -- client (before response body output has been flushed). If the response -- already has been committed, this method throws an IllegalStateException. -- Uncommitted output in the response buffer is automatically cleared before -- the forward. -- -- The request and response parameters must be either the same objects as were -- passed to the calling servlet's service method or be subclasses of the -- RequestWrapper or ResponseWrapper classes that wrap them. procedure Forward (Dispatcher : in Request_Dispatcher; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Includes the content of a resource (servlet, or, HTML file) in the response. -- In essence, this method enables programmatic server-side includes. -- -- The Response object has its path elements and parameters remain -- unchanged from the caller's. The included servlet cannot change the response -- status code or set headers; any attempt to make a change is ignored. -- -- The request and response parameters must be either the same objects as were -- passed to the calling servlet's service method or be subclasses of the -- RequestWrapper or ResponseWrapper classes that wrap them. procedure Include (Dispatcher : in Request_Dispatcher; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Returns the servlet that will be called when forwarding the request. function Get_Servlet (Dispatcher : in Request_Dispatcher) return Servlet_Access; -- Returns a Request_Dispatcher object that acts as a wrapper for the resource -- located at the given path. A Request_Dispatcher object can be used to forward -- a request to the resource or to include the resource in a response. -- The resource can be dynamic or static. function Get_Request_Dispatcher (Context : in Servlet_Registry; Path : in String) return Request_Dispatcher; -- Returns a Request_Dispatcher object that acts as a wrapper for the named servlet. -- -- Servlets may be given names via server administration or via a web application -- deployment descriptor. A servlet instance can determine its name using -- ServletConfig.getServletName(). function Get_Name_Dispatcher (Context : in Servlet_Registry; Name : in String) return Request_Dispatcher; -- Returns the context path of the web application. -- The context path is the portion of the request URI that is used to select the context -- of the request. The context path always comes first in a request URI. The path starts -- with a "/" character but does not end with a "/" character. For servlets in the default -- (root) context, this method returns "". function Get_Context_Path (Context : in Servlet_Registry) return String; -- Returns a String containing the value of the named context-wide initialization -- parameter, or null if the parameter does not exist. -- -- This method can make available configuration information useful to an entire -- "web application". For example, it can provide a webmaster's email address -- or the name of a system that holds critical data. function Get_Init_Parameter (Context : in Servlet_Registry; Name : in String; Default : in String := "") return String; function Get_Init_Parameter (Context : in Servlet_Registry; Name : in String; Default : in String := "") return Ada.Strings.Unbounded.Unbounded_String; -- Set the init parameter identified by <b>Name</b> to the value <b>Value</b>. procedure Set_Init_Parameter (Context : in out Servlet_Registry; Name : in String; Value : in String); -- Set the init parameters by copying the properties defined in <b>Params</b>. -- Existing parameters will be overriding by the new values. procedure Set_Init_Parameters (Context : in out Servlet_Registry; Params : in Util.Properties.Manager'Class); -- Get access to the init parameters. procedure Get_Init_Parameters (Context : in Servlet_Registry; Process : not null access procedure (Params : in Util.Properties.Manager'Class)); -- Returns the absolute path of the resource identified by the given relative path. -- The resource is searched in a list of directories configured by the application. -- The path must begin with a "/" and is interpreted as relative to the current -- context root. -- -- This method allows the servlet container to make a resource available to -- servlets from any source. -- -- This method returns an empty string if the resource could not be localized. function Get_Resource (Context : in Servlet_Registry; Path : in String) return String; -- Registers the given servlet instance with this ServletContext under -- the given servletName. -- -- If this ServletContext already contains a preliminary -- ServletRegistration for a servlet with the given servletName, -- it will be completed (by assigning the class name of the given -- servlet instance to it) and returned. procedure Add_Servlet (Registry : in out Servlet_Registry; Name : in String; Server : in Servlet_Access); -- Registers the given filter instance with this Servlet context. procedure Add_Filter (Registry : in out Servlet_Registry; Name : in String; Filter : in Filter_Access); -- Add a filter mapping with the given pattern -- If the URL pattern is already mapped to a different servlet, -- no updates will be performed. procedure Add_Filter_Mapping (Registry : in out Servlet_Registry; Pattern : in String; Name : in String); -- Add a servlet mapping with the given pattern -- If the URL pattern is already mapped to a different servlet, -- no updates will be performed. procedure Add_Mapping (Registry : in out Servlet_Registry; Pattern : in String; Name : in String); -- Add a servlet mapping with the given pattern -- If the URL pattern is already mapped to a different servlet, -- no updates will be performed. procedure Add_Mapping (Registry : in out Servlet_Registry; Pattern : in String; Server : in Servlet_Access); -- Add a route associated with the given path pattern. The pattern is split into components. -- Some path components can be a fixed string (/home) and others can be variable. -- When a path component is variable, the value can be retrieved from the route context. -- Once the route path is created, the <tt>Process</tt> procedure is called with the route -- reference. procedure Add_Route (Registry : in out Servlet_Registry; Pattern : in String; ELContext : in EL.Contexts.ELContext'Class; Process : not null access procedure (Route : in out Routes.Route_Type_Ref)); -- Set the error page that will be used if a servlet returns an error. procedure Set_Error_Page (Server : in out Servlet_Registry; Error : in Integer; Page : in String); -- Send the error page content defined by the response status. procedure Send_Error_Page (Server : in Servlet_Registry; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Report an error when an exception occurred while processing the request. procedure Error (Registry : in Servlet_Registry; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class; Ex : in Ada.Exceptions.Exception_Occurrence); -- Register the application represented by <b>Registry</b> under the base URI defined -- by <b>URI</b>. This is called by the Web container when the application is registered. -- The default implementation keeps track of the base URI to implement the context path -- operation. procedure Register_Application (Registry : in out Servlet_Registry; URI : in String); -- Start the application. procedure Start (Registry : in out Servlet_Registry); -- Get the application status. function Get_Status (Registry : in Servlet_Registry) return Status_Type; -- Disable the application. procedure Disable (Registry : in out Servlet_Registry); -- Enable the application. procedure Enable (Registry : in out Servlet_Registry); -- Stop the application. procedure Stop (Registry : in out Servlet_Registry); -- Finalize the servlet registry releasing the internal mappings. overriding procedure Finalize (Registry : in out Servlet_Registry); -- Dump the routes and filter configuration in the log with the given log level. procedure Dump_Routes (Registry : in out Servlet_Registry; Level : in Util.Log.Level_Type); private use Ada.Strings.Unbounded; type Filter_Chain is limited record Filter_Pos : Natural; Filters : Filter_List_Access; Servlet : Servlet_Access; end record; type Request_Dispatcher is limited record Context : aliased Routes.Route_Context_Type; Filters : Filter_List_Access; Servlet : Servlet_Access := null; Pos : Natural := 0; end record; type Servlet is new Ada.Finalization.Limited_Controlled with record Name : Unbounded_String; Context : Servlet_Registry_Access := null; end record; package Filter_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Filter_Access, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); package Filter_List_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Filter_List_Access, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); package Servlet_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Servlet_Access, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); function Hash (N : Integer) return Ada.Containers.Hash_Type; package Error_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => Integer, Element_Type => String, Hash => Hash, Equivalent_Keys => "="); use Routes; type Servlet_Registry is new Sessions.Factory.Session_Factory with record Config : Util.Properties.Manager; Servlets : Servlet_Maps.Map; Filters : Filter_Maps.Map; Filter_Rules : Filter_List_Maps.Map; Filter_Patterns : Util.Strings.Vectors.Vector; Error_Pages : Error_Maps.Map; Context_Path : Unbounded_String; Routes : Router_Type; Status : Status_Type := Ready; end record; -- Install the servlet filters after all the mappings have been registered. procedure Install_Filters (Registry : in out Servlet_Registry); type Filter_Config is record Name : Unbounded_String; Context : Servlet_Registry_Access := null; end record; end Servlet.Core;
------------------------------------------------------------------------------ -- -- -- J E W L . C A N V A S _ I M P L E M E N T A T I O N -- -- -- -- This is a private package containing the internal implementation -- -- details of the canvases, as defined in JEWL.Windows. -- -- -- -- Copyright (C) John English 2000. Contact address: je@brighton.ac.uk -- -- This software is released under the terms of the GNU General Public -- -- License and is intended primarily for educational use. Please contact -- -- the author to report bugs, suggestions and modifications. -- -- -- ------------------------------------------------------------------------------ -- $Id: jewl-canvas_implementation.ads 1.7 2007/01/08 17:00:00 JE Exp $ ------------------------------------------------------------------------------ -- -- $Log: jewl-canvas_implementation.ads $ -- Revision 1.7 2007/01/08 17:00:00 JE -- * Fixed linker options in JEWL.Win32_Interface to accommodate changes to GNAT -- GPL 2006 compiler (thanks to John McCormick for this) -- * Added delay in message loop to avoid the appearance of hogging 100% of CPU -- time -- -- Revision 1.6 2001/11/02 16:00:00 JE -- * Fixed canvas bug when saving an empty canvas -- * Restore with no prior save now acts as erase -- * Removed redundant variable declaration in Image function -- -- Revision 1.5 2001/08/22 15:00:00 JE -- * Minor bugfix to Get_Text for combo boxes -- * Minor changes to documentation (including new example involving dialogs) -- -- Revision 1.4 2001/01/25 09:00:00 je -- Changes visible to the user: -- -- * Added support for drawing bitmaps on canvases (Draw_Image operations -- and new type Image_Type) -- * Added Play_Sound -- * Added several new operations on all windows: Get_Origin, Get_Width, -- Get_Height, Set_Origin, Set_Size and Focus -- * Added several functions giving screen and window dimensions: Screen_Width, -- Screen_Height, Frame_Width, Frame_Height, Dialog_Width, Dialog_Height and -- Menu_Height -- * Canvases can now handle keyboard events: new constructor and Key_Code added -- * Added procedure Play_Sound -- * Operations "+" and "-" added for Point_Type -- * Pens can now be zero pixels wide -- * The absolute origin of a frame can now have be specified when the frame -- is created -- * Added new File_Dialog operations Add_Filter and Set_Directory -- * Added Get_Line renames to JEWL.IO for compatibility with Ada.Text_IO -- * Added all the Get(File,Item) operations mentioned in documentation but -- unaccountably missing :-( -- * Documentation updated to reflect the above changes -- * HTML versions of public package specifications added with links from -- main documentation pages -- -- Other internal changes: -- -- * Canvas fonts, pens etc. now use JEWL.Reference_Counted_Type rather than -- reinventing this particular wheel, as do images -- * Various minor code formatting changes: some code reordered for clarity, -- some comments added or amended, -- * Changes introduced in 1.2 to support GNAT 3.10 have been reversed, since -- GNAT 3.10 still couldn't compile this code correctly... ;-( -- -- Outstanding issues: -- -- * Optimisation breaks the code (workaround: don't optimise) -- -- Revision 1.3 2000/07/07 12:00:00 je -- * JEWL.Simple_Windows added; JEWL.IO modified to use JEWL.Simple_Windows. -- * JEWL.IO bug fix: Put_Line to file wrote newline to standard output -- instead of to the file (thanks to Jeff Carter for pointing this out). -- * Panels fixed so that mouse clicks are passed on correctly to subwindows. -- * Memos fixed so that tabs are handled properly. -- * Password feature added to editboxes. -- * Minor typos fixed in comments within the package sources. -- * Documentation corrected and updated following comments from Moti Ben-Ari -- and Don Overheu. -- -- Revision 1.2 2000/04/18 20:00:00 je -- * Minor code changes to enable compilation by GNAT 3.10 -- * Minor documentation errors corrected -- * Some redundant "with" clauses removed -- -- Revision 1.1 2000/04/09 21:00:00 je -- Initial revision -- ------------------------------------------------------------------------------ with Ada.Finalization; with JEWL.Win32_Interface; private package JEWL.Canvas_Implementation is use JEWL.Win32_Interface; type Point_List is array (Positive range <>) of aliased Win32_POINT; ---------------------------------------------------------------------------- -- Forward declarations (defined fully later). ---------------------------------------------------------------------------- type Canvas_Object_Type; type Canvas_Object_Ptr is access Canvas_Object_Type'Class; type Image_Internals; type Image_Ptr is access all Image_Internals; ---------------------------------------------------------------------------- -- -- C A N V A S _ M O N I T O R -- -- Every canvas contains one of these protected records to synchronise -- drawing operations with accesses from the message loop task. The -- canvas stores the objects which are drawn on it as a linked list -- of drawing objects (defined in JEWL.Objects). -- -- The private data of a Canvas_Monitor is as follows: -- -- First_Object : pointer to the first object in the drawing list -- Last_Object : pointer to the last object in the drawing list -- Save_Pointer : pointer to the saved position in the drawing list -- BG_Brush : the brush used to paint the background of the canvas -- Start_X : the X position where the mouse button was pressed -- Start_Y : the Y position where the mouse button was pressed -- End_X : the most recent X position while the mouse is down -- End_Y : the most recent Y position while the mouse is down -- Button : true if the mouse is down -- Moved : true is the mouse has moved while the button is down -- Keycode : the key that was pressed (or NUL if none) -- -- The operations on a Canvas_Monitor are as follows: -- -- Clear : delete all objects in the drawing list -- Save ; save a pointer to the current end of the drawing list -- Restore : truncate the drawing list to a previously saved point -- Draw : draw all objects in the drawing list (called from the -- message loop task) -- Add : add an object to the end of the drawing list -- Set_Brush : set the background brush -- Background : get the background brush (called from the message loop -- task) -- Set_Start : set the start position when the mouse button is pressed -- (called from the message loop task) -- Get_Start : get the start position when the mouse button is pressed -- Set_End : set the current mouse position and the mouse-move flag -- (called from the message loop task) -- Get_End : get the current mouse position -- Set_Button : set the mouse button state (called from the message loop -- task) -- Mouse_Down : return the mouse button state -- Mouse_Moved : return the mouse-move flag and reset it -- Set_Key : set the keycode for a key press -- Get_Key : get and reset the current keycode -- ---------------------------------------------------------------------------- protected type Canvas_Monitor is procedure Clear; procedure Save; procedure Restore; procedure Draw (Handle : in Win32_HWND; Font : in Win32_HFONT); procedure Add (Object : in Canvas_Object_Ptr); procedure Set_Brush (Brush : in Win32_HBRUSH); function Background return Win32_HBRUSH; procedure Set_Start (X, Y : in Integer); procedure Get_Start (X, Y : out Integer); procedure Set_End (X, Y : in Integer); procedure Get_End (X, Y : out Integer); procedure Set_Button (B : in Boolean); function Mouse_Down return Boolean; function Mouse_Moved return Boolean; procedure Set_Key (C : in Character); procedure Get_Key (C : out Character); private First_Object : Canvas_Object_Ptr; Last_Object : Canvas_Object_Ptr; Save_Pointer : Canvas_Object_Ptr; BG_Brush : Win32_HBRUSH; Start_X : Integer := 0; Start_Y : Integer := 0; End_X : Integer := 0; End_Y : Integer := 0; Button : Boolean := False; Moved : Boolean := False; Keycode : Character := ASCII.NUL; end Canvas_Monitor; ---------------------------------------------------------------------------- -- -- C A N V A S _ O B J E C T _ T Y P E -- -- Canvas_Object_Type is the base type from which all drawing objects -- are derived, and Canvas_Object_Ptr is a class-wide pointer. Each -- object contains a pointer so that a singly-linked list of objects -- can be constructed. Every object must define a Draw procedure which -- draws the object on a window (which is identified by a handle to a -- Windows display context). -- ---------------------------------------------------------------------------- type Canvas_Object_Type is abstract tagged record Next : Canvas_Object_Ptr; end record; procedure Draw (Object : in out Canvas_Object_Type; Window : in Win32_HDC) is abstract; ---------------------------------------------------------------------------- -- -- Text_Type: an object type containing a text string -- type Text_Type (Length : Natural) is new Canvas_Object_Type with record Text : String (1..Length); From, To : JEWL.Point_Type; Align : Integer; end record; procedure Draw (Object : in out Text_Type; Window : in Win32_HDC); ---------------------------------------------------------------------------- -- -- Line_Type: an object type which defines a line by a pair of endpoints. -- type Line_Type is new Canvas_Object_Type with record From, To : JEWL.Point_Type; end record; procedure Draw (Object : in out Line_Type; Window : in Win32_HDC); ---------------------------------------------------------------------------- -- -- Rectangle_Type: an object type which defines a rectangle as a pair -- of coordinates for two opposite corners. -- type Rectangle_Type is new Canvas_Object_Type with record From, To : JEWL.Point_Type; end record; procedure Draw (Object : in out Rectangle_Type; Window : in Win32_HDC); ---------------------------------------------------------------------------- -- -- Rounded_Rectangle_Type: an object type which defines a rectangle with -- rounded corners using a pair of coordinates -- for two opposite corners and a point to define -- the size of the arc used to round the corners. -- type Rounded_Rectangle_Type is new Canvas_Object_Type with record From, To, Corner : Point_Type; end record; procedure Draw (Object : in out Rounded_Rectangle_Type; Window : in Win32_HDC); ---------------------------------------------------------------------------- -- -- Ellipse_Type: an object type which defines an ellipse or circle using -- a pair of coordinates for two opposite corners of the -- bounding rectangle. -- type Ellipse_Type is new Canvas_Object_Type with record From, To : JEWL.Point_Type; end record; procedure Draw (Object : in out Ellipse_Type; Window : in Win32_HDC); ---------------------------------------------------------------------------- -- -- Polyline_Type: an object type which defines an open figure as a -- sequence of lines. -- type Polyline_Type (Count : Positive) is new Canvas_Object_Type with record Points : Point_List(1..Count); end record; procedure Draw (Object : in out PolyLine_Type; Window : in Win32_HDC); ---------------------------------------------------------------------------- -- -- Polygon_Type: an object type which defines an open figure as a -- sequence of lines. -- type Polygon_Type (Count : Positive) is new Canvas_Object_Type with record Points : Point_List(1..Count); end record; procedure Draw (Object : in out Polygon_Type; Window : in Win32_HDC); ---------------------------------------------------------------------------- -- -- Handle_Type: an object type which encapsulates a handle to a Windows -- GDI object (e.g. a pen or a brush). -- type Handle_Type is new Canvas_Object_Type with record Handle : JEWL.Controlled_Type; end record; procedure Draw (Object : in out Handle_Type; Window : in Win32_HDC); ---------------------------------------------------------------------------- -- -- Bitmap_Type: an object type representing a bitmap image. -- type Bitmap_Type is new Canvas_Object_Type with record From : JEWL.Point_Type; Width : Natural; Height : Natural; Bitmap : JEWL.Controlled_Type; end record; procedure Draw (Object : in out Bitmap_Type; Window : in Win32_HDC); ---------------------------------------------------------------------------- -- -- C O N T R O L L E D T Y P E S -- -- Each type below is a reference counted type which contains a handle to -- a Windows GDI object. The handle will be deleted automatically when the -- last object which refers to it is destroyed. -- ---------------------------------------------------------------------------- -- -- Image_Internals: used to store bitmaps in drawings -- type Image_Internals is new Reference_Counted_Type with record Image : Win32_HBITMAP; Width : Natural; Height : Natural; end record; procedure Cleanup (Object : in out Image_Internals); ---------------------------------------------------------------------------- -- -- Counted_Handle_Type: used to store pens, brushes etc. in drawings -- type Counted_Handle_Type is new JEWL.Reference_Counted_Type with record Handle : Win32_HGDIOBJ; end record; procedure Cleanup (Object : in out Counted_Handle_Type); ---------------------------------------------------------------------------- -- -- Handle: a function to create a controlled type object which contains -- a Counted_Handle_Type object. -- function Handle (Object : Win32_HGDIOBJ) return JEWL.Controlled_Type; end JEWL.Canvas_Implementation;
----------------------------------------------------------------------- -- awa-jobs-modules -- Job module -- Copyright (C) 2012, 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. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with ASF.Applications; with AWA.Modules; with AWA.Jobs.Services; -- == Integration == -- To be able to use the `jobs` module, you will need to add the -- following line in your GNAT project file: -- -- with "awa_jobs"; -- -- An instance of the `Job_Module` must be declared and registered in the -- AWA application. The module instance can be defined as follows: -- -- with AWA.Jobs.Modules; -- ... -- type Application is new AWA.Applications.Application with record -- Job_Module : aliased AWA.Jobs.Modules.Job_Module; -- end record; -- -- And registered in the `Initialize_Modules` procedure by using: -- -- Register (App => App.Self.all'Access, -- Name => AWA.Jobs.Modules.NAME, -- Module => App.Job_Module'Access); -- package AWA.Jobs.Modules is NAME : constant String := "jobs"; type Job_Module is new AWA.Modules.Module with private; type Job_Module_Access is access all Job_Module'Class; -- Initialize the job module. overriding procedure Initialize (Plugin : in out Job_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the job module instance associated with the current application. function Get_Job_Module return Job_Module_Access; -- Registers the job work procedure represented by `Work` under the name `Name`. procedure Register (Plugin : in out Job_Module; Definition : in AWA.Jobs.Services.Job_Factory_Access); -- Find the job work factory registered under the name `Name`. -- Returns null if there is no such factory. function Find_Factory (Plugin : in Job_Module; Name : in String) return AWA.Jobs.Services.Job_Factory_Access; private use AWA.Jobs.Services; -- A factory map to create job instances. package Job_Factory_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Job_Factory_Access, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); type Job_Module is new AWA.Modules.Module with record Factory : Job_Factory_Map.Map; end record; end AWA.Jobs.Modules;
-- EE3204A.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. --* -- OBJECTIVE: -- CHECK THAT AFTER THE DEFAULT FILES HAVE BEEN REDEFINED, -- OUTPUT ON THE STANDARD FILES IS STILL PROPERLY HANDLED. -- APPLICABILITY CRITERIA: -- THIS TEST IS ONLY APPLICABLE TO IMPLEMENTATIONS WHICH SUPPORT -- TEXT FILES. -- PASS/FAIL CRITERIA: -- THIS TEST IS PASSED IF IT EXECUTES, PRINTS TENTATIVELY PASSED, -- AND THE CONTENTS OF THE STANDARD OUTPUT FILE ARE CORRECT. -- HISTORY: -- JLH 07/08/88 CREATED ORIGINAL TEST. WITH REPORT; USE REPORT; WITH TEXT_IO; USE TEXT_IO; PROCEDURE EE3204A IS FILE1, FILE2 : FILE_TYPE; ITEM : CHARACTER := 'B'; INCOMPLETE : EXCEPTION; BEGIN TEST ("EE3204A", "CHECK THAT AFTER THE DEFAULT FILES HAVE BEEN " & "REDEFINED, OUTPUT ON THE STANDARD " & "FILES IS STILL PROPERLY HANDLED"); BEGIN BEGIN CREATE (FILE1, OUT_FILE, LEGAL_FILE_NAME); EXCEPTION WHEN USE_ERROR => NOT_APPLICABLE ("USE_ERROR RAISED ON CREATE " & "WITH MODE OUT_FILE"); RAISE INCOMPLETE; WHEN NAME_ERROR => NOT_APPLICABLE ("NAME_ERROR RAISED ON CREATE " & "WITH MODE OUT_FILE"); RAISE INCOMPLETE; WHEN OTHERS => FAILED ("UNEXPECTED EXCEPTION RAISED ON CREATE"); RAISE INCOMPLETE; END; CREATE (FILE2, OUT_FILE, LEGAL_FILE_NAME(2)); PUT (FILE2, 'A'); NEW_LINE (FILE2); PUT (FILE2, 'B'); CLOSE (FILE2); BEGIN OPEN (FILE2, IN_FILE, LEGAL_FILE_NAME(2)); EXCEPTION WHEN USE_ERROR => NOT_APPLICABLE ("USE_ERROR RAISED ON OPEN WITH " & "WITH MODE IN_FILE"); RAISE INCOMPLETE; END; SET_INPUT (FILE2); GET (ITEM); IF ITEM /= 'A' THEN FAILED ("INCORRECT VALUE READ FROM DEFAULT FILE"); END IF; SET_OUTPUT (FILE1); PUT ("THIS TEST FAILS IF THIS APPEARS IN STANDARD OUTPUT"); NEW_LINE; PUT ("THIS TEST FAILS IF THIS APPEARS IN STANDARD OUTPUT"); PUT (STANDARD_OUTPUT, "FIRST LINE OF INPUT"); NEW_LINE (STANDARD_OUTPUT); PUT (STANDARD_OUTPUT, "SECOND LINE OF INPUT"); SPECIAL_ACTION ("CHECK THAT THE CONTENTS OF THE STANDARD " & "OUTPUT FILE ARE CORRECT"); SPECIAL_ACTION ("IT SHOULD CONTAIN:"); SPECIAL_ACTION ("TEST HEADER LINES"); SPECIAL_ACTION ("FIRST LINE OF INPUT"); SPECIAL_ACTION ("SECOND LINE OF INPUT"); BEGIN DELETE (FILE1); DELETE (FILE2); EXCEPTION WHEN USE_ERROR => NULL; END; EXCEPTION WHEN INCOMPLETE => NULL; END; RESULT; END EE3204A;
package impact.d2.orbs.Joint.prismatic -- -- -- is -- -- #include <Box2D/Dynamics/Joints/b2Joint.h> -- -- /// Prismatic joint definition. This requires defining a line of -- /// motion using an axis and an anchor point. The definition uses local -- /// anchor points and a local axis so that the initial configuration -- /// can violate the constraint slightly. The joint translation is zero -- /// when the local anchor points coincide in world space. Using local -- /// anchors and a local axis helps when saving and loading a game. -- /// @warning at least one body should by dynamic with a non-fixed rotation. -- struct b2PrismaticJointDef : public b2JointDef -- { -- b2PrismaticJointDef() -- { -- type = e_prismaticJoint; -- localAnchorA.SetZero(); -- localAnchorB.SetZero(); -- localAxis1.Set(1.0f, 0.0f); -- referenceAngle = 0.0f; -- enableLimit = false; -- lowerTranslation = 0.0f; -- upperTranslation = 0.0f; -- enableMotor = false; -- maxMotorForce = 0.0f; -- motorSpeed = 0.0f; -- } -- -- /// Initialize the bodies, anchors, axis, and reference angle using the world -- /// anchor and world axis. -- void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis); -- -- /// The local anchor point relative to body1's origin. -- b2Vec2 localAnchorA; -- -- /// The local anchor point relative to body2's origin. -- b2Vec2 localAnchorB; -- -- /// The local translation axis in body1. -- b2Vec2 localAxis1; -- -- /// The constrained angle between the bodies: body2_angle - body1_angle. -- float32 referenceAngle; -- -- /// Enable/disable the joint limit. -- bool enableLimit; -- -- /// The lower translation limit, usually in meters. -- float32 lowerTranslation; -- -- /// The upper translation limit, usually in meters. -- float32 upperTranslation; -- -- /// Enable/disable the joint motor. -- bool enableMotor; -- -- /// The maximum motor torque, usually in N-m. -- float32 maxMotorForce; -- -- /// The desired motor speed in radians per second. -- float32 motorSpeed; -- }; -- -- /// A prismatic joint. This joint provides one degree of freedom: translation -- /// along an axis fixed in body1. Relative rotation is prevented. You can -- /// use a joint limit to restrict the range of motion and a joint motor to -- /// drive the motion or to model joint friction. -- class b2PrismaticJoint : public b2Joint -- { -- public: -- b2Vec2 GetAnchorA() const; -- b2Vec2 GetAnchorB() const; -- -- b2Vec2 GetReactionForce(float32 inv_dt) const; -- float32 GetReactionTorque(float32 inv_dt) const; -- -- /// Get the current joint translation, usually in meters. -- float32 GetJointTranslation() const; -- -- /// Get the current joint translation speed, usually in meters per second. -- float32 GetJointSpeed() const; -- -- /// Is the joint limit enabled? -- bool IsLimitEnabled() const; -- -- /// Enable/disable the joint limit. -- void EnableLimit(bool flag); -- -- /// Get the lower joint limit, usually in meters. -- float32 GetLowerLimit() const; -- -- /// Get the upper joint limit, usually in meters. -- float32 GetUpperLimit() const; -- -- /// Set the joint limits, usually in meters. -- void SetLimits(float32 lower, float32 upper); -- -- /// Is the joint motor enabled? -- bool IsMotorEnabled() const; -- -- /// Enable/disable the joint motor. -- void EnableMotor(bool flag); -- -- /// Set the motor speed, usually in meters per second. -- void SetMotorSpeed(float32 speed); -- -- /// Get the motor speed, usually in meters per second. -- float32 GetMotorSpeed() const; -- -- /// Set the maximum motor force, usually in N. -- void SetMaxMotorForce(float32 force); -- -- /// Get the current motor force, usually in N. -- float32 GetMotorForce() const; -- -- protected: -- friend class b2Joint; -- friend class b2GearJoint; -- b2PrismaticJoint(const b2PrismaticJointDef* def); -- -- void InitVelocityConstraints(const b2TimeStep& step); -- void SolveVelocityConstraints(const b2TimeStep& step); -- bool SolvePositionConstraints(float32 baumgarte); -- -- b2Vec2 m_localAnchor1; -- b2Vec2 m_localAnchor2; -- b2Vec2 m_localXAxis1; -- b2Vec2 m_localYAxis1; -- float32 m_refAngle; -- -- b2Vec2 m_axis, m_perp; -- float32 m_s1, m_s2; -- float32 m_a1, m_a2; -- -- b2Mat33 m_K; -- b2Vec3 m_impulse; -- -- float32 m_motorMass; // effective mass for motor/limit translational constraint. -- float32 m_motorImpulse; -- -- float32 m_lowerTranslation; -- float32 m_upperTranslation; -- float32 m_maxMotorForce; -- float32 m_motorSpeed; -- -- bool m_enableLimit; -- bool m_enableMotor; -- b2LimitState m_limitState; -- }; -- -- inline float32 b2PrismaticJoint::GetMotorSpeed() const -- { -- return m_motorSpeed; -- } -- -- #endif procedure dummy; end impact.d2.orbs.Joint.prismatic;
with Ada.Calendar.Time_Zones; with Ada.Calendar.Formatting; with Fmt.Integer_Argument; package body Fmt.Time_Argument is Default_Time_Edit : aliased constant String := "%Y-%m-%d %H:%M:%S"; overriding function Get_Placeholder_Width ( Self : in out Time_Argument_Type; Name : Character) return Natural is begin return ( case Name is when 'Y' => 4, when 'y' | 'm' | 'd' | 'H' | 'M' | 'S' => 2, when others => 0); end Get_Placeholder_Width; overriding function Is_Valid_Placeholder ( Self : Time_Argument_Type; Name : Character) return Boolean is begin return Name in 'Y' | 'y' | 'm' | 'd' | 'H' | 'M' | 'S'; end Is_Valid_Placeholder; overriding procedure Put_Placeholder ( Self : in out Time_Argument_Type; Name : Character; To : in out String) is use Ada.Calendar.Formatting; use Ada.Calendar.Time_Zones; use Integer_Argument; TZ : constant Time_Offset := Local_Time_Offset(Self.Value); begin case Name is when 'Y' => To := Format("{:w=4,f=0}", To_Argument(Year(Self.Value, TZ))); when 'm' => To := Format("{:w=2,f=0}", To_Argument(Month(Self.Value, TZ))); when 'd' => To := Format("{:w=2,f=0}", To_Argument(Day(Self.Value, TZ))); when 'H' => To := Format("{:w=2,f=0}", To_Argument(Hour(Self.Value, TZ))); when 'M' => To := Format("{:w=2,f=0}", To_Argument(Minute(Self.Value, TZ))); when 'S' => To := Format("{:w=2,f=0}", To_Argument(Second(Self.Value))); when others => null; end case; end Put_Placeholder; function To_Argument (X : Ada.Calendar.Time) return Argument_Type'Class is begin return Time_Argument_Type'( Value => X, Default_Edit => Default_Time_Edit'Access, others => <>); end To_Argument; function "&" (Args : Arguments; X : Ada.Calendar.Time) return Arguments is begin return Args & To_Argument(X); end "&"; end Fmt.Time_Argument;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- I N T E R F A C E S . V X W O R K S . I O -- -- -- -- S p e c -- -- -- -- Copyright (C) 2002-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. -- -- -- ------------------------------------------------------------------------------ -- This package provides a binding to the functions fileno and ioctl -- in VxWorks, providing a set of definitions of ioctl function codes -- and options for the use of these functions. -- A particular use of this interface is to enable use of Get_Immediate -- in Ada.Text_IO. There is no way in VxWorks to provide the desired -- functionality of Get_Immediate (no buffering and no waiting for a -- line return) without flushing the buffer, which violates the Ada -- semantic requirements for Ada.Text_IO. with Interfaces.C_Streams; package Interfaces.VxWorks.IO is ------------------------- -- The ioctl Interface -- -------------------------- type FUNCODE is new int; -- Type of the function codes in ioctl type IOOPT is mod 2 ** int'Size; -- Type of the option codes in ioctl -- ioctl function codes (for more information see ioLib.h) -- These values could be generated automatically in System.OS_Constants??? FIONREAD : constant FUNCODE := 1; FIOFLUSH : constant FUNCODE := 2; FIOOPTIONS : constant FUNCODE := 3; FIOBAUDRATE : constant FUNCODE := 4; FIODISKFORMAT : constant FUNCODE := 5; FIODISKINIT : constant FUNCODE := 6; FIOSEEK : constant FUNCODE := 7; FIOWHERE : constant FUNCODE := 8; FIODIRENTRY : constant FUNCODE := 9; FIORENAME : constant FUNCODE := 10; FIOREADYCHANGE : constant FUNCODE := 11; FIONWRITE : constant FUNCODE := 12; FIODISKCHANGE : constant FUNCODE := 13; FIOCANCEL : constant FUNCODE := 14; FIOSQUEEZE : constant FUNCODE := 15; FIONBIO : constant FUNCODE := 16; FIONMSGS : constant FUNCODE := 17; FIOGETNAME : constant FUNCODE := 18; FIOGETOPTIONS : constant FUNCODE := 19; FIOSETOPTIONS : constant FUNCODE := FIOOPTIONS; FIOISATTY : constant FUNCODE := 20; FIOSYNC : constant FUNCODE := 21; FIOPROTOHOOK : constant FUNCODE := 22; FIOPROTOARG : constant FUNCODE := 23; FIORBUFSET : constant FUNCODE := 24; FIOWBUFSET : constant FUNCODE := 25; FIORFLUSH : constant FUNCODE := 26; FIOWFLUSH : constant FUNCODE := 27; FIOSELECT : constant FUNCODE := 28; FIOUNSELECT : constant FUNCODE := 29; FIONFREE : constant FUNCODE := 30; FIOMKDIR : constant FUNCODE := 31; FIORMDIR : constant FUNCODE := 32; FIOLABELGET : constant FUNCODE := 33; FIOLABELSET : constant FUNCODE := 34; FIOATTRIBSE : constant FUNCODE := 35; FIOCONTIG : constant FUNCODE := 36; FIOREADDIR : constant FUNCODE := 37; FIOFSTATGET : constant FUNCODE := 38; FIOUNMOUNT : constant FUNCODE := 39; FIOSCSICOMMAND : constant FUNCODE := 40; FIONCONTIG : constant FUNCODE := 41; FIOTRUNC : constant FUNCODE := 42; FIOGETFL : constant FUNCODE := 43; FIOTIMESET : constant FUNCODE := 44; FIOINODETONAM : constant FUNCODE := 45; FIOFSTATFSGE : constant FUNCODE := 46; -- ioctl option values OPT_ECHO : constant IOOPT := 16#0001#; OPT_CRMOD : constant IOOPT := 16#0002#; OPT_TANDEM : constant IOOPT := 16#0004#; OPT_7_BIT : constant IOOPT := 16#0008#; OPT_MON_TRAP : constant IOOPT := 16#0010#; OPT_ABORT : constant IOOPT := 16#0020#; OPT_LINE : constant IOOPT := 16#0040#; OPT_RAW : constant IOOPT := 16#0000#; OPT_TERMINAL : constant IOOPT := OPT_ECHO or OPT_CRMOD or OPT_TANDEM or OPT_MON_TRAP or OPT_7_BIT or OPT_ABORT or OPT_LINE; function fileno (Fp : Interfaces.C_Streams.FILEs) return int; pragma Import (C, fileno, "fileno"); -- Binding to the C routine fileno function ioctl (Fd : int; Function_Code : FUNCODE; Arg : IOOPT) return int; pragma Import (C, ioctl, "ioctl"); -- Binding to the C routine ioctl -- -- Note: we are taking advantage of the fact that on currently supported -- VxWorks targets, it is fine to directly bind to a variadic C function. ------------------------------ -- Control of Get_Immediate -- ------------------------------ -- The procedures in this section make use of the interface to ioctl -- and fileno to provide a mechanism for enabling unbuffered behavior -- for Get_Immediate in VxWorks. -- The situation is that the RM requires that the use of Get_Immediate -- be identical to Get except that it is desirable (not required) that -- there be no buffering or line editing. -- Unfortunately, in VxWorks, the only way to enable this desired -- unbuffered behavior involves changing into raw mode. But this -- transition into raw mode flushes the input buffer, a behavior -- not permitted by the RM semantics for Get_Immediate. -- Given that Get_Immediate cannot be accurately implemented in -- raw mode, it seems best not to enable it by default, and instead -- to require specific programmer action, with the programmer being -- aware that input may be lost. -- The following is an example of the use of the two procedures -- in this section (Enable_Get_Immediate and Disable_Get_Immediate) -- with Ada.Text_IO; use Ada.Text_IO; -- with Ada.Text_IO.C_Streams; use Ada.Text_IO.C_Streams; -- with Interfaces.VxWorks.IO; use Interfaces.VxWorks.IO; -- procedure Example_IO is -- Input : Character; -- Available : Boolean; -- Success : Boolean; -- begin -- Enable_Get_Immediate (C_Stream (Current_Input), Success); -- if Success = False then -- raise Device_Error; -- end if; -- -- Example with the first type of Get_Immediate -- -- Waits for an entry on the input. Immediately returns -- -- after having received an character on the input -- Put ("Input -> "); -- Get_Immediate (Input); -- New_Line; -- Put_Line ("Character read: " & Input); -- -- Example with the second type of Get_Immediate -- -- This is equivalent to a non blocking read -- for J in 1 .. 10 loop -- Put ("Input -> "); -- Get_Immediate (Input, Available); -- New_Line; -- if Available = True then -- Put_Line ("Character read: " & Input); -- end if; -- delay 1.0; -- end loop; -- Disable_Get_Immediate (C_Stream (Current_Input), Success); -- if Success = False then -- raise Device_Error; -- end if; -- exception -- when Device_Error => -- Put_Line ("Device Error. Check your configuration"); -- end Example_IO; procedure Enable_Get_Immediate (File : Interfaces.C_Streams.FILEs; Success : out Boolean); -- On VxWorks, a call to this procedure is required before subsequent calls -- to Get_Immediate have the desired effect of not waiting for a line -- return. The reason that this call is not automatic on this target is -- that the call flushes the input buffer, discarding any previous input. -- Note: Following a call to Enable_Get_Immediate, the only permitted -- operations on the relevant file are Get_Immediate operations. Any -- other operations have undefined behavior. procedure Disable_Get_Immediate (File : Interfaces.C_Streams.FILEs; Success : out Boolean); -- This procedure resets File to standard mode, and permits subsequent -- use of the full range of Ada.Text_IO functions end Interfaces.VxWorks.IO;
-- SPDX-FileCopyrightText: 2019 Max Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT ------------------------------------------------------------- with Program.Elements.Statements; with Program.Lexical_Elements; package Program.Elements.Null_Statements is pragma Pure (Program.Elements.Null_Statements); type Null_Statement is limited interface and Program.Elements.Statements.Statement; type Null_Statement_Access is access all Null_Statement'Class with Storage_Size => 0; type Null_Statement_Text is limited interface; type Null_Statement_Text_Access is access all Null_Statement_Text'Class with Storage_Size => 0; not overriding function To_Null_Statement_Text (Self : in out Null_Statement) return Null_Statement_Text_Access is abstract; not overriding function Null_Token (Self : Null_Statement_Text) return not null Program.Lexical_Elements.Lexical_Element_Access is abstract; not overriding function Semicolon_Token (Self : Null_Statement_Text) return not null Program.Lexical_Elements.Lexical_Element_Access is abstract; end Program.Elements.Null_Statements;
with Ada.Text_IO; with Ada.Exceptions; use Ada.Exceptions; package body kv.avm.File_Reader is procedure Parse_Input_File (Self : in out Reader; File_In : in String) is File : Ada.Text_IO.File_Type; Buffer : String(1..1024); Length : Natural := 0; Line : Natural := 0; begin Ada.Text_IO.Open(File, Ada.Text_IO.IN_FILE, File_In); while not Ada.Text_IO.End_Of_File(File) loop Ada.Text_IO.Get_Line(File, Buffer, Length); Line := Line + 1; Self.Parse_Line(Buffer(1..Length)); end loop; Ada.Text_IO.Close(File); exception when Error: others => Ada.Text_IO.Put_Line("EXCEPTION: "&Exception_Information(Error)); Ada.Text_IO.Put_Line("File: "&File_In); Ada.Text_IO.Put_Line("Line: "&Natural'IMAGE(Line)); -- Ada.Text_IO.Line gives wrong answers. Ada.Text_IO.Put_Line("Code: "&Buffer(1..Length)); Ada.Text_IO.Close(File); raise; end Parse_Input_File; end kv.avm.File_Reader;
package body afrl.impact.ImpactAutomationRequest.SPARK_Boundary with SPARK_Mode => Off is -------------------------------------- -- Get_EntityList_From_TrialRequest -- -------------------------------------- function Get_EntityList_From_TrialRequest (Request : ImpactAutomationRequest) return Int64_Vect is L : constant Vect_Int64_Acc := Request.getTrialRequest.getEntityList; begin return R : Int64_Vect do for E of L.all loop Int64_Vects.Append (R, E); end loop; end return; end Get_EntityList_From_TrialRequest; ---------------------------------------------- -- Get_OperatingRegion_From_TrialRequest -- ---------------------------------------------- function Get_OperatingRegion_From_TrialRequest (Request : ImpactAutomationRequest) return Int64 is (Request.getTrialRequest.getOperatingRegion); ------------------------------------ -- Get_TaskList_From_TrialRequest -- ------------------------------------ function Get_TaskList_From_TrialRequest (Request : ImpactAutomationRequest) return Int64_Vect is L : constant Vect_Int64_Acc := Request.getTrialRequest.getTaskList; begin return R : Int64_Vect do for E of L.all loop Int64_Vects.Append (R, E); end loop; end return; end Get_TaskList_From_TrialRequest; end afrl.impact.ImpactAutomationRequest.SPARK_Boundary;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- I N T E R F A C E S -- -- -- -- S p e c -- -- -- -- $Revision$ -- -- -- This specification is adapted 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. -- -- -- ------------------------------------------------------------------------------ -- This is the OpenVMS version of this package which adds Float_Representation -- pragmas to the IEEE floating point types to enusre they remain IEEE in -- thse presence of a VAX_Float Float_Representatin configuration pragma. -- It assumes integer sizes of 8, 16, 32 and 64 are available, and that IEEE -- floating-point formats are available. package Interfaces is pragma Pure (Interfaces); 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); -- Floating point types. We use the digits value to define the IEEE -- forms, otherwise a configuration pragma specifying VAX float can -- default the digits to an illegal value for IEEE. -- 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_Float_32 is digits 6; pragma Float_Representation (IEEE_Float, IEEE_Float_32); type IEEE_Float_64 is digits 15; pragma Float_Representation (IEEE_Float, IEEE_Float_64); type IEEE_Extended_Float is digits 15; pragma Float_Representation (IEEE_Float, IEEE_Extended_Float); end Interfaces;
------------------------------------------------------------------------------ -- -- -- GNU ADA RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- S Y S T E M . I N T E R R U P T _ M A N A G E M E N T -- -- -- -- B o d y -- -- -- -- $Revision$ -- -- -- Copyright (C) 1991-2001 Florida State University -- -- -- -- 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 2, or (at your option) any later ver- -- -- sion. GNARL 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 GNARL; see file COPYING. If not, write -- -- to the Free Software Foundation, 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. -- -- -- -- GNARL was developed by the GNARL team at Florida State University. It is -- -- now maintained by Ada Core Technologies Inc. in cooperation with Florida -- -- State University (http://www.gnat.com). -- -- -- ------------------------------------------------------------------------------ -- This is the VxWorks version of this package. -- It is likely to need tailoring to fit each operating system -- and machine architecture. -- PLEASE DO NOT add any dependences on other packages. -- This package is designed to work with or without tasking support. -- See the other warnings in the package specification before making -- any modifications to this file. -- Make a careful study of all signals available under the OS, -- to see which need to be reserved, kept always unmasked, -- or kept always unmasked. -- Be on the lookout for special signals that -- may be used by the thread library. with Interfaces.C; -- used for int and other types with System.Error_Reporting; pragma Warnings (Off, System.Error_Reporting); -- used for Shutdown with System.OS_Interface; -- used for various Constants, Signal and types with Unchecked_Conversion; package body System.Interrupt_Management is use Interfaces.C; use System.Error_Reporting; use System.OS_Interface; function To_Isr is new Unchecked_Conversion (Long_Integer, isr_address); type Interrupt_List is array (Interrupt_ID range <>) of Interrupt_ID; Exception_Interrupts : constant Interrupt_List := (SIGFPE, SIGILL, SIGSEGV, SIGBUS); -- Keep these variables global so that they are initialized only once. Exception_Action : aliased struct_sigaction; Default_Action : aliased struct_sigaction; -- ????? Use these horrible imports here to solve elaboration order -- problems. type Task_Id is access all Integer; Interrupt_ID_Map : array (Interrupt_ID) of Task_Id; pragma Import (Ada, Interrupt_ID_Map, "system__task_primitives__interrupt_operations__interrupt_id_map"); ---------------------- -- Notify_Exception -- ---------------------- procedure Notify_Exception (signo : Signal); -- Identify the Ada exception to be raised using -- the information when the system received a synchronous signal. procedure Notify_Exception (signo : Signal) is Mask : aliased sigset_t; Result : Interfaces.C.int; My_Id : pthread_t; begin -- VxWorks will always mask out the signal during the signal -- handler and will reenable it on a longjmp. GNAT does -- not generate a longjmp to return from a signal handler -- so the signal will still be masked unless we unmask it. Result := pthread_sigmask (SIG_SETMASK, null, Mask'Unchecked_Access); Result := sigdelset (Mask'Access, signo); Result := pthread_sigmask (SIG_SETMASK, Mask'Unchecked_Access, null); -- VxWorks will suspend the task when it gets a hardware -- exception. We take the liberty of resuming the task -- for the application. My_Id := taskIdSelf; if taskIsSuspended (My_Id) /= 0 then Result := taskResume (My_Id); end if; -- As long as we are using a longjmp to return control to the -- exception handler on the runtime stack, we are safe. The original -- signal mask (the one we had before coming into this signal catching -- function) will be restored by the longjmp. Therefore, raising -- an exception in this handler should be a safe operation. -- Check that treatment of exception propagation here -- is consistent with treatment of the abort signal in -- System.Task_Primitives.Operations. -- How can SIGSEGV be split into constraint and storage errors? -- What should SIGILL really raise ? Some implementations have -- codes for different types of SIGILL and some raise Storage_Error. -- What causes SIGBUS and should it be caught? -- Peter Burwood case signo is when SIGFPE => raise Constraint_Error; when SIGILL => raise Constraint_Error; when SIGSEGV => raise Program_Error; when SIGBUS => raise Program_Error; when others => pragma Assert (Shutdown ("Unexpected signal")); null; end case; end Notify_Exception; ------------------- -- Notify_Signal -- ------------------- -- VxWorks needs a special casing here. Each VxWorks task has a completely -- separate signal handling, so the usual signal masking can't work. -- This idea is to handle all the signals in all the tasks, and when -- such a signal occurs, redirect it to the dedicated task (if any) or -- reraise it. procedure Notify_Signal (signo : Signal); procedure Notify_Signal (signo : Signal) is Mask : aliased sigset_t; Result : Interfaces.C.int; My_Id : pthread_t; old_isr : isr_address; function Get_Thread_Id (T : Task_Id) return pthread_t; pragma Import (Ada, Get_Thread_Id, "system__task_primitives__operations__get_thread_id"); begin -- VxWorks will always mask out the signal during the signal -- handler and will reenable it on a longjmp. GNAT does -- not generate a longjmp to return from a signal handler -- so the signal will still be masked unless we unmask it. Result := pthread_sigmask (SIG_SETMASK, null, Mask'Unchecked_Access); Result := sigdelset (Mask'Access, signo); Result := pthread_sigmask (SIG_SETMASK, Mask'Unchecked_Access, null); -- VxWorks will suspend the task when it gets a hardware -- exception. We take the liberty of resuming the task -- for the application. My_Id := taskIdSelf; if taskIsSuspended (My_Id) /= 0 then Result := taskResume (My_Id); end if; -- ??? Need a lock around this, in case the handler is detached -- between the two following statements. if Interrupt_ID_Map (Interrupt_ID (signo)) /= null then Result := kill (Get_Thread_Id (Interrupt_ID_Map (Interrupt_ID (signo))), Signal (signo)); else old_isr := c_signal (signo, To_Isr (SIG_DFL)); Result := kill (My_Id, Signal (signo)); end if; end Notify_Signal; --------------------------- -- Initialize_Interrupts -- --------------------------- -- Since there is no signal inheritance between VxWorks tasks, we need -- to initialize signal handling in each task. procedure Initialize_Interrupts is old_act : aliased struct_sigaction; Result : Interfaces.C.int; begin for J in Interrupt_ID'First + 1 .. Interrupt_ID'Last loop if J /= Abort_Task_Interrupt then Result := sigaction (Signal (J), Default_Action'Access, old_act'Unchecked_Access); pragma Assert (Result = 0); end if; end loop; for J in Exception_Interrupts'Range loop Keep_Unmasked (Exception_Interrupts (J)) := True; Result := sigaction (Signal (Exception_Interrupts (J)), Exception_Action'Access, old_act'Unchecked_Access); pragma Assert (Result = 0); end loop; end Initialize_Interrupts; begin declare mask : aliased sigset_t; default_mask : aliased sigset_t; Result : Interfaces.C.int; begin -- The VxWorks POSIX threads library currently needs initialization. -- We wish it could be in System.OS_Interface, but that would -- cause an elaboration problem. pthread_init; Abort_Task_Interrupt := SIGABRT; -- Change this if you want to use another signal for task abort. -- SIGTERM might be a good one. Exception_Action.sa_handler := Notify_Exception'Address; Default_Action.sa_handler := Notify_Signal'Address; Exception_Action.sa_flags := SA_SIGINFO + SA_ONSTACK; Default_Action.sa_flags := SA_SIGINFO + SA_ONSTACK; -- Send us extra signal information (SA_SIGINFO) on the -- stack (SA_ONSTACK). -- There is no SA_NODEFER in VxWorks. The signal mask is -- restored after a longjmp so the SA_NODEFER option is -- not needed. - Dan Eischen Result := sigemptyset (mask'Access); pragma Assert (Result = 0); Result := sigemptyset (default_mask'Access); pragma Assert (Result = 0); for J in Interrupt_ID'First + 1 .. Interrupt_ID'Last loop Result := sigaddset (default_mask'Access, Signal (J)); pragma Assert (Result = 0); end loop; for J in Exception_Interrupts'Range loop Result := sigaddset (mask'Access, Signal (Exception_Interrupts (J))); pragma Assert (Result = 0); Result := sigdelset (default_mask'Access, Signal (Exception_Interrupts (J))); pragma Assert (Result = 0); end loop; Exception_Action.sa_mask := mask; Default_Action.sa_mask := default_mask; -- Initialize_Interrupts is called for each task in Enter_Task Keep_Unmasked (Abort_Task_Interrupt) := True; Reserve := Reserve or Keep_Unmasked or Keep_Masked; Reserve (0) := True; -- We do not have Signal 0 in reality. We just use this value -- to identify non-existent signals (see s-intnam.ads). Therefore, -- Signal 0 should not be used in all signal related operations hence -- mark it as reserved. end; end System.Interrupt_Management;
pragma License (Unrestricted); -- implementation unit required by compiler with Ada.Assertions; package System.Assertions is pragma Pure; -- called from Ada.Assertions -- required by compiler ??? (s-assert.ads) Assert_Failure : exception renames Ada.Assertions.Assertion_Error; -- required for pragma Assert by compiler, and GDB knows (s-assert.ads) procedure Raise_Assert_Failure (Msg : String) renames Ada.Assertions.Raise_Assertion_Error; end System.Assertions;
-- This file is freely given to the Public Domain. -- with Ada.Command_Line; use Ada.Command_Line; with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; with Vole_Tokens; with kv.avm.Vole_Lex; with Vole_Lex_IO; with kv.avm.vole_parser; with kv.avm.vole_tree; with kv.avm.Tree_Dots; with kv.avm.Tree_Rewrite; with kv.avm.Code_Generator; procedure parse_test is subtype String_Type is Ada.Strings.Unbounded.Unbounded_String; -- Conversion operators to go back and forth between strings and unbounded strings. -- function "+"(S : String) return String_Type renames Ada.Strings.Unbounded.To_Unbounded_String; function "+"(U : String_Type) return String renames Ada.Strings.Unbounded.To_String; File_Name : String_Type := +"test_1.vole"; Grapher : aliased kv.avm.Tree_Dots.Grapher_Class; Rewriter : aliased kv.avm.Tree_Rewrite.Rewriter_Class; Code_Gen : aliased kv.avm.Code_Generator.Code_Generator_Class; begin for I in 1 .. Argument_Count loop if Argument(I) = "-v" then kv.avm.vole_parser.Verbose := True; else File_Name := +Argument(I); end if; end loop; Put_Line("//parse_test -- the vole parser test "&(+File_Name)); Vole_Lex_IO.open_input(+File_Name); Vole_Lex_IO.create_output; kv.avm.vole_parser.yyparse; Vole_Lex_IO.close_input; Vole_Lex_IO.close_output; Rewriter.Init; kv.avm.vole_tree.Get_Program.Visit(Rewriter'ACCESS, 0); Rewriter.Finalize; Grapher.Init("program.dot"); kv.avm.vole_tree.Get_Program.Visit(Grapher'ACCESS, 0); Grapher.Finalize; Code_Gen.Init; kv.avm.vole_tree.Get_Program.Visit(Code_Gen'ACCESS, 0); Code_Gen.Print; Code_Gen.Finalize; end parse_test;
----------------------------------------------------------------------- -- util-http-clients-curl -- HTTP Clients with CURL -- Copyright (C) 2012, 2017, 2018, 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 System; with Interfaces.C; with Interfaces.C.Strings; with Ada.Strings.Unbounded; with Util.Http.Mockups; package Util.Http.Clients.Curl is -- Register the CURL Http manager. procedure Register; private package C renames Interfaces.C; package Strings renames Interfaces.C.Strings; use type C.size_t; -- Define 'Int' and 'Chars_Ptr' with capitals to avoid GNAT warnings due -- to Eclipse capitalization. subtype Int is C.int; subtype Chars_Ptr is Strings.chars_ptr; subtype Size_T is C.size_t; subtype CURL is System.Address; type CURL_Code is new Interfaces.C.int; CURLE_OK : constant CURL_Code := 0; type CURL_Info is new Int; type Curl_Option is new Int; type CURL_Slist; type CURL_Slist_Access is access CURL_Slist; type CURL_Slist is record Data : Chars_Ptr; Next : CURL_Slist_Access; end record; -- Check the CURL result code and report and exception and a log message if -- the CURL code indicates an error. procedure Check_Code (Code : in CURL_Code; Message : in String); type Curl_Http_Manager is new Http_Manager with null record; type Curl_Http_Manager_Access is access all Http_Manager'Class; -- Create a new HTTP request associated with the current request manager. procedure Create (Manager : in Curl_Http_Manager; Http : in out Client'Class); overriding procedure Do_Get (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class); overriding procedure Do_Head (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class); overriding procedure Do_Post (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class); overriding procedure Do_Put (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class); overriding procedure Do_Patch (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class); overriding procedure Do_Delete (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class); overriding procedure Do_Options (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class); -- Set the timeout for the connection. overriding procedure Set_Timeout (Manager : in Curl_Http_Manager; Http : in Client'Class; Timeout : in Duration); type Curl_Http_Request is new Util.Http.Mockups.Mockup_Request with record Data : CURL := System.Null_Address; URL : Chars_Ptr := Interfaces.C.Strings.Null_Ptr; Content : Chars_Ptr := Interfaces.C.Strings.Null_Ptr; Curl_Headers : CURL_Slist_Access := null; end record; type Curl_Http_Request_Access is access all Curl_Http_Request'Class; -- Prepare to setup the headers in the request. procedure Set_Headers (Request : in out Curl_Http_Request); overriding procedure Finalize (Request : in out Curl_Http_Request); type Curl_Http_Response is new Util.Http.Mockups.Mockup_Response with record C : CURL; Content : Ada.Strings.Unbounded.Unbounded_String; Status : Natural; Parsing_Body : Boolean := False; end record; type Curl_Http_Response_Access is access all Curl_Http_Response'Class; -- Get the response body as a string. overriding function Get_Body (Reply : in Curl_Http_Response) return String; -- Get the response status code. overriding function Get_Status (Reply : in Curl_Http_Response) return Natural; -- Add a string to a CURL slist. function Curl_Slist_Append (List : in CURL_Slist_Access; Value : in Chars_Ptr) return CURL_Slist_Access; pragma Import (C, Curl_Slist_Append, "curl_slist_append"); -- Free an entrire CURL slist. procedure Curl_Slist_Free_All (List : in CURL_Slist_Access); pragma Import (C, Curl_Slist_Free_All, "curl_slist_free_all"); -- Start a libcurl easy session. function Curl_Easy_Init return CURL; pragma Import (C, Curl_Easy_Init, "curl_easy_init"); -- End a libcurl easy session. procedure Curl_Easy_Cleanup (Handle : in CURL); pragma Import (C, Curl_Easy_Cleanup, "curl_easy_cleanup"); -- Perform a file transfer. function Curl_Easy_Perform (Handle : in CURL) return CURL_Code; pragma Import (C, Curl_Easy_Perform, "curl_easy_perform"); -- Return the error message which correspond to the given CURL error code. function Curl_Easy_Strerror (Code : in CURL_Code) return Chars_Ptr; pragma Import (C, Curl_Easy_Strerror, "curl_easy_strerror"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_String (Handle : in CURL; Option : in Curl_Option; Value : in Chars_Ptr) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_String, "curl_easy_setopt"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_Slist (Handle : in CURL; Option : in Curl_Option; Value : in CURL_Slist_Access) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Slist, "curl_easy_setopt"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_Long (Handle : in CURL; Option : in Curl_Option; Value : in Interfaces.C.long) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Long, "curl_easy_setopt"); -- Get information from a CURL handle for an option returning a String. function Curl_Easy_Getinfo_String (Handle : in CURL; Option : in CURL_Info; Value : access Chars_Ptr) return CURL_Code; pragma Import (C, Curl_Easy_Getinfo_String, "curl_easy_getinfo"); -- Get information from a CURL handle for an option returning a Long. function Curl_Easy_Getinfo_Long (Handle : in CURL; Option : in CURL_Info; Value : access C.long) return CURL_Code; pragma Import (C, Curl_Easy_Getinfo_Long, "curl_easy_getinfo"); type Write_Callback_Access is access function (Data : in Chars_Ptr; Size : in Size_T; Nmemb : in Size_T; Ptr : in Curl_Http_Response_Access) return Size_T; pragma Convention (C, Write_Callback_Access); function Curl_Easy_Setopt_Write_Callback (Handle : in CURL; Option : in Curl_Option; Func : in Write_Callback_Access) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Write_Callback, "curl_easy_setopt"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_Data (Handle : in CURL; Option : in Curl_Option; Value : in Curl_Http_Response_Access) return CURL_Code; pragma Warnings (Off, Curl_Easy_Setopt_Data); pragma Import (C, Curl_Easy_Setopt_Data, "curl_easy_setopt"); function Read_Response (Data : in Chars_Ptr; Size : in Size_T; Nmemb : in Size_T; Response : in Curl_Http_Response_Access) return Size_T; pragma Convention (C, Read_Response); end Util.Http.Clients.Curl;
-- Lumen.Shader -- Helper routines to fetch shader source, load it, and compile -- -- Chip Richards, NiEstu, Phoenix AZ, Winter 2013 -- This code is covered by the ISC License: -- -- Copyright © 2010, NiEstu -- -- Permission to use, copy, modify, and/or 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 Ada.Directories; with Ada.Streams.Stream_IO; with Interfaces.C; with System; with Lumen.Binary; use type Lumen.Binary.Byte; package body Lumen.Shader is --------------------------------------------------------------------------- -- Read shader source from a disk file procedure From_File (Shader_Type : in GL.Enum; Name : in String; ID : out GL.UInt; Success : out Boolean) is Result : GL.UInt; Size : constant Ada.Directories.File_Size := Ada.Directories.Size (Name); Status : GL.Int; begin -- From_File -- Tell the GPU to create a new shader Result := GL.Create_Shader (Shader_Type); ID := Result; -- Read shader source from file declare use Ada.Streams; use type Ada.Directories.File_Size; File : Stream_IO.File_Type; -- +1 = room for terminating NUL Source : Stream_Element_Array (1 .. Stream_Element_Offset (Size + 1)); Last : Stream_Element_Offset; Source_Ptr : GL.Pointer := Source'Address; begin -- Open the file and try to read it all in one gulp, then close it Stream_IO.Open (File, Stream_IO.In_File, Name); Stream_IO.Read (File, Source, Last); Stream_IO.Close (File); -- Double-check that we got it all if Last /= Stream_Element_Offset (Size) then raise Read_Error with "Got only" & Stream_Element_Offset'Image (Last) & " bytes out of" & Ada.Directories.File_Size'Image (Size); end if; -- Add a NUL byte to the end of the source string Source (Source'Last) := 0; -- Pump the shader source down to the GPU GL.Shader_Source (Result, 1, Source_Ptr'Address, System.Null_Address); end; -- Tell it to compile the source GL.Compile_Shader (Result); -- Check that compile worked, return status to caller GL.Get_Shader (Result, GL.GL_COMPILE_STATUS, Status'Address); Success := GL.Bool (Status) = GL.GL_TRUE; return; end From_File; --------------------------------------------------------------------------- -- Use shader source provided in a string procedure From_String (Shader_Type : in GL.Enum; Source : in String; ID : out GL.UInt; Success : out Boolean) is Result : GL.UInt; -- doesn't hurt if caller already did it Text : String := Source & ASCII.NUL; Source_Ptr : GL.Pointer := Text'Address; Status : GL.Int; begin -- From_String -- Tell the GPU to create a new shader Result := GL.Create_Shader (Shader_Type); ID := Result; -- Pump the shader source down to the GPU GL.Shader_Source (Result, 1, Source_Ptr'Address, System.Null_Address); -- Tell it to compile the source GL.Compile_Shader (Result); -- Check that compile worked GL.Get_Shader (Result, GL.GL_COMPILE_STATUS, Status'Address); Success := GL.Bool (Status) = GL.GL_TRUE; return; end From_String; --------------------------------------------------------------------------- function Get_Info_Log (Shader : GL.UInt) return String is Log_Len : GL.Int; begin -- Get_Info_Log GL.Get_Shader (Shader, GL.GL_INFO_LOG_LENGTH, Log_Len'Address); declare Log : Interfaces.C.char_array (1 .. Interfaces.C.size_t (Log_Len)); Got : GL.SizeI; begin GL.Get_Shader_Info_Log (Shader, Log'Length, Got'Address, Log'Address); return Interfaces.C.To_Ada (Log); end; end Get_Info_Log; --------------------------------------------------------------------------- end Lumen.Shader;
-- { dg-do compile } -- { dg-options "-O2" } function slice1 (Offset : Integer) return String is Convert : constant String := "0123456789abcdef"; Buffer : String (1 .. 32); Pos : Natural := Buffer'Last; Value : Long_Long_Integer := Long_Long_Integer (Offset); begin while Value > 0 loop Buffer (Pos) := Convert (Integer (Value mod 16)); Pos := Pos - 1; Value := Value / 16; end loop; return Buffer (Pos + 1 .. Buffer'Last); end;
-- -- Copyright (C) 2021 Jeremy Grosser <jeremy@synack.me> -- -- SPDX-License-Identifier: BSD-3-Clause -- with RP.GPIO; with RP.PWM; with RP; package Piezo is type Beeper (Point_A : access RP.GPIO.GPIO_Point; Point_B : access RP.GPIO.GPIO_Point) is tagged record Slice : RP.PWM.PWM_Slice := RP.PWM.To_PWM (Point_A.all).Slice; end record; subtype Milliseconds is Natural; -- Timer and PWM must be initialized before this. procedure Beep (This : Beeper; Duration : Milliseconds := 1_000; Frequency : RP.Hertz := 440; Count : Positive := 1); end Piezo;
package datos is Max_Elem : constant Integer := 10; type Vector_De_Enteros is array (Integer range <>) of Integer; type Lista_Enteros is record Numeros : Vector_De_Enteros (1 .. Max_Elem); Cont : Integer; end record; type Vector_De_Reales is array (Integer range <>) of Float; type Vector_De_Booleanos is array (Integer range <>) of Boolean; type Vector_De_Caracteres is array (Integer range <>) of Character; end datos;
-- { dg-do compile } -- { dg-skip-if "No dwarf-2 support" { hppa*-*-hpux* } "*" "" } -- { dg-options "-cargs -gdwarf-2 -gstrict-dwarf -dA -margs" } -- { dg-final { scan-assembler "DW_TAG_imported_decl" } } package body Debug7 is function Next (I : Integer) return Integer is begin return I + 1; end Next; end Debug7;
with Ada.Directories; use Ada.Directories; with Ada.Text_IO; use Ada.Text_IO; with Ada.Characters.Handling; use Ada.Characters.Handling; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Exceptions; use Ada.Exceptions; with Glib.Xml_Int; use Glib.Xml_Int; with Templates_Parser; use Templates_Parser; with Signal_Storage; use Signal_Storage; with Gate3_Glib; use Gate3_Glib; package body Glade3_Generate is package UBS renames Ada.Strings.Unbounded; Template_Dir : UBS.String_Access; ----------------------- -- Set_Template_Dir -- ----------------------- procedure Set_Template_Dir (Dir : in String) is begin if Template_Dir /= null then Free (Template_Dir); end if; Template_Dir := new String'(Dir); end Set_Template_Dir; procedure Scan_Project (Project : in Node_Ptr); -- Process the Xml tree Project to find windows and signal -- Results are stored in package Signal_Storage function Print_Header (File_Name : String) return String; -- Generates header using gate3_header.tmplt function Print_Main (Project_Name : String; Glade_Name : String) return String; -- Generates main Ada procedure using gate3_main.tmplt function Print_Spec (Window_Nbr : Object_Index) return String; -- Generates Ada specs for one callback package using gate3_spec.tmplt function Print_Body (Window_Nbr : Object_Index) return String; -- Generates Ada body for one callback package using gate3_body.tmplt -------------- -- Generate -- -------------- ----------------------- -- Generate a string -- ----------------------- function Process (File_Name : String; Main_Name : String := ""; Project_Tree : Node_Ptr) return String is -- Scan the XML tree and outputs the text Result : UBS.Unbounded_String; Window_Nbr : Object_Index := 0; begin -- Populate the object and signal store Scan_Project (Project_Tree); -- Do some checks for the validity Window_Nbr := Get_Object_Number; if Window_Nbr = 0 then -- something is wrong in the glade file Raise_Exception (Bad_Xml'Identity, "Gate3 Error : " & "Cannot find any window in your project."); end if; if Get_Signal_Number = 0 then -- there is no signal in project - program will hang. Raise_Exception (Bad_Xml'Identity, "Gate3 Error : " & "There is no signal in your project." & " You must have at least a destroy signal."); end if; -- The real processing is done here. Result := To_Unbounded_String (Print_Header (File_Name)); Append (Result, Print_Main (Main_Name, File_Name)); for I in 1 .. Window_Nbr loop if Object_Store (I).Signumber > 0 then Append (Result, Print_Spec (I)); Append (Result, Print_Body (I)); end if; end loop; return UBS.To_String (Result); exception when E : Signal_Storage.Bad_Identifier => Raise_Exception (Bad_Xml'Identity, Exception_Message (E)); end Process; ---------------------- -- Generate a file -- ---------------------- procedure Generate (Glade_File : in String; Project_Name : in String := ""; Output_Dir : in String := "") is Project : Node_Ptr; Output : File_Type; Output_Name : UBS.String_Access; Mainproc_Name : UBS.String_Access; begin if Project_Name = "" then Mainproc_Name := new String'(To_Ada (To_Lower (Base_Name (Glade_File)))); else Mainproc_Name := new String'(Project_Name); end if; if Output_Dir = "" then Output_Name := new String' (Compose (Containing_Directory (Glade_File), To_Lower (Base_Name (Glade_File)), "ada")); else begin if Exists (Output_Dir) and then Kind (Output_Dir) = Directory then Output_Name := new String'(Compose (Output_Dir, To_Lower (Base_Name (Glade_File)), "ada")); else Output_Name := new String' (Compose (Containing_Directory (Glade_File), To_Lower (Base_Name (Glade_File)), "ada")); end if; exception when Ada.Directories.Name_Error => Output_Name := new String'(Compose ("", To_Lower (Base_Name (Glade_File)), "ada")); end; end if; -- Do the XML parsing. Project := Glib.Xml_Int.Parse (Glade_File); if Project = null then Raise_Exception (Bad_Xml'Identity, "Gate3 Error : XML parsing with glib failed." & "Check your glade file."); end if; if Ada.Directories.Exists (Output_Name.all) then Ada.Directories.Delete_File (Output_Name.all); end if; Create (Output, Out_File, Output_Name.all); Ada.Text_IO.Put (Output, Process (Glade_File, Mainproc_Name.all, Project)); Close (Output); Put_Line ("Result file is : " & Output_Name.all); -- Garbage collection Free (Output_Name); Free (Mainproc_Name); Glib.Xml_Int.Free (Project); end Generate; ------------------ -- Scan_Project -- ------------------ procedure Scan_Object (N : Node_Ptr; Top_Window : Object_Index); procedure Scan_Project (Project : Node_Ptr) is P : Node_Ptr; Top_Widget_Nbr : Object_Index := 0; begin if Project.Tag.all /= "interface" then -- sanity check against old version of Glade Raise_Exception (Old_Version'Identity, "Gate3 Error : Old version. " & "The top tag must be [interface]"); end if; Initialize_Signals_Store; P := Project.Child; while P /= null loop if P.Tag.all = "object" then if Debug then Put ("Scanning root object id [" & Get_Attribute (P, "id")); Put_Line ("] ; class [" & Get_Attribute (P, "class") & "]."); end if; declare Class : constant String := Get_Attribute (P, "class"); begin -- scan only objects that can contain signals or shows if Class = "GtkAction" or Class = "GtkActionGroup" or Class = "GtkAboutDialog" or Class = "GtkDialog" or Class = "GtkWindow" then Top_Widget_Nbr := Top_Widget_Nbr + 1; Object_Store (Top_Widget_Nbr).Node := P; Inc_Object_Number; Scan_Object (P, Top_Widget_Nbr); end if; end; elsif P.Tag.all = "widget" then -- sanity check against old version of Glade files Raise_Exception (Old_Version'Identity, "Gate3 Error : : Old version. " & "Tag [widget] is obsolete and replaced by [object]"); else null; end if; P := P.Next; end loop; end Scan_Project; ------------------ -- Scan_Object -- ------------------ procedure Scan_Object (N : Node_Ptr; Top_Window : Object_Index) is P, Q : Node_Ptr; begin P := N.Child; while P /= null loop if P.Tag.all = "signal" then -- Looking for the root window Store_Signal_Node (P, Top_Window); if Debug then Put (" Registering signal name [" & Get_Attribute (P, "name")); Put ("]; handler [" & Get_Attribute (P, "handler")); Put_Line ("]; widget [" & Get_Attribute (N, "id") & "]"); Put_Line (" Top object is [" & Get_Attribute (Object_Store (Top_Window).Node, "id") & "]."); end if; elsif P.Tag.all = "child" then Q := P.Child; while Q /= null loop if Q.Tag.all = "object" then -- go into recursion Scan_Object (Q, Top_Window); end if; Q := Q.Next; end loop; else null; end if; P := P.Next; end loop; end Scan_Object; ------------------ -- Print_Header -- ------------------ function Print_Header (File_Name : String) return String is File_Tag : constant Templates_Parser.Tag := +File_Name; Translations : constant Templates_Parser.Translate_Table (1 .. 1) := (1 => Templates_Parser.Assoc ("FILE", File_Tag)); Header_Template : constant String := Compose (Template_Dir.all, "gate3_header", "tmplt"); begin return Templates_Parser.Parse (Header_Template, Translations); end Print_Header; ------------------ -- Print_Main -- ------------------ function Print_Main (Project_Name : String; Glade_Name : String) return String is Window_Nbr : constant Object_Index := Get_Object_Number; Signal_Number : constant Natural := Get_Signal_Number; Project_Tag : constant Templates_Parser.Tag := +Project_Name; Glade_Tag : constant Templates_Parser.Tag := +Glade_Name; Objects : Templates_Parser.Vector_Tag; Ada_Objects : Templates_Parser.Vector_Tag; Shows : Templates_Parser.Vector_Tag; Signals : Templates_Parser.Vector_Tag; Ada_Signals : Templates_Parser.Vector_Tag; Translations : Templates_Parser.Translate_Table (1 .. 7); Main_Template : constant String := Compose (Template_Dir.all, "gate3_main", "tmplt"); -- the template file is <gate3_main.tmplt> located in -- directory of gate3 begin for I in 1 .. Window_Nbr loop declare P : constant String := Get_Attribute (Object_Store (I).Node, "id"); Class : constant String := Get_Attribute (Object_Store (I).Node, "class"); begin Append (Objects, P); if Object_Store (I).Signumber > 0 then Append (Ada_Objects, To_Ada (P)); end if; if Class = "GtkAboutDialog" or Class = "GtkDialog" or Class = "GtkWindow" then Append (Shows, True); else Append (Shows, False); end if; end; end loop; for I in 1 .. Signal_Number loop declare Handler : constant String := Get_Attribute (Retrieve_Signal_Node (I).Signal, "handler"); Ada_Handler : constant String := To_Ada (Handler); begin Append (Signals, Handler); Append (Ada_Signals, Ada_Handler); end; end loop; Translations := (1 => Templates_Parser.Assoc ("PROJECT", Project_Tag), 2 => Templates_Parser.Assoc ("GLADE_NAME", Glade_Tag), 3 => Templates_Parser.Assoc ("OBJECT", Objects), 4 => Templates_Parser.Assoc ("ADA_OBJECT", Ada_Objects), 5 => Templates_Parser.Assoc ("SHOW", Shows), 6 => Templates_Parser.Assoc ("SIGNAL", Signals), 7 => Templates_Parser.Assoc ("ADA_SIGNAL", Ada_Signals)); return Templates_Parser.Parse (Main_Template, Translations); end Print_Main; ------------------ -- Print_Spec -- ------------------ function Print_Spec (Window_Nbr : Object_Index) return String is Window : constant Node_Ptr := Object_Store (Window_Nbr).Node; Pack_Name : constant String := To_Ada (Get_Attribute (Window, "id")); Signal : Signal_Rec; Signal_Number : constant Natural := Get_Signal_Number; Package_Tag : constant Templates_Parser.Tag := +To_Ada (Pack_Name); Ada_Handlers : Templates_Parser.Vector_Tag; Cb_Procedures : Templates_Parser.Vector_Tag; Translations : Templates_Parser.Translate_Table (1 .. 3); Spec_Template : constant String := Compose (Template_Dir.all, "gate3_spec", "tmplt"); -- the template file is <gate3_spec.tmplt> located in -- directory of gate3 begin -- Output signal handlers for I in 1 .. Signal_Number loop Signal := Retrieve_Signal_Node (I); if Signal.Top_Window = Window_Nbr then -- output only signals belonging to present window/object declare Ada_Handler : constant String := To_Ada (Get_Attribute (Signal.Signal, "handler")); begin Append (Ada_Handlers, Ada_Handler); if Signal.Callback = Proc then Append (Cb_Procedures, True); else Append (Cb_Procedures, False); end if; end; end if; end loop; Translations := (1 => Templates_Parser.Assoc ("PACKAGE", Package_Tag), 2 => Templates_Parser.Assoc ("ADA_HANDLER", Ada_Handlers), 3 => Templates_Parser.Assoc ("CB_PROC", Cb_Procedures)); return Templates_Parser.Parse (Spec_Template, Translations); end Print_Spec; ------------------ -- Print_Body -- ------------------ function Print_Body (Window_Nbr : Object_Index) return String is Window : constant Node_Ptr := Object_Store (Window_Nbr).Node; Signal : Signal_Rec; Signal_Number : constant Natural := Get_Signal_Number; Pack_Name : constant String := To_Ada (Get_Attribute (Window, "id")); Package_Tag : constant Templates_Parser.Tag := +To_Ada (Pack_Name); Ada_Handlers : Templates_Parser.Vector_Tag; Cb_Procedures : Templates_Parser.Vector_Tag; Has_Quit : Templates_Parser.Vector_Tag; Translations : Templates_Parser.Translate_Table (1 .. 4); Body_Template : constant String := Compose (Template_Dir.all, "gate3_body", "tmplt"); -- the template file is <gate3_body.tmplt> located in directory of gate3 begin -- Output signal handlers for I in 1 .. Signal_Number loop Signal := Retrieve_Signal_Node (I); if Signal.Top_Window = Window_Nbr then -- output only signals belonging to present window/object declare Ada_Handler : constant String := To_Ada (Get_Attribute (Signal.Signal, "handler")); begin Append (Ada_Handlers, Ada_Handler); if Signal.Callback = Proc then Append (Cb_Procedures, True); else Append (Cb_Procedures, False); end if; -- Add a call to Main.Main_Quit if handler name contains <quit> if Signal.Has_Quit then Append (Has_Quit, True); else Append (Has_Quit, False); end if; end; end if; end loop; Translations := (1 => Templates_Parser.Assoc ("PACKAGE", Package_Tag), 2 => Templates_Parser.Assoc ("ADA_HANDLER", Ada_Handlers), 3 => Templates_Parser.Assoc ("CB_PROC", Cb_Procedures), 4 => Templates_Parser.Assoc ("HAS_QUIT", Has_Quit)); return Templates_Parser.Parse (Body_Template, Translations); end Print_Body; end Glade3_Generate;
------------------------------------------------------------------------------ -- -- -- GNAT EXAMPLE -- -- -- -- Copyright (C) 2014, 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. -- -- -- ------------------------------------------------------------------------------ -- Ignore false positive warnings pragma Warnings (Off, "*unused initial value*"); pragma Style_Checks ("M132"); package body Tetris with SPARK_Mode is ---------------------------- -- Include_Piece_In_Board -- ---------------------------- procedure Include_Piece_In_Board is begin case Cur_Piece.S is when O => Cur_Board (Cur_Piece.Y) (Cur_Piece.X) := Cur_Piece.S; Cur_Board (Cur_Piece.Y + 1) (Cur_Piece.X) := Cur_Piece.S; Cur_Board (Cur_Piece.Y) (Cur_Piece.X + 1) := Cur_Piece.S; Cur_Board (Cur_Piece.Y + 1) (Cur_Piece.X + 1) := Cur_Piece.S; when I => -- intermediate assertion needed for proof pragma Assert (for all YY in I_Delta => (for all XX in I_Delta => (if Possible_I_Shapes (Cur_Piece.D) (YY, XX) then Is_Empty (Cur_Board, Cur_Piece.Y + YY, Cur_Piece.X + XX)))); for Y in I_Delta loop pragma Loop_Invariant (for all YY in I_Delta range Y .. I_Delta'Last => (for all XX in I_Delta => (if Possible_I_Shapes (Cur_Piece.D) (YY, XX) then Is_Empty (Cur_Board, Cur_Piece.Y + YY, Cur_Piece.X + XX)))); for X in I_Delta loop pragma Loop_Invariant (for all YY in I_Delta range Y + 1 .. I_Delta'Last => (for all XX in I_Delta => (if Possible_I_Shapes (Cur_Piece.D) (YY, XX) then Is_Empty (Cur_Board, Cur_Piece.Y + YY, Cur_Piece.X + XX)))); pragma Loop_Invariant (for all XX in I_Delta range X .. I_Delta'Last => (if Possible_I_Shapes (Cur_Piece.D) (Y, XX) then Is_Empty (Cur_Board, Cur_Piece.Y + Y, Cur_Piece.X + XX))); if Possible_I_Shapes (Cur_Piece.D) (Y, X) then Cur_Board (Cur_Piece.Y + Y) (Cur_Piece.X + X) := Cur_Piece.S; end if; end loop; end loop; when Three_Shape => -- intermediate assertion needed for proof pragma Assert (for all YY in Three_Delta => (for all XX in Three_Delta => (if Possible_Three_Shapes (Cur_Piece.S, Cur_Piece.D) (YY, XX) then Is_Empty (Cur_Board, Cur_Piece.Y + YY, Cur_Piece.X + XX)))); for Y in Three_Delta loop pragma Loop_Invariant (for all YY in Three_Delta range Y .. Three_Delta'Last => (for all XX in Three_Delta => (if Possible_Three_Shapes (Cur_Piece.S, Cur_Piece.D) (YY, XX) then Is_Empty (Cur_Board, Cur_Piece.Y + YY, Cur_Piece.X + XX)))); for X in Three_Delta loop pragma Loop_Invariant (for all YY in Three_Delta range Y + 1 .. Three_Delta'Last => (for all XX in Three_Delta => (if Possible_Three_Shapes (Cur_Piece.S, Cur_Piece.D) (YY, XX) then Is_Empty (Cur_Board, Cur_Piece.Y + YY, Cur_Piece.X + XX)))); pragma Loop_Invariant (for all XX in Three_Delta range X .. Three_Delta'Last => (if Possible_Three_Shapes (Cur_Piece.S, Cur_Piece.D) (Y, XX) then Is_Empty (Cur_Board, Cur_Piece.Y + Y, Cur_Piece.X + XX))); if Possible_Three_Shapes (Cur_Piece.S, Cur_Piece.D) (Y, X) then Cur_Board (Cur_Piece.Y + Y) (Cur_Piece.X + X) := Cur_Piece.S; end if; end loop; end loop; end case; -- update current state Cur_State := Board_Before_Clean; end Include_Piece_In_Board; --------------------------- -- Delete_Complete_Lines -- --------------------------- procedure Delete_Complete_Lines is Empty_Line : constant Line := (others => Empty); To_Line : Y_Coord := Y_Coord'Last; Has_Complete_Lines : Boolean := False; begin -- delete all complete lines, identifying the first complete line from -- the bottom (higher value of Y) for Del_Line in Y_Coord loop if Is_Complete_Line (Cur_Board (Del_Line)) then Cur_Board (Del_Line) := Empty_Line; Has_Complete_Lines := True; To_Line := Del_Line; pragma Assert (Cur_Board (Del_Line)(X_Coord'First) = Empty); end if; pragma Loop_Invariant (for all Y in Y_Coord'First .. Del_Line => not Is_Complete_Line (Cur_Board (Y))); end loop; -- iteratively move non-empty lines to the bottom of the board if Has_Complete_Lines then for From_Line in reverse Y_Coord'First .. To_Line - 1 loop pragma Loop_Invariant (No_Complete_Lines (Cur_Board)); pragma Loop_Invariant (From_Line < To_Line); if not Is_Empty_Line (Cur_Board (From_Line)) then Cur_Board (To_Line) := Cur_Board (From_Line); Cur_Board (From_Line) := Empty_Line; To_Line := To_Line - 1; end if; end loop; end if; -- update current state Cur_State := Board_After_Clean; end Delete_Complete_Lines; --------------- -- Do_Action -- --------------- procedure Do_Action (A : Action; Success : out Boolean) is Candidate : Piece; begin if Move_Is_Possible (Cur_Piece, A) then Candidate := Move (Cur_Piece, A); if No_Overlap (Cur_Board, Candidate) then Cur_Piece := Candidate; Success := True; return; end if; end if; Success := False; end Do_Action; end Tetris;
with Ada.Numerics.Generic_Elementary_Functions; package body Ada_Voxel is package Float_Functions is new Ada.Numerics.Generic_Elementary_Functions (Float); ------------ -- Render -- ------------ procedure Render (Cam_X : Float; Cam_Y : Float; Cam_Angle : Float; Cam_Height : Float; Horizon : Float; Distance : Float; Scale_Height : Float) is Y_Buffer : array (0 .. Screen_Width - 1) of Integer := (others => Screen_Height); Dz : Float := 1.0; Z : Float := 1.0; begin while Z < Distance loop declare Sin : Float := Float_Functions.Sin (Cam_Angle); Cos : Float := Float_Functions.Cos (Cam_Angle); Left_X : Float := (-Cos * Z - Sin * Z) + Cam_X; Left_Y : Float := ( Sin * Z - Cos * Z) + Cam_Y; Right_X : Float := ( Cos * Z - Sin * Z) + Cam_X; Right_Y : Float := (-Sin * Z - Cos * Z) + Cam_Y; Dx : constant Float := (Right_X - Left_X) / Float (Screen_Width); Dy : constant Float := (Right_Y - Left_Y) / Float (Screen_Width); Height_On_Screen : Float; begin for A in 0 .. Screen_Width - 1 loop Height_On_Screen := Cam_Height - Float (Height_Map (Integer (Left_X), Integer (Left_Y))); Height_On_Screen := Float (Height_On_Screen / Z) * Scale_Height + Horizon; Draw_Vertical_Line (A, Integer (Height_On_Screen), Integer (Y_Buffer (A)), Color_Map (Integer (Left_X), Integer (Left_Y))); if Integer (Height_On_Screen) < Y_Buffer (A) then Y_Buffer (A) := Integer (Height_On_Screen); end if; Left_X := Left_X + Dx; Left_Y := Left_Y + Dy; end loop; end; Z := Z + Dz; Dz := Dz + 0.01; end loop; end Render; end Ada_Voxel;
-- { dg-do run } -- { dg-options "-O" } procedure Opt30 is function Id_I (I : Integer) return Integer is begin return I; end; A : array (Integer range -4..4) of Integer; begin A := (-ID_I(4), -ID_I(3), -ID_I(2), -ID_I(1), ID_I(100), ID_I(1), ID_I(2), ID_I(3), ID_I(4)); A(-4..0) := A(0..4); if A /= (100, 1, 2, 3, 4, 1, 2, 3, 4) then raise Program_Error; end if; end;
-- { dg-do compile } -- { dg-options "-O" } with Renaming7_Pkg; use Renaming7_Pkg; with System; procedure Renaming7 is C : constant System.Address := A'Address; D : System.Address renames C; begin null; end;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2012 Felix Krause <contact@flyx.org> -- -- 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 GL.API; with GL.Enums.Getter; with GL.Enums.Textures; package body GL.Objects.Textures is Base_Level : constant := 0; function Get_Dimensions (Kind : LE.Texture_Kind) return Dimension_Count is begin case Kind is when Texture_1D => return One; when Texture_2D | Texture_2D_Multisample | Texture_1D_Array | Texture_Rectangle | Texture_Cube_Map => return Two; when Texture_3D | Texture_2D_Array | Texture_2D_Multisample_Array | Texture_Cube_Map_Array => return Three; when Texture_Buffer => raise Constraint_Error; end case; end Get_Dimensions; function Dimensions (Object : Texture) return Dimension_Count is (Object.Dimensions); function Allocated (Object : Texture) return Boolean is (Object.Allocated); type Texture_View is new Texture with null record; overriding procedure Initialize_Id (Object : in out Texture_View) is New_Id : UInt := 0; begin -- A texture that is going to be used as a view must not be created -- with a target, therefore use Gen_Textures instead of Create_Textures API.Gen_Textures.Ref (1, New_Id); Object.Reference.GL_Id := New_Id; end Initialize_Id; function Create_View (Object : Texture; Kind : LE.Texture_Kind; Format : Pixels.Internal_Format; Min_Level, Levels : Mipmap_Level; Min_Layer, Layers : Size) return Texture is Result : Texture_View (Kind => Kind); begin API.Texture_View_I.Ref (Result.Reference.GL_Id, Kind, Object.Reference.GL_Id, Format, UInt (Min_Level), UInt (Levels), UInt (Min_Layer), UInt (Layers)); return Texture (Result); end Create_View; function Create_View (Object : Texture; Kind : LE.Texture_Kind; Format : Pixels.Compressed_Format; Min_Level, Levels : Mipmap_Level; Min_Layer, Layers : Size) return Texture is Result : Texture_View (Kind => Kind); begin API.Texture_View_C.Ref (Result.Reference.GL_Id, Kind, Object.Reference.GL_Id, Format, UInt (Min_Level), UInt (Levels), UInt (Min_Layer), UInt (Layers)); return Texture (Result); end Create_View; function Create_View (Object : Texture; Kind : LE.Texture_Kind; Layer : Size) return Texture is function Get_Layers (Kind : LE.Texture_Kind) return Positive_Size is (case Kind is when Texture_1D | Texture_2D | Texture_3D => 1, when Texture_Rectangle | Texture_2D_Multisample => 1, when Texture_Cube_Map | Texture_Cube_Map_Array => 6, when Texture_Buffer => raise Constraint_Error, when others => 1); begin if Object.Compressed then return Object.Create_View (Kind => Kind, Format => Object.Compressed_Format, Min_Level => Object.Lowest_Mipmap_Level, Levels => Object.Mipmap_Levels, Min_Layer => Layer, Layers => Get_Layers (Kind)); else return Object.Create_View (Kind => Kind, Format => Object.Internal_Format, Min_Level => Object.Lowest_Mipmap_Level, Levels => Object.Mipmap_Levels, Min_Layer => Layer, Layers => Get_Layers (Kind)); end if; end Create_View; function Width (Object : Texture; Level : Mipmap_Level) return Size is Result : Size := 0; begin API.Get_Texture_Level_Parameter.Ref (Object.Reference.GL_Id, Level, Enums.Textures.Width, Result); return Result; end Width; function Height (Object : Texture; Level : Mipmap_Level) return Size is Result : Size := 0; begin API.Get_Texture_Level_Parameter.Ref (Object.Reference.GL_Id, Level, Enums.Textures.Height, Result); return Result; end Height; function Depth (Object : Texture; Level : Mipmap_Level) return Size is Result : Size := 0; begin API.Get_Texture_Level_Parameter.Ref (Object.Reference.GL_Id, Level, Enums.Textures.Depth, Result); return Result; end Depth; function Internal_Format (Object : Texture) return Pixels.Internal_Format is Result : Pixels.Internal_Format := Pixels.Internal_Format'First; begin API.Get_Texture_Level_Parameter_Format_I.Ref (Object.Reference.GL_Id, Base_Level, Enums.Textures.Internal_Format, Result); return Result; end Internal_Format; function Compressed_Format (Object : Texture) return Pixels.Compressed_Format is Result : Pixels.Compressed_Format := Pixels.Compressed_Format'First; begin API.Get_Texture_Level_Parameter_Format_C.Ref (Object.Reference.GL_Id, Base_Level, Enums.Textures.Internal_Format, Result); return Result; end Compressed_Format; function Compressed (Object : Texture) return Boolean is Result : Size := 0; begin API.Get_Texture_Level_Parameter.Ref (Object.Reference.GL_Id, Base_Level, Enums.Textures.Compressed, Result); return Result = 1; end Compressed; function Compressed_Image_Size (Object : Texture; Level : Mipmap_Level) return Size is Ret : Size := 0; begin API.Get_Texture_Level_Parameter.Ref (Object.Reference.GL_Id, Level, Enums.Textures.Compressed_Image_Size, Ret); return Ret; end Compressed_Image_Size; function Buffer_Offset (Object : Buffer_Texture) return Size is Result : Size := 0; begin API.Get_Texture_Level_Parameter.Ref (Object.Reference.GL_Id, Base_Level, Enums.Textures.Buffer_Offset, Result); return Result; end Buffer_Offset; function Buffer_Size (Object : Buffer_Texture) return Size is Result : Size := 0; begin API.Get_Texture_Level_Parameter.Ref (Object.Reference.GL_Id, Base_Level, Enums.Textures.Buffer_Size, Result); return Result; end Buffer_Size; function Samples (Object : Texture) return Size is Result : Size := 0; begin API.Get_Texture_Level_Parameter.Ref (Object.Reference.GL_Id, Base_Level, Enums.Textures.Samples, Result); return Result; end Samples; function Fixed_Sample_Locations (Object : Texture) return Boolean is Result : Size := 0; begin API.Get_Texture_Level_Parameter.Ref (Object.Reference.GL_Id, Base_Level, Enums.Textures.Fixed_Sample_Locations, Result); return Result = 1; end Fixed_Sample_Locations; procedure Bind_Texture_Unit (Object : Texture_Base; Unit : Texture_Unit) is IDs : constant Low_Level.UInt_Array := (1 => Object.Reference.GL_Id); begin API.Bind_Textures.Ref (Unit, 1, IDs); end Bind_Texture_Unit; procedure Bind_Image_Texture (Object : Texture_Base; Unit : Image_Unit) is IDs : constant Low_Level.UInt_Array := (1 => Object.Reference.GL_Id); begin API.Bind_Image_Textures.Ref (Unit, 1, IDs); end Bind_Image_Texture; overriding procedure Initialize_Id (Object : in out Texture_Base) is New_Id : UInt := 0; begin API.Create_Textures.Ref (Object.Kind, 1, New_Id); Object.Reference.GL_Id := New_Id; end Initialize_Id; overriding procedure Delete_Id (Object : in out Texture_Base) is Arr : constant Low_Level.UInt_Array := (1 => Object.Reference.GL_Id); begin API.Delete_Textures.Ref (1, Arr); Object.Reference.GL_Id := 0; end Delete_Id; procedure Invalidate_Image (Object : Texture_Base; Level : Mipmap_Level) is begin API.Invalidate_Tex_Image.Ref (Object.Reference.GL_Id, Level); end Invalidate_Image; procedure Invalidate_Sub_Image (Object : Texture_Base; Level : Mipmap_Level; X, Y, Z : Int; Width, Height, Depth : Size) is begin API.Invalidate_Tex_Sub_Image.Ref (Object.Reference.GL_Id, Level, X, Y, Z, Width, Height, Depth); end Invalidate_Sub_Image; procedure Set_Lowest_Mipmap_Level (Object : Texture; Level : Mipmap_Level) is begin API.Texture_Parameter_Int.Ref (Object.Reference.GL_Id, Enums.Textures.Base_Level, Level); end Set_Lowest_Mipmap_Level; function Lowest_Mipmap_Level (Object : Texture) return Mipmap_Level is Ret : Mipmap_Level := Mipmap_Level'First; begin API.Get_Texture_Parameter_Int.Ref (Object.Reference.GL_Id, Enums.Textures.Base_Level, Ret); return Ret; end Lowest_Mipmap_Level; procedure Set_Highest_Mipmap_Level (Object : Texture; Level : Mipmap_Level) is begin API.Texture_Parameter_Int.Ref (Object.Reference.GL_Id, Enums.Textures.Max_Level, Level); end Set_Highest_Mipmap_Level; function Highest_Mipmap_Level (Object : Texture) return Mipmap_Level is Ret : Mipmap_Level := Mipmap_Level'First; begin API.Get_Texture_Parameter_Int.Ref (Object.Reference.GL_Id, Enums.Textures.Max_Level, Ret); return Ret; end Highest_Mipmap_Level; function Mipmap_Levels (Object : Texture) return Mipmap_Level is Result : Mipmap_Level := Mipmap_Level'First; begin API.Get_Texture_Parameter_Int.Ref (Object.Reference.GL_Id, Enums.Textures.Immutable_Levels, Result); return Result; end Mipmap_Levels; procedure Clear_Using_Data (Object : Texture; Level : Mipmap_Level; Source_Format : Pixels.Format; Source_Type : Pixels.Data_Type; Source : System.Address) is begin API.Clear_Tex_Image.Ref (Object.Reference.GL_Id, Level, Source_Format, Source_Type, Source); end Clear_Using_Data; procedure Clear_Using_Zeros (Object : Texture; Level : Mipmap_Level) is begin API.Clear_Tex_Image.Ref (Object.Reference.GL_Id, Level, Pixels.Format'First, Pixels.Data_Type'First, System.Null_Address); end Clear_Using_Zeros; procedure Generate_Mipmap (Object : Texture) is begin API.Generate_Texture_Mipmap.Ref (Object.Reference.GL_Id); end Generate_Mipmap; function Texture_Unit_Count return Natural is Count : Int := 0; begin API.Get_Integer.Ref (Enums.Getter.Max_Combined_Texture_Image_Units, Count); return Natural (Count); end Texture_Unit_Count; function Texture_Unit_Count (Shader : Shaders.Shader_Type) return Natural is Count : Int := 0; use all type Shaders.Shader_Type; begin case Shader is when Vertex_Shader => API.Get_Integer.Ref (Enums.Getter.Max_Vertex_Texture_Image_Units, Count); when Fragment_Shader => API.Get_Integer.Ref (Enums.Getter.Max_Texture_Image_Units, Count); when Geometry_Shader => API.Get_Integer.Ref (Enums.Getter.Max_Geometry_Texture_Image_Units, Count); when Tess_Control_Shader => API.Get_Integer.Ref (Enums.Getter.Max_Tess_Control_Texture_Image_Units, Count); when Tess_Evaluation_Shader => API.Get_Integer.Ref (Enums.Getter.Max_Tess_Evaluation_Texture_Image_Units, Count); when Compute_Shader => API.Get_Integer.Ref (Enums.Getter.Max_Compute_Texture_Image_Units, Count); end case; return Natural (Count); end Texture_Unit_Count; function Maximum_Anisotropy return Single is Ret : Single := 16.0; begin API.Get_Single.Ref (Enums.Getter.Max_Texture_Max_Anisotropy, Ret); return Ret; end Maximum_Anisotropy; ----------------------------------------------------------------------------- -- Buffer Texture Loading -- ----------------------------------------------------------------------------- procedure Attach_Buffer (Object : Buffer_Texture; Internal_Format : Pixels.Internal_Format_Buffer_Texture; Buffer : Objects.Buffers.Buffer) is begin API.Texture_Buffer.Ref (Object.Reference.GL_Id, Internal_Format, Buffer.Raw_Id); end Attach_Buffer; procedure Attach_Buffer (Object : Buffer_Texture; Internal_Format : Pixels.Internal_Format_Buffer_Texture; Buffer : Objects.Buffers.Buffer; Offset, Size : Types.Size) is begin API.Texture_Buffer_Range.Ref (Object.Reference.GL_Id, Internal_Format, Buffer.Raw_Id, Low_Level.IntPtr (Offset), Size); end Attach_Buffer; ----------------------------------------------------------------------------- -- Texture Loading -- ----------------------------------------------------------------------------- procedure Allocate_Storage (Object : in out Texture; Levels, Samples : Types.Size; Format : Pixels.Internal_Format; Width, Height, Depth : Types.Size; Fixed_Locations : Boolean := True) is begin if Object.Kind in Texture_2D_Multisample | Texture_2D_Multisample_Array then case Object.Dimensions is when One => raise Program_Error; when Two => API.Texture_Storage_2D_Multisample_I.Ref (Object.Reference.GL_Id, Samples, Format, Width, Height, Low_Level.Bool (Fixed_Locations)); when Three => API.Texture_Storage_3D_Multisample_I.Ref (Object.Reference.GL_Id, Samples, Format, Width, Height, Depth, Low_Level.Bool (Fixed_Locations)); end case; else case Object.Dimensions is when One => API.Texture_Storage_1D.Ref (Object.Reference.GL_Id, Levels, Format, Width); when Two => API.Texture_Storage_2D_I.Ref (Object.Reference.GL_Id, Levels, Format, Width, Height); when Three => API.Texture_Storage_3D_I.Ref (Object.Reference.GL_Id, Levels, Format, Width, Height, Depth); end case; end if; Object.Allocated := True; end Allocate_Storage; procedure Allocate_Storage (Object : in out Texture; Levels, Samples : Types.Size; Format : Pixels.Compressed_Format; Width, Height, Depth : Types.Size; Fixed_Locations : Boolean := True) is begin if Object.Kind in Texture_2D_Multisample | Texture_2D_Multisample_Array then case Object.Dimensions is when One => raise Program_Error; when Two => API.Texture_Storage_2D_Multisample_C.Ref (Object.Reference.GL_Id, Samples, Format, Width, Height, Low_Level.Bool (Fixed_Locations)); when Three => API.Texture_Storage_3D_Multisample_C.Ref (Object.Reference.GL_Id, Samples, Format, Width, Height, Depth, Low_Level.Bool (Fixed_Locations)); end case; else case Object.Dimensions is when One => raise Program_Error; when Two => API.Texture_Storage_2D_C.Ref (Object.Reference.GL_Id, Levels, Format, Width, Height); when Three => API.Texture_Storage_3D_C.Ref (Object.Reference.GL_Id, Levels, Format, Width, Height, Depth); end case; end if; Object.Allocated := True; end Allocate_Storage; procedure Allocate_Storage (Object : in out Texture; Subject : Texture; Fixed_Locations : Boolean := True) is begin if Subject.Compressed then Object.Allocate_Storage (Subject.Mipmap_Levels, Subject.Samples, Subject.Compressed_Format, Subject.Width (0), Subject.Height (0), Subject.Depth (0), Fixed_Locations); else Object.Allocate_Storage (Subject.Mipmap_Levels, Subject.Samples, Subject.Internal_Format, Subject.Width (0), Subject.Height (0), Subject.Depth (0), Fixed_Locations); end if; end Allocate_Storage; procedure Load_From_Data (Object : Texture; Level : Mipmap_Level; X, Y, Z : Types.Size := 0; Width, Height, Depth : Types.Positive_Size; Source_Format : Pixels.Format; Source_Type : Pixels.Data_Type; Source : System.Address) is -- Texture_Cube_Map uses 2D storage, but 3D load operation -- according to Table 8.15 of the OpenGL specification Dimensions : constant Dimension_Count := (if Object.Kind = Texture_Cube_Map then Three else Object.Dimensions); begin case Dimensions is when One => API.Texture_Sub_Image_1D.Ref (Object.Reference.GL_Id, Level, X, Width, Source_Format, Source_Type, Source); when Two => API.Texture_Sub_Image_2D.Ref (Object.Reference.GL_Id, Level, X, Y, Width, Height, Source_Format, Source_Type, Source); when Three => API.Texture_Sub_Image_3D.Ref (Object.Reference.GL_Id, Level, X, Y, Z, Width, Height, Depth, Source_Format, Source_Type, Source); end case; end Load_From_Data; procedure Load_From_Data (Object : Texture; Level : Mipmap_Level; X, Y, Z : Types.Size := 0; Width, Height, Depth : Types.Positive_Size; Source_Format : Pixels.Compressed_Format; Image_Size : Types.Size; Source : System.Address) is -- Texture_Cube_Map uses 2D storage, but 3D load operation -- according to Table 8.15 of the OpenGL specification Dimensions : constant Dimension_Count := (if Object.Kind = Texture_Cube_Map then Three else Object.Dimensions); begin case Dimensions is when One => raise Program_Error; when Two => API.Compressed_Texture_Sub_Image_2D.Ref (Object.Reference.GL_Id, Level, X, Y, Width, Height, Source_Format, Image_Size, Source); when Three => API.Compressed_Texture_Sub_Image_3D.Ref (Object.Reference.GL_Id, Level, X, Y, Z, Width, Height, Depth, Source_Format, Image_Size, Source); end case; end Load_From_Data; procedure Copy_Data (Object : Texture; Subject : Texture; Source_Level, Target_Level : Mipmap_Level) is begin Object.Copy_Sub_Data (Subject, Source_Level, Target_Level, 0, 0, 0, 0, 0, 0, Object.Width (Source_Level), Object.Height (Source_Level), Object.Depth (Source_Level)); end Copy_Data; procedure Copy_Sub_Data (Object : Texture; Subject : Texture; Source_Level, Target_Level : Mipmap_Level; Source_X, Source_Y, Source_Z : Types.Size := 0; Target_X, Target_Y, Target_Z : Types.Size := 0; Width, Height, Depth : Types.Size) is begin API.Copy_Image_Sub_Data.Ref (Object.Reference.GL_Id, Object.Kind, Source_Level, Source_X, Source_Y, Source_Z, Subject.Reference.GL_Id, Subject.Kind, Target_Level, Target_X, Target_Y, Target_Z, Width, Height, Depth); end Copy_Sub_Data; procedure Clear_Using_Data (Object : Texture; Level : Mipmap_Level; X, Y, Z : Types.Size := 0; Width, Height, Depth : Types.Positive_Size; Source_Format : Pixels.Format; Source_Type : Pixels.Data_Type; Source : System.Address) is begin API.Clear_Tex_Sub_Image.Ref (Object.Reference.GL_Id, Level, X, Y, Z, Width, Height, Depth, Source_Format, Source_Type, Source); end Clear_Using_Data; procedure Clear_Using_Zeros (Object : Texture; Level : Mipmap_Level; X, Y, Z : Types.Size := 0; Width, Height, Depth : Types.Positive_Size) is begin API.Clear_Tex_Sub_Image.Ref (Object.Reference.GL_Id, Level, X, Y, Z, Width, Height, Depth, Pixels.Format'First, Pixels.Data_Type'First, System.Null_Address); end Clear_Using_Zeros; ----------------------------------------------------------------------------- function Get_Compressed_Data (Object : Texture; Level : Mipmap_Level; X, Y, Z : Types.Size := 0; Width, Height, Depth : Types.Positive_Size; Format : Pixels.Compressed_Format) return not null Types.Pointers.UByte_Array_Access is Blocks : constant Int := ((Width + 3) / 4) * ((Height + 3) / 4) * Depth; Number_Of_Bytes : constant Int := Blocks * PE.Block_Bytes (Format); Result : constant Types.Pointers.UByte_Array_Access := new UByte_Array (1 .. Number_Of_Bytes); begin API.Get_Compressed_Texture_Sub_Image.Ref (Object.Reference.GL_Id, Level, X, Y, Z, Width, Height, Depth, Number_Of_Bytes, Result); return Result; end Get_Compressed_Data; package body Texture_Pointers is package Get_Texture_Sub_Image is new API.Loader.Procedure_With_12_Params ("glGetTextureSubImage", UInt, Objects.Textures.Mipmap_Level, Int, Int, Int, Size, Size, Size, Pixels.Format, Pixels.Data_Type, Size, Element_Array_Access); function Get_Data (Object : Texture; Level : Mipmap_Level; X, Y, Z : Types.Size := 0; Width, Height, Depth : Types.Positive_Size; Format : Pixels.Format; Data_Type : PE.Non_Packed_Data_Type) return not null Element_Array_Access is -- Texture data is considered to be unpacked. When retrieving -- it from a texture, it will be packed. Therefore, each row -- must be a multiple of the current pack alignment. Call -- Set_Pack_Alignment if necessary. Alignment : constant Byte_Count := PE.Byte_Alignment (Pixels.Pack_Alignment); pragma Assert ((Width * PE.Bytes (Data_Type)) mod Alignment = 0); Bytes_Per_Element : constant Int := Pointers.Element'Size / System.Storage_Unit; Bytes_Per_Texel : constant Int := PE.Components (Format) * PE.Bytes (Data_Type); -- TODO Handle packed data types and depth/stencil formats (see Table 8.5) pragma Assert (Bytes_Per_Texel rem Bytes_Per_Element = 0); Texels : constant Size := Width * Height * Depth; pragma Assert (Texels > 0); Number_Of_Bytes : constant Int := Texels * Bytes_Per_Texel; Length : constant Long := Long (Texels * (Bytes_Per_Texel / Bytes_Per_Element)); I1 : constant Pointers.Index := Pointers.Index'First; I2 : constant Pointers.Index := Pointers.Index'Val (Pointers.Index'Pos (I1) + Length); Result : constant Element_Array_Access := new Pointers.Element_Array (I1 .. Pointers.Index'Pred (I2)); pragma Assert (Result'Length > 0); begin Get_Texture_Sub_Image.Ref (Object.Reference.GL_Id, Level, X, Y, Z, Width, Height, Depth, Format, Data_Type, Number_Of_Bytes, Result); return Result; end Get_Data; end Texture_Pointers; package body Texture_Bindings is procedure Bind_Textures (Textures : Texture_Array) is IDs : Low_Level.UInt_Array (Integer (Textures'First) .. Integer (Textures'Last)); begin for Unit in Textures'Range loop IDs (Integer (Unit)) := Textures (Unit).Reference.GL_Id; end loop; API.Bind_Textures.Ref (Textures'First, Textures'Length, IDs); end Bind_Textures; procedure Bind_Images (Images : Image_Array) is IDs : Low_Level.UInt_Array (Integer (Images'First) .. Integer (Images'Last)); begin for Unit in Images'Range loop IDs (Integer (Unit)) := Images (Unit).Reference.GL_Id; end loop; API.Bind_Image_Textures.Ref (Images'First, Images'Length, IDs); end Bind_Images; end Texture_Bindings; end GL.Objects.Textures;
-- { dg-do run { target i?86-*-* x86_64-*-* alpha*-*-* ia64-*-* } } with Unchecked_Conversion; procedure Unchecked_Convert6b is subtype c_5 is string(1..5); function int2c5 is -- { dg-warning "different sizes" } new unchecked_conversion (source => integer, target => c_5); c5 : c_5; begin c5 := int2c5(16#12#); if c5 (1) /= ASCII.DC2 then raise Program_Error; end if; end;
------------------------------------------------------------------------------ -- -- -- Ada User Repository Annex (AURA) -- -- ANNEXI-STRAYLINE Reference Implementation -- -- -- -- ------------------------------------------------------------------------ -- -- -- -- Copyright (C) 2019-2021, 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. -- -- -- ------------------------------------------------------------------------------ -- This package contains the core worker pool which executes queued -- "work orders". -- -- The intent is that "work orders" are used internally within various -- subsystems, rather than acting as a general calling convention. -- -- In general, derrivatives of Work_Order should not appear in package -- specifications (except in private parts or private packages) with Ada.Containers; with Progress; package Workers is ----------------- -- Work Orders -- ----------------- type Work_Order is abstract tagged record Tracker: Progress.Progress_Tracker_Access := null; -- If non-null, the Work_Order will invoke Increment_Completed_Items -- on the successful completion of the Order, or -- Increment_Failed_Items otherwise end record; -- Any derrivative of the Work_Order interface may be submitted to -- Queue_Order for a Worker task to call Execute on the order. function Image (Order: Work_Order) return String is abstract; -- Return a string describing the details of the work order, used by -- work tasks to create reports when Execute raises an exception. procedure Execute (Order: in out Work_Order) is abstract; -- Dispatching operation to execute the work of the work order. Called by -- a worker tasks when executing an order procedure Phase_Trigger (Order: in out Work_Order) is null; -- If Order has a non-null tracker, and at completion of the order -- when the tracker is incremented, if the tracker is completed -- (Is_Complete) evaluates True, the worker executes Phase_Trigger -- -- The concept for a phase trigger is essentially equivalent to the join -- in a fork-join concurrency model. -- -- If Phase_Trigger raises an exception, the worker files a failure report -- using image of the triggering order, with a worker note of -- "Phase Trigger failed" -- -- Since Phase_Triggers are often used to schedule (enqueue) more work, -- and since that work can sometimes include deallocating concurrent shared -- memory for the just completed task, it is important that any work -- submitted during a phase trigger is not executed until the phase trigger -- completes. Therefore all workers will be held while a phase trigger -- executes - again this is conformant with the fork-join model. -- -- Note that the worker will not interact with tracker after executing -- an associated Phase_Trigger. ---------------- -- Work Queue -- ---------------- subtype Count_Type is Ada.Containers.Count_Type; use type Count_Type; procedure Enqueue_Order (Order: in Work_Order'Class); -- Enqueus a (normal) Work_Order on the work queue. procedure Defer_Order (Order : in Work_Order'Class; Wait_Tracker: not null Progress.Progress_Tracker_Access); -- Order Deferral -- ============== -- -- Each deferred order is dependent on a Progress_Tracker on which the -- deferred order is waiting completion. -- -- Deferred orders are intended to act as triggers pending some other -- process. It is expected that a given Work Order completes a tracker -- on which a deferred work order is waiting. That/those Work Orders -- can then be executed. This ensures that the workers are not exhausted -- blocking on a progress tracker happening inside of a normal work order. -- -- When submitted, Deferred Orders are enqueued on to the main work queue. -- When a worker dequeues a Deferred Order, it immediately checks the -- Wait_Tracker for completion. If the tracker indicates completion, -- the worker immediately executes the Deferred Order as it would a -- regular Work Order. If the tracker does not indicate completion, the -- Order is then enqueued on a separate "deferral queue". -- -- Every worker that completes any work order always drains the deferral -- queue back to the main queue, so that each deferred order may then -- be re-checked. -- -- The design of this algorithm has a number of features: -- -- * It ensures that the minimum time is spent re-checking Deferred Orders -- that likely have not had their tracker completed, and that the Orders -- that release Deferred Orders will tend to be processed before the -- related Deferred Order is processed -- -- * Once the main queue is empty, all workers will wait for new orders to -- be enqueued, and will not spin, even if there remains Deferred Orders -- that have not been released. This is desireable because, if such -- Deferred Orders remained in this case, it should be impossible for -- them to complete anyways. -- -- * In theory, any erroneous Deferred Orders (who's tracker will never -- complete) will accumulate on the deferral queue after the main queue -- has been empty. This should be easy to spot since a higher-level -- process will stall on the Deferred Order, but there will not be -- misleading behaviour such as high CPU usage, or random performance -- (and potential live lock) due to spinning. function Queue_Level return Count_Type; function Peak_Queue_Level return Count_Type; -- Number of work order in the Queue, or the peak recorded number, not -- including deferred orders that have been moved to the deferral queue function Deferred return Count_Type; function Peak_Deferred return Count_Type; -- Number of work orders in the deferral queue ----------------- -- Worker Pool -- ----------------- -- All Workers simply Execute work orders off the Work Queue or Deferral -- Queue -- -- Any exception encountered is contained and reported via the failure -- reporting facilities subtype Worker_Count is Natural; task type Worker_Task; type Worker_Pool is array (Worker_Count range <>) of Worker_Task; -- The environment task is expected to initialize an appropriate pool of -- workers procedure Enable_Completion_Reports; procedure Disable_Completion_Reports; -- If enabled, all workers submit a report on completion of a work order. -- This setting is Disabled by default procedure Wait_Workers; procedure Wait_Workers (Timeout: in Duration; Timedout: out Boolean); -- Wait until all workers are Idle (no more jobs on the work queue), -- or until Timeout expires procedure Disband_Workers; -- Perminantly terminates all worker tasks in the partition. -- This cannot be reversed. function Busy_Workers return Worker_Count; function Peak_Busy_Workers return Worker_Count; -- Total number of Worker tasks currently executing a Work_Order end Workers;
----------------------------------------------------------------------- -- AWA.Users.Models -- AWA.Users.Models ----------------------------------------------------------------------- -- File generated by ada-gen DO NOT MODIFY -- Template used: templates/model/package-body.xhtml -- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 1095 ----------------------------------------------------------------------- -- Copyright (C) 2017 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.Unchecked_Deallocation; with Util.Beans.Objects.Time; package body AWA.Users.Models is use type ADO.Objects.Object_Record_Access; use type ADO.Objects.Object_Ref; use type ADO.Objects.Object_Record; pragma Warnings (Off, "formal parameter * is not referenced"); function Email_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => EMAIL_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Email_Key; function Email_Key (Id : in String) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => EMAIL_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Email_Key; function "=" (Left, Right : Email_Ref'Class) return Boolean is begin return ADO.Objects.Object_Ref'Class (Left) = ADO.Objects.Object_Ref'Class (Right); end "="; procedure Set_Field (Object : in out Email_Ref'Class; Impl : out Email_Access) is Result : ADO.Objects.Object_Record_Access; begin Object.Prepare_Modify (Result); Impl := Email_Impl (Result.all)'Access; end Set_Field; -- Internal method to allocate the Object_Record instance procedure Allocate (Object : in out Email_Ref) is Impl : Email_Access; begin Impl := new Email_Impl; Impl.Status := AWA.Users.Models.MailDeliveryStatus'First; Impl.Last_Error_Date := ADO.DEFAULT_TIME; Impl.Version := 0; Impl.User_Id := ADO.NO_IDENTIFIER; ADO.Objects.Set_Object (Object, Impl.all'Access); end Allocate; -- ---------------------------------------- -- Data object: Email -- ---------------------------------------- procedure Set_Email (Object : in out Email_Ref; Value : in String) is Impl : Email_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 1, Impl.Email, Value); end Set_Email; procedure Set_Email (Object : in out Email_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : Email_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 1, Impl.Email, Value); end Set_Email; function Get_Email (Object : in Email_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_Email); end Get_Email; function Get_Email (Object : in Email_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant Email_Access := Email_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Email; end Get_Email; procedure Set_Status (Object : in out Email_Ref; Value : in AWA.Users.Models.MailDeliveryStatus) is procedure Set_Field_Enum is new ADO.Objects.Set_Field_Operation (MailDeliveryStatus); Impl : Email_Access; begin Set_Field (Object, Impl); Set_Field_Enum (Impl.all, 2, Impl.Status, Value); end Set_Status; function Get_Status (Object : in Email_Ref) return AWA.Users.Models.MailDeliveryStatus is Impl : constant Email_Access := Email_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Status; end Get_Status; procedure Set_Last_Error_Date (Object : in out Email_Ref; Value : in Ada.Calendar.Time) is Impl : Email_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Time (Impl.all, 3, Impl.Last_Error_Date, Value); end Set_Last_Error_Date; function Get_Last_Error_Date (Object : in Email_Ref) return Ada.Calendar.Time is Impl : constant Email_Access := Email_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Last_Error_Date; end Get_Last_Error_Date; function Get_Version (Object : in Email_Ref) return Integer is Impl : constant Email_Access := Email_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Version; end Get_Version; procedure Set_Id (Object : in out Email_Ref; Value : in ADO.Identifier) is Impl : Email_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Key_Value (Impl.all, 5, Value); end Set_Id; function Get_Id (Object : in Email_Ref) return ADO.Identifier is Impl : constant Email_Access := Email_Impl (Object.Get_Object.all)'Access; begin return Impl.Get_Key_Value; end Get_Id; procedure Set_User_Id (Object : in out Email_Ref; Value : in ADO.Identifier) is Impl : Email_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Identifier (Impl.all, 6, Impl.User_Id, Value); end Set_User_Id; function Get_User_Id (Object : in Email_Ref) return ADO.Identifier is Impl : constant Email_Access := Email_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.User_Id; end Get_User_Id; -- Copy of the object. procedure Copy (Object : in Email_Ref; Into : in out Email_Ref) is Result : Email_Ref; begin if not Object.Is_Null then declare Impl : constant Email_Access := Email_Impl (Object.Get_Load_Object.all)'Access; Copy : constant Email_Access := new Email_Impl; begin ADO.Objects.Set_Object (Result, Copy.all'Access); Copy.Copy (Impl.all); Copy.Email := Impl.Email; Copy.Status := Impl.Status; Copy.Last_Error_Date := Impl.Last_Error_Date; Copy.Version := Impl.Version; Copy.User_Id := Impl.User_Id; end; end if; Into := Result; end Copy; procedure Find (Object : in out Email_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Impl : constant Email_Access := new Email_Impl; begin Impl.Find (Session, Query, Found); if Found then ADO.Objects.Set_Object (Object, Impl.all'Access); else ADO.Objects.Set_Object (Object, null); Destroy (Impl); end if; end Find; procedure Load (Object : in out Email_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier) is Impl : constant Email_Access := new Email_Impl; Found : Boolean; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); raise ADO.Objects.NOT_FOUND; end if; ADO.Objects.Set_Object (Object, Impl.all'Access); end Load; procedure Load (Object : in out Email_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean) is Impl : constant Email_Access := new Email_Impl; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); else ADO.Objects.Set_Object (Object, Impl.all'Access); end if; end Load; procedure Save (Object : in out Email_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl = null then Impl := new Email_Impl; ADO.Objects.Set_Object (Object, Impl); end if; if not ADO.Objects.Is_Created (Impl.all) then Impl.Create (Session); else Impl.Save (Session); end if; end Save; procedure Delete (Object : in out Email_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : constant ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl /= null then Impl.Delete (Session); end if; end Delete; -- -------------------- -- Free the object -- -------------------- procedure Destroy (Object : access Email_Impl) is type Email_Impl_Ptr is access all Email_Impl; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Email_Impl, Email_Impl_Ptr); pragma Warnings (Off, "*redundant conversion*"); Ptr : Email_Impl_Ptr := Email_Impl (Object.all)'Access; pragma Warnings (On, "*redundant conversion*"); begin Unchecked_Free (Ptr); end Destroy; procedure Find (Object : in out Email_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, EMAIL_DEF'Access); begin Stmt.Execute; if Stmt.Has_Elements then Object.Load (Stmt, Session); Stmt.Next; Found := not Stmt.Has_Elements; else Found := False; end if; end Find; overriding procedure Load (Object : in out Email_Impl; Session : in out ADO.Sessions.Session'Class) is Found : Boolean; Query : ADO.SQL.Query; Id : constant ADO.Identifier := Object.Get_Key_Value; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Object.Find (Session, Query, Found); if not Found then raise ADO.Objects.NOT_FOUND; end if; end Load; procedure Save (Object : in out Email_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Update_Statement := Session.Create_Statement (EMAIL_DEF'Access); begin if Object.Is_Modified (1) then Stmt.Save_Field (Name => COL_0_1_NAME, -- email Value => Object.Email); Object.Clear_Modified (1); end if; if Object.Is_Modified (2) then Stmt.Save_Field (Name => COL_1_1_NAME, -- status Value => Integer (MailDeliveryStatus'Pos (Object.Status))); Object.Clear_Modified (2); end if; if Object.Is_Modified (3) then Stmt.Save_Field (Name => COL_2_1_NAME, -- last_error_date Value => Object.Last_Error_Date); Object.Clear_Modified (3); end if; if Object.Is_Modified (5) then Stmt.Save_Field (Name => COL_4_1_NAME, -- id Value => Object.Get_Key); Object.Clear_Modified (5); end if; if Object.Is_Modified (6) then Stmt.Save_Field (Name => COL_5_1_NAME, -- user_id Value => Object.User_Id); Object.Clear_Modified (6); end if; if Stmt.Has_Save_Fields then Object.Version := Object.Version + 1; Stmt.Save_Field (Name => "version", Value => Object.Version); Stmt.Set_Filter (Filter => "id = ? and version = ?"); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Add_Param (Value => Object.Version - 1); declare Result : Integer; begin Stmt.Execute (Result); if Result /= 1 then if Result /= 0 then raise ADO.Objects.UPDATE_ERROR; else raise ADO.Objects.LAZY_LOCK; end if; end if; end; end if; end Save; procedure Create (Object : in out Email_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Query : ADO.Statements.Insert_Statement := Session.Create_Statement (EMAIL_DEF'Access); Result : Integer; begin Object.Version := 1; Query.Save_Field (Name => COL_0_1_NAME, -- email Value => Object.Email); Query.Save_Field (Name => COL_1_1_NAME, -- status Value => Integer (MailDeliveryStatus'Pos (Object.Status))); Query.Save_Field (Name => COL_2_1_NAME, -- last_error_date Value => Object.Last_Error_Date); Query.Save_Field (Name => COL_3_1_NAME, -- version Value => Object.Version); Session.Allocate (Id => Object); Query.Save_Field (Name => COL_4_1_NAME, -- id Value => Object.Get_Key); Query.Save_Field (Name => COL_5_1_NAME, -- user_id Value => Object.User_Id); Query.Execute (Result); if Result /= 1 then raise ADO.Objects.INSERT_ERROR; end if; ADO.Objects.Set_Created (Object); end Create; procedure Delete (Object : in out Email_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Delete_Statement := Session.Create_Statement (EMAIL_DEF'Access); begin Stmt.Set_Filter (Filter => "id = ?"); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Execute; end Delete; -- ------------------------------ -- Get the bean attribute identified by the name. -- ------------------------------ overriding function Get_Value (From : in Email_Ref; Name : in String) return Util.Beans.Objects.Object is Obj : ADO.Objects.Object_Record_Access; Impl : access Email_Impl; begin if From.Is_Null then return Util.Beans.Objects.Null_Object; end if; Obj := From.Get_Load_Object; Impl := Email_Impl (Obj.all)'Access; if Name = "email" then return Util.Beans.Objects.To_Object (Impl.Email); elsif Name = "status" then return AWA.Users.Models.MailDeliveryStatus_Objects.To_Object (Impl.Status); elsif Name = "last_error_date" then return Util.Beans.Objects.Time.To_Object (Impl.Last_Error_Date); elsif Name = "id" then return ADO.Objects.To_Object (Impl.Get_Key); elsif Name = "user_id" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.User_Id)); end if; return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Load the object from current iterator position -- ------------------------------ procedure Load (Object : in out Email_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class) is begin Object.Email := Stmt.Get_Unbounded_String (0); Object.Status := MailDeliveryStatus'Val (Stmt.Get_Integer (1)); Object.Last_Error_Date := Stmt.Get_Time (2); Object.Set_Key_Value (Stmt.Get_Identifier (4)); Object.User_Id := Stmt.Get_Identifier (5); Object.Version := Stmt.Get_Integer (3); ADO.Objects.Set_Created (Object); end Load; function User_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => USER_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end User_Key; function User_Key (Id : in String) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => USER_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end User_Key; function "=" (Left, Right : User_Ref'Class) return Boolean is begin return ADO.Objects.Object_Ref'Class (Left) = ADO.Objects.Object_Ref'Class (Right); end "="; procedure Set_Field (Object : in out User_Ref'Class; Impl : out User_Access) is Result : ADO.Objects.Object_Record_Access; begin Object.Prepare_Modify (Result); Impl := User_Impl (Result.all)'Access; end Set_Field; -- Internal method to allocate the Object_Record instance procedure Allocate (Object : in out User_Ref) is Impl : User_Access; begin Impl := new User_Impl; Impl.Version := 0; ADO.Objects.Set_Object (Object, Impl.all'Access); end Allocate; -- ---------------------------------------- -- Data object: User -- ---------------------------------------- procedure Set_First_Name (Object : in out User_Ref; Value : in String) is Impl : User_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 1, Impl.First_Name, Value); end Set_First_Name; procedure Set_First_Name (Object : in out User_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : User_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 1, Impl.First_Name, Value); end Set_First_Name; function Get_First_Name (Object : in User_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_First_Name); end Get_First_Name; function Get_First_Name (Object : in User_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant User_Access := User_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.First_Name; end Get_First_Name; procedure Set_Last_Name (Object : in out User_Ref; Value : in String) is Impl : User_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 2, Impl.Last_Name, Value); end Set_Last_Name; procedure Set_Last_Name (Object : in out User_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : User_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 2, Impl.Last_Name, Value); end Set_Last_Name; function Get_Last_Name (Object : in User_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_Last_Name); end Get_Last_Name; function Get_Last_Name (Object : in User_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant User_Access := User_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Last_Name; end Get_Last_Name; procedure Set_Password (Object : in out User_Ref; Value : in String) is Impl : User_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 3, Impl.Password, Value); end Set_Password; procedure Set_Password (Object : in out User_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : User_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 3, Impl.Password, Value); end Set_Password; function Get_Password (Object : in User_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_Password); end Get_Password; function Get_Password (Object : in User_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant User_Access := User_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Password; end Get_Password; procedure Set_Open_Id (Object : in out User_Ref; Value : in String) is Impl : User_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 4, Impl.Open_Id, Value); end Set_Open_Id; procedure Set_Open_Id (Object : in out User_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : User_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 4, Impl.Open_Id, Value); end Set_Open_Id; function Get_Open_Id (Object : in User_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_Open_Id); end Get_Open_Id; function Get_Open_Id (Object : in User_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant User_Access := User_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Open_Id; end Get_Open_Id; procedure Set_Country (Object : in out User_Ref; Value : in String) is Impl : User_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 5, Impl.Country, Value); end Set_Country; procedure Set_Country (Object : in out User_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : User_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 5, Impl.Country, Value); end Set_Country; function Get_Country (Object : in User_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_Country); end Get_Country; function Get_Country (Object : in User_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant User_Access := User_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Country; end Get_Country; procedure Set_Name (Object : in out User_Ref; Value : in String) is Impl : User_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 6, Impl.Name, Value); end Set_Name; procedure Set_Name (Object : in out User_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : User_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 6, Impl.Name, Value); end Set_Name; function Get_Name (Object : in User_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_Name); end Get_Name; function Get_Name (Object : in User_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant User_Access := User_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Name; end Get_Name; function Get_Version (Object : in User_Ref) return Integer is Impl : constant User_Access := User_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Version; end Get_Version; procedure Set_Id (Object : in out User_Ref; Value : in ADO.Identifier) is Impl : User_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Key_Value (Impl.all, 8, Value); end Set_Id; function Get_Id (Object : in User_Ref) return ADO.Identifier is Impl : constant User_Access := User_Impl (Object.Get_Object.all)'Access; begin return Impl.Get_Key_Value; end Get_Id; procedure Set_Salt (Object : in out User_Ref; Value : in String) is Impl : User_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 9, Impl.Salt, Value); end Set_Salt; procedure Set_Salt (Object : in out User_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : User_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 9, Impl.Salt, Value); end Set_Salt; function Get_Salt (Object : in User_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_Salt); end Get_Salt; function Get_Salt (Object : in User_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant User_Access := User_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Salt; end Get_Salt; procedure Set_Email (Object : in out User_Ref; Value : in AWA.Users.Models.Email_Ref'Class) is Impl : User_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Object (Impl.all, 10, Impl.Email, Value); end Set_Email; function Get_Email (Object : in User_Ref) return AWA.Users.Models.Email_Ref'Class is Impl : constant User_Access := User_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Email; end Get_Email; -- Copy of the object. procedure Copy (Object : in User_Ref; Into : in out User_Ref) is Result : User_Ref; begin if not Object.Is_Null then declare Impl : constant User_Access := User_Impl (Object.Get_Load_Object.all)'Access; Copy : constant User_Access := new User_Impl; begin ADO.Objects.Set_Object (Result, Copy.all'Access); Copy.Copy (Impl.all); Copy.First_Name := Impl.First_Name; Copy.Last_Name := Impl.Last_Name; Copy.Password := Impl.Password; Copy.Open_Id := Impl.Open_Id; Copy.Country := Impl.Country; Copy.Name := Impl.Name; Copy.Version := Impl.Version; Copy.Salt := Impl.Salt; Copy.Email := Impl.Email; end; end if; Into := Result; end Copy; procedure Find (Object : in out User_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Impl : constant User_Access := new User_Impl; begin Impl.Find (Session, Query, Found); if Found then ADO.Objects.Set_Object (Object, Impl.all'Access); else ADO.Objects.Set_Object (Object, null); Destroy (Impl); end if; end Find; procedure Load (Object : in out User_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier) is Impl : constant User_Access := new User_Impl; Found : Boolean; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); raise ADO.Objects.NOT_FOUND; end if; ADO.Objects.Set_Object (Object, Impl.all'Access); end Load; procedure Load (Object : in out User_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean) is Impl : constant User_Access := new User_Impl; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); else ADO.Objects.Set_Object (Object, Impl.all'Access); end if; end Load; procedure Save (Object : in out User_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl = null then Impl := new User_Impl; ADO.Objects.Set_Object (Object, Impl); end if; if not ADO.Objects.Is_Created (Impl.all) then Impl.Create (Session); else Impl.Save (Session); end if; end Save; procedure Delete (Object : in out User_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : constant ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl /= null then Impl.Delete (Session); end if; end Delete; -- -------------------- -- Free the object -- -------------------- procedure Destroy (Object : access User_Impl) is type User_Impl_Ptr is access all User_Impl; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (User_Impl, User_Impl_Ptr); pragma Warnings (Off, "*redundant conversion*"); Ptr : User_Impl_Ptr := User_Impl (Object.all)'Access; pragma Warnings (On, "*redundant conversion*"); begin Unchecked_Free (Ptr); end Destroy; procedure Find (Object : in out User_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, USER_DEF'Access); begin Stmt.Execute; if Stmt.Has_Elements then Object.Load (Stmt, Session); Stmt.Next; Found := not Stmt.Has_Elements; else Found := False; end if; end Find; overriding procedure Load (Object : in out User_Impl; Session : in out ADO.Sessions.Session'Class) is Found : Boolean; Query : ADO.SQL.Query; Id : constant ADO.Identifier := Object.Get_Key_Value; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Object.Find (Session, Query, Found); if not Found then raise ADO.Objects.NOT_FOUND; end if; end Load; procedure Save (Object : in out User_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Update_Statement := Session.Create_Statement (USER_DEF'Access); begin if Object.Is_Modified (1) then Stmt.Save_Field (Name => COL_0_2_NAME, -- first_name Value => Object.First_Name); Object.Clear_Modified (1); end if; if Object.Is_Modified (2) then Stmt.Save_Field (Name => COL_1_2_NAME, -- last_name Value => Object.Last_Name); Object.Clear_Modified (2); end if; if Object.Is_Modified (3) then Stmt.Save_Field (Name => COL_2_2_NAME, -- password Value => Object.Password); Object.Clear_Modified (3); end if; if Object.Is_Modified (4) then Stmt.Save_Field (Name => COL_3_2_NAME, -- open_id Value => Object.Open_Id); Object.Clear_Modified (4); end if; if Object.Is_Modified (5) then Stmt.Save_Field (Name => COL_4_2_NAME, -- country Value => Object.Country); Object.Clear_Modified (5); end if; if Object.Is_Modified (6) then Stmt.Save_Field (Name => COL_5_2_NAME, -- name Value => Object.Name); Object.Clear_Modified (6); end if; if Object.Is_Modified (8) then Stmt.Save_Field (Name => COL_7_2_NAME, -- id Value => Object.Get_Key); Object.Clear_Modified (8); end if; if Object.Is_Modified (9) then Stmt.Save_Field (Name => COL_8_2_NAME, -- salt Value => Object.Salt); Object.Clear_Modified (9); end if; if Object.Is_Modified (10) then Stmt.Save_Field (Name => COL_9_2_NAME, -- email_id Value => Object.Email); Object.Clear_Modified (10); end if; if Stmt.Has_Save_Fields then Object.Version := Object.Version + 1; Stmt.Save_Field (Name => "version", Value => Object.Version); Stmt.Set_Filter (Filter => "id = ? and version = ?"); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Add_Param (Value => Object.Version - 1); declare Result : Integer; begin Stmt.Execute (Result); if Result /= 1 then if Result /= 0 then raise ADO.Objects.UPDATE_ERROR; else raise ADO.Objects.LAZY_LOCK; end if; end if; end; end if; end Save; procedure Create (Object : in out User_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Query : ADO.Statements.Insert_Statement := Session.Create_Statement (USER_DEF'Access); Result : Integer; begin Object.Version := 1; Query.Save_Field (Name => COL_0_2_NAME, -- first_name Value => Object.First_Name); Query.Save_Field (Name => COL_1_2_NAME, -- last_name Value => Object.Last_Name); Query.Save_Field (Name => COL_2_2_NAME, -- password Value => Object.Password); Query.Save_Field (Name => COL_3_2_NAME, -- open_id Value => Object.Open_Id); Query.Save_Field (Name => COL_4_2_NAME, -- country Value => Object.Country); Query.Save_Field (Name => COL_5_2_NAME, -- name Value => Object.Name); Query.Save_Field (Name => COL_6_2_NAME, -- version Value => Object.Version); Session.Allocate (Id => Object); Query.Save_Field (Name => COL_7_2_NAME, -- id Value => Object.Get_Key); Query.Save_Field (Name => COL_8_2_NAME, -- salt Value => Object.Salt); Query.Save_Field (Name => COL_9_2_NAME, -- email_id Value => Object.Email); Query.Execute (Result); if Result /= 1 then raise ADO.Objects.INSERT_ERROR; end if; ADO.Objects.Set_Created (Object); end Create; procedure Delete (Object : in out User_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Delete_Statement := Session.Create_Statement (USER_DEF'Access); begin Stmt.Set_Filter (Filter => "id = ?"); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Execute; end Delete; -- ------------------------------ -- Get the bean attribute identified by the name. -- ------------------------------ overriding function Get_Value (From : in User_Ref; Name : in String) return Util.Beans.Objects.Object is Obj : ADO.Objects.Object_Record_Access; Impl : access User_Impl; begin if From.Is_Null then return Util.Beans.Objects.Null_Object; end if; Obj := From.Get_Load_Object; Impl := User_Impl (Obj.all)'Access; if Name = "first_name" then return Util.Beans.Objects.To_Object (Impl.First_Name); elsif Name = "last_name" then return Util.Beans.Objects.To_Object (Impl.Last_Name); elsif Name = "password" then return Util.Beans.Objects.To_Object (Impl.Password); elsif Name = "open_id" then return Util.Beans.Objects.To_Object (Impl.Open_Id); elsif Name = "country" then return Util.Beans.Objects.To_Object (Impl.Country); elsif Name = "name" then return Util.Beans.Objects.To_Object (Impl.Name); elsif Name = "id" then return ADO.Objects.To_Object (Impl.Get_Key); elsif Name = "salt" then return Util.Beans.Objects.To_Object (Impl.Salt); end if; return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Load the object from current iterator position -- ------------------------------ procedure Load (Object : in out User_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class) is begin Object.First_Name := Stmt.Get_Unbounded_String (0); Object.Last_Name := Stmt.Get_Unbounded_String (1); Object.Password := Stmt.Get_Unbounded_String (2); Object.Open_Id := Stmt.Get_Unbounded_String (3); Object.Country := Stmt.Get_Unbounded_String (4); Object.Name := Stmt.Get_Unbounded_String (5); Object.Set_Key_Value (Stmt.Get_Identifier (7)); Object.Salt := Stmt.Get_Unbounded_String (8); if not Stmt.Is_Null (9) then Object.Email.Set_Key_Value (Stmt.Get_Identifier (9), Session); end if; Object.Version := Stmt.Get_Integer (6); ADO.Objects.Set_Created (Object); end Load; function Access_Key_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => ACCESS_KEY_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Access_Key_Key; function Access_Key_Key (Id : in String) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => ACCESS_KEY_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Access_Key_Key; function "=" (Left, Right : Access_Key_Ref'Class) return Boolean is begin return ADO.Objects.Object_Ref'Class (Left) = ADO.Objects.Object_Ref'Class (Right); end "="; procedure Set_Field (Object : in out Access_Key_Ref'Class; Impl : out Access_Key_Access) is Result : ADO.Objects.Object_Record_Access; begin Object.Prepare_Modify (Result); Impl := Access_Key_Impl (Result.all)'Access; end Set_Field; -- Internal method to allocate the Object_Record instance procedure Allocate (Object : in out Access_Key_Ref) is Impl : Access_Key_Access; begin Impl := new Access_Key_Impl; Impl.Expire_Date := ADO.DEFAULT_TIME; Impl.Version := 0; Impl.Kind := AWA.Users.Models.Key_Type'First; ADO.Objects.Set_Object (Object, Impl.all'Access); end Allocate; -- ---------------------------------------- -- Data object: Access_Key -- ---------------------------------------- procedure Set_Access_Key (Object : in out Access_Key_Ref; Value : in String) is Impl : Access_Key_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 1, Impl.Access_Key, Value); end Set_Access_Key; procedure Set_Access_Key (Object : in out Access_Key_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : Access_Key_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 1, Impl.Access_Key, Value); end Set_Access_Key; function Get_Access_Key (Object : in Access_Key_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_Access_Key); end Get_Access_Key; function Get_Access_Key (Object : in Access_Key_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant Access_Key_Access := Access_Key_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Access_Key; end Get_Access_Key; procedure Set_Expire_Date (Object : in out Access_Key_Ref; Value : in Ada.Calendar.Time) is Impl : Access_Key_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Time (Impl.all, 2, Impl.Expire_Date, Value); end Set_Expire_Date; function Get_Expire_Date (Object : in Access_Key_Ref) return Ada.Calendar.Time is Impl : constant Access_Key_Access := Access_Key_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Expire_Date; end Get_Expire_Date; procedure Set_Id (Object : in out Access_Key_Ref; Value : in ADO.Identifier) is Impl : Access_Key_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Key_Value (Impl.all, 3, Value); end Set_Id; function Get_Id (Object : in Access_Key_Ref) return ADO.Identifier is Impl : constant Access_Key_Access := Access_Key_Impl (Object.Get_Object.all)'Access; begin return Impl.Get_Key_Value; end Get_Id; function Get_Version (Object : in Access_Key_Ref) return Integer is Impl : constant Access_Key_Access := Access_Key_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Version; end Get_Version; procedure Set_Kind (Object : in out Access_Key_Ref; Value : in AWA.Users.Models.Key_Type) is procedure Set_Field_Enum is new ADO.Objects.Set_Field_Operation (Key_Type); Impl : Access_Key_Access; begin Set_Field (Object, Impl); Set_Field_Enum (Impl.all, 5, Impl.Kind, Value); end Set_Kind; function Get_Kind (Object : in Access_Key_Ref) return AWA.Users.Models.Key_Type is Impl : constant Access_Key_Access := Access_Key_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Kind; end Get_Kind; procedure Set_User (Object : in out Access_Key_Ref; Value : in AWA.Users.Models.User_Ref'Class) is Impl : Access_Key_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Object (Impl.all, 6, Impl.User, Value); end Set_User; function Get_User (Object : in Access_Key_Ref) return AWA.Users.Models.User_Ref'Class is Impl : constant Access_Key_Access := Access_Key_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.User; end Get_User; -- Copy of the object. procedure Copy (Object : in Access_Key_Ref; Into : in out Access_Key_Ref) is Result : Access_Key_Ref; begin if not Object.Is_Null then declare Impl : constant Access_Key_Access := Access_Key_Impl (Object.Get_Load_Object.all)'Access; Copy : constant Access_Key_Access := new Access_Key_Impl; begin ADO.Objects.Set_Object (Result, Copy.all'Access); Copy.Copy (Impl.all); Copy.Access_Key := Impl.Access_Key; Copy.Expire_Date := Impl.Expire_Date; Copy.Version := Impl.Version; Copy.Kind := Impl.Kind; Copy.User := Impl.User; end; end if; Into := Result; end Copy; procedure Find (Object : in out Access_Key_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Impl : constant Access_Key_Access := new Access_Key_Impl; begin Impl.Find (Session, Query, Found); if Found then ADO.Objects.Set_Object (Object, Impl.all'Access); else ADO.Objects.Set_Object (Object, null); Destroy (Impl); end if; end Find; procedure Load (Object : in out Access_Key_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier) is Impl : constant Access_Key_Access := new Access_Key_Impl; Found : Boolean; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); raise ADO.Objects.NOT_FOUND; end if; ADO.Objects.Set_Object (Object, Impl.all'Access); end Load; procedure Load (Object : in out Access_Key_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean) is Impl : constant Access_Key_Access := new Access_Key_Impl; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); else ADO.Objects.Set_Object (Object, Impl.all'Access); end if; end Load; procedure Save (Object : in out Access_Key_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl = null then Impl := new Access_Key_Impl; ADO.Objects.Set_Object (Object, Impl); end if; if not ADO.Objects.Is_Created (Impl.all) then Impl.Create (Session); else Impl.Save (Session); end if; end Save; procedure Delete (Object : in out Access_Key_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : constant ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl /= null then Impl.Delete (Session); end if; end Delete; -- -------------------- -- Free the object -- -------------------- procedure Destroy (Object : access Access_Key_Impl) is type Access_Key_Impl_Ptr is access all Access_Key_Impl; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Access_Key_Impl, Access_Key_Impl_Ptr); pragma Warnings (Off, "*redundant conversion*"); Ptr : Access_Key_Impl_Ptr := Access_Key_Impl (Object.all)'Access; pragma Warnings (On, "*redundant conversion*"); begin Unchecked_Free (Ptr); end Destroy; procedure Find (Object : in out Access_Key_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, ACCESS_KEY_DEF'Access); begin Stmt.Execute; if Stmt.Has_Elements then Object.Load (Stmt, Session); Stmt.Next; Found := not Stmt.Has_Elements; else Found := False; end if; end Find; overriding procedure Load (Object : in out Access_Key_Impl; Session : in out ADO.Sessions.Session'Class) is Found : Boolean; Query : ADO.SQL.Query; Id : constant ADO.Identifier := Object.Get_Key_Value; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Object.Find (Session, Query, Found); if not Found then raise ADO.Objects.NOT_FOUND; end if; end Load; procedure Save (Object : in out Access_Key_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Update_Statement := Session.Create_Statement (ACCESS_KEY_DEF'Access); begin if Object.Is_Modified (1) then Stmt.Save_Field (Name => COL_0_3_NAME, -- access_key Value => Object.Access_Key); Object.Clear_Modified (1); end if; if Object.Is_Modified (2) then Stmt.Save_Field (Name => COL_1_3_NAME, -- expire_date Value => Object.Expire_Date); Object.Clear_Modified (2); end if; if Object.Is_Modified (3) then Stmt.Save_Field (Name => COL_2_3_NAME, -- id Value => Object.Get_Key); Object.Clear_Modified (3); end if; if Object.Is_Modified (5) then Stmt.Save_Field (Name => COL_4_3_NAME, -- kind Value => Integer (Key_Type'Pos (Object.Kind))); Object.Clear_Modified (5); end if; if Object.Is_Modified (6) then Stmt.Save_Field (Name => COL_5_3_NAME, -- user_id Value => Object.User); Object.Clear_Modified (6); end if; if Stmt.Has_Save_Fields then Object.Version := Object.Version + 1; Stmt.Save_Field (Name => "version", Value => Object.Version); Stmt.Set_Filter (Filter => "id = ? and version = ?"); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Add_Param (Value => Object.Version - 1); declare Result : Integer; begin Stmt.Execute (Result); if Result /= 1 then if Result /= 0 then raise ADO.Objects.UPDATE_ERROR; else raise ADO.Objects.LAZY_LOCK; end if; end if; end; end if; end Save; procedure Create (Object : in out Access_Key_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Query : ADO.Statements.Insert_Statement := Session.Create_Statement (ACCESS_KEY_DEF'Access); Result : Integer; begin Object.Version := 1; Query.Save_Field (Name => COL_0_3_NAME, -- access_key Value => Object.Access_Key); Query.Save_Field (Name => COL_1_3_NAME, -- expire_date Value => Object.Expire_Date); Session.Allocate (Id => Object); Query.Save_Field (Name => COL_2_3_NAME, -- id Value => Object.Get_Key); Query.Save_Field (Name => COL_3_3_NAME, -- version Value => Object.Version); Query.Save_Field (Name => COL_4_3_NAME, -- kind Value => Integer (Key_Type'Pos (Object.Kind))); Query.Save_Field (Name => COL_5_3_NAME, -- user_id Value => Object.User); Query.Execute (Result); if Result /= 1 then raise ADO.Objects.INSERT_ERROR; end if; ADO.Objects.Set_Created (Object); end Create; procedure Delete (Object : in out Access_Key_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Delete_Statement := Session.Create_Statement (ACCESS_KEY_DEF'Access); begin Stmt.Set_Filter (Filter => "id = ?"); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Execute; end Delete; -- ------------------------------ -- Get the bean attribute identified by the name. -- ------------------------------ overriding function Get_Value (From : in Access_Key_Ref; Name : in String) return Util.Beans.Objects.Object is Obj : ADO.Objects.Object_Record_Access; Impl : access Access_Key_Impl; begin if From.Is_Null then return Util.Beans.Objects.Null_Object; end if; Obj := From.Get_Load_Object; Impl := Access_Key_Impl (Obj.all)'Access; if Name = "access_key" then return Util.Beans.Objects.To_Object (Impl.Access_Key); elsif Name = "expire_date" then return Util.Beans.Objects.Time.To_Object (Impl.Expire_Date); elsif Name = "id" then return ADO.Objects.To_Object (Impl.Get_Key); elsif Name = "kind" then return AWA.Users.Models.Key_Type_Objects.To_Object (Impl.Kind); end if; return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Load the object from current iterator position -- ------------------------------ procedure Load (Object : in out Access_Key_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class) is begin Object.Access_Key := Stmt.Get_Unbounded_String (0); Object.Expire_Date := Stmt.Get_Time (1); Object.Set_Key_Value (Stmt.Get_Identifier (2)); Object.Kind := Key_Type'Val (Stmt.Get_Integer (4)); if not Stmt.Is_Null (5) then Object.User.Set_Key_Value (Stmt.Get_Identifier (5), Session); end if; Object.Version := Stmt.Get_Integer (3); ADO.Objects.Set_Created (Object); end Load; function Session_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => SESSION_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Session_Key; function Session_Key (Id : in String) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => SESSION_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Session_Key; function "=" (Left, Right : Session_Ref'Class) return Boolean is begin return ADO.Objects.Object_Ref'Class (Left) = ADO.Objects.Object_Ref'Class (Right); end "="; procedure Set_Field (Object : in out Session_Ref'Class; Impl : out Session_Access) is Result : ADO.Objects.Object_Record_Access; begin Object.Prepare_Modify (Result); Impl := Session_Impl (Result.all)'Access; end Set_Field; -- Internal method to allocate the Object_Record instance procedure Allocate (Object : in out Session_Ref) is Impl : Session_Access; begin Impl := new Session_Impl; Impl.Start_Date := ADO.DEFAULT_TIME; Impl.End_Date.Is_Null := True; Impl.Stype := AWA.Users.Models.Session_Type'First; Impl.Version := 0; Impl.Server_Id := 0; ADO.Objects.Set_Object (Object, Impl.all'Access); end Allocate; -- ---------------------------------------- -- Data object: Session -- ---------------------------------------- procedure Set_Start_Date (Object : in out Session_Ref; Value : in Ada.Calendar.Time) is Impl : Session_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Time (Impl.all, 1, Impl.Start_Date, Value); end Set_Start_Date; function Get_Start_Date (Object : in Session_Ref) return Ada.Calendar.Time is Impl : constant Session_Access := Session_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Start_Date; end Get_Start_Date; procedure Set_End_Date (Object : in out Session_Ref; Value : in ADO.Nullable_Time) is Impl : Session_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Time (Impl.all, 2, Impl.End_Date, Value); end Set_End_Date; function Get_End_Date (Object : in Session_Ref) return ADO.Nullable_Time is Impl : constant Session_Access := Session_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.End_Date; end Get_End_Date; procedure Set_Ip_Address (Object : in out Session_Ref; Value : in String) is Impl : Session_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 3, Impl.Ip_Address, Value); end Set_Ip_Address; procedure Set_Ip_Address (Object : in out Session_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : Session_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 3, Impl.Ip_Address, Value); end Set_Ip_Address; function Get_Ip_Address (Object : in Session_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_Ip_Address); end Get_Ip_Address; function Get_Ip_Address (Object : in Session_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant Session_Access := Session_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Ip_Address; end Get_Ip_Address; procedure Set_Stype (Object : in out Session_Ref; Value : in AWA.Users.Models.Session_Type) is procedure Set_Field_Enum is new ADO.Objects.Set_Field_Operation (Session_Type); Impl : Session_Access; begin Set_Field (Object, Impl); Set_Field_Enum (Impl.all, 4, Impl.Stype, Value); end Set_Stype; function Get_Stype (Object : in Session_Ref) return AWA.Users.Models.Session_Type is Impl : constant Session_Access := Session_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Stype; end Get_Stype; function Get_Version (Object : in Session_Ref) return Integer is Impl : constant Session_Access := Session_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Version; end Get_Version; procedure Set_Server_Id (Object : in out Session_Ref; Value : in Integer) is Impl : Session_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Integer (Impl.all, 6, Impl.Server_Id, Value); end Set_Server_Id; function Get_Server_Id (Object : in Session_Ref) return Integer is Impl : constant Session_Access := Session_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Server_Id; end Get_Server_Id; procedure Set_Id (Object : in out Session_Ref; Value : in ADO.Identifier) is Impl : Session_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Key_Value (Impl.all, 7, Value); end Set_Id; function Get_Id (Object : in Session_Ref) return ADO.Identifier is Impl : constant Session_Access := Session_Impl (Object.Get_Object.all)'Access; begin return Impl.Get_Key_Value; end Get_Id; procedure Set_Auth (Object : in out Session_Ref; Value : in AWA.Users.Models.Session_Ref'Class) is Impl : Session_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Object (Impl.all, 8, Impl.Auth, Value); end Set_Auth; function Get_Auth (Object : in Session_Ref) return AWA.Users.Models.Session_Ref'Class is Impl : constant Session_Access := Session_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Auth; end Get_Auth; procedure Set_User (Object : in out Session_Ref; Value : in AWA.Users.Models.User_Ref'Class) is Impl : Session_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Object (Impl.all, 9, Impl.User, Value); end Set_User; function Get_User (Object : in Session_Ref) return AWA.Users.Models.User_Ref'Class is Impl : constant Session_Access := Session_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.User; end Get_User; -- Copy of the object. procedure Copy (Object : in Session_Ref; Into : in out Session_Ref) is Result : Session_Ref; begin if not Object.Is_Null then declare Impl : constant Session_Access := Session_Impl (Object.Get_Load_Object.all)'Access; Copy : constant Session_Access := new Session_Impl; begin ADO.Objects.Set_Object (Result, Copy.all'Access); Copy.Copy (Impl.all); Copy.Start_Date := Impl.Start_Date; Copy.End_Date := Impl.End_Date; Copy.Ip_Address := Impl.Ip_Address; Copy.Stype := Impl.Stype; Copy.Version := Impl.Version; Copy.Server_Id := Impl.Server_Id; Copy.Auth := Impl.Auth; Copy.User := Impl.User; end; end if; Into := Result; end Copy; procedure Find (Object : in out Session_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Impl : constant Session_Access := new Session_Impl; begin Impl.Find (Session, Query, Found); if Found then ADO.Objects.Set_Object (Object, Impl.all'Access); else ADO.Objects.Set_Object (Object, null); Destroy (Impl); end if; end Find; procedure Load (Object : in out Session_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier) is Impl : constant Session_Access := new Session_Impl; Found : Boolean; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); raise ADO.Objects.NOT_FOUND; end if; ADO.Objects.Set_Object (Object, Impl.all'Access); end Load; procedure Load (Object : in out Session_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean) is Impl : constant Session_Access := new Session_Impl; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); else ADO.Objects.Set_Object (Object, Impl.all'Access); end if; end Load; procedure Save (Object : in out Session_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl = null then Impl := new Session_Impl; ADO.Objects.Set_Object (Object, Impl); end if; if not ADO.Objects.Is_Created (Impl.all) then Impl.Create (Session); else Impl.Save (Session); end if; end Save; procedure Delete (Object : in out Session_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : constant ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl /= null then Impl.Delete (Session); end if; end Delete; -- -------------------- -- Free the object -- -------------------- procedure Destroy (Object : access Session_Impl) is type Session_Impl_Ptr is access all Session_Impl; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Session_Impl, Session_Impl_Ptr); pragma Warnings (Off, "*redundant conversion*"); Ptr : Session_Impl_Ptr := Session_Impl (Object.all)'Access; pragma Warnings (On, "*redundant conversion*"); begin Unchecked_Free (Ptr); end Destroy; procedure Find (Object : in out Session_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, SESSION_DEF'Access); begin Stmt.Execute; if Stmt.Has_Elements then Object.Load (Stmt, Session); Stmt.Next; Found := not Stmt.Has_Elements; else Found := False; end if; end Find; overriding procedure Load (Object : in out Session_Impl; Session : in out ADO.Sessions.Session'Class) is Found : Boolean; Query : ADO.SQL.Query; Id : constant ADO.Identifier := Object.Get_Key_Value; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Object.Find (Session, Query, Found); if not Found then raise ADO.Objects.NOT_FOUND; end if; end Load; procedure Save (Object : in out Session_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Update_Statement := Session.Create_Statement (SESSION_DEF'Access); begin if Object.Is_Modified (1) then Stmt.Save_Field (Name => COL_0_4_NAME, -- start_date Value => Object.Start_Date); Object.Clear_Modified (1); end if; if Object.Is_Modified (2) then Stmt.Save_Field (Name => COL_1_4_NAME, -- end_date Value => Object.End_Date); Object.Clear_Modified (2); end if; if Object.Is_Modified (3) then Stmt.Save_Field (Name => COL_2_4_NAME, -- ip_address Value => Object.Ip_Address); Object.Clear_Modified (3); end if; if Object.Is_Modified (4) then Stmt.Save_Field (Name => COL_3_4_NAME, -- stype Value => Integer (Session_Type'Pos (Object.Stype))); Object.Clear_Modified (4); end if; if Object.Is_Modified (6) then Stmt.Save_Field (Name => COL_5_4_NAME, -- server_id Value => Object.Server_Id); Object.Clear_Modified (6); end if; if Object.Is_Modified (7) then Stmt.Save_Field (Name => COL_6_4_NAME, -- id Value => Object.Get_Key); Object.Clear_Modified (7); end if; if Object.Is_Modified (8) then Stmt.Save_Field (Name => COL_7_4_NAME, -- auth_id Value => Object.Auth); Object.Clear_Modified (8); end if; if Object.Is_Modified (9) then Stmt.Save_Field (Name => COL_8_4_NAME, -- user_id Value => Object.User); Object.Clear_Modified (9); end if; if Stmt.Has_Save_Fields then Object.Version := Object.Version + 1; Stmt.Save_Field (Name => "version", Value => Object.Version); Stmt.Set_Filter (Filter => "id = ? and version = ?"); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Add_Param (Value => Object.Version - 1); declare Result : Integer; begin Stmt.Execute (Result); if Result /= 1 then if Result /= 0 then raise ADO.Objects.UPDATE_ERROR; else raise ADO.Objects.LAZY_LOCK; end if; end if; end; end if; end Save; procedure Create (Object : in out Session_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Query : ADO.Statements.Insert_Statement := Session.Create_Statement (SESSION_DEF'Access); Result : Integer; begin Object.Version := 1; Query.Save_Field (Name => COL_0_4_NAME, -- start_date Value => Object.Start_Date); Query.Save_Field (Name => COL_1_4_NAME, -- end_date Value => Object.End_Date); Query.Save_Field (Name => COL_2_4_NAME, -- ip_address Value => Object.Ip_Address); Query.Save_Field (Name => COL_3_4_NAME, -- stype Value => Integer (Session_Type'Pos (Object.Stype))); Query.Save_Field (Name => COL_4_4_NAME, -- version Value => Object.Version); Query.Save_Field (Name => COL_5_4_NAME, -- server_id Value => Object.Server_Id); Session.Allocate (Id => Object); Query.Save_Field (Name => COL_6_4_NAME, -- id Value => Object.Get_Key); Query.Save_Field (Name => COL_7_4_NAME, -- auth_id Value => Object.Auth); Query.Save_Field (Name => COL_8_4_NAME, -- user_id Value => Object.User); Query.Execute (Result); if Result /= 1 then raise ADO.Objects.INSERT_ERROR; end if; ADO.Objects.Set_Created (Object); end Create; procedure Delete (Object : in out Session_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Delete_Statement := Session.Create_Statement (SESSION_DEF'Access); begin Stmt.Set_Filter (Filter => "id = ?"); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Execute; end Delete; -- ------------------------------ -- Get the bean attribute identified by the name. -- ------------------------------ overriding function Get_Value (From : in Session_Ref; Name : in String) return Util.Beans.Objects.Object is Obj : ADO.Objects.Object_Record_Access; Impl : access Session_Impl; begin if From.Is_Null then return Util.Beans.Objects.Null_Object; end if; Obj := From.Get_Load_Object; Impl := Session_Impl (Obj.all)'Access; if Name = "start_date" then return Util.Beans.Objects.Time.To_Object (Impl.Start_Date); elsif Name = "end_date" then if Impl.End_Date.Is_Null then return Util.Beans.Objects.Null_Object; else return Util.Beans.Objects.Time.To_Object (Impl.End_Date.Value); end if; elsif Name = "ip_address" then return Util.Beans.Objects.To_Object (Impl.Ip_Address); elsif Name = "stype" then return AWA.Users.Models.Session_Type_Objects.To_Object (Impl.Stype); elsif Name = "server_id" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Server_Id)); elsif Name = "id" then return ADO.Objects.To_Object (Impl.Get_Key); end if; return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Load the object from current iterator position -- ------------------------------ procedure Load (Object : in out Session_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class) is begin Object.Start_Date := Stmt.Get_Time (0); Object.End_Date := Stmt.Get_Time (1); Object.Ip_Address := Stmt.Get_Unbounded_String (2); Object.Stype := Session_Type'Val (Stmt.Get_Integer (3)); Object.Server_Id := Stmt.Get_Integer (5); Object.Set_Key_Value (Stmt.Get_Identifier (6)); if not Stmt.Is_Null (7) then Object.Auth.Set_Key_Value (Stmt.Get_Identifier (7), Session); end if; if not Stmt.Is_Null (8) then Object.User.Set_Key_Value (Stmt.Get_Identifier (8), Session); end if; Object.Version := Stmt.Get_Integer (4); ADO.Objects.Set_Created (Object); end Load; end AWA.Users.Models;
package body impact.d2.Joint.mouse is procedure dummy is begin null; end dummy; -- #include <Box2D/Dynamics/Joints/b2MouseJoint.h> -- #include <Box2D/Dynamics/b2Body.h> -- #include <Box2D/Dynamics/b2TimeStep.h> -- -- // p = attached point, m = mouse point -- // C = p - m -- // Cdot = v -- // = v + cross(w, r) -- // J = [I r_skew] -- // Identity used: -- // w k % (rx i + ry j) = w * (-ry i + rx j) -- -- b2MouseJoint::b2MouseJoint(const b2MouseJointDef* def) -- : b2Joint(def) -- { -- b2Assert(def->target.IsValid()); -- b2Assert(b2IsValid(def->maxForce) && def->maxForce >= 0.0f); -- b2Assert(b2IsValid(def->frequencyHz) && def->frequencyHz >= 0.0f); -- b2Assert(b2IsValid(def->dampingRatio) && def->dampingRatio >= 0.0f); -- -- m_target = def->target; -- m_localAnchor = b2MulT(m_bodyB->GetTransform(), m_target); -- -- m_maxForce = def->maxForce; -- m_impulse.SetZero(); -- -- m_frequencyHz = def->frequencyHz; -- m_dampingRatio = def->dampingRatio; -- -- m_beta = 0.0f; -- m_gamma = 0.0f; -- } -- -- void b2MouseJoint::SetTarget(const b2Vec2& target) -- { -- if (m_bodyB->IsAwake() == false) -- { -- m_bodyB->SetAwake(true); -- } -- m_target = target; -- } -- -- const b2Vec2& b2MouseJoint::GetTarget() const -- { -- return m_target; -- } -- -- void b2MouseJoint::SetMaxForce(float32 force) -- { -- m_maxForce = force; -- } -- -- float32 b2MouseJoint::GetMaxForce() const -- { -- return m_maxForce; -- } -- -- void b2MouseJoint::SetFrequency(float32 hz) -- { -- m_frequencyHz = hz; -- } -- -- float32 b2MouseJoint::GetFrequency() const -- { -- return m_frequencyHz; -- } -- -- void b2MouseJoint::SetDampingRatio(float32 ratio) -- { -- m_dampingRatio = ratio; -- } -- -- float32 b2MouseJoint::GetDampingRatio() const -- { -- return m_dampingRatio; -- } -- -- void b2MouseJoint::InitVelocityConstraints(const b2TimeStep& step) -- { -- b2Body* b = m_bodyB; -- -- float32 mass = b->GetMass(); -- -- // Frequency -- float32 omega = 2.0f * b2_pi * m_frequencyHz; -- -- // Damping coefficient -- float32 d = 2.0f * mass * m_dampingRatio * omega; -- -- // Spring stiffness -- float32 k = mass * (omega * omega); -- -- // magic formulas -- // gamma has units of inverse mass. -- // beta has units of inverse time. -- b2Assert(d + step.dt * k > b2_epsilon); -- m_gamma = step.dt * (d + step.dt * k); -- if (m_gamma != 0.0f) -- { -- m_gamma = 1.0f / m_gamma; -- } -- m_beta = step.dt * k * m_gamma; -- -- // Compute the effective mass matrix. -- b2Vec2 r = b2Mul(b->GetTransform().R, m_localAnchor - b->GetLocalCenter()); -- -- // K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)] -- // = [1/m1+1/m2 0 ] + invI1 * [r1.y*r1.y -r1.x*r1.y] + invI2 * [r1.y*r1.y -r1.x*r1.y] -- // [ 0 1/m1+1/m2] [-r1.x*r1.y r1.x*r1.x] [-r1.x*r1.y r1.x*r1.x] -- float32 invMass = b->m_invMass; -- float32 invI = b->m_invI; -- -- b2Mat22 K1; -- K1.col1.x = invMass; K1.col2.x = 0.0f; -- K1.col1.y = 0.0f; K1.col2.y = invMass; -- -- b2Mat22 K2; -- K2.col1.x = invI * r.y * r.y; K2.col2.x = -invI * r.x * r.y; -- K2.col1.y = -invI * r.x * r.y; K2.col2.y = invI * r.x * r.x; -- -- b2Mat22 K = K1 + K2; -- K.col1.x += m_gamma; -- K.col2.y += m_gamma; -- -- m_mass = K.GetInverse(); -- -- m_C = b->m_sweep.c + r - m_target; -- -- // Cheat with some damping -- b->m_angularVelocity *= 0.98f; -- -- // Warm starting. -- m_impulse *= step.dtRatio; -- b->m_linearVelocity += invMass * m_impulse; -- b->m_angularVelocity += invI * b2Cross(r, m_impulse); -- } -- -- void b2MouseJoint::SolveVelocityConstraints(const b2TimeStep& step) -- { -- b2Body* b = m_bodyB; -- -- b2Vec2 r = b2Mul(b->GetTransform().R, m_localAnchor - b->GetLocalCenter()); -- -- // Cdot = v + cross(w, r) -- b2Vec2 Cdot = b->m_linearVelocity + b2Cross(b->m_angularVelocity, r); -- b2Vec2 impulse = b2Mul(m_mass, -(Cdot + m_beta * m_C + m_gamma * m_impulse)); -- -- b2Vec2 oldImpulse = m_impulse; -- m_impulse += impulse; -- float32 maxImpulse = step.dt * m_maxForce; -- if (m_impulse.LengthSquared() > maxImpulse * maxImpulse) -- { -- m_impulse *= maxImpulse / m_impulse.Length(); -- } -- impulse = m_impulse - oldImpulse; -- -- b->m_linearVelocity += b->m_invMass * impulse; -- b->m_angularVelocity += b->m_invI * b2Cross(r, impulse); -- } -- -- b2Vec2 b2MouseJoint::GetAnchorA() const -- { -- return m_target; -- } -- -- b2Vec2 b2MouseJoint::GetAnchorB() const -- { -- return m_bodyB->GetWorldPoint(m_localAnchor); -- } -- -- b2Vec2 b2MouseJoint::GetReactionForce(float32 inv_dt) const -- { -- return inv_dt * m_impulse; -- } -- -- float32 b2MouseJoint::GetReactionTorque(float32 inv_dt) const -- { -- return inv_dt * 0.0f; -- } end impact.d2.Joint.mouse;
package body World is --------------- -- New_World -- --------------- function New_World (Size : Positive) return World_Grid is begin return World_Grid'(Size => Size, Grid1 => (others => (others => False)), Grid2 => (others => (others => False)), Step => 0); end; -------------- -- Get_Spot -- -------------- function Get_Spot (W : World_Grid; X, Y : Positive) return Boolean is begin if X not in 1 .. W.Size or Y not in 1 .. W.Size then return False; elsif W.Size mod 2 = 1 then return W.Grid1 (X, Y); else return W.Grid2 (X, Y); end if; end; -------------- -- Set_Spot -- -------------- procedure Set_Spot (W : in out World_Grid; X, Y : Positive; B : Boolean) is begin if W.Size mod 2 = 1 then W.Grid2 (X, Y) := B; else W.Grid1 (X, Y) := B; end if; end; -------------- -- Run_Step -- -------------- procedure Run_Step (W : in out World_Grid) is Count : Natural; begin W.Step := W.Step + 1; for X in Positive range 1 .. W.Size loop for Y in Positive range 1 .. W.Size loop Count := Live_Neighbors (W, X, Y); if Count < 2 then Set_Spot (W, X, Y, False); -- Underpopulation elsif Count = 2 then Set_Spot (W, X, Y, Get_Spot (W, X, Y)); -- Survival elsif Count = 3 then Set_Spot (W, X, Y, True); -- Reproduction elsif Count > 3 then Set_Spot (W, X, Y, False); -- Overpopulation end if; end loop; end loop; end; -------------------- -- Live_Neighbors -- -------------------- function Live_Neighbors (W : World_Grid; X, Y : Positive) return Natural is Count : Natural := 0; procedure Count_Neighbor (W : World_Grid; Count : in out Natural; X, Y : Positive) is begin if Get_Spot (W, X, Y) then Count := Count + 1; end if; end Count_Neighbor; begin Count_Neighbor (W, Count, X - 1, Y - 1); Count_Neighbor (W, Count, X, Y - 1); Count_Neighbor (W, Count, X + 1, Y - 1); Count_Neighbor (W, Count, X - 1, Y); Count_Neighbor (W, Count, X + 1, Y); Count_Neighbor (W, Count, X - 1, Y + 1); Count_Neighbor (W, Count, X, Y + 1); Count_Neighbor (W, Count, X + 1, Y + 1); return Count; end; end;
with Ada.Text_Io, Ada.Integer_Text_Io; use Ada.Text_Io, Ada.Integer_Text_Io; with vectores; use vectores; procedure escribir_vector (V : in Vector_De_Enteros) is --Pre: --Post: se han escrito en pantalla todos los valores de V -- begin for pos in V'First..V'Last loop put(V(pos), width => 3); end loop; new_line; end escribir_vector;
-- -- The author disclaims copyright to this source code. In place of -- a legal notice, here is a blessing: -- -- May you do good and not evil. -- May you find forgiveness for yourself and forgive others. -- May you share freely, not taking more than you give. -- with Ada.Text_IO; with Ada.Strings.Fixed; with Ada.Strings.Unbounded; with Ada.Directories; with Setup; with Auxiliary; with Symbols; with Types; package body Generate_C is procedure Open_Template (Context : in out Context_Type; User_Template : in String; File_Name : in String; Error_Count : in out Integer) is use Ada.Text_IO; use Ada.Strings.Unbounded; Default_Template : String renames Setup.Default_Template_C; Template_Name : Unbounded_String; begin -- First, see if user specified a template filename on the command line. if User_Template /= "" then -- Eksisterer den angivede template fil if not Ada.Directories.Exists (User_Template) then Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Error, "Can not find the parser driver template file '" & User_Template & "'."); Error_Count := Error_Count + 1; Template_Name := Null_Unbounded_String; return; end if; -- Can User_Template open. begin Open (Context.File_Template, In_File, User_Template); exception when others => -- No it could not open User_Template. Put_Line (Standard_Error, "Can not open the template file '" & User_Template & "'."); Error_Count := Error_Count + 1; Template_Name := Null_Unbounded_String; return; end; return; -- User template open with success. end if; -- No user template. declare use Ada.Strings.Fixed; Point : constant Natural := Index (File_Name, "."); Buf : Unbounded_String; begin if Point = 0 then Buf := To_Unbounded_String (File_Name & ".lt"); else Buf := To_Unbounded_String (File_Name & ".lt"); -- XXX end if; if Ada.Directories.Exists (To_String (Buf)) then Template_Name := Buf; elsif Ada.Directories.Exists (Default_Template) then Template_Name := To_Unbounded_String (Default_Template); -- else -- null; -- Template_Name := Pathsearch (Lemp.Argv0, Templatename, 0); end if; end; if Template_Name = Null_Unbounded_String then Put_Line (Standard_Error, "Can not find then parser driver template file '" & To_String (Template_Name) & "'."); Error_Count := Error_Count + 1; return; end if; begin Open (Context.File_Template, In_File, To_String (Template_Name)); exception when others => Put_Line (Standard_Error, "Can not open then template file '" & To_String (Template_Name) & "."); Error_Count := Error_Count + 1; return; end; end Open_Template; Header_Extension : constant String := ".h"; procedure Generate_Spec (Session : in Sessions.Session_Type; Context : in out Context_Type; File_Name : in String; Module : in String; Prefix : in String; First : in Integer; Last : in Integer) is pragma Unreferenced (Session, Context, Module); package Integer_IO is new Ada.Text_IO.Integer_IO (Num => Integer); use Ada.Text_IO, Auxiliary; use Symbols; File : File_Type; begin Recreate (File, Out_File, File_Name & Header_Extension); for I in First .. Last - 1 loop declare Symbol : constant String := Prefix & Name_Of (Element_At (Types.Symbol_Index (I))); begin Put (File, "#define "); Put (File, Symbol); Set_Col (File, 40); Integer_IO.Put (File, I, Width => 6); New_Line (File); end; end loop; Close (File); end Generate_Spec; end Generate_C;