repo_name
stringlengths
9
74
language
stringclasses
1 value
length_bytes
int64
11
9.34M
extension
stringclasses
2 values
content
stringlengths
11
9.34M
Fabien-Chouteau/samd51-hal
Ada
5,568
ads
pragma Style_Checks (Off); -- This spec has been automatically generated from ATSAMD51G19A.svd pragma Restrictions (No_Elaboration_Code); with HAL; with System; package SAM_SVD.SysTick is pragma Preelaborate; --------------- -- Registers -- --------------- -- SysTick Counter Enable type CSR_ENABLESelect is (-- Counter disabled VALUE_0, -- Counter enabled VALUE_1) with Size => 1; for CSR_ENABLESelect use (VALUE_0 => 0, VALUE_1 => 1); -- SysTick Exception Request Enable type CSR_TICKINTSelect is (-- Counting down to 0 does not assert the SysTick exception request VALUE_0, -- Counting down to 0 asserts the SysTick exception request VALUE_1) with Size => 1; for CSR_TICKINTSelect use (VALUE_0 => 0, VALUE_1 => 1); -- Clock Source 0=external, 1=processor type CSR_CLKSOURCESelect is (-- External clock VALUE_0, -- Processor clock VALUE_1) with Size => 1; for CSR_CLKSOURCESelect use (VALUE_0 => 0, VALUE_1 => 1); -- SysTick Control and Status Register type SysTick_CSR_Register is record -- SysTick Counter Enable ENABLE : CSR_ENABLESelect := SAM_SVD.SysTick.VALUE_0; -- SysTick Exception Request Enable TICKINT : CSR_TICKINTSelect := SAM_SVD.SysTick.VALUE_0; -- Clock Source 0=external, 1=processor CLKSOURCE : CSR_CLKSOURCESelect := SAM_SVD.SysTick.VALUE_1; -- unspecified Reserved_3_15 : HAL.UInt13 := 16#0#; -- Timer counted to 0 since last read of register COUNTFLAG : Boolean := False; -- unspecified Reserved_17_31 : HAL.UInt15 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for SysTick_CSR_Register use record ENABLE at 0 range 0 .. 0; TICKINT at 0 range 1 .. 1; CLKSOURCE at 0 range 2 .. 2; Reserved_3_15 at 0 range 3 .. 15; COUNTFLAG at 0 range 16 .. 16; Reserved_17_31 at 0 range 17 .. 31; end record; subtype SysTick_RVR_RELOAD_Field is HAL.UInt24; -- SysTick Reload Value Register type SysTick_RVR_Register is record -- Value to load into the SysTick Current Value Register when the -- counter reaches 0 RELOAD : SysTick_RVR_RELOAD_Field := 16#0#; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for SysTick_RVR_Register use record RELOAD at 0 range 0 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype SysTick_CVR_CURRENT_Field is HAL.UInt24; -- SysTick Current Value Register type SysTick_CVR_Register is record -- Current value at the time the register is accessed CURRENT : SysTick_CVR_CURRENT_Field := 16#0#; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for SysTick_CVR_Register use record CURRENT at 0 range 0 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype SysTick_CALIB_TENMS_Field is HAL.UInt24; -- TENMS is rounded from non-integer ratio type CALIB_SKEWSelect is (-- 10ms calibration value is exact VALUE_0, -- 10ms calibration value is inexact, because of the clock frequency VALUE_1) with Size => 1; for CALIB_SKEWSelect use (VALUE_0 => 0, VALUE_1 => 1); -- No Separate Reference Clock type CALIB_NOREFSelect is (-- The reference clock is provided VALUE_0, -- The reference clock is not provided VALUE_1) with Size => 1; for CALIB_NOREFSelect use (VALUE_0 => 0, VALUE_1 => 1); -- SysTick Calibration Value Register type SysTick_CALIB_Register is record -- Read-only. Reload value to use for 10ms timing TENMS : SysTick_CALIB_TENMS_Field; -- unspecified Reserved_24_29 : HAL.UInt6; -- Read-only. TENMS is rounded from non-integer ratio SKEW : CALIB_SKEWSelect; -- Read-only. No Separate Reference Clock NOREF : CALIB_NOREFSelect; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for SysTick_CALIB_Register use record TENMS at 0 range 0 .. 23; Reserved_24_29 at 0 range 24 .. 29; SKEW at 0 range 30 .. 30; NOREF at 0 range 31 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- System timer type SysTick_Peripheral is record -- SysTick Control and Status Register CSR : aliased SysTick_CSR_Register; -- SysTick Reload Value Register RVR : aliased SysTick_RVR_Register; -- SysTick Current Value Register CVR : aliased SysTick_CVR_Register; -- SysTick Calibration Value Register CALIB : aliased SysTick_CALIB_Register; end record with Volatile; for SysTick_Peripheral use record CSR at 16#0# range 0 .. 31; RVR at 16#4# range 0 .. 31; CVR at 16#8# range 0 .. 31; CALIB at 16#C# range 0 .. 31; end record; -- System timer SysTick_Periph : aliased SysTick_Peripheral with Import, Address => SysTick_Base; end SAM_SVD.SysTick;
AdaCore/libadalang
Ada
246
adb
procedure Gen_Pragma is generic pragma Warnings (Off); type T is private; pragma Warnings (On); package Gen is end Gen; package My_Pkg is new Gen (Integer); --% node.p_inst_params begin null; end Gen_Pragma;
zhmu/ananas
Ada
6,382
ads
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- A D A . I N T E R R U P T S . N A M E S -- -- -- -- S p e c -- -- -- -- Copyright (C) 1991-2022, 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 is a QNX version of this package -- The pragma Unreserve_All_Interrupts affects the following signal(s): -- SIGINT: made available for Ada handler -- This target-dependent package spec contains names of interrupts -- supported by the local system. with System.OS_Interface; package Ada.Interrupts.Names is -- All identifiers in this unit are implementation defined pragma Implementation_Defined; -- Beware that the mapping of names to signals may be many-to-one. There -- may be aliases. Also, for all signal names that are not supported on the -- current system the value of the corresponding constant will be zero. SIGHUP : constant Interrupt_ID := System.OS_Interface.SIGHUP; -- hangup SIGINT : constant Interrupt_ID := System.OS_Interface.SIGINT; -- interrupt (rubout) SIGQUIT : constant Interrupt_ID := System.OS_Interface.SIGQUIT; -- quit (ASCD FS) SIGILL : constant Interrupt_ID := System.OS_Interface.SIGILL; -- illegal instruction (not reset) SIGTRAP : constant Interrupt_ID := System.OS_Interface.SIGTRAP; -- trace trap (not reset) SIGIOT : constant Interrupt_ID := System.OS_Interface.SIGIOT; -- IOT instruction SIGABRT : constant Interrupt_ID := -- used by abort, System.OS_Interface.SIGABRT; -- replace SIGIOT in the future SIGFPE : constant Interrupt_ID := System.OS_Interface.SIGFPE; -- floating point exception SIGKILL : constant Interrupt_ID := System.OS_Interface.SIGKILL; -- kill (cannot be caught or ignored) SIGBUS : constant Interrupt_ID := System.OS_Interface.SIGBUS; -- bus error SIGSEGV : constant Interrupt_ID := System.OS_Interface.SIGSEGV; -- segmentation violation SIGPIPE : constant Interrupt_ID := -- write on a pipe with System.OS_Interface.SIGPIPE; -- no one to read it SIGALRM : constant Interrupt_ID := System.OS_Interface.SIGALRM; -- alarm clock SIGTERM : constant Interrupt_ID := System.OS_Interface.SIGTERM; -- software termination signal from kill SIGUSR1 : constant Interrupt_ID := System.OS_Interface.SIGUSR1; -- user defined signal 1 SIGUSR2 : constant Interrupt_ID := System.OS_Interface.SIGUSR2; -- user defined signal 2 SIGCLD : constant Interrupt_ID := System.OS_Interface.SIGCLD; -- child status change SIGCHLD : constant Interrupt_ID := System.OS_Interface.SIGCHLD; -- 4.3BSD's/POSIX name for SIGCLD SIGWINCH : constant Interrupt_ID := System.OS_Interface.SIGWINCH; -- window size change SIGURG : constant Interrupt_ID := System.OS_Interface.SIGURG; -- urgent condition on IO channel SIGPOLL : constant Interrupt_ID := System.OS_Interface.SIGPOLL; -- pollable event occurred SIGIO : constant Interrupt_ID := -- input/output possible, System.OS_Interface.SIGIO; -- SIGPOLL alias (Solaris) SIGSTOP : constant Interrupt_ID := System.OS_Interface.SIGSTOP; -- stop (cannot be caught or ignored) SIGTSTP : constant Interrupt_ID := System.OS_Interface.SIGTSTP; -- user stop requested from tty SIGCONT : constant Interrupt_ID := System.OS_Interface.SIGCONT; -- stopped process has been continued SIGTTIN : constant Interrupt_ID := System.OS_Interface.SIGTTIN; -- background tty read attempted SIGTTOU : constant Interrupt_ID := System.OS_Interface.SIGTTOU; -- background tty write attempted SIGVTALRM : constant Interrupt_ID := System.OS_Interface.SIGVTALRM; -- virtual timer expired SIGPROF : constant Interrupt_ID := System.OS_Interface.SIGPROF; -- profiling timer expired SIGXCPU : constant Interrupt_ID := System.OS_Interface.SIGXCPU; -- CPU time limit exceeded SIGXFSZ : constant Interrupt_ID := System.OS_Interface.SIGXFSZ; -- filesize limit exceeded end Ada.Interrupts.Names;
vpodzime/ada-util
Ada
3,974
adb
----------------------------------------------------------------------- -- events-channel -- Event Channels -- Copyright (C) 2001, 2002, 2003, 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; package body Util.Events.Channels is use Containers; use Ada.Strings.Unbounded; use Util.Strings; type Factory_Line is record Name : Name_Access; Creator : Channel_Creator; end record; type Factory_Table is array (Natural range <>) of Factory_Line; DIRECT_NAME : aliased constant String := "direct"; Factory : constant Factory_Table (1 .. 1) := (1 => (Name => DIRECT_NAME'Access, Creator => Create_Direct_Channel'Access)); -- ----------------------- -- Get the name of this event channel. -- ----------------------- function Get_Name (C : Channel) return String is begin return To_String (C.Name); end Get_Name; -- ----------------------- -- Post an event and dispatch it immediately. -- ----------------------- procedure Post (To : in out Channel; Item : in Event'Class) is Iter : Cursor := First (To.Clients); begin -- Dispatch_One makes the connection between the common implementation -- and the generics while Has_Element (Iter) loop declare Client : constant Subscriber_Access := Element (Iter); begin Client.Receive_Event (Item); end; Iter := Next (Iter); end loop; end Post; -- ----------------------- -- Subscribe to events sent on the event channel. -- ----------------------- procedure Subscribe (To : in out Channel; Client : in Subscriber_Access) is begin pragma Assert (Client /= null, "Client subscriber must not be null"); Append (To.Clients, Client); end Subscribe; -- ----------------------- -- Unsubscribe to events sent on the event channel. -- ----------------------- procedure Unsubscribe (To : in out Channel; Client : in Subscriber_Access) is Iter : Cursor := First (To.Clients); begin while Has_Element (Iter) loop if Element (Iter) = Client then Delete (To.Clients, Iter); return; end if; Iter := Next (Iter); end loop; end Unsubscribe; -- ----------------------- -- Create an event channel with the given name. The type of channel -- is controlled by <b>Kind</b>. -- ----------------------- function Create (Name : String; Kind : String) return Channel_Access is begin for I in Factory'Range loop if Factory (I).Name.all = Kind then return Factory (I).Creator (Name); end if; end loop; return Create_Direct_Channel (Name); end Create; -- ----------------------- -- Create an event channel that post the event immediately. -- ----------------------- function Create_Direct_Channel (Name : String) return Channel_Access is Result : constant Channel_Access := new Channel; begin Result.Name := To_Unbounded_String (Name); return Result; end Create_Direct_Channel; end Util.Events.Channels;
Rodeo-McCabe/orka
Ada
3,701
ads
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- 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.Streams; with Ada.Strings.Hash; with GL.Low_Level.Enums; with GL.Objects.Textures; with GL.Pixels; with GL.Types; with Orka.Resources; private package Orka.KTX is pragma Preelaborate; package String_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => String, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); use GL.Low_Level.Enums; use type GL.Types.Size; type Header (Compressed : Boolean) is record Kind : GL.Low_Level.Enums.Texture_Kind; Width : GL.Types.Size; Height : GL.Types.Size; Depth : GL.Types.Size; Array_Elements : GL.Types.Size; Mipmap_Levels : GL.Objects.Textures.Mipmap_Level; Bytes_Key_Value : GL.Types.Size; case Compressed is when True => Compressed_Format : GL.Pixels.Compressed_Format; when False => Data_Type : GL.Pixels.Data_Type; Format : GL.Pixels.Format; Internal_Format : GL.Pixels.Internal_Format; end case; end record with Dynamic_Predicate => Header.Width > 0 and not (Header.Height = 0 and Header.Depth > 0) and (if Header.Compressed then Header.Mipmap_Levels > 0) and (case Header.Kind is when Texture_1D | Texture_2D | Texture_3D => Header.Array_Elements = 0, when Texture_Cube_Map => Header.Array_Elements = 0, when others => Header.Array_Elements > 0) and (case Header.Kind is when Texture_1D | Texture_1D_Array => Header.Height = 0, when Texture_2D | Texture_2D_Array => Header.Height > 0 and Header.Depth = 0, when Texture_3D => Header.Depth > 0, when Texture_Cube_Map => Header.Width = Header.Height and Header.Depth = 0, when Texture_Cube_Map_Array => Header.Width = Header.Height and Header.Depth = 0, when others => raise Constraint_Error); subtype Bytes_Reference is Resources.Byte_Array_Pointers.Constant_Reference; function Valid_Identifier (Bytes : Bytes_Reference) return Boolean; function Get_Header (Bytes : Bytes_Reference) return Header; function Get_Key_Value_Map (Bytes : Bytes_Reference; Length : GL.Types.Size) return String_Maps.Map; function Get_Length (Bytes : Bytes_Reference; Offset : Ada.Streams.Stream_Element_Offset) return Natural; function Get_Data_Offset (Bytes : Bytes_Reference; Bytes_Key_Value : GL.Types.Size) return Ada.Streams.Stream_Element_Offset; Invalid_Enum_Error : exception; function Create_KTX_Bytes (KTX_Header : Header; Get_Data : not null access function (Level : GL.Objects.Textures.Mipmap_Level) return Resources.Byte_Array_Pointers.Pointer) return Resources.Byte_Array_Pointers.Pointer; end Orka.KTX;
usnistgov/rcslib
Ada
3,122
adb
with Nml; with Nml_Msg; with Nml_Test_Format_N_Ada; use Nml_Test_Format_N_Ada; with Ada.Text_IO; with Ada.Integer_Text_IO; with Unchecked_Conversion; with Interfaces.C; use Interfaces.C; with Ada.Command_Line; procedure Nml_Test_Dl_Write_Ada is Connection1 : Nml.NmlConnection_Access; Tst_Msg : Nml_Test_Format_N_Ada.Test_Message_Access; Ok : Integer := 0; begin if Ada.Command_Line.Argument_Count < 4 then Ada.Text_IO.Put("usage: buffername processname cfgsource lastvar"); Ada.Text_IO.New_Line; Ada.Command_Line.Set_Exit_Status(Ada.Command_Line.Failure); return; end if; Connection1 := Nml.CreateConnection(Nml_Test_Format_N_Ada.Format'Access, Ada.Command_Line.Argument(1), Ada.Command_Line.Argument(2), Ada.Command_Line.Argument(3)); if True /= Nml.Valid(Connection1) then Nml.Free(Connection1); Ada.Command_Line.Set_Exit_Status(Ada.Command_Line.Failure); return; end if; Tst_Msg := new Nml_Test_Format_N_Ada.Test_Message; Tst_Msg.I := 67; Tst_Msg.Ia(1) := 61; Tst_Msg.Ia(4) := 64; Tst_Msg.Ida_Length := 3; Tst_Msg.Ida(1) := 51; Tst_Msg.Ida(3) := 53; Tst_Msg.Ida(4) := 54; Tst_Msg.Ida(8) := 58; -- These will be sent. Tst_Msg.etd := xxx; Tst_Msg.etd2 := uuu; Tst_Msg.enumtestvar := aa; Tst_Msg.enumtestvar := aa; Tst_Msg.Enum_Array(1) := aa; Tst_Msg.Enum_Array(2) := bb; Tst_Msg.Enum_Array(3) := bb; Tst_Msg.Enum_Array(4) := bb; Tst_Msg.Enum_Array(5) := bb; Tst_Msg.enumtest_dla_length := 3; Tst_Msg.Enumtest_Dla(1) := aa; Tst_Msg.Enumtest_Dla(2) := bb; Tst_Msg.Enumtest_Dla(3) := aa; -- These will NOT be sent. Tst_Msg.Enumtest_Dla(4) := bb; Tst_Msg.Enumtest_Dla(5) := aa; Tst_Msg.Enumtest_Dla(6) := bb; Tst_Msg.Enumtest_Dla(7) := aa; -- These will be sent. Tst_Msg.f := -(1.0E-37); Tst_Msg.Three_D_Array(Tst_Msg.Three_D_Array'Last) := 3.33; Tst_Msg.cda_length := 3; Tst_Msg.Cda(1) := '0'; Tst_Msg.Cda(2) := '1'; Tst_Msg.Cda(3) := nul; -- This string will NOT be sent. Tst_Msg.Cda(4) := '2'; Tst_Msg.Cda(5) := '3'; Tst_Msg.Cda(6) := '4'; Tst_Msg.Cda(7) := '5'; Tst_Msg.Cda(8) := nul; -- This will be sent. Tst_Msg.sda_length:=1; Tst_Msg.Sda(1).c:= 'x'; -- This will NOT be sent. Tst_Msg.Sda(2).c := 'y'; -- Skip the Test some integer length features. Tst_Msg.do_int_size_test:=False; Tst_Msg.dda_length:=0; Tst_Msg.false_bool :=False; Tst_Msg.true_bool:=True; Tst_Msg.sminusone := -1; Tst_Msg.iminusone := -1; Tst_Msg.lminusone := -1; Tst_Msg.fminusone := -1.0; Tst_Msg.dminusone := -1.0; -- This will be sent. Tst_Msg.lastvar:= Interfaces.C.Long'Value(Ada.Command_Line.Argument(4)); Ok := Nml.Write(Connection1,Nml_Msg.NmlMsg_Access(Tst_Msg)); Nml.Free(Connection1); Nml_Test_Format_N_Ada.Free(Tst_Msg); if 0 /= Ok then Ada.Command_Line.Set_Exit_Status(Ada.Command_Line.Failure); end if; end Nml_Test_Dl_Write_Ada;
sungyeon/drake
Ada
2,147
adb
with System.Address_To_Constant_Access_Conversions; with System.Address_To_Named_Access_Conversions; package body System.Zero_Terminated_Strings is pragma Suppress (All_Checks); use type C.size_t; function strlen (s : not null access constant C.char) return C.size_t with Import, Convention => Intrinsic, External_Name => "__builtin_strlen"; procedure memcpy (s1, s2 : Address; n : C.size_t) with Import, Convention => Intrinsic, External_Name => "__builtin_memcpy"; -- implementation function Value (Item : not null access constant C.char) return String is begin return Value (Item, strlen (Item)); end Value; function Value (Item : not null access constant C.char; Length : C.size_t) return String is type char_const_ptr is access constant C.char -- local type with Convention => C; for char_const_ptr'Storage_Size use 0; package Conv is new Address_To_Constant_Access_Conversions (C.char, char_const_ptr); Item_All : String (1 .. Natural (Length)); for Item_All'Address use Conv.To_Address (char_const_ptr (Item)); begin return Item_All; end Value; procedure To_C (Source : String; Result : not null access C.char) is Dummy : C.size_t; begin To_C (Source, Result, Dummy); end To_C; procedure To_C ( Source : String; Result : not null access C.char; Result_Length : out C.size_t) is begin -- Source and Result should not be overlapped Result_Length := Source'Length; declare type char_ptr is access all C.char -- local type with Convention => C; for char_ptr'Storage_Size use 0; package Conv is new Address_To_Named_Access_Conversions (C.char, char_ptr); Result_All : aliased C.char_array (0 .. Result_Length); for Result_All'Address use Conv.To_Address (char_ptr (Result)); begin memcpy (Result_All'Address, Source'Address, Result_Length); Result_All (Result_Length) := C.char'Val (0); end; end To_C; end System.Zero_Terminated_Strings;
AdaCore/libadalang
Ada
307,927
adb
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- E X P _ A G G R -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2016, 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. -- -- -- ------------------------------------------------------------------------------ with Atree; use Atree; with Checks; use Checks; with Debug; use Debug; with Einfo; use Einfo; with Elists; use Elists; with Errout; use Errout; with Expander; use Expander; with Exp_Util; use Exp_Util; with Exp_Ch3; use Exp_Ch3; with Exp_Ch6; use Exp_Ch6; with Exp_Ch7; use Exp_Ch7; with Exp_Ch9; use Exp_Ch9; with Exp_Disp; use Exp_Disp; with Exp_Tss; use Exp_Tss; with Fname; use Fname; with Freeze; use Freeze; with Itypes; use Itypes; with Lib; use Lib; with Namet; use Namet; with Nmake; use Nmake; with Nlists; use Nlists; with Opt; use Opt; with Restrict; use Restrict; with Rident; use Rident; with Rtsfind; use Rtsfind; with Ttypes; use Ttypes; with Sem; use Sem; with Sem_Aggr; use Sem_Aggr; with Sem_Aux; use Sem_Aux; with Sem_Ch3; use Sem_Ch3; with Sem_Eval; use Sem_Eval; with Sem_Res; use Sem_Res; with Sem_Util; use Sem_Util; with Sinfo; use Sinfo; with Snames; use Snames; with Stand; use Stand; with Stringt; use Stringt; with Targparm; use Targparm; with Tbuild; use Tbuild; with Uintp; use Uintp; package body Exp_Aggr is type Case_Bounds is record Choice_Lo : Node_Id; Choice_Hi : Node_Id; Choice_Node : Node_Id; end record; type Case_Table_Type is array (Nat range <>) of Case_Bounds; -- Table type used by Check_Case_Choices procedure procedure Collect_Initialization_Statements (Obj : Entity_Id; N : Node_Id; Node_After : Node_Id); -- If Obj is not frozen, collect actions inserted after N until, but not -- including, Node_After, for initialization of Obj, and move them to an -- expression with actions, which becomes the Initialization_Statements for -- Obj. procedure Expand_Delta_Array_Aggregate (N : Node_Id; Deltas : List_Id); procedure Expand_Delta_Record_Aggregate (N : Node_Id; Deltas : List_Id); function Has_Default_Init_Comps (N : Node_Id) return Boolean; -- N is an aggregate (record or array). Checks the presence of default -- initialization (<>) in any component (Ada 2005: AI-287). function In_Object_Declaration (N : Node_Id) return Boolean; -- Return True if N is part of an object declaration, False otherwise function Is_Static_Dispatch_Table_Aggregate (N : Node_Id) return Boolean; -- Returns true if N is an aggregate used to initialize the components -- of a statically allocated dispatch table. function Late_Expansion (N : Node_Id; Typ : Entity_Id; Target : Node_Id) return List_Id; -- This routine implements top-down expansion of nested aggregates. In -- doing so, it avoids the generation of temporaries at each level. N is -- a nested record or array aggregate with the Expansion_Delayed flag. -- Typ is the expected type of the aggregate. Target is a (duplicatable) -- expression that will hold the result of the aggregate expansion. function Make_OK_Assignment_Statement (Sloc : Source_Ptr; Name : Node_Id; Expression : Node_Id) return Node_Id; -- This is like Make_Assignment_Statement, except that Assignment_OK -- is set in the left operand. All assignments built by this unit use -- this routine. This is needed to deal with assignments to initialized -- constants that are done in place. function Must_Slide (Obj_Type : Entity_Id; Typ : Entity_Id) return Boolean; -- A static array aggregate in an object declaration can in most cases be -- expanded in place. The one exception is when the aggregate is given -- with component associations that specify different bounds from those of -- the type definition in the object declaration. In this pathological -- case the aggregate must slide, and we must introduce an intermediate -- temporary to hold it. -- -- The same holds in an assignment to one-dimensional array of arrays, -- when a component may be given with bounds that differ from those of the -- component type. function Number_Of_Choices (N : Node_Id) return Nat; -- Returns the number of discrete choices (not including the others choice -- if present) contained in (sub-)aggregate N. procedure Process_Transient_Component (Loc : Source_Ptr; Comp_Typ : Entity_Id; Init_Expr : Node_Id; Fin_Call : out Node_Id; Hook_Clear : out Node_Id; Aggr : Node_Id := Empty; Stmts : List_Id := No_List); -- Subsidiary to the expansion of array and record aggregates. Generate -- part of the necessary code to finalize a transient component. Comp_Typ -- is the component type. Init_Expr is the initialization expression of the -- component which is always a function call. Fin_Call is the finalization -- call used to clean up the transient function result. Hook_Clear is the -- hook reset statement. Aggr and Stmts both control the placement of the -- generated code. Aggr is the related aggregate. If present, all code is -- inserted prior to Aggr using Insert_Action. Stmts is the initialization -- statements of the component. If present, all code is added to Stmts. procedure Process_Transient_Component_Completion (Loc : Source_Ptr; Aggr : Node_Id; Fin_Call : Node_Id; Hook_Clear : Node_Id; Stmts : List_Id); -- Subsidiary to the expansion of array and record aggregates. Generate -- part of the necessary code to finalize a transient component. Aggr is -- the related aggregate. Fin_Clear is the finalization call used to clean -- up the transient component. Hook_Clear is the hook reset statment. Stmts -- is the initialization statement list for the component. All generated -- code is added to Stmts. procedure Sort_Case_Table (Case_Table : in out Case_Table_Type); -- Sort the Case Table using the Lower Bound of each Choice as the key. -- A simple insertion sort is used since the number of choices in a case -- statement of variant part will usually be small and probably in near -- sorted order. ------------------------------------------------------ -- Local subprograms for Record Aggregate Expansion -- ------------------------------------------------------ function Build_Record_Aggr_Code (N : Node_Id; Typ : Entity_Id; Lhs : Node_Id) return List_Id; -- N is an N_Aggregate or an N_Extension_Aggregate. Typ is the type of the -- aggregate. Target is an expression containing the location on which the -- component by component assignments will take place. Returns the list of -- assignments plus all other adjustments needed for tagged and controlled -- types. procedure Convert_To_Assignments (N : Node_Id; Typ : Entity_Id); -- N is an N_Aggregate or an N_Extension_Aggregate. Typ is the type of the -- aggregate (which can only be a record type, this procedure is only used -- for record types). Transform the given aggregate into a sequence of -- assignments performed component by component. procedure Expand_Record_Aggregate (N : Node_Id; Orig_Tag : Node_Id := Empty; Parent_Expr : Node_Id := Empty); -- This is the top level procedure for record aggregate expansion. -- Expansion for record aggregates needs expand aggregates for tagged -- record types. Specifically Expand_Record_Aggregate adds the Tag -- field in front of the Component_Association list that was created -- during resolution by Resolve_Record_Aggregate. -- -- N is the record aggregate node. -- Orig_Tag is the value of the Tag that has to be provided for this -- specific aggregate. It carries the tag corresponding to the type -- of the outermost aggregate during the recursive expansion -- Parent_Expr is the ancestor part of the original extension -- aggregate function Has_Mutable_Components (Typ : Entity_Id) return Boolean; -- Return true if one of the components is of a discriminated type with -- defaults. An aggregate for a type with mutable components must be -- expanded into individual assignments. procedure Initialize_Discriminants (N : Node_Id; Typ : Entity_Id); -- If the type of the aggregate is a type extension with renamed discrimi- -- nants, we must initialize the hidden discriminants of the parent. -- Otherwise, the target object must not be initialized. The discriminants -- are initialized by calling the initialization procedure for the type. -- This is incorrect if the initialization of other components has any -- side effects. We restrict this call to the case where the parent type -- has a variant part, because this is the only case where the hidden -- discriminants are accessed, namely when calling discriminant checking -- functions of the parent type, and when applying a stream attribute to -- an object of the derived type. ----------------------------------------------------- -- Local Subprograms for Array Aggregate Expansion -- ----------------------------------------------------- function Aggr_Size_OK (N : Node_Id; Typ : Entity_Id) return Boolean; -- Very large static aggregates present problems to the back-end, and are -- transformed into assignments and loops. This function verifies that the -- total number of components of an aggregate is acceptable for rewriting -- into a purely positional static form. Aggr_Size_OK must be called before -- calling Flatten. -- -- This function also detects and warns about one-component aggregates that -- appear in a non-static context. Even if the component value is static, -- such an aggregate must be expanded into an assignment. function Backend_Processing_Possible (N : Node_Id) return Boolean; -- This function checks if array aggregate N can be processed directly -- by the backend. If this is the case, True is returned. function Build_Array_Aggr_Code (N : Node_Id; Ctype : Entity_Id; Index : Node_Id; Into : Node_Id; Scalar_Comp : Boolean; Indexes : List_Id := No_List) return List_Id; -- This recursive routine returns a list of statements containing the -- loops and assignments that are needed for the expansion of the array -- aggregate N. -- -- N is the (sub-)aggregate node to be expanded into code. This node has -- been fully analyzed, and its Etype is properly set. -- -- Index is the index node corresponding to the array subaggregate N -- -- Into is the target expression into which we are copying the aggregate. -- Note that this node may not have been analyzed yet, and so the Etype -- field may not be set. -- -- Scalar_Comp is True if the component type of the aggregate is scalar -- -- Indexes is the current list of expressions used to index the object we -- are writing into. procedure Convert_Array_Aggr_In_Allocator (Decl : Node_Id; Aggr : Node_Id; Target : Node_Id); -- If the aggregate appears within an allocator and can be expanded in -- place, this routine generates the individual assignments to components -- of the designated object. This is an optimization over the general -- case, where a temporary is first created on the stack and then used to -- construct the allocated object on the heap. procedure Convert_To_Positional (N : Node_Id; Max_Others_Replicate : Nat := 5; Handle_Bit_Packed : Boolean := False); -- If possible, convert named notation to positional notation. This -- conversion is possible only in some static cases. If the conversion is -- possible, then N is rewritten with the analyzed converted aggregate. -- The parameter Max_Others_Replicate controls the maximum number of -- values corresponding to an others choice that will be converted to -- positional notation (the default of 5 is the normal limit, and reflects -- the fact that normally the loop is better than a lot of separate -- assignments). Note that this limit gets overridden in any case if -- either of the restrictions No_Elaboration_Code or No_Implicit_Loops is -- set. The parameter Handle_Bit_Packed is usually set False (since we do -- not expect the back end to handle bit packed arrays, so the normal case -- of conversion is pointless), but in the special case of a call from -- Packed_Array_Aggregate_Handled, we set this parameter to True, since -- these are cases we handle in there. -- It would seem useful to have a higher default for Max_Others_Replicate, -- but aggregates in the compiler make this impossible: the compiler -- bootstrap fails if Max_Others_Replicate is greater than 25. This -- is unexpected ??? procedure Expand_Array_Aggregate (N : Node_Id); -- This is the top-level routine to perform array aggregate expansion. -- N is the N_Aggregate node to be expanded. function Is_Two_Dim_Packed_Array (Typ : Entity_Id) return Boolean; -- For two-dimensional packed aggregates with constant bounds and constant -- components, it is preferable to pack the inner aggregates because the -- whole matrix can then be presented to the back-end as a one-dimensional -- list of literals. This is much more efficient than expanding into single -- component assignments. This function determines if the type Typ is for -- an array that is suitable for this optimization: it returns True if Typ -- is a two dimensional bit packed array with component size 1, 2, or 4. function Packed_Array_Aggregate_Handled (N : Node_Id) return Boolean; -- Given an array aggregate, this function handles the case of a packed -- array aggregate with all constant values, where the aggregate can be -- evaluated at compile time. If this is possible, then N is rewritten -- to be its proper compile time value with all the components properly -- assembled. The expression is analyzed and resolved and True is returned. -- If this transformation is not possible, N is unchanged and False is -- returned. function Two_Dim_Packed_Array_Handled (N : Node_Id) return Boolean; -- If the type of the aggregate is a two-dimensional bit_packed array -- it may be transformed into an array of bytes with constant values, -- and presented to the back-end as a static value. The function returns -- false if this transformation cannot be performed. THis is similar to, -- and reuses part of the machinery in Packed_Array_Aggregate_Handled. ------------------ -- Aggr_Size_OK -- ------------------ function Aggr_Size_OK (N : Node_Id; Typ : Entity_Id) return Boolean is Lo : Node_Id; Hi : Node_Id; Indx : Node_Id; Siz : Int; Lov : Uint; Hiv : Uint; Max_Aggr_Size : Nat; -- Determines the maximum size of an array aggregate produced by -- converting named to positional notation (e.g. from others clauses). -- This avoids running away with attempts to convert huge aggregates, -- which hit memory limits in the backend. function Component_Count (T : Entity_Id) return Nat; -- The limit is applied to the total number of subcomponents that the -- aggregate will have, which is the number of static expressions -- that will appear in the flattened array. This requires a recursive -- computation of the number of scalar components of the structure. --------------------- -- Component_Count -- --------------------- function Component_Count (T : Entity_Id) return Nat is Res : Nat := 0; Comp : Entity_Id; begin if Is_Scalar_Type (T) then return 1; elsif Is_Record_Type (T) then Comp := First_Component (T); while Present (Comp) loop Res := Res + Component_Count (Etype (Comp)); Next_Component (Comp); end loop; return Res; elsif Is_Array_Type (T) then declare Lo : constant Node_Id := Type_Low_Bound (Etype (First_Index (T))); Hi : constant Node_Id := Type_High_Bound (Etype (First_Index (T))); Siz : constant Nat := Component_Count (Component_Type (T)); begin -- Check for superflat arrays, i.e. arrays with such bounds -- as 4 .. 2, to insure that this function never returns a -- meaningless negative value. if not Compile_Time_Known_Value (Lo) or else not Compile_Time_Known_Value (Hi) or else Expr_Value (Hi) < Expr_Value (Lo) then return 0; else -- If the number of components is greater than Int'Last, -- then return Int'Last, so caller will return False (Aggr -- size is not OK). Otherwise, UI_To_Int will crash. declare UI : constant Uint := Expr_Value (Hi) - Expr_Value (Lo) + 1; begin if UI_Is_In_Int_Range (UI) then return Siz * UI_To_Int (UI); else return Int'Last; end if; end; end if; end; else -- Can only be a null for an access type return 1; end if; end Component_Count; -- Start of processing for Aggr_Size_OK begin -- The normal aggregate limit is 50000, but we increase this limit to -- 2**24 (about 16 million) if Restrictions (No_Elaboration_Code) or -- Restrictions (No_Implicit_Loops) is specified, since in either case -- we are at risk of declaring the program illegal because of this -- limit. We also increase the limit when Static_Elaboration_Desired, -- given that this means that objects are intended to be placed in data -- memory. -- We also increase the limit if the aggregate is for a packed two- -- dimensional array, because if components are static it is much more -- efficient to construct a one-dimensional equivalent array with static -- components. -- Conversely, we decrease the maximum size if none of the above -- requirements apply, and if the aggregate has a single component -- association, which will be more efficient if implemented with a loop. -- Finally, we use a small limit in CodePeer mode where we favor loops -- instead of thousands of single assignments (from large aggregates). Max_Aggr_Size := 50000; if CodePeer_Mode then Max_Aggr_Size := 100; elsif Restriction_Active (No_Elaboration_Code) or else Restriction_Active (No_Implicit_Loops) or else Is_Two_Dim_Packed_Array (Typ) or else (Ekind (Current_Scope) = E_Package and then Static_Elaboration_Desired (Current_Scope)) then Max_Aggr_Size := 2 ** 24; elsif No (Expressions (N)) and then No (Next (First (Component_Associations (N)))) then Max_Aggr_Size := 5000; end if; Siz := Component_Count (Component_Type (Typ)); Indx := First_Index (Typ); while Present (Indx) loop Lo := Type_Low_Bound (Etype (Indx)); Hi := Type_High_Bound (Etype (Indx)); -- Bounds need to be known at compile time if not Compile_Time_Known_Value (Lo) or else not Compile_Time_Known_Value (Hi) then return False; end if; Lov := Expr_Value (Lo); Hiv := Expr_Value (Hi); -- A flat array is always safe if Hiv < Lov then return True; end if; -- One-component aggregates are suspicious, and if the context type -- is an object declaration with non-static bounds it will trip gcc; -- such an aggregate must be expanded into a single assignment. if Hiv = Lov and then Nkind (Parent (N)) = N_Object_Declaration then declare Index_Type : constant Entity_Id := Etype (First_Index (Etype (Defining_Identifier (Parent (N))))); Indx : Node_Id; begin if not Compile_Time_Known_Value (Type_Low_Bound (Index_Type)) or else not Compile_Time_Known_Value (Type_High_Bound (Index_Type)) then if Present (Component_Associations (N)) then Indx := First (Choice_List (First (Component_Associations (N)))); if Is_Entity_Name (Indx) and then not Is_Type (Entity (Indx)) then Error_Msg_N ("single component aggregate in " & "non-static context??", Indx); Error_Msg_N ("\maybe subtype name was meant??", Indx); end if; end if; return False; end if; end; end if; declare Rng : constant Uint := Hiv - Lov + 1; begin -- Check if size is too large if not UI_Is_In_Int_Range (Rng) then return False; end if; Siz := Siz * UI_To_Int (Rng); end; if Siz <= 0 or else Siz > Max_Aggr_Size then return False; end if; -- Bounds must be in integer range, for later array construction if not UI_Is_In_Int_Range (Lov) or else not UI_Is_In_Int_Range (Hiv) then return False; end if; Next_Index (Indx); end loop; return True; end Aggr_Size_OK; --------------------------------- -- Backend_Processing_Possible -- --------------------------------- -- Backend processing by Gigi/gcc is possible only if all the following -- conditions are met: -- 1. N is fully positional -- 2. N is not a bit-packed array aggregate; -- 3. The size of N's array type must be known at compile time. Note -- that this implies that the component size is also known -- 4. The array type of N does not follow the Fortran layout convention -- or if it does it must be 1 dimensional. -- 5. The array component type may not be tagged (which could necessitate -- reassignment of proper tags). -- 6. The array component type must not have unaligned bit components -- 7. None of the components of the aggregate may be bit unaligned -- components. -- 8. There cannot be delayed components, since we do not know enough -- at this stage to know if back end processing is possible. -- 9. There cannot be any discriminated record components, since the -- back end cannot handle this complex case. -- 10. No controlled actions need to be generated for components -- 11. When generating C code, N must be part of a N_Object_Declaration -- 12. When generating C code, N must not include function calls function Backend_Processing_Possible (N : Node_Id) return Boolean is Typ : constant Entity_Id := Etype (N); -- Typ is the correct constrained array subtype of the aggregate function Component_Check (N : Node_Id; Index : Node_Id) return Boolean; -- This routine checks components of aggregate N, enforcing checks -- 1, 7, 8, 9, 11, and 12. In the multidimensional case, these checks -- are performed on subaggregates. The Index value is the current index -- being checked in the multidimensional case. --------------------- -- Component_Check -- --------------------- function Component_Check (N : Node_Id; Index : Node_Id) return Boolean is function Ultimate_Original_Expression (N : Node_Id) return Node_Id; -- Given a type conversion or an unchecked type conversion N, return -- its innermost original expression. ---------------------------------- -- Ultimate_Original_Expression -- ---------------------------------- function Ultimate_Original_Expression (N : Node_Id) return Node_Id is Expr : Node_Id := Original_Node (N); begin while Nkind_In (Expr, N_Type_Conversion, N_Unchecked_Type_Conversion) loop Expr := Original_Node (Expression (Expr)); end loop; return Expr; end Ultimate_Original_Expression; -- Local variables Expr : Node_Id; -- Start of processing for Component_Check begin -- Checks 1: (no component associations) if Present (Component_Associations (N)) then return False; end if; -- Checks 11: (part of an object declaration) if Modify_Tree_For_C and then Nkind (Parent (N)) /= N_Object_Declaration and then (Nkind (Parent (N)) /= N_Qualified_Expression or else Nkind (Parent (Parent (N))) /= N_Object_Declaration) then return False; end if; -- Checks on components -- Recurse to check subaggregates, which may appear in qualified -- expressions. If delayed, the front-end will have to expand. -- If the component is a discriminated record, treat as non-static, -- as the back-end cannot handle this properly. Expr := First (Expressions (N)); while Present (Expr) loop -- Checks 8: (no delayed components) if Is_Delayed_Aggregate (Expr) then return False; end if; -- Checks 9: (no discriminated records) if Present (Etype (Expr)) and then Is_Record_Type (Etype (Expr)) and then Has_Discriminants (Etype (Expr)) then return False; end if; -- Checks 7. Component must not be bit aligned component if Possible_Bit_Aligned_Component (Expr) then return False; end if; -- Checks 12: (no function call) if Modify_Tree_For_C and then Nkind (Ultimate_Original_Expression (Expr)) = N_Function_Call then return False; end if; -- Recursion to following indexes for multiple dimension case if Present (Next_Index (Index)) and then not Component_Check (Expr, Next_Index (Index)) then return False; end if; -- All checks for that component finished, on to next Next (Expr); end loop; return True; end Component_Check; -- Start of processing for Backend_Processing_Possible begin -- Checks 2 (array not bit packed) and 10 (no controlled actions) if Is_Bit_Packed_Array (Typ) or else Needs_Finalization (Typ) then return False; end if; -- If component is limited, aggregate must be expanded because each -- component assignment must be built in place. if Is_Limited_View (Component_Type (Typ)) then return False; end if; -- Checks 4 (array must not be multidimensional Fortran case) if Convention (Typ) = Convention_Fortran and then Number_Dimensions (Typ) > 1 then return False; end if; -- Checks 3 (size of array must be known at compile time) if not Size_Known_At_Compile_Time (Typ) then return False; end if; -- Checks on components if not Component_Check (N, First_Index (Typ)) then return False; end if; -- Checks 5 (if the component type is tagged, then we may need to do -- tag adjustments. Perhaps this should be refined to check for any -- component associations that actually need tag adjustment, similar -- to the test in Component_Not_OK_For_Backend for record aggregates -- with tagged components, but not clear whether it's worthwhile ???; -- in the case of virtual machines (no Tagged_Type_Expansion), object -- tags are handled implicitly). if Is_Tagged_Type (Component_Type (Typ)) and then Tagged_Type_Expansion then return False; end if; -- Checks 6 (component type must not have bit aligned components) if Type_May_Have_Bit_Aligned_Components (Component_Type (Typ)) then return False; end if; -- Backend processing is possible Set_Size_Known_At_Compile_Time (Etype (N), True); return True; end Backend_Processing_Possible; --------------------------- -- Build_Array_Aggr_Code -- --------------------------- -- The code that we generate from a one dimensional aggregate is -- 1. If the subaggregate contains discrete choices we -- (a) Sort the discrete choices -- (b) Otherwise for each discrete choice that specifies a range we -- emit a loop. If a range specifies a maximum of three values, or -- we are dealing with an expression we emit a sequence of -- assignments instead of a loop. -- (c) Generate the remaining loops to cover the others choice if any -- 2. If the aggregate contains positional elements we -- (a) translate the positional elements in a series of assignments -- (b) Generate a final loop to cover the others choice if any. -- Note that this final loop has to be a while loop since the case -- L : Integer := Integer'Last; -- H : Integer := Integer'Last; -- A : array (L .. H) := (1, others =>0); -- cannot be handled by a for loop. Thus for the following -- array (L .. H) := (.. positional elements.., others =>E); -- we always generate something like: -- J : Index_Type := Index_Of_Last_Positional_Element; -- while J < H loop -- J := Index_Base'Succ (J) -- Tmp (J) := E; -- end loop; function Build_Array_Aggr_Code (N : Node_Id; Ctype : Entity_Id; Index : Node_Id; Into : Node_Id; Scalar_Comp : Boolean; Indexes : List_Id := No_List) return List_Id is Loc : constant Source_Ptr := Sloc (N); Index_Base : constant Entity_Id := Base_Type (Etype (Index)); Index_Base_L : constant Node_Id := Type_Low_Bound (Index_Base); Index_Base_H : constant Node_Id := Type_High_Bound (Index_Base); function Add (Val : Int; To : Node_Id) return Node_Id; -- Returns an expression where Val is added to expression To, unless -- To+Val is provably out of To's base type range. To must be an -- already analyzed expression. function Empty_Range (L, H : Node_Id) return Boolean; -- Returns True if the range defined by L .. H is certainly empty function Equal (L, H : Node_Id) return Boolean; -- Returns True if L = H for sure function Index_Base_Name return Node_Id; -- Returns a new reference to the index type name function Gen_Assign (Ind : Node_Id; Expr : Node_Id; In_Loop : Boolean := False) return List_Id; -- Ind must be a side-effect-free expression. If the input aggregate N -- to Build_Loop contains no subaggregates, then this function returns -- the assignment statement: -- -- Into (Indexes, Ind) := Expr; -- -- Otherwise we call Build_Code recursively. Flag In_Loop should be set -- when the assignment appears within a generated loop. -- -- Ada 2005 (AI-287): In case of default initialized component, Expr -- is empty and we generate a call to the corresponding IP subprogram. function Gen_Loop (L, H : Node_Id; Expr : Node_Id) return List_Id; -- Nodes L and H must be side-effect-free expressions. If the input -- aggregate N to Build_Loop contains no subaggregates, this routine -- returns the for loop statement: -- -- for J in Index_Base'(L) .. Index_Base'(H) loop -- Into (Indexes, J) := Expr; -- end loop; -- -- Otherwise we call Build_Code recursively. As an optimization if the -- loop covers 3 or fewer scalar elements we generate a sequence of -- assignments. -- If the component association that generates the loop comes from an -- Iterated_Component_Association, the loop parameter has the name of -- the corresponding parameter in the original construct. function Gen_While (L, H : Node_Id; Expr : Node_Id) return List_Id; -- Nodes L and H must be side-effect-free expressions. If the input -- aggregate N to Build_Loop contains no subaggregates, this routine -- returns the while loop statement: -- -- J : Index_Base := L; -- while J < H loop -- J := Index_Base'Succ (J); -- Into (Indexes, J) := Expr; -- end loop; -- -- Otherwise we call Build_Code recursively function Get_Assoc_Expr (Assoc : Node_Id) return Node_Id; -- For an association with a box, use value given by aspect -- Default_Component_Value of array type if specified, else use -- value given by aspect Default_Value for component type itself -- if specified, else return Empty. function Local_Compile_Time_Known_Value (E : Node_Id) return Boolean; function Local_Expr_Value (E : Node_Id) return Uint; -- These two Local routines are used to replace the corresponding ones -- in sem_eval because while processing the bounds of an aggregate with -- discrete choices whose index type is an enumeration, we build static -- expressions not recognized by Compile_Time_Known_Value as such since -- they have not yet been analyzed and resolved. All the expressions in -- question are things like Index_Base_Name'Val (Const) which we can -- easily recognize as being constant. --------- -- Add -- --------- function Add (Val : Int; To : Node_Id) return Node_Id is Expr_Pos : Node_Id; Expr : Node_Id; To_Pos : Node_Id; U_To : Uint; U_Val : constant Uint := UI_From_Int (Val); begin -- Note: do not try to optimize the case of Val = 0, because -- we need to build a new node with the proper Sloc value anyway. -- First test if we can do constant folding if Local_Compile_Time_Known_Value (To) then U_To := Local_Expr_Value (To) + Val; -- Determine if our constant is outside the range of the index. -- If so return an Empty node. This empty node will be caught -- by Empty_Range below. if Compile_Time_Known_Value (Index_Base_L) and then U_To < Expr_Value (Index_Base_L) then return Empty; elsif Compile_Time_Known_Value (Index_Base_H) and then U_To > Expr_Value (Index_Base_H) then return Empty; end if; Expr_Pos := Make_Integer_Literal (Loc, U_To); Set_Is_Static_Expression (Expr_Pos); if not Is_Enumeration_Type (Index_Base) then Expr := Expr_Pos; -- If we are dealing with enumeration return -- Index_Base'Val (Expr_Pos) else Expr := Make_Attribute_Reference (Loc, Prefix => Index_Base_Name, Attribute_Name => Name_Val, Expressions => New_List (Expr_Pos)); end if; return Expr; end if; -- If we are here no constant folding possible if not Is_Enumeration_Type (Index_Base) then Expr := Make_Op_Add (Loc, Left_Opnd => Duplicate_Subexpr (To), Right_Opnd => Make_Integer_Literal (Loc, U_Val)); -- If we are dealing with enumeration return -- Index_Base'Val (Index_Base'Pos (To) + Val) else To_Pos := Make_Attribute_Reference (Loc, Prefix => Index_Base_Name, Attribute_Name => Name_Pos, Expressions => New_List (Duplicate_Subexpr (To))); Expr_Pos := Make_Op_Add (Loc, Left_Opnd => To_Pos, Right_Opnd => Make_Integer_Literal (Loc, U_Val)); Expr := Make_Attribute_Reference (Loc, Prefix => Index_Base_Name, Attribute_Name => Name_Val, Expressions => New_List (Expr_Pos)); end if; return Expr; end Add; ----------------- -- Empty_Range -- ----------------- function Empty_Range (L, H : Node_Id) return Boolean is Is_Empty : Boolean := False; Low : Node_Id; High : Node_Id; begin -- First check if L or H were already detected as overflowing the -- index base range type by function Add above. If this is so Add -- returns the empty node. if No (L) or else No (H) then return True; end if; for J in 1 .. 3 loop case J is -- L > H range is empty when 1 => Low := L; High := H; -- B_L > H range must be empty when 2 => Low := Index_Base_L; High := H; -- L > B_H range must be empty when 3 => Low := L; High := Index_Base_H; end case; if Local_Compile_Time_Known_Value (Low) and then Local_Compile_Time_Known_Value (High) then Is_Empty := UI_Gt (Local_Expr_Value (Low), Local_Expr_Value (High)); end if; exit when Is_Empty; end loop; return Is_Empty; end Empty_Range; ----------- -- Equal -- ----------- function Equal (L, H : Node_Id) return Boolean is begin if L = H then return True; elsif Local_Compile_Time_Known_Value (L) and then Local_Compile_Time_Known_Value (H) then return UI_Eq (Local_Expr_Value (L), Local_Expr_Value (H)); end if; return False; end Equal; ---------------- -- Gen_Assign -- ---------------- function Gen_Assign (Ind : Node_Id; Expr : Node_Id; In_Loop : Boolean := False) return List_Id is function Add_Loop_Actions (Lis : List_Id) return List_Id; -- Collect insert_actions generated in the construction of a loop, -- and prepend them to the sequence of assignments to complete the -- eventual body of the loop. procedure Initialize_Array_Component (Arr_Comp : Node_Id; Comp_Typ : Node_Id; Init_Expr : Node_Id; Stmts : List_Id); -- Perform the initialization of array component Arr_Comp with -- expected type Comp_Typ. Init_Expr denotes the initialization -- expression of the array component. All generated code is added -- to list Stmts. procedure Initialize_Ctrl_Array_Component (Arr_Comp : Node_Id; Comp_Typ : Entity_Id; Init_Expr : Node_Id; Stmts : List_Id); -- Perform the initialization of array component Arr_Comp when its -- expected type Comp_Typ needs finalization actions. Init_Expr is -- the initialization expression of the array component. All hook- -- related declarations are inserted prior to aggregate N. Remaining -- code is added to list Stmts. ---------------------- -- Add_Loop_Actions -- ---------------------- function Add_Loop_Actions (Lis : List_Id) return List_Id is Res : List_Id; begin -- Ada 2005 (AI-287): Do nothing else in case of default -- initialized component. if No (Expr) then return Lis; elsif Nkind (Parent (Expr)) = N_Component_Association and then Present (Loop_Actions (Parent (Expr))) then Append_List (Lis, Loop_Actions (Parent (Expr))); Res := Loop_Actions (Parent (Expr)); Set_Loop_Actions (Parent (Expr), No_List); return Res; else return Lis; end if; end Add_Loop_Actions; -------------------------------- -- Initialize_Array_Component -- -------------------------------- procedure Initialize_Array_Component (Arr_Comp : Node_Id; Comp_Typ : Node_Id; Init_Expr : Node_Id; Stmts : List_Id) is Exceptions_OK : constant Boolean := not Restriction_Active (No_Exception_Propagation); Finalization_OK : constant Boolean := Present (Comp_Typ) and then Needs_Finalization (Comp_Typ); Full_Typ : constant Entity_Id := Underlying_Type (Comp_Typ); Adj_Call : Node_Id; Blk_Stmts : List_Id; Init_Stmt : Node_Id; begin -- Protect the initialization statements from aborts. Generate: -- Abort_Defer; if Finalization_OK and Abort_Allowed then if Exceptions_OK then Blk_Stmts := New_List; else Blk_Stmts := Stmts; end if; Append_To (Blk_Stmts, Build_Runtime_Call (Loc, RE_Abort_Defer)); -- Otherwise aborts are not allowed. All generated code is added -- directly to the input list. else Blk_Stmts := Stmts; end if; -- Initialize the array element. Generate: -- Arr_Comp := Init_Expr; -- Note that the initialization expression is replicated because -- it has to be reevaluated within a generated loop. Init_Stmt := Make_OK_Assignment_Statement (Loc, Name => New_Copy_Tree (Arr_Comp), Expression => New_Copy_Tree (Init_Expr)); Set_No_Ctrl_Actions (Init_Stmt); -- If this is an aggregate for an array of arrays, each -- subaggregate will be expanded as well, and even with -- No_Ctrl_Actions the assignments of inner components will -- require attachment in their assignments to temporaries. These -- temporaries must be finalized for each subaggregate. Generate: -- begin -- Arr_Comp := Init_Expr; -- end; if Finalization_OK and then Is_Array_Type (Comp_Typ) then Init_Stmt := Make_Block_Statement (Loc, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => New_List (Init_Stmt))); end if; Append_To (Blk_Stmts, Init_Stmt); -- Adjust the tag due to a possible view conversion. Generate: -- Arr_Comp._tag := Full_TypP; if Tagged_Type_Expansion and then Present (Comp_Typ) and then Is_Tagged_Type (Comp_Typ) then Append_To (Blk_Stmts, Make_OK_Assignment_Statement (Loc, Name => Make_Selected_Component (Loc, Prefix => New_Copy_Tree (Arr_Comp), Selector_Name => New_Occurrence_Of (First_Tag_Component (Full_Typ), Loc)), Expression => Unchecked_Convert_To (RTE (RE_Tag), New_Occurrence_Of (Node (First_Elmt (Access_Disp_Table (Full_Typ))), Loc)))); end if; -- Adjust the array component. Controlled subaggregates are not -- considered because each of their individual elements will -- receive an adjustment of its own. Generate: -- [Deep_]Adjust (Arr_Comp); if Finalization_OK and then not Is_Limited_Type (Comp_Typ) and then not (Is_Array_Type (Comp_Typ) and then Is_Controlled (Component_Type (Comp_Typ)) and then Nkind (Expr) = N_Aggregate) then Adj_Call := Make_Adjust_Call (Obj_Ref => New_Copy_Tree (Arr_Comp), Typ => Comp_Typ); -- Guard against a missing [Deep_]Adjust when the component -- type was not frozen properly. if Present (Adj_Call) then Append_To (Blk_Stmts, Adj_Call); end if; end if; -- Complete the protection of the initialization statements if Finalization_OK and Abort_Allowed then -- Wrap the initialization statements in a block to catch a -- potential exception. Generate: -- begin -- Abort_Defer; -- Arr_Comp := Init_Expr; -- Arr_Comp._tag := Full_TypP; -- [Deep_]Adjust (Arr_Comp); -- at end -- Abort_Undefer_Direct; -- end; if Exceptions_OK then Append_To (Stmts, Build_Abort_Undefer_Block (Loc, Stmts => Blk_Stmts, Context => N)); -- Otherwise exceptions are not propagated. Generate: -- Abort_Defer; -- Arr_Comp := Init_Expr; -- Arr_Comp._tag := Full_TypP; -- [Deep_]Adjust (Arr_Comp); -- Abort_Undefer; else Append_To (Blk_Stmts, Build_Runtime_Call (Loc, RE_Abort_Undefer)); end if; end if; end Initialize_Array_Component; ------------------------------------- -- Initialize_Ctrl_Array_Component -- ------------------------------------- procedure Initialize_Ctrl_Array_Component (Arr_Comp : Node_Id; Comp_Typ : Entity_Id; Init_Expr : Node_Id; Stmts : List_Id) is Act_Aggr : Node_Id; Act_Stmts : List_Id; Expr : Node_Id; Fin_Call : Node_Id; Hook_Clear : Node_Id; In_Place_Expansion : Boolean; -- Flag set when a nonlimited controlled function call requires -- in-place expansion. begin -- Duplicate the initialization expression in case the context is -- a multi choice list or an "others" choice which plugs various -- holes in the aggregate. As a result the expression is no longer -- shared between the various components and is reevaluated for -- each such component. Expr := New_Copy_Tree (Init_Expr); Set_Parent (Expr, Parent (Init_Expr)); -- Perform a preliminary analysis and resolution to determine what -- the initialization expression denotes. An unanalyzed function -- call may appear as an identifier or an indexed component. if Nkind_In (Expr, N_Function_Call, N_Identifier, N_Indexed_Component) and then not Analyzed (Expr) then Preanalyze_And_Resolve (Expr, Comp_Typ); end if; In_Place_Expansion := Nkind (Expr) = N_Function_Call and then not Is_Limited_Type (Comp_Typ); -- The initialization expression is a controlled function call. -- Perform in-place removal of side effects to avoid creating a -- transient scope, which leads to premature finalization. -- This in-place expansion is not performed for limited transient -- objects because the initialization is already done in-place. if In_Place_Expansion then -- Suppress the removal of side effects by general analysis -- because this behavior is emulated here. This avoids the -- generation of a transient scope, which leads to out-of-order -- adjustment and finalization. Set_No_Side_Effect_Removal (Expr); -- When the transient component initialization is related to a -- range or an "others", keep all generated statements within -- the enclosing loop. This way the controlled function call -- will be evaluated at each iteration, and its result will be -- finalized at the end of each iteration. if In_Loop then Act_Aggr := Empty; Act_Stmts := Stmts; -- Otherwise this is a single component initialization. Hook- -- related statements are inserted prior to the aggregate. else Act_Aggr := N; Act_Stmts := No_List; end if; -- Install all hook-related declarations and prepare the clean -- up statements. Process_Transient_Component (Loc => Loc, Comp_Typ => Comp_Typ, Init_Expr => Expr, Fin_Call => Fin_Call, Hook_Clear => Hook_Clear, Aggr => Act_Aggr, Stmts => Act_Stmts); end if; -- Use the noncontrolled component initialization circuitry to -- assign the result of the function call to the array element. -- This also performs subaggregate wrapping, tag adjustment, and -- [deep] adjustment of the array element. Initialize_Array_Component (Arr_Comp => Arr_Comp, Comp_Typ => Comp_Typ, Init_Expr => Expr, Stmts => Stmts); -- At this point the array element is fully initialized. Complete -- the processing of the controlled array component by finalizing -- the transient function result. if In_Place_Expansion then Process_Transient_Component_Completion (Loc => Loc, Aggr => N, Fin_Call => Fin_Call, Hook_Clear => Hook_Clear, Stmts => Stmts); end if; end Initialize_Ctrl_Array_Component; -- Local variables Stmts : constant List_Id := New_List; Comp_Typ : Entity_Id := Empty; Expr_Q : Node_Id; Indexed_Comp : Node_Id; Init_Call : Node_Id; New_Indexes : List_Id; -- Start of processing for Gen_Assign begin if No (Indexes) then New_Indexes := New_List; else New_Indexes := New_Copy_List_Tree (Indexes); end if; Append_To (New_Indexes, Ind); if Present (Next_Index (Index)) then return Add_Loop_Actions ( Build_Array_Aggr_Code (N => Expr, Ctype => Ctype, Index => Next_Index (Index), Into => Into, Scalar_Comp => Scalar_Comp, Indexes => New_Indexes)); end if; -- If we get here then we are at a bottom-level (sub-)aggregate Indexed_Comp := Checks_Off (Make_Indexed_Component (Loc, Prefix => New_Copy_Tree (Into), Expressions => New_Indexes)); Set_Assignment_OK (Indexed_Comp); -- Ada 2005 (AI-287): In case of default initialized component, Expr -- is not present (and therefore we also initialize Expr_Q to empty). if No (Expr) then Expr_Q := Empty; elsif Nkind (Expr) = N_Qualified_Expression then Expr_Q := Expression (Expr); else Expr_Q := Expr; end if; if Present (Etype (N)) and then Etype (N) /= Any_Composite then Comp_Typ := Component_Type (Etype (N)); pragma Assert (Comp_Typ = Ctype); -- AI-287 elsif Present (Next (First (New_Indexes))) then -- Ada 2005 (AI-287): Do nothing in case of default initialized -- component because we have received the component type in -- the formal parameter Ctype. -- ??? Some assert pragmas have been added to check if this new -- formal can be used to replace this code in all cases. if Present (Expr) then -- This is a multidimensional array. Recover the component type -- from the outermost aggregate, because subaggregates do not -- have an assigned type. declare P : Node_Id; begin P := Parent (Expr); while Present (P) loop if Nkind (P) = N_Aggregate and then Present (Etype (P)) then Comp_Typ := Component_Type (Etype (P)); exit; else P := Parent (P); end if; end loop; pragma Assert (Comp_Typ = Ctype); -- AI-287 end; end if; end if; -- Ada 2005 (AI-287): We only analyze the expression in case of non- -- default initialized components (otherwise Expr_Q is not present). if Present (Expr_Q) and then Nkind_In (Expr_Q, N_Aggregate, N_Extension_Aggregate) then -- At this stage the Expression may not have been analyzed yet -- because the array aggregate code has not been updated to use -- the Expansion_Delayed flag and avoid analysis altogether to -- solve the same problem (see Resolve_Aggr_Expr). So let us do -- the analysis of non-array aggregates now in order to get the -- value of Expansion_Delayed flag for the inner aggregate ??? if Present (Comp_Typ) and then not Is_Array_Type (Comp_Typ) then Analyze_And_Resolve (Expr_Q, Comp_Typ); end if; if Is_Delayed_Aggregate (Expr_Q) then -- This is either a subaggregate of a multidimensional array, -- or a component of an array type whose component type is -- also an array. In the latter case, the expression may have -- component associations that provide different bounds from -- those of the component type, and sliding must occur. Instead -- of decomposing the current aggregate assignment, force the -- reanalysis of the assignment, so that a temporary will be -- generated in the usual fashion, and sliding will take place. if Nkind (Parent (N)) = N_Assignment_Statement and then Is_Array_Type (Comp_Typ) and then Present (Component_Associations (Expr_Q)) and then Must_Slide (Comp_Typ, Etype (Expr_Q)) then Set_Expansion_Delayed (Expr_Q, False); Set_Analyzed (Expr_Q, False); else return Add_Loop_Actions ( Late_Expansion (Expr_Q, Etype (Expr_Q), Indexed_Comp)); end if; end if; end if; if Present (Expr) then -- Handle an initialization expression of a controlled type in -- case it denotes a function call. In general such a scenario -- will produce a transient scope, but this will lead to wrong -- order of initialization, adjustment, and finalization in the -- context of aggregates. -- Target (1) := Ctrl_Func_Call; -- begin -- scope -- Trans_Obj : ... := Ctrl_Func_Call; -- object -- Target (1) := Trans_Obj; -- Finalize (Trans_Obj); -- end; -- Target (1)._tag := ...; -- Adjust (Target (1)); -- In the example above, the call to Finalize occurs too early -- and as a result it may leave the array component in a bad -- state. Finalization of the transient object should really -- happen after adjustment. -- To avoid this scenario, perform in-place side-effect removal -- of the function call. This eliminates the transient property -- of the function result and ensures correct order of actions. -- Res : ... := Ctrl_Func_Call; -- Target (1) := Res; -- Target (1)._tag := ...; -- Adjust (Target (1)); -- Finalize (Res); if Present (Comp_Typ) and then Needs_Finalization (Comp_Typ) and then Nkind (Expr) /= N_Aggregate then Initialize_Ctrl_Array_Component (Arr_Comp => Indexed_Comp, Comp_Typ => Comp_Typ, Init_Expr => Expr, Stmts => Stmts); -- Otherwise perform simple component initialization else Initialize_Array_Component (Arr_Comp => Indexed_Comp, Comp_Typ => Comp_Typ, Init_Expr => Expr, Stmts => Stmts); end if; -- Ada 2005 (AI-287): In case of default initialized component, call -- the initialization subprogram associated with the component type. -- If the component type is an access type, add an explicit null -- assignment, because for the back-end there is an initialization -- present for the whole aggregate, and no default initialization -- will take place. -- In addition, if the component type is controlled, we must call -- its Initialize procedure explicitly, because there is no explicit -- object creation that will invoke it otherwise. else if Present (Base_Init_Proc (Base_Type (Ctype))) or else Has_Task (Base_Type (Ctype)) then Append_List_To (Stmts, Build_Initialization_Call (Loc, Id_Ref => Indexed_Comp, Typ => Ctype, With_Default_Init => True)); -- If the component type has invariants, add an invariant -- check after the component is default-initialized. It will -- be analyzed and resolved before the code for initialization -- of other components. if Has_Invariants (Ctype) then Set_Etype (Indexed_Comp, Ctype); Append_To (Stmts, Make_Invariant_Call (Indexed_Comp)); end if; elsif Is_Access_Type (Ctype) then Append_To (Stmts, Make_Assignment_Statement (Loc, Name => New_Copy_Tree (Indexed_Comp), Expression => Make_Null (Loc))); end if; if Needs_Finalization (Ctype) then Init_Call := Make_Init_Call (Obj_Ref => New_Copy_Tree (Indexed_Comp), Typ => Ctype); -- Guard against a missing [Deep_]Initialize when the component -- type was not properly frozen. if Present (Init_Call) then Append_To (Stmts, Init_Call); end if; end if; end if; return Add_Loop_Actions (Stmts); end Gen_Assign; -------------- -- Gen_Loop -- -------------- function Gen_Loop (L, H : Node_Id; Expr : Node_Id) return List_Id is Is_Iterated_Component : constant Boolean := Nkind (Parent (Expr)) = N_Iterated_Component_Association; L_J : Node_Id; L_L : Node_Id; -- Index_Base'(L) L_H : Node_Id; -- Index_Base'(H) L_Range : Node_Id; -- Index_Base'(L) .. Index_Base'(H) L_Iteration_Scheme : Node_Id; -- L_J in Index_Base'(L) .. Index_Base'(H) L_Body : List_Id; -- The statements to execute in the loop S : constant List_Id := New_List; -- List of statements Tcopy : Node_Id; -- Copy of expression tree, used for checking purposes begin -- If loop bounds define an empty range return the null statement if Empty_Range (L, H) then Append_To (S, Make_Null_Statement (Loc)); -- Ada 2005 (AI-287): Nothing else need to be done in case of -- default initialized component. if No (Expr) then null; else -- The expression must be type-checked even though no component -- of the aggregate will have this value. This is done only for -- actual components of the array, not for subaggregates. Do -- the check on a copy, because the expression may be shared -- among several choices, some of which might be non-null. if Present (Etype (N)) and then Is_Array_Type (Etype (N)) and then No (Next_Index (Index)) then Expander_Mode_Save_And_Set (False); Tcopy := New_Copy_Tree (Expr); Set_Parent (Tcopy, N); Analyze_And_Resolve (Tcopy, Component_Type (Etype (N))); Expander_Mode_Restore; end if; end if; return S; -- If loop bounds are the same then generate an assignment, unless -- the parent construct is an Iterated_Component_Association. elsif Equal (L, H) and then not Is_Iterated_Component then return Gen_Assign (New_Copy_Tree (L), Expr); -- If H - L <= 2 then generate a sequence of assignments when we are -- processing the bottom most aggregate and it contains scalar -- components. elsif No (Next_Index (Index)) and then Scalar_Comp and then Local_Compile_Time_Known_Value (L) and then Local_Compile_Time_Known_Value (H) and then Local_Expr_Value (H) - Local_Expr_Value (L) <= 2 and then not Is_Iterated_Component then Append_List_To (S, Gen_Assign (New_Copy_Tree (L), Expr)); Append_List_To (S, Gen_Assign (Add (1, To => L), Expr)); if Local_Expr_Value (H) - Local_Expr_Value (L) = 2 then Append_List_To (S, Gen_Assign (Add (2, To => L), Expr)); end if; return S; end if; -- Otherwise construct the loop, starting with the loop index L_J if Is_Iterated_Component then L_J := Make_Defining_Identifier (Loc, Chars => (Chars (Defining_Identifier (Parent (Expr))))); else L_J := Make_Temporary (Loc, 'J', L); end if; -- Construct "L .. H" in Index_Base. We use a qualified expression -- for the bound to convert to the index base, but we don't need -- to do that if we already have the base type at hand. if Etype (L) = Index_Base then L_L := L; else L_L := Make_Qualified_Expression (Loc, Subtype_Mark => Index_Base_Name, Expression => New_Copy_Tree (L)); end if; if Etype (H) = Index_Base then L_H := H; else L_H := Make_Qualified_Expression (Loc, Subtype_Mark => Index_Base_Name, Expression => New_Copy_Tree (H)); end if; L_Range := Make_Range (Loc, Low_Bound => L_L, High_Bound => L_H); -- Construct "for L_J in Index_Base range L .. H" L_Iteration_Scheme := Make_Iteration_Scheme (Loc, Loop_Parameter_Specification => Make_Loop_Parameter_Specification (Loc, Defining_Identifier => L_J, Discrete_Subtype_Definition => L_Range)); -- Construct the statements to execute in the loop body L_Body := Gen_Assign (New_Occurrence_Of (L_J, Loc), Expr, In_Loop => True); -- Construct the final loop Append_To (S, Make_Implicit_Loop_Statement (Node => N, Identifier => Empty, Iteration_Scheme => L_Iteration_Scheme, Statements => L_Body)); -- A small optimization: if the aggregate is initialized with a box -- and the component type has no initialization procedure, remove the -- useless empty loop. if Nkind (First (S)) = N_Loop_Statement and then Is_Empty_List (Statements (First (S))) then return New_List (Make_Null_Statement (Loc)); else return S; end if; end Gen_Loop; --------------- -- Gen_While -- --------------- -- The code built is -- W_J : Index_Base := L; -- while W_J < H loop -- W_J := Index_Base'Succ (W); -- L_Body; -- end loop; function Gen_While (L, H : Node_Id; Expr : Node_Id) return List_Id is W_J : Node_Id; W_Decl : Node_Id; -- W_J : Base_Type := L; W_Iteration_Scheme : Node_Id; -- while W_J < H W_Index_Succ : Node_Id; -- Index_Base'Succ (J) W_Increment : Node_Id; -- W_J := Index_Base'Succ (W) W_Body : constant List_Id := New_List; -- The statements to execute in the loop S : constant List_Id := New_List; -- list of statement begin -- If loop bounds define an empty range or are equal return null if Empty_Range (L, H) or else Equal (L, H) then Append_To (S, Make_Null_Statement (Loc)); return S; end if; -- Build the decl of W_J W_J := Make_Temporary (Loc, 'J', L); W_Decl := Make_Object_Declaration (Loc, Defining_Identifier => W_J, Object_Definition => Index_Base_Name, Expression => L); -- Theoretically we should do a New_Copy_Tree (L) here, but we know -- that in this particular case L is a fresh Expr generated by -- Add which we are the only ones to use. Append_To (S, W_Decl); -- Construct " while W_J < H" W_Iteration_Scheme := Make_Iteration_Scheme (Loc, Condition => Make_Op_Lt (Loc, Left_Opnd => New_Occurrence_Of (W_J, Loc), Right_Opnd => New_Copy_Tree (H))); -- Construct the statements to execute in the loop body W_Index_Succ := Make_Attribute_Reference (Loc, Prefix => Index_Base_Name, Attribute_Name => Name_Succ, Expressions => New_List (New_Occurrence_Of (W_J, Loc))); W_Increment := Make_OK_Assignment_Statement (Loc, Name => New_Occurrence_Of (W_J, Loc), Expression => W_Index_Succ); Append_To (W_Body, W_Increment); Append_List_To (W_Body, Gen_Assign (New_Occurrence_Of (W_J, Loc), Expr, In_Loop => True)); -- Construct the final loop Append_To (S, Make_Implicit_Loop_Statement (Node => N, Identifier => Empty, Iteration_Scheme => W_Iteration_Scheme, Statements => W_Body)); return S; end Gen_While; -------------------- -- Get_Assoc_Expr -- -------------------- function Get_Assoc_Expr (Assoc : Node_Id) return Node_Id is Typ : constant Entity_Id := Base_Type (Etype (N)); begin if Box_Present (Assoc) then if Is_Scalar_Type (Ctype) then if Present (Default_Aspect_Component_Value (Typ)) then return Default_Aspect_Component_Value (Typ); elsif Present (Default_Aspect_Value (Ctype)) then return Default_Aspect_Value (Ctype); else return Empty; end if; else return Empty; end if; else return Expression (Assoc); end if; end Get_Assoc_Expr; --------------------- -- Index_Base_Name -- --------------------- function Index_Base_Name return Node_Id is begin return New_Occurrence_Of (Index_Base, Sloc (N)); end Index_Base_Name; ------------------------------------ -- Local_Compile_Time_Known_Value -- ------------------------------------ function Local_Compile_Time_Known_Value (E : Node_Id) return Boolean is begin return Compile_Time_Known_Value (E) or else (Nkind (E) = N_Attribute_Reference and then Attribute_Name (E) = Name_Val and then Compile_Time_Known_Value (First (Expressions (E)))); end Local_Compile_Time_Known_Value; ---------------------- -- Local_Expr_Value -- ---------------------- function Local_Expr_Value (E : Node_Id) return Uint is begin if Compile_Time_Known_Value (E) then return Expr_Value (E); else return Expr_Value (First (Expressions (E))); end if; end Local_Expr_Value; -- Local variables New_Code : constant List_Id := New_List; Aggr_L : constant Node_Id := Low_Bound (Aggregate_Bounds (N)); Aggr_H : constant Node_Id := High_Bound (Aggregate_Bounds (N)); -- The aggregate bounds of this specific subaggregate. Note that if the -- code generated by Build_Array_Aggr_Code is executed then these bounds -- are OK. Otherwise a Constraint_Error would have been raised. Aggr_Low : constant Node_Id := Duplicate_Subexpr_No_Checks (Aggr_L); Aggr_High : constant Node_Id := Duplicate_Subexpr_No_Checks (Aggr_H); -- After Duplicate_Subexpr these are side-effect free Assoc : Node_Id; Choice : Node_Id; Expr : Node_Id; High : Node_Id; Low : Node_Id; Typ : Entity_Id; Nb_Choices : Nat := 0; Table : Case_Table_Type (1 .. Number_Of_Choices (N)); -- Used to sort all the different choice values Nb_Elements : Int; -- Number of elements in the positional aggregate Others_Assoc : Node_Id := Empty; -- Start of processing for Build_Array_Aggr_Code begin -- First before we start, a special case. if we have a bit packed -- array represented as a modular type, then clear the value to -- zero first, to ensure that unused bits are properly cleared. Typ := Etype (N); if Present (Typ) and then Is_Bit_Packed_Array (Typ) and then Is_Modular_Integer_Type (Packed_Array_Impl_Type (Typ)) then Append_To (New_Code, Make_Assignment_Statement (Loc, Name => New_Copy_Tree (Into), Expression => Unchecked_Convert_To (Typ, Make_Integer_Literal (Loc, Uint_0)))); end if; -- If the component type contains tasks, we need to build a Master -- entity in the current scope, because it will be needed if build- -- in-place functions are called in the expanded code. if Nkind (Parent (N)) = N_Object_Declaration and then Has_Task (Typ) then Build_Master_Entity (Defining_Identifier (Parent (N))); end if; -- STEP 1: Process component associations -- For those associations that may generate a loop, initialize -- Loop_Actions to collect inserted actions that may be crated. -- Skip this if no component associations if No (Expressions (N)) then -- STEP 1 (a): Sort the discrete choices Assoc := First (Component_Associations (N)); while Present (Assoc) loop Choice := First (Choice_List (Assoc)); while Present (Choice) loop if Nkind (Choice) = N_Others_Choice then Set_Loop_Actions (Assoc, New_List); Others_Assoc := Assoc; exit; end if; Get_Index_Bounds (Choice, Low, High); if Low /= High then Set_Loop_Actions (Assoc, New_List); end if; Nb_Choices := Nb_Choices + 1; Table (Nb_Choices) := (Choice_Lo => Low, Choice_Hi => High, Choice_Node => Get_Assoc_Expr (Assoc)); Next (Choice); end loop; Next (Assoc); end loop; -- If there is more than one set of choices these must be static -- and we can therefore sort them. Remember that Nb_Choices does not -- account for an others choice. if Nb_Choices > 1 then Sort_Case_Table (Table); end if; -- STEP 1 (b): take care of the whole set of discrete choices for J in 1 .. Nb_Choices loop Low := Table (J).Choice_Lo; High := Table (J).Choice_Hi; Expr := Table (J).Choice_Node; Append_List (Gen_Loop (Low, High, Expr), To => New_Code); end loop; -- STEP 1 (c): generate the remaining loops to cover others choice -- We don't need to generate loops over empty gaps, but if there is -- a single empty range we must analyze the expression for semantics if Present (Others_Assoc) then declare First : Boolean := True; begin for J in 0 .. Nb_Choices loop if J = 0 then Low := Aggr_Low; else Low := Add (1, To => Table (J).Choice_Hi); end if; if J = Nb_Choices then High := Aggr_High; else High := Add (-1, To => Table (J + 1).Choice_Lo); end if; -- If this is an expansion within an init proc, make -- sure that discriminant references are replaced by -- the corresponding discriminal. if Inside_Init_Proc then if Is_Entity_Name (Low) and then Ekind (Entity (Low)) = E_Discriminant then Set_Entity (Low, Discriminal (Entity (Low))); end if; if Is_Entity_Name (High) and then Ekind (Entity (High)) = E_Discriminant then Set_Entity (High, Discriminal (Entity (High))); end if; end if; if First or else not Empty_Range (Low, High) then First := False; Append_List (Gen_Loop (Low, High, Get_Assoc_Expr (Others_Assoc)), To => New_Code); end if; end loop; end; end if; -- STEP 2: Process positional components else -- STEP 2 (a): Generate the assignments for each positional element -- Note that here we have to use Aggr_L rather than Aggr_Low because -- Aggr_L is analyzed and Add wants an analyzed expression. Expr := First (Expressions (N)); Nb_Elements := -1; while Present (Expr) loop Nb_Elements := Nb_Elements + 1; Append_List (Gen_Assign (Add (Nb_Elements, To => Aggr_L), Expr), To => New_Code); Next (Expr); end loop; -- STEP 2 (b): Generate final loop if an others choice is present -- Here Nb_Elements gives the offset of the last positional element. if Present (Component_Associations (N)) then Assoc := Last (Component_Associations (N)); -- Ada 2005 (AI-287) Append_List (Gen_While (Add (Nb_Elements, To => Aggr_L), Aggr_High, Get_Assoc_Expr (Assoc)), -- AI-287 To => New_Code); end if; end if; return New_Code; end Build_Array_Aggr_Code; ---------------------------- -- Build_Record_Aggr_Code -- ---------------------------- function Build_Record_Aggr_Code (N : Node_Id; Typ : Entity_Id; Lhs : Node_Id) return List_Id is Loc : constant Source_Ptr := Sloc (N); L : constant List_Id := New_List; N_Typ : constant Entity_Id := Etype (N); Comp : Node_Id; Instr : Node_Id; Ref : Node_Id; Target : Entity_Id; Comp_Type : Entity_Id; Selector : Entity_Id; Comp_Expr : Node_Id; Expr_Q : Node_Id; -- If this is an internal aggregate, the External_Final_List is an -- expression for the controller record of the enclosing type. -- If the current aggregate has several controlled components, this -- expression will appear in several calls to attach to the finali- -- zation list, and it must not be shared. Ancestor_Is_Expression : Boolean := False; Ancestor_Is_Subtype_Mark : Boolean := False; Init_Typ : Entity_Id := Empty; Finalization_Done : Boolean := False; -- True if Generate_Finalization_Actions has already been called; calls -- after the first do nothing. function Ancestor_Discriminant_Value (Disc : Entity_Id) return Node_Id; -- Returns the value that the given discriminant of an ancestor type -- should receive (in the absence of a conflict with the value provided -- by an ancestor part of an extension aggregate). procedure Check_Ancestor_Discriminants (Anc_Typ : Entity_Id); -- Check that each of the discriminant values defined by the ancestor -- part of an extension aggregate match the corresponding values -- provided by either an association of the aggregate or by the -- constraint imposed by a parent type (RM95-4.3.2(8)). function Compatible_Int_Bounds (Agg_Bounds : Node_Id; Typ_Bounds : Node_Id) return Boolean; -- Return true if Agg_Bounds are equal or within Typ_Bounds. It is -- assumed that both bounds are integer ranges. procedure Generate_Finalization_Actions; -- Deal with the various controlled type data structure initializations -- (but only if it hasn't been done already). function Get_Constraint_Association (T : Entity_Id) return Node_Id; -- Returns the first discriminant association in the constraint -- associated with T, if any, otherwise returns Empty. function Get_Explicit_Discriminant_Value (D : Entity_Id) return Node_Id; -- If the ancestor part is an unconstrained type and further ancestors -- do not provide discriminants for it, check aggregate components for -- values of the discriminants. procedure Init_Hidden_Discriminants (Typ : Entity_Id; List : List_Id); -- If Typ is derived, and constrains discriminants of the parent type, -- these discriminants are not components of the aggregate, and must be -- initialized. The assignments are appended to List. The same is done -- if Typ derives fron an already constrained subtype of a discriminated -- parent type. procedure Init_Stored_Discriminants; -- If the type is derived and has inherited discriminants, generate -- explicit assignments for each, using the store constraint of the -- type. Note that both visible and stored discriminants must be -- initialized in case the derived type has some renamed and some -- constrained discriminants. procedure Init_Visible_Discriminants; -- If type has discriminants, retrieve their values from aggregate, -- and generate explicit assignments for each. This does not include -- discriminants inherited from ancestor, which are handled above. -- The type of the aggregate is a subtype created ealier using the -- given values of the discriminant components of the aggregate. procedure Initialize_Ctrl_Record_Component (Rec_Comp : Node_Id; Comp_Typ : Entity_Id; Init_Expr : Node_Id; Stmts : List_Id); -- Perform the initialization of controlled record component Rec_Comp. -- Comp_Typ is the component type. Init_Expr is the initialization -- expression for the record component. Hook-related declarations are -- inserted prior to aggregate N using Insert_Action. All remaining -- generated code is added to list Stmts. procedure Initialize_Record_Component (Rec_Comp : Node_Id; Comp_Typ : Entity_Id; Init_Expr : Node_Id; Stmts : List_Id); -- Perform the initialization of record component Rec_Comp. Comp_Typ -- is the component type. Init_Expr is the initialization expression -- of the record component. All generated code is added to list Stmts. function Is_Int_Range_Bounds (Bounds : Node_Id) return Boolean; -- Check whether Bounds is a range node and its lower and higher bounds -- are integers literals. function Replace_Type (Expr : Node_Id) return Traverse_Result; -- If the aggregate contains a self-reference, traverse each expression -- to replace a possible self-reference with a reference to the proper -- component of the target of the assignment. function Rewrite_Discriminant (Expr : Node_Id) return Traverse_Result; -- If default expression of a component mentions a discriminant of the -- type, it must be rewritten as the discriminant of the target object. --------------------------------- -- Ancestor_Discriminant_Value -- --------------------------------- function Ancestor_Discriminant_Value (Disc : Entity_Id) return Node_Id is Assoc : Node_Id; Assoc_Elmt : Elmt_Id; Aggr_Comp : Entity_Id; Corresp_Disc : Entity_Id; Current_Typ : Entity_Id := Base_Type (Typ); Parent_Typ : Entity_Id; Parent_Disc : Entity_Id; Save_Assoc : Node_Id := Empty; begin -- First check any discriminant associations to see if any of them -- provide a value for the discriminant. if Present (Discriminant_Specifications (Parent (Current_Typ))) then Assoc := First (Component_Associations (N)); while Present (Assoc) loop Aggr_Comp := Entity (First (Choices (Assoc))); if Ekind (Aggr_Comp) = E_Discriminant then Save_Assoc := Expression (Assoc); Corresp_Disc := Corresponding_Discriminant (Aggr_Comp); while Present (Corresp_Disc) loop -- If found a corresponding discriminant then return the -- value given in the aggregate. (Note: this is not -- correct in the presence of side effects. ???) if Disc = Corresp_Disc then return Duplicate_Subexpr (Expression (Assoc)); end if; Corresp_Disc := Corresponding_Discriminant (Corresp_Disc); end loop; end if; Next (Assoc); end loop; end if; -- No match found in aggregate, so chain up parent types to find -- a constraint that defines the value of the discriminant. Parent_Typ := Etype (Current_Typ); while Current_Typ /= Parent_Typ loop if Has_Discriminants (Parent_Typ) and then not Has_Unknown_Discriminants (Parent_Typ) then Parent_Disc := First_Discriminant (Parent_Typ); -- We either get the association from the subtype indication -- of the type definition itself, or from the discriminant -- constraint associated with the type entity (which is -- preferable, but it's not always present ???) if Is_Empty_Elmt_List (Discriminant_Constraint (Current_Typ)) then Assoc := Get_Constraint_Association (Current_Typ); Assoc_Elmt := No_Elmt; else Assoc_Elmt := First_Elmt (Discriminant_Constraint (Current_Typ)); Assoc := Node (Assoc_Elmt); end if; -- Traverse the discriminants of the parent type looking -- for one that corresponds. while Present (Parent_Disc) and then Present (Assoc) loop Corresp_Disc := Parent_Disc; while Present (Corresp_Disc) and then Disc /= Corresp_Disc loop Corresp_Disc := Corresponding_Discriminant (Corresp_Disc); end loop; if Disc = Corresp_Disc then if Nkind (Assoc) = N_Discriminant_Association then Assoc := Expression (Assoc); end if; -- If the located association directly denotes -- a discriminant, then use the value of a saved -- association of the aggregate. This is an approach -- used to handle certain cases involving multiple -- discriminants mapped to a single discriminant of -- a descendant. It's not clear how to locate the -- appropriate discriminant value for such cases. ??? if Is_Entity_Name (Assoc) and then Ekind (Entity (Assoc)) = E_Discriminant then Assoc := Save_Assoc; end if; return Duplicate_Subexpr (Assoc); end if; Next_Discriminant (Parent_Disc); if No (Assoc_Elmt) then Next (Assoc); else Next_Elmt (Assoc_Elmt); if Present (Assoc_Elmt) then Assoc := Node (Assoc_Elmt); else Assoc := Empty; end if; end if; end loop; end if; Current_Typ := Parent_Typ; Parent_Typ := Etype (Current_Typ); end loop; -- In some cases there's no ancestor value to locate (such as -- when an ancestor part given by an expression defines the -- discriminant value). return Empty; end Ancestor_Discriminant_Value; ---------------------------------- -- Check_Ancestor_Discriminants -- ---------------------------------- procedure Check_Ancestor_Discriminants (Anc_Typ : Entity_Id) is Discr : Entity_Id; Disc_Value : Node_Id; Cond : Node_Id; begin Discr := First_Discriminant (Base_Type (Anc_Typ)); while Present (Discr) loop Disc_Value := Ancestor_Discriminant_Value (Discr); if Present (Disc_Value) then Cond := Make_Op_Ne (Loc, Left_Opnd => Make_Selected_Component (Loc, Prefix => New_Copy_Tree (Target), Selector_Name => New_Occurrence_Of (Discr, Loc)), Right_Opnd => Disc_Value); Append_To (L, Make_Raise_Constraint_Error (Loc, Condition => Cond, Reason => CE_Discriminant_Check_Failed)); end if; Next_Discriminant (Discr); end loop; end Check_Ancestor_Discriminants; --------------------------- -- Compatible_Int_Bounds -- --------------------------- function Compatible_Int_Bounds (Agg_Bounds : Node_Id; Typ_Bounds : Node_Id) return Boolean is Agg_Lo : constant Uint := Intval (Low_Bound (Agg_Bounds)); Agg_Hi : constant Uint := Intval (High_Bound (Agg_Bounds)); Typ_Lo : constant Uint := Intval (Low_Bound (Typ_Bounds)); Typ_Hi : constant Uint := Intval (High_Bound (Typ_Bounds)); begin return Typ_Lo <= Agg_Lo and then Agg_Hi <= Typ_Hi; end Compatible_Int_Bounds; ----------------------------------- -- Generate_Finalization_Actions -- ----------------------------------- procedure Generate_Finalization_Actions is begin -- Do the work only the first time this is called if Finalization_Done then return; end if; Finalization_Done := True; -- Determine the external finalization list. It is either the -- finalization list of the outer scope or the one coming from an -- outer aggregate. When the target is not a temporary, the proper -- scope is the scope of the target rather than the potentially -- transient current scope. if Is_Controlled (Typ) and then Ancestor_Is_Subtype_Mark then Ref := Convert_To (Init_Typ, New_Copy_Tree (Target)); Set_Assignment_OK (Ref); Append_To (L, Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (Find_Prim_Op (Init_Typ, Name_Initialize), Loc), Parameter_Associations => New_List (New_Copy_Tree (Ref)))); end if; end Generate_Finalization_Actions; -------------------------------- -- Get_Constraint_Association -- -------------------------------- function Get_Constraint_Association (T : Entity_Id) return Node_Id is Indic : Node_Id; Typ : Entity_Id; begin Typ := T; -- If type is private, get constraint from full view. This was -- previously done in an instance context, but is needed whenever -- the ancestor part has a discriminant, possibly inherited through -- multiple derivations. if Is_Private_Type (Typ) and then Present (Full_View (Typ)) then Typ := Full_View (Typ); end if; Indic := Subtype_Indication (Type_Definition (Parent (Typ))); -- Verify that the subtype indication carries a constraint if Nkind (Indic) = N_Subtype_Indication and then Present (Constraint (Indic)) then return First (Constraints (Constraint (Indic))); end if; return Empty; end Get_Constraint_Association; ------------------------------------- -- Get_Explicit_Discriminant_Value -- ------------------------------------- function Get_Explicit_Discriminant_Value (D : Entity_Id) return Node_Id is Assoc : Node_Id; Choice : Node_Id; Val : Node_Id; begin -- The aggregate has been normalized and all associations have a -- single choice. Assoc := First (Component_Associations (N)); while Present (Assoc) loop Choice := First (Choices (Assoc)); if Chars (Choice) = Chars (D) then Val := Expression (Assoc); Remove (Assoc); return Val; end if; Next (Assoc); end loop; return Empty; end Get_Explicit_Discriminant_Value; ------------------------------- -- Init_Hidden_Discriminants -- ------------------------------- procedure Init_Hidden_Discriminants (Typ : Entity_Id; List : List_Id) is function Is_Completely_Hidden_Discriminant (Discr : Entity_Id) return Boolean; -- Determine whether Discr is a completely hidden discriminant of -- type Typ. --------------------------------------- -- Is_Completely_Hidden_Discriminant -- --------------------------------------- function Is_Completely_Hidden_Discriminant (Discr : Entity_Id) return Boolean is Item : Entity_Id; begin -- Use First/Next_Entity as First/Next_Discriminant do not yield -- completely hidden discriminants. Item := First_Entity (Typ); while Present (Item) loop if Ekind (Item) = E_Discriminant and then Is_Completely_Hidden (Item) and then Chars (Original_Record_Component (Item)) = Chars (Discr) then return True; end if; Next_Entity (Item); end loop; return False; end Is_Completely_Hidden_Discriminant; -- Local variables Base_Typ : Entity_Id; Discr : Entity_Id; Discr_Constr : Elmt_Id; Discr_Init : Node_Id; Discr_Val : Node_Id; In_Aggr_Type : Boolean; Par_Typ : Entity_Id; -- Start of processing for Init_Hidden_Discriminants begin -- The constraints on the hidden discriminants, if present, are kept -- in the Stored_Constraint list of the type itself, or in that of -- the base type. If not in the constraints of the aggregate itself, -- we examine ancestors to find discriminants that are not renamed -- by other discriminants but constrained explicitly. In_Aggr_Type := True; Base_Typ := Base_Type (Typ); while Is_Derived_Type (Base_Typ) and then (Present (Stored_Constraint (Base_Typ)) or else (In_Aggr_Type and then Present (Stored_Constraint (Typ)))) loop Par_Typ := Etype (Base_Typ); if not Has_Discriminants (Par_Typ) then return; end if; Discr := First_Discriminant (Par_Typ); -- We know that one of the stored-constraint lists is present if Present (Stored_Constraint (Base_Typ)) then Discr_Constr := First_Elmt (Stored_Constraint (Base_Typ)); -- For private extension, stored constraint may be on full view elsif Is_Private_Type (Base_Typ) and then Present (Full_View (Base_Typ)) and then Present (Stored_Constraint (Full_View (Base_Typ))) then Discr_Constr := First_Elmt (Stored_Constraint (Full_View (Base_Typ))); else Discr_Constr := First_Elmt (Stored_Constraint (Typ)); end if; while Present (Discr) and then Present (Discr_Constr) loop Discr_Val := Node (Discr_Constr); -- The parent discriminant is renamed in the derived type, -- nothing to initialize. -- type Deriv_Typ (Discr : ...) -- is new Parent_Typ (Discr => Discr); if Is_Entity_Name (Discr_Val) and then Ekind (Entity (Discr_Val)) = E_Discriminant then null; -- When the parent discriminant is constrained at the type -- extension level, it does not appear in the derived type. -- type Deriv_Typ (Discr : ...) -- is new Parent_Typ (Discr => Discr, -- Hidden_Discr => Expression); elsif Is_Completely_Hidden_Discriminant (Discr) then null; -- Otherwise initialize the discriminant else Discr_Init := Make_OK_Assignment_Statement (Loc, Name => Make_Selected_Component (Loc, Prefix => New_Copy_Tree (Target), Selector_Name => New_Occurrence_Of (Discr, Loc)), Expression => New_Copy_Tree (Discr_Val)); Set_No_Ctrl_Actions (Discr_Init); Append_To (List, Discr_Init); end if; Next_Elmt (Discr_Constr); Next_Discriminant (Discr); end loop; In_Aggr_Type := False; Base_Typ := Base_Type (Par_Typ); end loop; end Init_Hidden_Discriminants; -------------------------------- -- Init_Visible_Discriminants -- -------------------------------- procedure Init_Visible_Discriminants is Discriminant : Entity_Id; Discriminant_Value : Node_Id; begin Discriminant := First_Discriminant (Typ); while Present (Discriminant) loop Comp_Expr := Make_Selected_Component (Loc, Prefix => New_Copy_Tree (Target), Selector_Name => New_Occurrence_Of (Discriminant, Loc)); Discriminant_Value := Get_Discriminant_Value (Discriminant, Typ, Discriminant_Constraint (N_Typ)); Instr := Make_OK_Assignment_Statement (Loc, Name => Comp_Expr, Expression => New_Copy_Tree (Discriminant_Value)); Set_No_Ctrl_Actions (Instr); Append_To (L, Instr); Next_Discriminant (Discriminant); end loop; end Init_Visible_Discriminants; ------------------------------- -- Init_Stored_Discriminants -- ------------------------------- procedure Init_Stored_Discriminants is Discriminant : Entity_Id; Discriminant_Value : Node_Id; begin Discriminant := First_Stored_Discriminant (Typ); while Present (Discriminant) loop Comp_Expr := Make_Selected_Component (Loc, Prefix => New_Copy_Tree (Target), Selector_Name => New_Occurrence_Of (Discriminant, Loc)); Discriminant_Value := Get_Discriminant_Value (Discriminant, N_Typ, Discriminant_Constraint (N_Typ)); Instr := Make_OK_Assignment_Statement (Loc, Name => Comp_Expr, Expression => New_Copy_Tree (Discriminant_Value)); Set_No_Ctrl_Actions (Instr); Append_To (L, Instr); Next_Stored_Discriminant (Discriminant); end loop; end Init_Stored_Discriminants; -------------------------------------- -- Initialize_Ctrl_Record_Component -- -------------------------------------- procedure Initialize_Ctrl_Record_Component (Rec_Comp : Node_Id; Comp_Typ : Entity_Id; Init_Expr : Node_Id; Stmts : List_Id) is Fin_Call : Node_Id; Hook_Clear : Node_Id; In_Place_Expansion : Boolean; -- Flag set when a nonlimited controlled function call requires -- in-place expansion. begin -- Perform a preliminary analysis and resolution to determine what -- the initialization expression denotes. Unanalyzed function calls -- may appear as identifiers or indexed components. if Nkind_In (Init_Expr, N_Function_Call, N_Identifier, N_Indexed_Component) and then not Analyzed (Init_Expr) then Preanalyze_And_Resolve (Init_Expr, Comp_Typ); end if; In_Place_Expansion := Nkind (Init_Expr) = N_Function_Call and then not Is_Limited_Type (Comp_Typ); -- The initialization expression is a controlled function call. -- Perform in-place removal of side effects to avoid creating a -- transient scope. -- This in-place expansion is not performed for limited transient -- objects because the initialization is already done in place. if In_Place_Expansion then -- Suppress the removal of side effects by general analysis -- because this behavior is emulated here. This avoids the -- generation of a transient scope, which leads to out-of-order -- adjustment and finalization. Set_No_Side_Effect_Removal (Init_Expr); -- Install all hook-related declarations and prepare the clean up -- statements. Process_Transient_Component (Loc => Loc, Comp_Typ => Comp_Typ, Init_Expr => Init_Expr, Fin_Call => Fin_Call, Hook_Clear => Hook_Clear, Aggr => N); end if; -- Use the noncontrolled component initialization circuitry to -- assign the result of the function call to the record component. -- This also performs tag adjustment and [deep] adjustment of the -- record component. Initialize_Record_Component (Rec_Comp => Rec_Comp, Comp_Typ => Comp_Typ, Init_Expr => Init_Expr, Stmts => Stmts); -- At this point the record component is fully initialized. Complete -- the processing of the controlled record component by finalizing -- the transient function result. if In_Place_Expansion then Process_Transient_Component_Completion (Loc => Loc, Aggr => N, Fin_Call => Fin_Call, Hook_Clear => Hook_Clear, Stmts => Stmts); end if; end Initialize_Ctrl_Record_Component; --------------------------------- -- Initialize_Record_Component -- --------------------------------- procedure Initialize_Record_Component (Rec_Comp : Node_Id; Comp_Typ : Entity_Id; Init_Expr : Node_Id; Stmts : List_Id) is Exceptions_OK : constant Boolean := not Restriction_Active (No_Exception_Propagation); Finalization_OK : constant Boolean := Needs_Finalization (Comp_Typ); Full_Typ : constant Entity_Id := Underlying_Type (Comp_Typ); Adj_Call : Node_Id; Blk_Stmts : List_Id; Init_Stmt : Node_Id; begin -- Protect the initialization statements from aborts. Generate: -- Abort_Defer; if Finalization_OK and Abort_Allowed then if Exceptions_OK then Blk_Stmts := New_List; else Blk_Stmts := Stmts; end if; Append_To (Blk_Stmts, Build_Runtime_Call (Loc, RE_Abort_Defer)); -- Otherwise aborts are not allowed. All generated code is added -- directly to the input list. else Blk_Stmts := Stmts; end if; -- Initialize the record component. Generate: -- Rec_Comp := Init_Expr; -- Note that the initialization expression is NOT replicated because -- only a single component may be initialized by it. Init_Stmt := Make_OK_Assignment_Statement (Loc, Name => New_Copy_Tree (Rec_Comp), Expression => Init_Expr); Set_No_Ctrl_Actions (Init_Stmt); Append_To (Blk_Stmts, Init_Stmt); -- Adjust the tag due to a possible view conversion. Generate: -- Rec_Comp._tag := Full_TypeP; if Tagged_Type_Expansion and then Is_Tagged_Type (Comp_Typ) then Append_To (Blk_Stmts, Make_OK_Assignment_Statement (Loc, Name => Make_Selected_Component (Loc, Prefix => New_Copy_Tree (Rec_Comp), Selector_Name => New_Occurrence_Of (First_Tag_Component (Full_Typ), Loc)), Expression => Unchecked_Convert_To (RTE (RE_Tag), New_Occurrence_Of (Node (First_Elmt (Access_Disp_Table (Full_Typ))), Loc)))); end if; -- Adjust the component. Generate: -- [Deep_]Adjust (Rec_Comp); if Finalization_OK and then not Is_Limited_Type (Comp_Typ) then Adj_Call := Make_Adjust_Call (Obj_Ref => New_Copy_Tree (Rec_Comp), Typ => Comp_Typ); -- Guard against a missing [Deep_]Adjust when the component type -- was not properly frozen. if Present (Adj_Call) then Append_To (Blk_Stmts, Adj_Call); end if; end if; -- Complete the protection of the initialization statements if Finalization_OK and Abort_Allowed then -- Wrap the initialization statements in a block to catch a -- potential exception. Generate: -- begin -- Abort_Defer; -- Rec_Comp := Init_Expr; -- Rec_Comp._tag := Full_TypP; -- [Deep_]Adjust (Rec_Comp); -- at end -- Abort_Undefer_Direct; -- end; if Exceptions_OK then Append_To (Stmts, Build_Abort_Undefer_Block (Loc, Stmts => Blk_Stmts, Context => N)); -- Otherwise exceptions are not propagated. Generate: -- Abort_Defer; -- Rec_Comp := Init_Expr; -- Rec_Comp._tag := Full_TypP; -- [Deep_]Adjust (Rec_Comp); -- Abort_Undefer; else Append_To (Blk_Stmts, Build_Runtime_Call (Loc, RE_Abort_Undefer)); end if; end if; end Initialize_Record_Component; ------------------------- -- Is_Int_Range_Bounds -- ------------------------- function Is_Int_Range_Bounds (Bounds : Node_Id) return Boolean is begin return Nkind (Bounds) = N_Range and then Nkind (Low_Bound (Bounds)) = N_Integer_Literal and then Nkind (High_Bound (Bounds)) = N_Integer_Literal; end Is_Int_Range_Bounds; ------------------ -- Replace_Type -- ------------------ function Replace_Type (Expr : Node_Id) return Traverse_Result is begin -- Note regarding the Root_Type test below: Aggregate components for -- self-referential types include attribute references to the current -- instance, of the form: Typ'access, etc.. These references are -- rewritten as references to the target of the aggregate: the -- left-hand side of an assignment, the entity in a declaration, -- or a temporary. Without this test, we would improperly extended -- this rewriting to attribute references whose prefix was not the -- type of the aggregate. if Nkind (Expr) = N_Attribute_Reference and then Is_Entity_Name (Prefix (Expr)) and then Is_Type (Entity (Prefix (Expr))) and then Root_Type (Etype (N)) = Root_Type (Entity (Prefix (Expr))) then if Is_Entity_Name (Lhs) then Rewrite (Prefix (Expr), New_Occurrence_Of (Entity (Lhs), Loc)); elsif Nkind (Lhs) = N_Selected_Component then Rewrite (Expr, Make_Attribute_Reference (Loc, Attribute_Name => Name_Unrestricted_Access, Prefix => New_Copy_Tree (Lhs))); Set_Analyzed (Parent (Expr), False); else Rewrite (Expr, Make_Attribute_Reference (Loc, Attribute_Name => Name_Unrestricted_Access, Prefix => New_Copy_Tree (Lhs))); Set_Analyzed (Parent (Expr), False); end if; end if; return OK; end Replace_Type; -------------------------- -- Rewrite_Discriminant -- -------------------------- function Rewrite_Discriminant (Expr : Node_Id) return Traverse_Result is begin if Is_Entity_Name (Expr) and then Present (Entity (Expr)) and then Ekind (Entity (Expr)) = E_In_Parameter and then Present (Discriminal_Link (Entity (Expr))) and then Scope (Discriminal_Link (Entity (Expr))) = Base_Type (Etype (N)) then Rewrite (Expr, Make_Selected_Component (Loc, Prefix => New_Copy_Tree (Lhs), Selector_Name => Make_Identifier (Loc, Chars (Expr)))); end if; return OK; end Rewrite_Discriminant; procedure Replace_Discriminants is new Traverse_Proc (Rewrite_Discriminant); procedure Replace_Self_Reference is new Traverse_Proc (Replace_Type); -- Start of processing for Build_Record_Aggr_Code begin if Has_Self_Reference (N) then Replace_Self_Reference (N); end if; -- If the target of the aggregate is class-wide, we must convert it -- to the actual type of the aggregate, so that the proper components -- are visible. We know already that the types are compatible. if Present (Etype (Lhs)) and then Is_Class_Wide_Type (Etype (Lhs)) then Target := Unchecked_Convert_To (Typ, Lhs); else Target := Lhs; end if; -- Deal with the ancestor part of extension aggregates or with the -- discriminants of the root type. if Nkind (N) = N_Extension_Aggregate then declare Ancestor : constant Node_Id := Ancestor_Part (N); Adj_Call : Node_Id; Assign : List_Id; begin -- If the ancestor part is a subtype mark "T", we generate -- init-proc (T (tmp)); if T is constrained and -- init-proc (S (tmp)); where S applies an appropriate -- constraint if T is unconstrained if Is_Entity_Name (Ancestor) and then Is_Type (Entity (Ancestor)) then Ancestor_Is_Subtype_Mark := True; if Is_Constrained (Entity (Ancestor)) then Init_Typ := Entity (Ancestor); -- For an ancestor part given by an unconstrained type mark, -- create a subtype constrained by appropriate corresponding -- discriminant values coming from either associations of the -- aggregate or a constraint on a parent type. The subtype will -- be used to generate the correct default value for the -- ancestor part. elsif Has_Discriminants (Entity (Ancestor)) then declare Anc_Typ : constant Entity_Id := Entity (Ancestor); Anc_Constr : constant List_Id := New_List; Discrim : Entity_Id; Disc_Value : Node_Id; New_Indic : Node_Id; Subt_Decl : Node_Id; begin Discrim := First_Discriminant (Anc_Typ); while Present (Discrim) loop Disc_Value := Ancestor_Discriminant_Value (Discrim); -- If no usable discriminant in ancestors, check -- whether aggregate has an explicit value for it. if No (Disc_Value) then Disc_Value := Get_Explicit_Discriminant_Value (Discrim); end if; Append_To (Anc_Constr, Disc_Value); Next_Discriminant (Discrim); end loop; New_Indic := Make_Subtype_Indication (Loc, Subtype_Mark => New_Occurrence_Of (Anc_Typ, Loc), Constraint => Make_Index_Or_Discriminant_Constraint (Loc, Constraints => Anc_Constr)); Init_Typ := Create_Itype (Ekind (Anc_Typ), N); Subt_Decl := Make_Subtype_Declaration (Loc, Defining_Identifier => Init_Typ, Subtype_Indication => New_Indic); -- Itypes must be analyzed with checks off Declaration -- must have a parent for proper handling of subsidiary -- actions. Set_Parent (Subt_Decl, N); Analyze (Subt_Decl, Suppress => All_Checks); end; end if; Ref := Convert_To (Init_Typ, New_Copy_Tree (Target)); Set_Assignment_OK (Ref); if not Is_Interface (Init_Typ) then Append_List_To (L, Build_Initialization_Call (Loc, Id_Ref => Ref, Typ => Init_Typ, In_Init_Proc => Within_Init_Proc, With_Default_Init => Has_Default_Init_Comps (N) or else Has_Task (Base_Type (Init_Typ)))); if Is_Constrained (Entity (Ancestor)) and then Has_Discriminants (Entity (Ancestor)) then Check_Ancestor_Discriminants (Entity (Ancestor)); end if; end if; -- Handle calls to C++ constructors elsif Is_CPP_Constructor_Call (Ancestor) then Init_Typ := Etype (Ancestor); Ref := Convert_To (Init_Typ, New_Copy_Tree (Target)); Set_Assignment_OK (Ref); Append_List_To (L, Build_Initialization_Call (Loc, Id_Ref => Ref, Typ => Init_Typ, In_Init_Proc => Within_Init_Proc, With_Default_Init => Has_Default_Init_Comps (N), Constructor_Ref => Ancestor)); -- Ada 2005 (AI-287): If the ancestor part is an aggregate of -- limited type, a recursive call expands the ancestor. Note that -- in the limited case, the ancestor part must be either a -- function call (possibly qualified, or wrapped in an unchecked -- conversion) or aggregate (definitely qualified). -- The ancestor part can also be a function call (that may be -- transformed into an explicit dereference) or a qualification -- of one such. elsif Is_Limited_Type (Etype (Ancestor)) and then Nkind_In (Unqualify (Ancestor), N_Aggregate, N_Extension_Aggregate) then Ancestor_Is_Expression := True; -- Set up finalization data for enclosing record, because -- controlled subcomponents of the ancestor part will be -- attached to it. Generate_Finalization_Actions; Append_List_To (L, Build_Record_Aggr_Code (N => Unqualify (Ancestor), Typ => Etype (Unqualify (Ancestor)), Lhs => Target)); -- If the ancestor part is an expression "E", we generate -- T (tmp) := E; -- In Ada 2005, this includes the case of a (possibly qualified) -- limited function call. The assignment will turn into a -- build-in-place function call (for further details, see -- Make_Build_In_Place_Call_In_Assignment). else Ancestor_Is_Expression := True; Init_Typ := Etype (Ancestor); -- If the ancestor part is an aggregate, force its full -- expansion, which was delayed. if Nkind_In (Unqualify (Ancestor), N_Aggregate, N_Extension_Aggregate) then Set_Analyzed (Ancestor, False); Set_Analyzed (Expression (Ancestor), False); end if; Ref := Convert_To (Init_Typ, New_Copy_Tree (Target)); Set_Assignment_OK (Ref); -- Make the assignment without usual controlled actions, since -- we only want to Adjust afterwards, but not to Finalize -- beforehand. Add manual Adjust when necessary. Assign := New_List ( Make_OK_Assignment_Statement (Loc, Name => Ref, Expression => Ancestor)); Set_No_Ctrl_Actions (First (Assign)); -- Assign the tag now to make sure that the dispatching call in -- the subsequent deep_adjust works properly (unless -- Tagged_Type_Expansion where tags are implicit). if Tagged_Type_Expansion then Instr := Make_OK_Assignment_Statement (Loc, Name => Make_Selected_Component (Loc, Prefix => New_Copy_Tree (Target), Selector_Name => New_Occurrence_Of (First_Tag_Component (Base_Type (Typ)), Loc)), Expression => Unchecked_Convert_To (RTE (RE_Tag), New_Occurrence_Of (Node (First_Elmt (Access_Disp_Table (Base_Type (Typ)))), Loc))); Set_Assignment_OK (Name (Instr)); Append_To (Assign, Instr); -- Ada 2005 (AI-251): If tagged type has progenitors we must -- also initialize tags of the secondary dispatch tables. if Has_Interfaces (Base_Type (Typ)) then Init_Secondary_Tags (Typ => Base_Type (Typ), Target => Target, Stmts_List => Assign); end if; end if; -- Call Adjust manually if Needs_Finalization (Etype (Ancestor)) and then not Is_Limited_Type (Etype (Ancestor)) then Adj_Call := Make_Adjust_Call (Obj_Ref => New_Copy_Tree (Ref), Typ => Etype (Ancestor)); -- Guard against a missing [Deep_]Adjust when the ancestor -- type was not properly frozen. if Present (Adj_Call) then Append_To (Assign, Adj_Call); end if; end if; Append_To (L, Make_Unsuppress_Block (Loc, Name_Discriminant_Check, Assign)); if Has_Discriminants (Init_Typ) then Check_Ancestor_Discriminants (Init_Typ); end if; end if; end; -- Generate assignments of hidden discriminants. If the base type is -- an unchecked union, the discriminants are unknown to the back-end -- and absent from a value of the type, so assignments for them are -- not emitted. if Has_Discriminants (Typ) and then not Is_Unchecked_Union (Base_Type (Typ)) then Init_Hidden_Discriminants (Typ, L); end if; -- Normal case (not an extension aggregate) else -- Generate the discriminant expressions, component by component. -- If the base type is an unchecked union, the discriminants are -- unknown to the back-end and absent from a value of the type, so -- assignments for them are not emitted. if Has_Discriminants (Typ) and then not Is_Unchecked_Union (Base_Type (Typ)) then Init_Hidden_Discriminants (Typ, L); -- Generate discriminant init values for the visible discriminants Init_Visible_Discriminants; if Is_Derived_Type (N_Typ) then Init_Stored_Discriminants; end if; end if; end if; -- For CPP types we generate an implicit call to the C++ default -- constructor to ensure the proper initialization of the _Tag -- component. if Is_CPP_Class (Root_Type (Typ)) and then CPP_Num_Prims (Typ) > 0 then Invoke_Constructor : declare CPP_Parent : constant Entity_Id := Enclosing_CPP_Parent (Typ); procedure Invoke_IC_Proc (T : Entity_Id); -- Recursive routine used to climb to parents. Required because -- parents must be initialized before descendants to ensure -- propagation of inherited C++ slots. -------------------- -- Invoke_IC_Proc -- -------------------- procedure Invoke_IC_Proc (T : Entity_Id) is begin -- Avoid generating extra calls. Initialization required -- only for types defined from the level of derivation of -- type of the constructor and the type of the aggregate. if T = CPP_Parent then return; end if; Invoke_IC_Proc (Etype (T)); -- Generate call to the IC routine if Present (CPP_Init_Proc (T)) then Append_To (L, Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (CPP_Init_Proc (T), Loc))); end if; end Invoke_IC_Proc; -- Start of processing for Invoke_Constructor begin -- Implicit invocation of the C++ constructor if Nkind (N) = N_Aggregate then Append_To (L, Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (Base_Init_Proc (CPP_Parent), Loc), Parameter_Associations => New_List ( Unchecked_Convert_To (CPP_Parent, New_Copy_Tree (Lhs))))); end if; Invoke_IC_Proc (Typ); end Invoke_Constructor; end if; -- Generate the assignments, component by component -- tmp.comp1 := Expr1_From_Aggr; -- tmp.comp2 := Expr2_From_Aggr; -- .... Comp := First (Component_Associations (N)); while Present (Comp) loop Selector := Entity (First (Choices (Comp))); -- C++ constructors if Is_CPP_Constructor_Call (Expression (Comp)) then Append_List_To (L, Build_Initialization_Call (Loc, Id_Ref => Make_Selected_Component (Loc, Prefix => New_Copy_Tree (Target), Selector_Name => New_Occurrence_Of (Selector, Loc)), Typ => Etype (Selector), Enclos_Type => Typ, With_Default_Init => True, Constructor_Ref => Expression (Comp))); -- Ada 2005 (AI-287): For each default-initialized component generate -- a call to the corresponding IP subprogram if available. elsif Box_Present (Comp) and then Has_Non_Null_Base_Init_Proc (Etype (Selector)) then if Ekind (Selector) /= E_Discriminant then Generate_Finalization_Actions; end if; -- Ada 2005 (AI-287): If the component type has tasks then -- generate the activation chain and master entities (except -- in case of an allocator because in that case these entities -- are generated by Build_Task_Allocate_Block_With_Init_Stmts). declare Ctype : constant Entity_Id := Etype (Selector); Inside_Allocator : Boolean := False; P : Node_Id := Parent (N); begin if Is_Task_Type (Ctype) or else Has_Task (Ctype) then while Present (P) loop if Nkind (P) = N_Allocator then Inside_Allocator := True; exit; end if; P := Parent (P); end loop; if not Inside_Init_Proc and not Inside_Allocator then Build_Activation_Chain_Entity (N); end if; end if; end; Append_List_To (L, Build_Initialization_Call (Loc, Id_Ref => Make_Selected_Component (Loc, Prefix => New_Copy_Tree (Target), Selector_Name => New_Occurrence_Of (Selector, Loc)), Typ => Etype (Selector), Enclos_Type => Typ, With_Default_Init => True)); -- Prepare for component assignment elsif Ekind (Selector) /= E_Discriminant or else Nkind (N) = N_Extension_Aggregate then -- All the discriminants have now been assigned -- This is now a good moment to initialize and attach all the -- controllers. Their position may depend on the discriminants. if Ekind (Selector) /= E_Discriminant then Generate_Finalization_Actions; end if; Comp_Type := Underlying_Type (Etype (Selector)); Comp_Expr := Make_Selected_Component (Loc, Prefix => New_Copy_Tree (Target), Selector_Name => New_Occurrence_Of (Selector, Loc)); if Nkind (Expression (Comp)) = N_Qualified_Expression then Expr_Q := Expression (Expression (Comp)); else Expr_Q := Expression (Comp); end if; -- Now either create the assignment or generate the code for the -- inner aggregate top-down. if Is_Delayed_Aggregate (Expr_Q) then -- We have the following case of aggregate nesting inside -- an object declaration: -- type Arr_Typ is array (Integer range <>) of ...; -- type Rec_Typ (...) is record -- Obj_Arr_Typ : Arr_Typ (A .. B); -- end record; -- Obj_Rec_Typ : Rec_Typ := (..., -- Obj_Arr_Typ => (X => (...), Y => (...))); -- The length of the ranges of the aggregate and Obj_Add_Typ -- are equal (B - A = Y - X), but they do not coincide (X /= -- A and B /= Y). This case requires array sliding which is -- performed in the following manner: -- subtype Arr_Sub is Arr_Typ (X .. Y); -- Temp : Arr_Sub; -- Temp (X) := (...); -- ... -- Temp (Y) := (...); -- Obj_Rec_Typ.Obj_Arr_Typ := Temp; if Ekind (Comp_Type) = E_Array_Subtype and then Is_Int_Range_Bounds (Aggregate_Bounds (Expr_Q)) and then Is_Int_Range_Bounds (First_Index (Comp_Type)) and then not Compatible_Int_Bounds (Agg_Bounds => Aggregate_Bounds (Expr_Q), Typ_Bounds => First_Index (Comp_Type)) then -- Create the array subtype with bounds equal to those of -- the corresponding aggregate. declare SubE : constant Entity_Id := Make_Temporary (Loc, 'T'); SubD : constant Node_Id := Make_Subtype_Declaration (Loc, Defining_Identifier => SubE, Subtype_Indication => Make_Subtype_Indication (Loc, Subtype_Mark => New_Occurrence_Of (Etype (Comp_Type), Loc), Constraint => Make_Index_Or_Discriminant_Constraint (Loc, Constraints => New_List ( New_Copy_Tree (Aggregate_Bounds (Expr_Q)))))); -- Create a temporary array of the above subtype which -- will be used to capture the aggregate assignments. TmpE : constant Entity_Id := Make_Temporary (Loc, 'A', N); TmpD : constant Node_Id := Make_Object_Declaration (Loc, Defining_Identifier => TmpE, Object_Definition => New_Occurrence_Of (SubE, Loc)); begin Set_No_Initialization (TmpD); Append_To (L, SubD); Append_To (L, TmpD); -- Expand aggregate into assignments to the temp array Append_List_To (L, Late_Expansion (Expr_Q, Comp_Type, New_Occurrence_Of (TmpE, Loc))); -- Slide Append_To (L, Make_Assignment_Statement (Loc, Name => New_Copy_Tree (Comp_Expr), Expression => New_Occurrence_Of (TmpE, Loc))); end; -- Normal case (sliding not required) else Append_List_To (L, Late_Expansion (Expr_Q, Comp_Type, Comp_Expr)); end if; -- Expr_Q is not delayed aggregate else if Has_Discriminants (Typ) then Replace_Discriminants (Expr_Q); -- If the component is an array type that depends on -- discriminants, and the expression is a single Others -- clause, create an explicit subtype for it because the -- backend has troubles recovering the actual bounds. if Nkind (Expr_Q) = N_Aggregate and then Is_Array_Type (Comp_Type) and then Present (Component_Associations (Expr_Q)) then declare Assoc : constant Node_Id := First (Component_Associations (Expr_Q)); Decl : Node_Id; begin if Nkind (First (Choices (Assoc))) = N_Others_Choice then Decl := Build_Actual_Subtype_Of_Component (Comp_Type, Comp_Expr); -- If the component type does not in fact depend on -- discriminants, the subtype declaration is empty. if Present (Decl) then Append_To (L, Decl); Set_Etype (Comp_Expr, Defining_Entity (Decl)); end if; end if; end; end if; end if; if Modify_Tree_For_C and then Nkind (Expr_Q) = N_Aggregate and then Is_Array_Type (Etype (Expr_Q)) and then Present (First_Index (Etype (Expr_Q))) then declare Expr_Q_Type : constant Node_Id := Etype (Expr_Q); begin Append_List_To (L, Build_Array_Aggr_Code (N => Expr_Q, Ctype => Component_Type (Expr_Q_Type), Index => First_Index (Expr_Q_Type), Into => Comp_Expr, Scalar_Comp => Is_Scalar_Type (Component_Type (Expr_Q_Type)))); end; else -- Handle an initialization expression of a controlled type -- in case it denotes a function call. In general such a -- scenario will produce a transient scope, but this will -- lead to wrong order of initialization, adjustment, and -- finalization in the context of aggregates. -- Target.Comp := Ctrl_Func_Call; -- begin -- scope -- Trans_Obj : ... := Ctrl_Func_Call; -- object -- Target.Comp := Trans_Obj; -- Finalize (Trans_Obj); -- end -- Target.Comp._tag := ...; -- Adjust (Target.Comp); -- In the example above, the call to Finalize occurs too -- early and as a result it may leave the record component -- in a bad state. Finalization of the transient object -- should really happen after adjustment. -- To avoid this scenario, perform in-place side-effect -- removal of the function call. This eliminates the -- transient property of the function result and ensures -- correct order of actions. -- Res : ... := Ctrl_Func_Call; -- Target.Comp := Res; -- Target.Comp._tag := ...; -- Adjust (Target.Comp); -- Finalize (Res); if Needs_Finalization (Comp_Type) and then Nkind (Expr_Q) /= N_Aggregate then Initialize_Ctrl_Record_Component (Rec_Comp => Comp_Expr, Comp_Typ => Etype (Selector), Init_Expr => Expr_Q, Stmts => L); -- Otherwise perform single component initialization else Initialize_Record_Component (Rec_Comp => Comp_Expr, Comp_Typ => Etype (Selector), Init_Expr => Expr_Q, Stmts => L); end if; end if; end if; -- comment would be good here ??? elsif Ekind (Selector) = E_Discriminant and then Nkind (N) /= N_Extension_Aggregate and then Nkind (Parent (N)) = N_Component_Association and then Is_Constrained (Typ) then -- We must check that the discriminant value imposed by the -- context is the same as the value given in the subaggregate, -- because after the expansion into assignments there is no -- record on which to perform a regular discriminant check. declare D_Val : Elmt_Id; Disc : Entity_Id; begin D_Val := First_Elmt (Discriminant_Constraint (Typ)); Disc := First_Discriminant (Typ); while Chars (Disc) /= Chars (Selector) loop Next_Discriminant (Disc); Next_Elmt (D_Val); end loop; pragma Assert (Present (D_Val)); -- This check cannot performed for components that are -- constrained by a current instance, because this is not a -- value that can be compared with the actual constraint. if Nkind (Node (D_Val)) /= N_Attribute_Reference or else not Is_Entity_Name (Prefix (Node (D_Val))) or else not Is_Type (Entity (Prefix (Node (D_Val)))) then Append_To (L, Make_Raise_Constraint_Error (Loc, Condition => Make_Op_Ne (Loc, Left_Opnd => New_Copy_Tree (Node (D_Val)), Right_Opnd => Expression (Comp)), Reason => CE_Discriminant_Check_Failed)); else -- Find self-reference in previous discriminant assignment, -- and replace with proper expression. declare Ass : Node_Id; begin Ass := First (L); while Present (Ass) loop if Nkind (Ass) = N_Assignment_Statement and then Nkind (Name (Ass)) = N_Selected_Component and then Chars (Selector_Name (Name (Ass))) = Chars (Disc) then Set_Expression (Ass, New_Copy_Tree (Expression (Comp))); exit; end if; Next (Ass); end loop; end; end if; end; end if; Next (Comp); end loop; -- If the type is tagged, the tag needs to be initialized (unless we -- are in VM-mode where tags are implicit). It is done late in the -- initialization process because in some cases, we call the init -- proc of an ancestor which will not leave out the right tag. if Ancestor_Is_Expression then null; -- For CPP types we generated a call to the C++ default constructor -- before the components have been initialized to ensure the proper -- initialization of the _Tag component (see above). elsif Is_CPP_Class (Typ) then null; elsif Is_Tagged_Type (Typ) and then Tagged_Type_Expansion then Instr := Make_OK_Assignment_Statement (Loc, Name => Make_Selected_Component (Loc, Prefix => New_Copy_Tree (Target), Selector_Name => New_Occurrence_Of (First_Tag_Component (Base_Type (Typ)), Loc)), Expression => Unchecked_Convert_To (RTE (RE_Tag), New_Occurrence_Of (Node (First_Elmt (Access_Disp_Table (Base_Type (Typ)))), Loc))); Append_To (L, Instr); -- Ada 2005 (AI-251): If the tagged type has been derived from an -- abstract interfaces we must also initialize the tags of the -- secondary dispatch tables. if Has_Interfaces (Base_Type (Typ)) then Init_Secondary_Tags (Typ => Base_Type (Typ), Target => Target, Stmts_List => L); end if; end if; -- If the controllers have not been initialized yet (by lack of non- -- discriminant components), let's do it now. Generate_Finalization_Actions; return L; end Build_Record_Aggr_Code; --------------------------------------- -- Collect_Initialization_Statements -- --------------------------------------- procedure Collect_Initialization_Statements (Obj : Entity_Id; N : Node_Id; Node_After : Node_Id) is Loc : constant Source_Ptr := Sloc (N); Init_Actions : constant List_Id := New_List; Init_Node : Node_Id; Comp_Stmt : Node_Id; begin -- Nothing to do if Obj is already frozen, as in this case we known we -- won't need to move the initialization statements about later on. if Is_Frozen (Obj) then return; end if; Init_Node := N; while Next (Init_Node) /= Node_After loop Append_To (Init_Actions, Remove_Next (Init_Node)); end loop; if not Is_Empty_List (Init_Actions) then Comp_Stmt := Make_Compound_Statement (Loc, Actions => Init_Actions); Insert_Action_After (Init_Node, Comp_Stmt); Set_Initialization_Statements (Obj, Comp_Stmt); end if; end Collect_Initialization_Statements; ------------------------------- -- Convert_Aggr_In_Allocator -- ------------------------------- procedure Convert_Aggr_In_Allocator (Alloc : Node_Id; Decl : Node_Id; Aggr : Node_Id) is Loc : constant Source_Ptr := Sloc (Aggr); Typ : constant Entity_Id := Etype (Aggr); Temp : constant Entity_Id := Defining_Identifier (Decl); Occ : constant Node_Id := Unchecked_Convert_To (Typ, Make_Explicit_Dereference (Loc, New_Occurrence_Of (Temp, Loc))); begin if Is_Array_Type (Typ) then Convert_Array_Aggr_In_Allocator (Decl, Aggr, Occ); elsif Has_Default_Init_Comps (Aggr) then declare L : constant List_Id := New_List; Init_Stmts : List_Id; begin Init_Stmts := Late_Expansion (Aggr, Typ, Occ); if Has_Task (Typ) then Build_Task_Allocate_Block_With_Init_Stmts (L, Aggr, Init_Stmts); Insert_Actions (Alloc, L); else Insert_Actions (Alloc, Init_Stmts); end if; end; else Insert_Actions (Alloc, Late_Expansion (Aggr, Typ, Occ)); end if; end Convert_Aggr_In_Allocator; -------------------------------- -- Convert_Aggr_In_Assignment -- -------------------------------- procedure Convert_Aggr_In_Assignment (N : Node_Id) is Aggr : Node_Id := Expression (N); Typ : constant Entity_Id := Etype (Aggr); Occ : constant Node_Id := New_Copy_Tree (Name (N)); begin if Nkind (Aggr) = N_Qualified_Expression then Aggr := Expression (Aggr); end if; Insert_Actions_After (N, Late_Expansion (Aggr, Typ, Occ)); end Convert_Aggr_In_Assignment; --------------------------------- -- Convert_Aggr_In_Object_Decl -- --------------------------------- procedure Convert_Aggr_In_Object_Decl (N : Node_Id) is Obj : constant Entity_Id := Defining_Identifier (N); Aggr : Node_Id := Expression (N); Loc : constant Source_Ptr := Sloc (Aggr); Typ : constant Entity_Id := Etype (Aggr); Occ : constant Node_Id := New_Occurrence_Of (Obj, Loc); function Discriminants_Ok return Boolean; -- If the object type is constrained, the discriminants in the -- aggregate must be checked against the discriminants of the subtype. -- This cannot be done using Apply_Discriminant_Checks because after -- expansion there is no aggregate left to check. ---------------------- -- Discriminants_Ok -- ---------------------- function Discriminants_Ok return Boolean is Cond : Node_Id := Empty; Check : Node_Id; D : Entity_Id; Disc1 : Elmt_Id; Disc2 : Elmt_Id; Val1 : Node_Id; Val2 : Node_Id; begin D := First_Discriminant (Typ); Disc1 := First_Elmt (Discriminant_Constraint (Typ)); Disc2 := First_Elmt (Discriminant_Constraint (Etype (Obj))); while Present (Disc1) and then Present (Disc2) loop Val1 := Node (Disc1); Val2 := Node (Disc2); if not Is_OK_Static_Expression (Val1) or else not Is_OK_Static_Expression (Val2) then Check := Make_Op_Ne (Loc, Left_Opnd => Duplicate_Subexpr (Val1), Right_Opnd => Duplicate_Subexpr (Val2)); if No (Cond) then Cond := Check; else Cond := Make_Or_Else (Loc, Left_Opnd => Cond, Right_Opnd => Check); end if; elsif Expr_Value (Val1) /= Expr_Value (Val2) then Apply_Compile_Time_Constraint_Error (Aggr, Msg => "incorrect value for discriminant&??", Reason => CE_Discriminant_Check_Failed, Ent => D); return False; end if; Next_Discriminant (D); Next_Elmt (Disc1); Next_Elmt (Disc2); end loop; -- If any discriminant constraint is non-static, emit a check if Present (Cond) then Insert_Action (N, Make_Raise_Constraint_Error (Loc, Condition => Cond, Reason => CE_Discriminant_Check_Failed)); end if; return True; end Discriminants_Ok; -- Start of processing for Convert_Aggr_In_Object_Decl begin Set_Assignment_OK (Occ); if Nkind (Aggr) = N_Qualified_Expression then Aggr := Expression (Aggr); end if; if Has_Discriminants (Typ) and then Typ /= Etype (Obj) and then Is_Constrained (Etype (Obj)) and then not Discriminants_Ok then return; end if; -- If the context is an extended return statement, it has its own -- finalization machinery (i.e. works like a transient scope) and -- we do not want to create an additional one, because objects on -- the finalization list of the return must be moved to the caller's -- finalization list to complete the return. -- However, if the aggregate is limited, it is built in place, and the -- controlled components are not assigned to intermediate temporaries -- so there is no need for a transient scope in this case either. if Requires_Transient_Scope (Typ) and then Ekind (Current_Scope) /= E_Return_Statement and then not Is_Limited_Type (Typ) then Establish_Transient_Scope (Aggr, Sec_Stack => Is_Controlled (Typ) or else Has_Controlled_Component (Typ)); end if; declare Node_After : constant Node_Id := Next (N); begin Insert_Actions_After (N, Late_Expansion (Aggr, Typ, Occ)); Collect_Initialization_Statements (Obj, N, Node_After); end; Set_No_Initialization (N); Initialize_Discriminants (N, Typ); end Convert_Aggr_In_Object_Decl; ------------------------------------- -- Convert_Array_Aggr_In_Allocator -- ------------------------------------- procedure Convert_Array_Aggr_In_Allocator (Decl : Node_Id; Aggr : Node_Id; Target : Node_Id) is Aggr_Code : List_Id; Typ : constant Entity_Id := Etype (Aggr); Ctyp : constant Entity_Id := Component_Type (Typ); begin -- The target is an explicit dereference of the allocated object. -- Generate component assignments to it, as for an aggregate that -- appears on the right-hand side of an assignment statement. Aggr_Code := Build_Array_Aggr_Code (Aggr, Ctype => Ctyp, Index => First_Index (Typ), Into => Target, Scalar_Comp => Is_Scalar_Type (Ctyp)); Insert_Actions_After (Decl, Aggr_Code); end Convert_Array_Aggr_In_Allocator; ---------------------------- -- Convert_To_Assignments -- ---------------------------- procedure Convert_To_Assignments (N : Node_Id; Typ : Entity_Id) is Loc : constant Source_Ptr := Sloc (N); T : Entity_Id; Temp : Entity_Id; Aggr_Code : List_Id; Instr : Node_Id; Target_Expr : Node_Id; Parent_Kind : Node_Kind; Unc_Decl : Boolean := False; Parent_Node : Node_Id; begin pragma Assert (not Is_Static_Dispatch_Table_Aggregate (N)); pragma Assert (Is_Record_Type (Typ)); Parent_Node := Parent (N); Parent_Kind := Nkind (Parent_Node); if Parent_Kind = N_Qualified_Expression then -- Check if we are in a unconstrained declaration because in this -- case the current delayed expansion mechanism doesn't work when -- the declared object size depend on the initializing expr. Parent_Node := Parent (Parent_Node); Parent_Kind := Nkind (Parent_Node); if Parent_Kind = N_Object_Declaration then Unc_Decl := not Is_Entity_Name (Object_Definition (Parent_Node)) or else Has_Discriminants (Entity (Object_Definition (Parent_Node))) or else Is_Class_Wide_Type (Entity (Object_Definition (Parent_Node))); end if; end if; -- Just set the Delay flag in the cases where the transformation will be -- done top down from above. if False -- Internal aggregate (transformed when expanding the parent) or else Parent_Kind = N_Aggregate or else Parent_Kind = N_Extension_Aggregate or else Parent_Kind = N_Component_Association -- Allocator (see Convert_Aggr_In_Allocator) or else Parent_Kind = N_Allocator -- Object declaration (see Convert_Aggr_In_Object_Decl) or else (Parent_Kind = N_Object_Declaration and then not Unc_Decl) -- Safe assignment (see Convert_Aggr_Assignments). So far only the -- assignments in init procs are taken into account. or else (Parent_Kind = N_Assignment_Statement and then Inside_Init_Proc) -- (Ada 2005) An inherently limited type in a return statement, which -- will be handled in a build-in-place fashion, and may be rewritten -- as an extended return and have its own finalization machinery. -- In the case of a simple return, the aggregate needs to be delayed -- until the scope for the return statement has been created, so -- that any finalization chain will be associated with that scope. -- For extended returns, we delay expansion to avoid the creation -- of an unwanted transient scope that could result in premature -- finalization of the return object (which is built in place -- within the caller's scope). or else (Is_Limited_View (Typ) and then (Nkind (Parent (Parent_Node)) = N_Extended_Return_Statement or else Nkind (Parent_Node) = N_Simple_Return_Statement)) then Set_Expansion_Delayed (N); return; end if; -- Otherwise, if a transient scope is required, create it now. If we -- are within an initialization procedure do not create such, because -- the target of the assignment must not be declared within a local -- block, and because cleanup will take place on return from the -- initialization procedure. -- Should the condition be more restrictive ??? if Requires_Transient_Scope (Typ) and then not Inside_Init_Proc then Establish_Transient_Scope (N, Sec_Stack => Needs_Finalization (Typ)); end if; -- If the aggregate is nonlimited, create a temporary. If it is limited -- and context is an assignment, this is a subaggregate for an enclosing -- aggregate being expanded. It must be built in place, so use target of -- the current assignment. if Is_Limited_Type (Typ) and then Nkind (Parent (N)) = N_Assignment_Statement then Target_Expr := New_Copy_Tree (Name (Parent (N))); Insert_Actions (Parent (N), Build_Record_Aggr_Code (N, Typ, Target_Expr)); Rewrite (Parent (N), Make_Null_Statement (Loc)); else Temp := Make_Temporary (Loc, 'A', N); -- If the type inherits unknown discriminants, use the view with -- known discriminants if available. if Has_Unknown_Discriminants (Typ) and then Present (Underlying_Record_View (Typ)) then T := Underlying_Record_View (Typ); else T := Typ; end if; Instr := Make_Object_Declaration (Loc, Defining_Identifier => Temp, Object_Definition => New_Occurrence_Of (T, Loc)); Set_No_Initialization (Instr); Insert_Action (N, Instr); Initialize_Discriminants (Instr, T); Target_Expr := New_Occurrence_Of (Temp, Loc); Aggr_Code := Build_Record_Aggr_Code (N, T, Target_Expr); -- Save the last assignment statement associated with the aggregate -- when building a controlled object. This reference is utilized by -- the finalization machinery when marking an object as successfully -- initialized. if Needs_Finalization (T) then Set_Last_Aggregate_Assignment (Temp, Last (Aggr_Code)); end if; Insert_Actions (N, Aggr_Code); Rewrite (N, New_Occurrence_Of (Temp, Loc)); Analyze_And_Resolve (N, T); end if; end Convert_To_Assignments; --------------------------- -- Convert_To_Positional -- --------------------------- procedure Convert_To_Positional (N : Node_Id; Max_Others_Replicate : Nat := 5; Handle_Bit_Packed : Boolean := False) is Typ : constant Entity_Id := Etype (N); Static_Components : Boolean := True; procedure Check_Static_Components; -- Check whether all components of the aggregate are compile-time known -- values, and can be passed as is to the back-end without further -- expansion. -- An Iterated_Component_Association is treated as non-static, but there -- are possibilities for optimization here. function Flatten (N : Node_Id; Ix : Node_Id; Ixb : Node_Id) return Boolean; -- Convert the aggregate into a purely positional form if possible. On -- entry the bounds of all dimensions are known to be static, and the -- total number of components is safe enough to expand. function Is_Flat (N : Node_Id; Dims : Int) return Boolean; -- Return True iff the array N is flat (which is not trivial in the case -- of multidimensional aggregates). ----------------------------- -- Check_Static_Components -- ----------------------------- -- Could use some comments in this body ??? procedure Check_Static_Components is Expr : Node_Id; begin Static_Components := True; if Nkind (N) = N_String_Literal then null; elsif Present (Expressions (N)) then Expr := First (Expressions (N)); while Present (Expr) loop if Nkind (Expr) /= N_Aggregate or else not Compile_Time_Known_Aggregate (Expr) or else Expansion_Delayed (Expr) then Static_Components := False; exit; end if; Next (Expr); end loop; end if; if Nkind (N) = N_Aggregate and then Present (Component_Associations (N)) then Expr := First (Component_Associations (N)); while Present (Expr) loop if Nkind_In (Expression (Expr), N_Integer_Literal, N_Real_Literal) then null; elsif Is_Entity_Name (Expression (Expr)) and then Present (Entity (Expression (Expr))) and then Ekind (Entity (Expression (Expr))) = E_Enumeration_Literal then null; elsif Nkind (Expression (Expr)) /= N_Aggregate or else not Compile_Time_Known_Aggregate (Expression (Expr)) or else Expansion_Delayed (Expression (Expr)) or else Nkind (Expr) = N_Iterated_Component_Association then Static_Components := False; exit; end if; Next (Expr); end loop; end if; end Check_Static_Components; ------------- -- Flatten -- ------------- function Flatten (N : Node_Id; Ix : Node_Id; Ixb : Node_Id) return Boolean is Loc : constant Source_Ptr := Sloc (N); Blo : constant Node_Id := Type_Low_Bound (Etype (Ixb)); Lo : constant Node_Id := Type_Low_Bound (Etype (Ix)); Hi : constant Node_Id := Type_High_Bound (Etype (Ix)); Lov : Uint; Hiv : Uint; Others_Present : Boolean := False; begin if Nkind (Original_Node (N)) = N_String_Literal then return True; end if; if not Compile_Time_Known_Value (Lo) or else not Compile_Time_Known_Value (Hi) then return False; end if; Lov := Expr_Value (Lo); Hiv := Expr_Value (Hi); -- Check if there is an others choice if Present (Component_Associations (N)) then declare Assoc : Node_Id; Choice : Node_Id; begin Assoc := First (Component_Associations (N)); while Present (Assoc) loop -- If this is a box association, flattening is in general -- not possible because at this point we cannot tell if the -- default is static or even exists. if Box_Present (Assoc) then return False; elsif Nkind (Assoc) = N_Iterated_Component_Association then return False; end if; Choice := First (Choice_List (Assoc)); while Present (Choice) loop if Nkind (Choice) = N_Others_Choice then Others_Present := True; end if; Next (Choice); end loop; Next (Assoc); end loop; end; end if; -- If the low bound is not known at compile time and others is not -- present we can proceed since the bounds can be obtained from the -- aggregate. if Hiv < Lov or else (not Compile_Time_Known_Value (Blo) and then Others_Present) then return False; end if; -- Determine if set of alternatives is suitable for conversion and -- build an array containing the values in sequence. declare Vals : array (UI_To_Int (Lov) .. UI_To_Int (Hiv)) of Node_Id := (others => Empty); -- The values in the aggregate sorted appropriately Vlist : List_Id; -- Same data as Vals in list form Rep_Count : Nat; -- Used to validate Max_Others_Replicate limit Elmt : Node_Id; Num : Int := UI_To_Int (Lov); Choice_Index : Int; Choice : Node_Id; Lo, Hi : Node_Id; begin if Present (Expressions (N)) then Elmt := First (Expressions (N)); while Present (Elmt) loop if Nkind (Elmt) = N_Aggregate and then Present (Next_Index (Ix)) and then not Flatten (Elmt, Next_Index (Ix), Next_Index (Ixb)) then return False; end if; Vals (Num) := Relocate_Node (Elmt); Num := Num + 1; Next (Elmt); end loop; end if; if No (Component_Associations (N)) then return True; end if; Elmt := First (Component_Associations (N)); if Nkind (Expression (Elmt)) = N_Aggregate then if Present (Next_Index (Ix)) and then not Flatten (Expression (Elmt), Next_Index (Ix), Next_Index (Ixb)) then return False; end if; end if; Component_Loop : while Present (Elmt) loop Choice := First (Choice_List (Elmt)); Choice_Loop : while Present (Choice) loop -- If we have an others choice, fill in the missing elements -- subject to the limit established by Max_Others_Replicate. if Nkind (Choice) = N_Others_Choice then Rep_Count := 0; for J in Vals'Range loop if No (Vals (J)) then Vals (J) := New_Copy_Tree (Expression (Elmt)); Rep_Count := Rep_Count + 1; -- Check for maximum others replication. Note that -- we skip this test if either of the restrictions -- No_Elaboration_Code or No_Implicit_Loops is -- active, if this is a preelaborable unit or -- a predefined unit, or if the unit must be -- placed in data memory. This also ensures that -- predefined units get the same level of constant -- folding in Ada 95 and Ada 2005, where their -- categorization has changed. declare P : constant Entity_Id := Cunit_Entity (Current_Sem_Unit); begin -- Check if duplication OK and if so continue -- processing. if Restriction_Active (No_Elaboration_Code) or else Restriction_Active (No_Implicit_Loops) or else (Ekind (Current_Scope) = E_Package and then Static_Elaboration_Desired (Current_Scope)) or else Is_Preelaborated (P) or else (Ekind (P) = E_Package_Body and then Is_Preelaborated (Spec_Entity (P))) or else Is_Predefined_File_Name (Unit_File_Name (Get_Source_Unit (P))) then null; -- If duplication not OK, then we return False -- if the replication count is too high elsif Rep_Count > Max_Others_Replicate then return False; -- Continue on if duplication not OK, but the -- replication count is not excessive. else null; end if; end; end if; end loop; exit Component_Loop; -- Case of a subtype mark, identifier or expanded name elsif Is_Entity_Name (Choice) and then Is_Type (Entity (Choice)) then Lo := Type_Low_Bound (Etype (Choice)); Hi := Type_High_Bound (Etype (Choice)); -- Case of subtype indication elsif Nkind (Choice) = N_Subtype_Indication then Lo := Low_Bound (Range_Expression (Constraint (Choice))); Hi := High_Bound (Range_Expression (Constraint (Choice))); -- Case of a range elsif Nkind (Choice) = N_Range then Lo := Low_Bound (Choice); Hi := High_Bound (Choice); -- Normal subexpression case else pragma Assert (Nkind (Choice) in N_Subexpr); if not Compile_Time_Known_Value (Choice) then return False; else Choice_Index := UI_To_Int (Expr_Value (Choice)); if Choice_Index in Vals'Range then Vals (Choice_Index) := New_Copy_Tree (Expression (Elmt)); goto Continue; -- Choice is statically out-of-range, will be -- rewritten to raise Constraint_Error. else return False; end if; end if; end if; -- Range cases merge with Lo,Hi set if not Compile_Time_Known_Value (Lo) or else not Compile_Time_Known_Value (Hi) then return False; else for J in UI_To_Int (Expr_Value (Lo)) .. UI_To_Int (Expr_Value (Hi)) loop Vals (J) := New_Copy_Tree (Expression (Elmt)); end loop; end if; <<Continue>> Next (Choice); end loop Choice_Loop; Next (Elmt); end loop Component_Loop; -- If we get here the conversion is possible Vlist := New_List; for J in Vals'Range loop Append (Vals (J), Vlist); end loop; Rewrite (N, Make_Aggregate (Loc, Expressions => Vlist)); Set_Aggregate_Bounds (N, Aggregate_Bounds (Original_Node (N))); return True; end; end Flatten; ------------- -- Is_Flat -- ------------- function Is_Flat (N : Node_Id; Dims : Int) return Boolean is Elmt : Node_Id; begin if Dims = 0 then return True; elsif Nkind (N) = N_Aggregate then if Present (Component_Associations (N)) then return False; else Elmt := First (Expressions (N)); while Present (Elmt) loop if not Is_Flat (Elmt, Dims - 1) then return False; end if; Next (Elmt); end loop; return True; end if; else return True; end if; end Is_Flat; -- Start of processing for Convert_To_Positional begin -- Only convert to positional when generating C in case of an -- object declaration, this is the only case where aggregates are -- supported in C. if Modify_Tree_For_C and then not In_Object_Declaration (N) then return; end if; -- Ada 2005 (AI-287): Do not convert in case of default initialized -- components because in this case will need to call the corresponding -- IP procedure. if Has_Default_Init_Comps (N) then return; end if; if Is_Flat (N, Number_Dimensions (Typ)) then return; end if; if Is_Bit_Packed_Array (Typ) and then not Handle_Bit_Packed then return; end if; -- Do not convert to positional if controlled components are involved -- since these require special processing if Has_Controlled_Component (Typ) then return; end if; Check_Static_Components; -- If the size is known, or all the components are static, try to -- build a fully positional aggregate. -- The size of the type may not be known for an aggregate with -- discriminated array components, but if the components are static -- it is still possible to verify statically that the length is -- compatible with the upper bound of the type, and therefore it is -- worth flattening such aggregates as well. -- For now the back-end expands these aggregates into individual -- assignments to the target anyway, but it is conceivable that -- it will eventually be able to treat such aggregates statically??? if Aggr_Size_OK (N, Typ) and then Flatten (N, First_Index (Typ), First_Index (Base_Type (Typ))) then if Static_Components then Set_Compile_Time_Known_Aggregate (N); Set_Expansion_Delayed (N, False); end if; Analyze_And_Resolve (N, Typ); end if; -- If Static_Elaboration_Desired has been specified, diagnose aggregates -- that will still require initialization code. if (Ekind (Current_Scope) = E_Package and then Static_Elaboration_Desired (Current_Scope)) and then Nkind (Parent (N)) = N_Object_Declaration then declare Expr : Node_Id; begin if Nkind (N) = N_Aggregate and then Present (Expressions (N)) then Expr := First (Expressions (N)); while Present (Expr) loop if Nkind_In (Expr, N_Integer_Literal, N_Real_Literal) or else (Is_Entity_Name (Expr) and then Ekind (Entity (Expr)) = E_Enumeration_Literal) then null; else Error_Msg_N ("non-static object requires elaboration code??", N); exit; end if; Next (Expr); end loop; if Present (Component_Associations (N)) then Error_Msg_N ("object requires elaboration code??", N); end if; end if; end; end if; end Convert_To_Positional; ---------------------------- -- Expand_Array_Aggregate -- ---------------------------- -- Array aggregate expansion proceeds as follows: -- 1. If requested we generate code to perform all the array aggregate -- bound checks, specifically -- (a) Check that the index range defined by aggregate bounds is -- compatible with corresponding index subtype. -- (b) If an others choice is present check that no aggregate -- index is outside the bounds of the index constraint. -- (c) For multidimensional arrays make sure that all subaggregates -- corresponding to the same dimension have the same bounds. -- 2. Check for packed array aggregate which can be converted to a -- constant so that the aggregate disappears completely. -- 3. Check case of nested aggregate. Generally nested aggregates are -- handled during the processing of the parent aggregate. -- 4. Check if the aggregate can be statically processed. If this is the -- case pass it as is to Gigi. Note that a necessary condition for -- static processing is that the aggregate be fully positional. -- 5. If in place aggregate expansion is possible (i.e. no need to create -- a temporary) then mark the aggregate as such and return. Otherwise -- create a new temporary and generate the appropriate initialization -- code. procedure Expand_Array_Aggregate (N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); Typ : constant Entity_Id := Etype (N); Ctyp : constant Entity_Id := Component_Type (Typ); -- Typ is the correct constrained array subtype of the aggregate -- Ctyp is the corresponding component type. Aggr_Dimension : constant Pos := Number_Dimensions (Typ); -- Number of aggregate index dimensions Aggr_Low : array (1 .. Aggr_Dimension) of Node_Id; Aggr_High : array (1 .. Aggr_Dimension) of Node_Id; -- Low and High bounds of the constraint for each aggregate index Aggr_Index_Typ : array (1 .. Aggr_Dimension) of Entity_Id; -- The type of each index In_Place_Assign_OK_For_Declaration : Boolean := False; -- True if we are to generate an in place assignment for a declaration Maybe_In_Place_OK : Boolean; -- If the type is neither controlled nor packed and the aggregate -- is the expression in an assignment, assignment in place may be -- possible, provided other conditions are met on the LHS. Others_Present : array (1 .. Aggr_Dimension) of Boolean := (others => False); -- If Others_Present (J) is True, then there is an others choice in one -- of the subaggregates of N at dimension J. function Aggr_Assignment_OK_For_Backend (N : Node_Id) return Boolean; -- Returns true if an aggregate assignment can be done by the back end procedure Build_Constrained_Type (Positional : Boolean); -- If the subtype is not static or unconstrained, build a constrained -- type using the computable sizes of the aggregate and its sub- -- aggregates. procedure Check_Bounds (Aggr_Bounds : Node_Id; Index_Bounds : Node_Id); -- Checks that the bounds of Aggr_Bounds are within the bounds defined -- by Index_Bounds. procedure Check_Same_Aggr_Bounds (Sub_Aggr : Node_Id; Dim : Pos); -- Checks that in a multidimensional array aggregate all subaggregates -- corresponding to the same dimension have the same bounds. Sub_Aggr is -- an array subaggregate. Dim is the dimension corresponding to the -- subaggregate. procedure Compute_Others_Present (Sub_Aggr : Node_Id; Dim : Pos); -- Computes the values of array Others_Present. Sub_Aggr is the array -- subaggregate we start the computation from. Dim is the dimension -- corresponding to the subaggregate. function In_Place_Assign_OK return Boolean; -- Simple predicate to determine whether an aggregate assignment can -- be done in place, because none of the new values can depend on the -- components of the target of the assignment. procedure Others_Check (Sub_Aggr : Node_Id; Dim : Pos); -- Checks that if an others choice is present in any subaggregate, no -- aggregate index is outside the bounds of the index constraint. -- Sub_Aggr is an array subaggregate. Dim is the dimension corresponding -- to the subaggregate. function Safe_Left_Hand_Side (N : Node_Id) return Boolean; -- In addition to Maybe_In_Place_OK, in order for an aggregate to be -- built directly into the target of the assignment it must be free -- of side effects. ------------------------------------ -- Aggr_Assignment_OK_For_Backend -- ------------------------------------ -- Backend processing by Gigi/gcc is possible only if all the following -- conditions are met: -- 1. N consists of a single OTHERS choice, possibly recursively -- 2. The array type is not packed -- 3. The array type has no atomic components -- 4. The array type has no null ranges (the purpose of this is to -- avoid a bogus warning for an out-of-range value). -- 5. The component type is discrete -- 6. The component size is Storage_Unit or the value is of the form -- M * (1 + A**1 + A**2 + .. A**(K-1)) where A = 2**(Storage_Unit) -- and M in 1 .. A-1. This can also be viewed as K occurrences of -- the 8-bit value M, concatenated together. -- The ultimate goal is to generate a call to a fast memset routine -- specifically optimized for the target. function Aggr_Assignment_OK_For_Backend (N : Node_Id) return Boolean is Ctyp : Entity_Id; Index : Entity_Id; Expr : Node_Id := N; Low : Node_Id; High : Node_Id; Remainder : Uint; Value : Uint; Nunits : Nat; begin -- Recurse as far as possible to find the innermost component type Ctyp := Etype (N); while Is_Array_Type (Ctyp) loop if Nkind (Expr) /= N_Aggregate or else not Is_Others_Aggregate (Expr) then return False; end if; if Present (Packed_Array_Impl_Type (Ctyp)) then return False; end if; if Has_Atomic_Components (Ctyp) then return False; end if; Index := First_Index (Ctyp); while Present (Index) loop Get_Index_Bounds (Index, Low, High); if Is_Null_Range (Low, High) then return False; end if; Next_Index (Index); end loop; Expr := Expression (First (Component_Associations (Expr))); for J in 1 .. Number_Dimensions (Ctyp) - 1 loop if Nkind (Expr) /= N_Aggregate or else not Is_Others_Aggregate (Expr) then return False; end if; Expr := Expression (First (Component_Associations (Expr))); end loop; Ctyp := Component_Type (Ctyp); if Is_Atomic_Or_VFA (Ctyp) then return False; end if; end loop; -- An Iterated_Component_Association involves a loop (in most cases) -- and is never static. if Nkind (Parent (Expr)) = N_Iterated_Component_Association then return False; end if; if not Is_Discrete_Type (Ctyp) then return False; end if; -- The expression needs to be analyzed if True is returned Analyze_And_Resolve (Expr, Ctyp); -- The back end uses the Esize as the precision of the type Nunits := UI_To_Int (Esize (Ctyp)) / System_Storage_Unit; if Nunits = 1 then return True; end if; if not Compile_Time_Known_Value (Expr) then return False; end if; Value := Expr_Value (Expr); if Has_Biased_Representation (Ctyp) then Value := Value - Expr_Value (Type_Low_Bound (Ctyp)); end if; -- Values 0 and -1 immediately satisfy the last check if Value = Uint_0 or else Value = Uint_Minus_1 then return True; end if; -- We need to work with an unsigned value if Value < 0 then Value := Value + 2**(System_Storage_Unit * Nunits); end if; Remainder := Value rem 2**System_Storage_Unit; for J in 1 .. Nunits - 1 loop Value := Value / 2**System_Storage_Unit; if Value rem 2**System_Storage_Unit /= Remainder then return False; end if; end loop; return True; end Aggr_Assignment_OK_For_Backend; ---------------------------- -- Build_Constrained_Type -- ---------------------------- procedure Build_Constrained_Type (Positional : Boolean) is Loc : constant Source_Ptr := Sloc (N); Agg_Type : constant Entity_Id := Make_Temporary (Loc, 'A'); Comp : Node_Id; Decl : Node_Id; Typ : constant Entity_Id := Etype (N); Indexes : constant List_Id := New_List; Num : Nat; Sub_Agg : Node_Id; begin -- If the aggregate is purely positional, all its subaggregates -- have the same size. We collect the dimensions from the first -- subaggregate at each level. if Positional then Sub_Agg := N; for D in 1 .. Number_Dimensions (Typ) loop Sub_Agg := First (Expressions (Sub_Agg)); Comp := Sub_Agg; Num := 0; while Present (Comp) loop Num := Num + 1; Next (Comp); end loop; Append_To (Indexes, Make_Range (Loc, Low_Bound => Make_Integer_Literal (Loc, 1), High_Bound => Make_Integer_Literal (Loc, Num))); end loop; else -- We know the aggregate type is unconstrained and the aggregate -- is not processable by the back end, therefore not necessarily -- positional. Retrieve each dimension bounds (computed earlier). for D in 1 .. Number_Dimensions (Typ) loop Append_To (Indexes, Make_Range (Loc, Low_Bound => Aggr_Low (D), High_Bound => Aggr_High (D))); end loop; end if; Decl := Make_Full_Type_Declaration (Loc, Defining_Identifier => Agg_Type, Type_Definition => Make_Constrained_Array_Definition (Loc, Discrete_Subtype_Definitions => Indexes, Component_Definition => Make_Component_Definition (Loc, Aliased_Present => False, Subtype_Indication => New_Occurrence_Of (Component_Type (Typ), Loc)))); Insert_Action (N, Decl); Analyze (Decl); Set_Etype (N, Agg_Type); Set_Is_Itype (Agg_Type); Freeze_Itype (Agg_Type, N); end Build_Constrained_Type; ------------------ -- Check_Bounds -- ------------------ procedure Check_Bounds (Aggr_Bounds : Node_Id; Index_Bounds : Node_Id) is Aggr_Lo : Node_Id; Aggr_Hi : Node_Id; Ind_Lo : Node_Id; Ind_Hi : Node_Id; Cond : Node_Id := Empty; begin Get_Index_Bounds (Aggr_Bounds, Aggr_Lo, Aggr_Hi); Get_Index_Bounds (Index_Bounds, Ind_Lo, Ind_Hi); -- Generate the following test: -- [constraint_error when -- Aggr_Lo <= Aggr_Hi and then -- (Aggr_Lo < Ind_Lo or else Aggr_Hi > Ind_Hi)] -- As an optimization try to see if some tests are trivially vacuous -- because we are comparing an expression against itself. if Aggr_Lo = Ind_Lo and then Aggr_Hi = Ind_Hi then Cond := Empty; elsif Aggr_Hi = Ind_Hi then Cond := Make_Op_Lt (Loc, Left_Opnd => Duplicate_Subexpr_Move_Checks (Aggr_Lo), Right_Opnd => Duplicate_Subexpr_Move_Checks (Ind_Lo)); elsif Aggr_Lo = Ind_Lo then Cond := Make_Op_Gt (Loc, Left_Opnd => Duplicate_Subexpr_Move_Checks (Aggr_Hi), Right_Opnd => Duplicate_Subexpr_Move_Checks (Ind_Hi)); else Cond := Make_Or_Else (Loc, Left_Opnd => Make_Op_Lt (Loc, Left_Opnd => Duplicate_Subexpr_Move_Checks (Aggr_Lo), Right_Opnd => Duplicate_Subexpr_Move_Checks (Ind_Lo)), Right_Opnd => Make_Op_Gt (Loc, Left_Opnd => Duplicate_Subexpr (Aggr_Hi), Right_Opnd => Duplicate_Subexpr (Ind_Hi))); end if; if Present (Cond) then Cond := Make_And_Then (Loc, Left_Opnd => Make_Op_Le (Loc, Left_Opnd => Duplicate_Subexpr_Move_Checks (Aggr_Lo), Right_Opnd => Duplicate_Subexpr_Move_Checks (Aggr_Hi)), Right_Opnd => Cond); Set_Analyzed (Left_Opnd (Left_Opnd (Cond)), False); Set_Analyzed (Right_Opnd (Left_Opnd (Cond)), False); Insert_Action (N, Make_Raise_Constraint_Error (Loc, Condition => Cond, Reason => CE_Range_Check_Failed)); end if; end Check_Bounds; ---------------------------- -- Check_Same_Aggr_Bounds -- ---------------------------- procedure Check_Same_Aggr_Bounds (Sub_Aggr : Node_Id; Dim : Pos) is Sub_Lo : constant Node_Id := Low_Bound (Aggregate_Bounds (Sub_Aggr)); Sub_Hi : constant Node_Id := High_Bound (Aggregate_Bounds (Sub_Aggr)); -- The bounds of this specific subaggregate Aggr_Lo : constant Node_Id := Aggr_Low (Dim); Aggr_Hi : constant Node_Id := Aggr_High (Dim); -- The bounds of the aggregate for this dimension Ind_Typ : constant Entity_Id := Aggr_Index_Typ (Dim); -- The index type for this dimension.xxx Cond : Node_Id := Empty; Assoc : Node_Id; Expr : Node_Id; begin -- If index checks are on generate the test -- [constraint_error when -- Aggr_Lo /= Sub_Lo or else Aggr_Hi /= Sub_Hi] -- As an optimization try to see if some tests are trivially vacuos -- because we are comparing an expression against itself. Also for -- the first dimension the test is trivially vacuous because there -- is just one aggregate for dimension 1. if Index_Checks_Suppressed (Ind_Typ) then Cond := Empty; elsif Dim = 1 or else (Aggr_Lo = Sub_Lo and then Aggr_Hi = Sub_Hi) then Cond := Empty; elsif Aggr_Hi = Sub_Hi then Cond := Make_Op_Ne (Loc, Left_Opnd => Duplicate_Subexpr_Move_Checks (Aggr_Lo), Right_Opnd => Duplicate_Subexpr_Move_Checks (Sub_Lo)); elsif Aggr_Lo = Sub_Lo then Cond := Make_Op_Ne (Loc, Left_Opnd => Duplicate_Subexpr_Move_Checks (Aggr_Hi), Right_Opnd => Duplicate_Subexpr_Move_Checks (Sub_Hi)); else Cond := Make_Or_Else (Loc, Left_Opnd => Make_Op_Ne (Loc, Left_Opnd => Duplicate_Subexpr_Move_Checks (Aggr_Lo), Right_Opnd => Duplicate_Subexpr_Move_Checks (Sub_Lo)), Right_Opnd => Make_Op_Ne (Loc, Left_Opnd => Duplicate_Subexpr (Aggr_Hi), Right_Opnd => Duplicate_Subexpr (Sub_Hi))); end if; if Present (Cond) then Insert_Action (N, Make_Raise_Constraint_Error (Loc, Condition => Cond, Reason => CE_Length_Check_Failed)); end if; -- Now look inside the subaggregate to see if there is more work if Dim < Aggr_Dimension then -- Process positional components if Present (Expressions (Sub_Aggr)) then Expr := First (Expressions (Sub_Aggr)); while Present (Expr) loop Check_Same_Aggr_Bounds (Expr, Dim + 1); Next (Expr); end loop; end if; -- Process component associations if Present (Component_Associations (Sub_Aggr)) then Assoc := First (Component_Associations (Sub_Aggr)); while Present (Assoc) loop Expr := Expression (Assoc); Check_Same_Aggr_Bounds (Expr, Dim + 1); Next (Assoc); end loop; end if; end if; end Check_Same_Aggr_Bounds; ---------------------------- -- Compute_Others_Present -- ---------------------------- procedure Compute_Others_Present (Sub_Aggr : Node_Id; Dim : Pos) is Assoc : Node_Id; Expr : Node_Id; begin if Present (Component_Associations (Sub_Aggr)) then Assoc := Last (Component_Associations (Sub_Aggr)); if Nkind (First (Choice_List (Assoc))) = N_Others_Choice then Others_Present (Dim) := True; end if; end if; -- Now look inside the subaggregate to see if there is more work if Dim < Aggr_Dimension then -- Process positional components if Present (Expressions (Sub_Aggr)) then Expr := First (Expressions (Sub_Aggr)); while Present (Expr) loop Compute_Others_Present (Expr, Dim + 1); Next (Expr); end loop; end if; -- Process component associations if Present (Component_Associations (Sub_Aggr)) then Assoc := First (Component_Associations (Sub_Aggr)); while Present (Assoc) loop Expr := Expression (Assoc); Compute_Others_Present (Expr, Dim + 1); Next (Assoc); end loop; end if; end if; end Compute_Others_Present; ------------------------ -- In_Place_Assign_OK -- ------------------------ function In_Place_Assign_OK return Boolean is Aggr_In : Node_Id; Aggr_Lo : Node_Id; Aggr_Hi : Node_Id; Obj_In : Node_Id; Obj_Lo : Node_Id; Obj_Hi : Node_Id; function Safe_Aggregate (Aggr : Node_Id) return Boolean; -- Check recursively that each component of a (sub)aggregate does not -- depend on the variable being assigned to. function Safe_Component (Expr : Node_Id) return Boolean; -- Verify that an expression cannot depend on the variable being -- assigned to. Room for improvement here (but less than before). -------------------- -- Safe_Aggregate -- -------------------- function Safe_Aggregate (Aggr : Node_Id) return Boolean is Expr : Node_Id; begin if Present (Expressions (Aggr)) then Expr := First (Expressions (Aggr)); while Present (Expr) loop if Nkind (Expr) = N_Aggregate then if not Safe_Aggregate (Expr) then return False; end if; elsif not Safe_Component (Expr) then return False; end if; Next (Expr); end loop; end if; if Present (Component_Associations (Aggr)) then Expr := First (Component_Associations (Aggr)); while Present (Expr) loop if Nkind (Expression (Expr)) = N_Aggregate then if not Safe_Aggregate (Expression (Expr)) then return False; end if; -- If association has a box, no way to determine yet -- whether default can be assigned in place. elsif Box_Present (Expr) then return False; elsif not Safe_Component (Expression (Expr)) then return False; end if; Next (Expr); end loop; end if; return True; end Safe_Aggregate; -------------------- -- Safe_Component -- -------------------- function Safe_Component (Expr : Node_Id) return Boolean is Comp : Node_Id := Expr; function Check_Component (Comp : Node_Id) return Boolean; -- Do the recursive traversal, after copy --------------------- -- Check_Component -- --------------------- function Check_Component (Comp : Node_Id) return Boolean is begin if Is_Overloaded (Comp) then return False; end if; return Compile_Time_Known_Value (Comp) or else (Is_Entity_Name (Comp) and then Present (Entity (Comp)) and then No (Renamed_Object (Entity (Comp)))) or else (Nkind (Comp) = N_Attribute_Reference and then Check_Component (Prefix (Comp))) or else (Nkind (Comp) in N_Binary_Op and then Check_Component (Left_Opnd (Comp)) and then Check_Component (Right_Opnd (Comp))) or else (Nkind (Comp) in N_Unary_Op and then Check_Component (Right_Opnd (Comp))) or else (Nkind (Comp) = N_Selected_Component and then Check_Component (Prefix (Comp))) or else (Nkind (Comp) = N_Unchecked_Type_Conversion and then Check_Component (Expression (Comp))); end Check_Component; -- Start of processing for Safe_Component begin -- If the component appears in an association that may correspond -- to more than one element, it is not analyzed before expansion -- into assignments, to avoid side effects. We analyze, but do not -- resolve the copy, to obtain sufficient entity information for -- the checks that follow. If component is overloaded we assume -- an unsafe function call. if not Analyzed (Comp) then if Is_Overloaded (Expr) then return False; elsif Nkind (Expr) = N_Aggregate and then not Is_Others_Aggregate (Expr) then return False; elsif Nkind (Expr) = N_Allocator then -- For now, too complex to analyze return False; end if; Comp := New_Copy_Tree (Expr); Set_Parent (Comp, Parent (Expr)); Analyze (Comp); end if; if Nkind (Comp) = N_Aggregate then return Safe_Aggregate (Comp); else return Check_Component (Comp); end if; end Safe_Component; -- Start of processing for In_Place_Assign_OK begin if Present (Component_Associations (N)) then -- On assignment, sliding can take place, so we cannot do the -- assignment in place unless the bounds of the aggregate are -- statically equal to those of the target. -- If the aggregate is given by an others choice, the bounds are -- derived from the left-hand side, and the assignment is safe if -- the expression is. if Is_Others_Aggregate (N) then return Safe_Component (Expression (First (Component_Associations (N)))); end if; Aggr_In := First_Index (Etype (N)); if Nkind (Parent (N)) = N_Assignment_Statement then Obj_In := First_Index (Etype (Name (Parent (N)))); else -- Context is an allocator. Check bounds of aggregate against -- given type in qualified expression. pragma Assert (Nkind (Parent (Parent (N))) = N_Allocator); Obj_In := First_Index (Etype (Entity (Subtype_Mark (Parent (N))))); end if; while Present (Aggr_In) loop Get_Index_Bounds (Aggr_In, Aggr_Lo, Aggr_Hi); Get_Index_Bounds (Obj_In, Obj_Lo, Obj_Hi); if not Compile_Time_Known_Value (Aggr_Lo) or else not Compile_Time_Known_Value (Aggr_Hi) or else not Compile_Time_Known_Value (Obj_Lo) or else not Compile_Time_Known_Value (Obj_Hi) or else Expr_Value (Aggr_Lo) /= Expr_Value (Obj_Lo) or else Expr_Value (Aggr_Hi) /= Expr_Value (Obj_Hi) then return False; end if; Next_Index (Aggr_In); Next_Index (Obj_In); end loop; end if; -- Now check the component values themselves return Safe_Aggregate (N); end In_Place_Assign_OK; ------------------ -- Others_Check -- ------------------ procedure Others_Check (Sub_Aggr : Node_Id; Dim : Pos) is Aggr_Lo : constant Node_Id := Aggr_Low (Dim); Aggr_Hi : constant Node_Id := Aggr_High (Dim); -- The bounds of the aggregate for this dimension Ind_Typ : constant Entity_Id := Aggr_Index_Typ (Dim); -- The index type for this dimension Need_To_Check : Boolean := False; Choices_Lo : Node_Id := Empty; Choices_Hi : Node_Id := Empty; -- The lowest and highest discrete choices for a named subaggregate Nb_Choices : Int := -1; -- The number of discrete non-others choices in this subaggregate Nb_Elements : Uint := Uint_0; -- The number of elements in a positional aggregate Cond : Node_Id := Empty; Assoc : Node_Id; Choice : Node_Id; Expr : Node_Id; begin -- Check if we have an others choice. If we do make sure that this -- subaggregate contains at least one element in addition to the -- others choice. if Range_Checks_Suppressed (Ind_Typ) then Need_To_Check := False; elsif Present (Expressions (Sub_Aggr)) and then Present (Component_Associations (Sub_Aggr)) then Need_To_Check := True; elsif Present (Component_Associations (Sub_Aggr)) then Assoc := Last (Component_Associations (Sub_Aggr)); if Nkind (First (Choice_List (Assoc))) /= N_Others_Choice then Need_To_Check := False; else -- Count the number of discrete choices. Start with -1 because -- the others choice does not count. -- Is there some reason we do not use List_Length here ??? Nb_Choices := -1; Assoc := First (Component_Associations (Sub_Aggr)); while Present (Assoc) loop Choice := First (Choice_List (Assoc)); while Present (Choice) loop Nb_Choices := Nb_Choices + 1; Next (Choice); end loop; Next (Assoc); end loop; -- If there is only an others choice nothing to do Need_To_Check := (Nb_Choices > 0); end if; else Need_To_Check := False; end if; -- If we are dealing with a positional subaggregate with an others -- choice then compute the number or positional elements. if Need_To_Check and then Present (Expressions (Sub_Aggr)) then Expr := First (Expressions (Sub_Aggr)); Nb_Elements := Uint_0; while Present (Expr) loop Nb_Elements := Nb_Elements + 1; Next (Expr); end loop; -- If the aggregate contains discrete choices and an others choice -- compute the smallest and largest discrete choice values. elsif Need_To_Check then Compute_Choices_Lo_And_Choices_Hi : declare Table : Case_Table_Type (1 .. Nb_Choices); -- Used to sort all the different choice values J : Pos := 1; Low : Node_Id; High : Node_Id; begin Assoc := First (Component_Associations (Sub_Aggr)); while Present (Assoc) loop Choice := First (Choice_List (Assoc)); while Present (Choice) loop if Nkind (Choice) = N_Others_Choice then exit; end if; Get_Index_Bounds (Choice, Low, High); Table (J).Choice_Lo := Low; Table (J).Choice_Hi := High; J := J + 1; Next (Choice); end loop; Next (Assoc); end loop; -- Sort the discrete choices Sort_Case_Table (Table); Choices_Lo := Table (1).Choice_Lo; Choices_Hi := Table (Nb_Choices).Choice_Hi; end Compute_Choices_Lo_And_Choices_Hi; end if; -- If no others choice in this subaggregate, or the aggregate -- comprises only an others choice, nothing to do. if not Need_To_Check then Cond := Empty; -- If we are dealing with an aggregate containing an others choice -- and positional components, we generate the following test: -- if Ind_Typ'Pos (Aggr_Lo) + (Nb_Elements - 1) > -- Ind_Typ'Pos (Aggr_Hi) -- then -- raise Constraint_Error; -- end if; elsif Nb_Elements > Uint_0 then Cond := Make_Op_Gt (Loc, Left_Opnd => Make_Op_Add (Loc, Left_Opnd => Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Ind_Typ, Loc), Attribute_Name => Name_Pos, Expressions => New_List (Duplicate_Subexpr_Move_Checks (Aggr_Lo))), Right_Opnd => Make_Integer_Literal (Loc, Nb_Elements - 1)), Right_Opnd => Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Ind_Typ, Loc), Attribute_Name => Name_Pos, Expressions => New_List ( Duplicate_Subexpr_Move_Checks (Aggr_Hi)))); -- If we are dealing with an aggregate containing an others choice -- and discrete choices we generate the following test: -- [constraint_error when -- Choices_Lo < Aggr_Lo or else Choices_Hi > Aggr_Hi]; else Cond := Make_Or_Else (Loc, Left_Opnd => Make_Op_Lt (Loc, Left_Opnd => Duplicate_Subexpr_Move_Checks (Choices_Lo), Right_Opnd => Duplicate_Subexpr_Move_Checks (Aggr_Lo)), Right_Opnd => Make_Op_Gt (Loc, Left_Opnd => Duplicate_Subexpr (Choices_Hi), Right_Opnd => Duplicate_Subexpr (Aggr_Hi))); end if; if Present (Cond) then Insert_Action (N, Make_Raise_Constraint_Error (Loc, Condition => Cond, Reason => CE_Length_Check_Failed)); -- Questionable reason code, shouldn't that be a -- CE_Range_Check_Failed ??? end if; -- Now look inside the subaggregate to see if there is more work if Dim < Aggr_Dimension then -- Process positional components if Present (Expressions (Sub_Aggr)) then Expr := First (Expressions (Sub_Aggr)); while Present (Expr) loop Others_Check (Expr, Dim + 1); Next (Expr); end loop; end if; -- Process component associations if Present (Component_Associations (Sub_Aggr)) then Assoc := First (Component_Associations (Sub_Aggr)); while Present (Assoc) loop Expr := Expression (Assoc); Others_Check (Expr, Dim + 1); Next (Assoc); end loop; end if; end if; end Others_Check; ------------------------- -- Safe_Left_Hand_Side -- ------------------------- function Safe_Left_Hand_Side (N : Node_Id) return Boolean is function Is_Safe_Index (Indx : Node_Id) return Boolean; -- If the left-hand side includes an indexed component, check that -- the indexes are free of side effects. ------------------- -- Is_Safe_Index -- ------------------- function Is_Safe_Index (Indx : Node_Id) return Boolean is begin if Is_Entity_Name (Indx) then return True; elsif Nkind (Indx) = N_Integer_Literal then return True; elsif Nkind (Indx) = N_Function_Call and then Is_Entity_Name (Name (Indx)) and then Has_Pragma_Pure_Function (Entity (Name (Indx))) then return True; elsif Nkind (Indx) = N_Type_Conversion and then Is_Safe_Index (Expression (Indx)) then return True; else return False; end if; end Is_Safe_Index; -- Start of processing for Safe_Left_Hand_Side begin if Is_Entity_Name (N) then return True; elsif Nkind_In (N, N_Explicit_Dereference, N_Selected_Component) and then Safe_Left_Hand_Side (Prefix (N)) then return True; elsif Nkind (N) = N_Indexed_Component and then Safe_Left_Hand_Side (Prefix (N)) and then Is_Safe_Index (First (Expressions (N))) then return True; elsif Nkind (N) = N_Unchecked_Type_Conversion then return Safe_Left_Hand_Side (Expression (N)); else return False; end if; end Safe_Left_Hand_Side; -- Local variables Tmp : Entity_Id; -- Holds the temporary aggregate value Tmp_Decl : Node_Id; -- Holds the declaration of Tmp Aggr_Code : List_Id; Parent_Node : Node_Id; Parent_Kind : Node_Kind; -- Start of processing for Expand_Array_Aggregate begin -- Do not touch the special aggregates of attributes used for Asm calls if Is_RTE (Ctyp, RE_Asm_Input_Operand) or else Is_RTE (Ctyp, RE_Asm_Output_Operand) then return; -- Do not expand an aggregate for an array type which contains tasks if -- the aggregate is associated with an unexpanded return statement of a -- build-in-place function. The aggregate is expanded when the related -- return statement (rewritten into an extended return) is processed. -- This delay ensures that any temporaries and initialization code -- generated for the aggregate appear in the proper return block and -- use the correct _chain and _master. elsif Has_Task (Base_Type (Etype (N))) and then Nkind (Parent (N)) = N_Simple_Return_Statement and then Is_Build_In_Place_Function (Return_Applies_To (Return_Statement_Entity (Parent (N)))) then return; -- Do not attempt expansion if error already detected. We may reach this -- point in spite of previous errors when compiling with -gnatq, to -- force all possible errors (this is the usual ACATS mode). elsif Error_Posted (N) then return; end if; -- If the semantic analyzer has determined that aggregate N will raise -- Constraint_Error at run time, then the aggregate node has been -- replaced with an N_Raise_Constraint_Error node and we should -- never get here. pragma Assert (not Raises_Constraint_Error (N)); -- STEP 1a -- Check that the index range defined by aggregate bounds is -- compatible with corresponding index subtype. Index_Compatibility_Check : declare Aggr_Index_Range : Node_Id := First_Index (Typ); -- The current aggregate index range Index_Constraint : Node_Id := First_Index (Etype (Typ)); -- The corresponding index constraint against which we have to -- check the above aggregate index range. begin Compute_Others_Present (N, 1); for J in 1 .. Aggr_Dimension loop -- There is no need to emit a check if an others choice is present -- for this array aggregate dimension since in this case one of -- N's subaggregates has taken its bounds from the context and -- these bounds must have been checked already. In addition all -- subaggregates corresponding to the same dimension must all have -- the same bounds (checked in (c) below). if not Range_Checks_Suppressed (Etype (Index_Constraint)) and then not Others_Present (J) then -- We don't use Checks.Apply_Range_Check here because it emits -- a spurious check. Namely it checks that the range defined by -- the aggregate bounds is nonempty. But we know this already -- if we get here. Check_Bounds (Aggr_Index_Range, Index_Constraint); end if; -- Save the low and high bounds of the aggregate index as well as -- the index type for later use in checks (b) and (c) below. Aggr_Low (J) := Low_Bound (Aggr_Index_Range); Aggr_High (J) := High_Bound (Aggr_Index_Range); Aggr_Index_Typ (J) := Etype (Index_Constraint); Next_Index (Aggr_Index_Range); Next_Index (Index_Constraint); end loop; end Index_Compatibility_Check; -- STEP 1b -- If an others choice is present check that no aggregate index is -- outside the bounds of the index constraint. Others_Check (N, 1); -- STEP 1c -- For multidimensional arrays make sure that all subaggregates -- corresponding to the same dimension have the same bounds. if Aggr_Dimension > 1 then Check_Same_Aggr_Bounds (N, 1); end if; -- STEP 1d -- If we have a default component value, or simple initialization is -- required for the component type, then we replace <> in component -- associations by the required default value. declare Default_Val : Node_Id; Assoc : Node_Id; begin if (Present (Default_Aspect_Component_Value (Typ)) or else Needs_Simple_Initialization (Ctyp)) and then Present (Component_Associations (N)) then Assoc := First (Component_Associations (N)); while Present (Assoc) loop if Nkind (Assoc) = N_Component_Association and then Box_Present (Assoc) then Set_Box_Present (Assoc, False); if Present (Default_Aspect_Component_Value (Typ)) then Default_Val := Default_Aspect_Component_Value (Typ); else Default_Val := Get_Simple_Init_Val (Ctyp, N); end if; Set_Expression (Assoc, New_Copy_Tree (Default_Val)); Analyze_And_Resolve (Expression (Assoc), Ctyp); end if; Next (Assoc); end loop; end if; end; -- STEP 2 -- Here we test for is packed array aggregate that we can handle at -- compile time. If so, return with transformation done. Note that we do -- this even if the aggregate is nested, because once we have done this -- processing, there is no more nested aggregate. if Packed_Array_Aggregate_Handled (N) then return; end if; -- At this point we try to convert to positional form if Ekind (Current_Scope) = E_Package and then Static_Elaboration_Desired (Current_Scope) then Convert_To_Positional (N, Max_Others_Replicate => 100); else Convert_To_Positional (N); end if; -- if the result is no longer an aggregate (e.g. it may be a string -- literal, or a temporary which has the needed value), then we are -- done, since there is no longer a nested aggregate. if Nkind (N) /= N_Aggregate then return; -- We are also done if the result is an analyzed aggregate, indicating -- that Convert_To_Positional succeeded and reanalyzed the rewritten -- aggregate. elsif Analyzed (N) and then N /= Original_Node (N) then return; end if; -- If all aggregate components are compile-time known and the aggregate -- has been flattened, nothing left to do. The same occurs if the -- aggregate is used to initialize the components of a statically -- allocated dispatch table. if Compile_Time_Known_Aggregate (N) or else Is_Static_Dispatch_Table_Aggregate (N) then Set_Expansion_Delayed (N, False); return; end if; -- Now see if back end processing is possible if Backend_Processing_Possible (N) then -- If the aggregate is static but the constraints are not, build -- a static subtype for the aggregate, so that Gigi can place it -- in static memory. Perform an unchecked_conversion to the non- -- static type imposed by the context. declare Itype : constant Entity_Id := Etype (N); Index : Node_Id; Needs_Type : Boolean := False; begin Index := First_Index (Itype); while Present (Index) loop if not Is_OK_Static_Subtype (Etype (Index)) then Needs_Type := True; exit; else Next_Index (Index); end if; end loop; if Needs_Type then Build_Constrained_Type (Positional => True); Rewrite (N, Unchecked_Convert_To (Itype, N)); Analyze (N); end if; end; return; end if; -- STEP 3 -- Delay expansion for nested aggregates: it will be taken care of when -- the parent aggregate is expanded. Parent_Node := Parent (N); Parent_Kind := Nkind (Parent_Node); if Parent_Kind = N_Qualified_Expression then Parent_Node := Parent (Parent_Node); Parent_Kind := Nkind (Parent_Node); end if; if Parent_Kind = N_Aggregate or else Parent_Kind = N_Extension_Aggregate or else Parent_Kind = N_Component_Association or else (Parent_Kind = N_Object_Declaration and then Needs_Finalization (Typ)) or else (Parent_Kind = N_Assignment_Statement and then Inside_Init_Proc) then if Static_Array_Aggregate (N) or else Compile_Time_Known_Aggregate (N) then Set_Expansion_Delayed (N, False); return; else Set_Expansion_Delayed (N); return; end if; end if; -- STEP 4 -- Look if in place aggregate expansion is possible -- For object declarations we build the aggregate in place, unless -- the array is bit-packed or the component is controlled. -- For assignments we do the assignment in place if all the component -- associations have compile-time known values. For other cases we -- create a temporary. The analysis for safety of on-line assignment -- is delicate, i.e. we don't know how to do it fully yet ??? -- For allocators we assign to the designated object in place if the -- aggregate meets the same conditions as other in-place assignments. -- In this case the aggregate may not come from source but was created -- for default initialization, e.g. with Initialize_Scalars. if Requires_Transient_Scope (Typ) then Establish_Transient_Scope (N, Sec_Stack => Has_Controlled_Component (Typ)); end if; if Has_Default_Init_Comps (N) then Maybe_In_Place_OK := False; elsif Is_Bit_Packed_Array (Typ) or else Has_Controlled_Component (Typ) then Maybe_In_Place_OK := False; else Maybe_In_Place_OK := (Nkind (Parent (N)) = N_Assignment_Statement and then In_Place_Assign_OK) or else (Nkind (Parent (Parent (N))) = N_Allocator and then In_Place_Assign_OK); end if; -- If this is an array of tasks, it will be expanded into build-in-place -- assignments. Build an activation chain for the tasks now. if Has_Task (Etype (N)) then Build_Activation_Chain_Entity (N); end if; -- Perform in-place expansion of aggregate in an object declaration. -- Note: actions generated for the aggregate will be captured in an -- expression-with-actions statement so that they can be transferred -- to freeze actions later if there is an address clause for the -- object. (Note: we don't use a block statement because this would -- cause generated freeze nodes to be elaborated in the wrong scope). -- Do not perform in-place expansion for SPARK 05 because aggregates are -- expected to appear in qualified form. In-place expansion eliminates -- the qualification and eventually violates this SPARK 05 restiction. -- Should document the rest of the guards ??? if not Has_Default_Init_Comps (N) and then Comes_From_Source (Parent_Node) and then Parent_Kind = N_Object_Declaration and then Present (Expression (Parent_Node)) and then not Must_Slide (Etype (Defining_Identifier (Parent_Node)), Typ) and then not Has_Controlled_Component (Typ) and then not Is_Bit_Packed_Array (Typ) and then not Restriction_Check_Required (SPARK_05) then In_Place_Assign_OK_For_Declaration := True; Tmp := Defining_Identifier (Parent_Node); Set_No_Initialization (Parent_Node); Set_Expression (Parent_Node, Empty); -- Set kind and type of the entity, for use in the analysis -- of the subsequent assignments. If the nominal type is not -- constrained, build a subtype from the known bounds of the -- aggregate. If the declaration has a subtype mark, use it, -- otherwise use the itype of the aggregate. Set_Ekind (Tmp, E_Variable); if not Is_Constrained (Typ) then Build_Constrained_Type (Positional => False); elsif Is_Entity_Name (Object_Definition (Parent_Node)) and then Is_Constrained (Entity (Object_Definition (Parent_Node))) then Set_Etype (Tmp, Entity (Object_Definition (Parent_Node))); else Set_Size_Known_At_Compile_Time (Typ, False); Set_Etype (Tmp, Typ); end if; elsif Maybe_In_Place_OK and then Nkind (Parent (N)) = N_Qualified_Expression and then Nkind (Parent (Parent (N))) = N_Allocator then Set_Expansion_Delayed (N); return; -- In the remaining cases the aggregate is the RHS of an assignment elsif Maybe_In_Place_OK and then Safe_Left_Hand_Side (Name (Parent (N))) then Tmp := Name (Parent (N)); if Etype (Tmp) /= Etype (N) then Apply_Length_Check (N, Etype (Tmp)); if Nkind (N) = N_Raise_Constraint_Error then -- Static error, nothing further to expand return; end if; end if; -- If a slice assignment has an aggregate with a single others_choice, -- the assignment can be done in place even if bounds are not static, -- by converting it into a loop over the discrete range of the slice. elsif Maybe_In_Place_OK and then Nkind (Name (Parent (N))) = N_Slice and then Is_Others_Aggregate (N) then Tmp := Name (Parent (N)); -- Set type of aggregate to be type of lhs in assignment, in order -- to suppress redundant length checks. Set_Etype (N, Etype (Tmp)); -- Step 5 -- In place aggregate expansion is not possible else Maybe_In_Place_OK := False; Tmp := Make_Temporary (Loc, 'A', N); Tmp_Decl := Make_Object_Declaration (Loc, Defining_Identifier => Tmp, Object_Definition => New_Occurrence_Of (Typ, Loc)); Set_No_Initialization (Tmp_Decl, True); -- If we are within a loop, the temporary will be pushed on the -- stack at each iteration. If the aggregate is the expression for an -- allocator, it will be immediately copied to the heap and can -- be reclaimed at once. We create a transient scope around the -- aggregate for this purpose. if Ekind (Current_Scope) = E_Loop and then Nkind (Parent (Parent (N))) = N_Allocator then Establish_Transient_Scope (N, False); end if; Insert_Action (N, Tmp_Decl); end if; -- Construct and insert the aggregate code. We can safely suppress index -- checks because this code is guaranteed not to raise CE on index -- checks. However we should *not* suppress all checks. declare Target : Node_Id; begin if Nkind (Tmp) = N_Defining_Identifier then Target := New_Occurrence_Of (Tmp, Loc); else if Has_Default_Init_Comps (N) then -- Ada 2005 (AI-287): This case has not been analyzed??? raise Program_Error; end if; -- Name in assignment is explicit dereference Target := New_Copy (Tmp); end if; -- If we are to generate an in place assignment for a declaration or -- an assignment statement, and the assignment can be done directly -- by the back end, then do not expand further. -- ??? We can also do that if in place expansion is not possible but -- then we could go into an infinite recursion. if (In_Place_Assign_OK_For_Declaration or else Maybe_In_Place_OK) and then not AAMP_On_Target and then not CodePeer_Mode and then not Modify_Tree_For_C and then not Possible_Bit_Aligned_Component (Target) and then not Is_Possibly_Unaligned_Slice (Target) and then Aggr_Assignment_OK_For_Backend (N) then if Maybe_In_Place_OK then return; end if; Aggr_Code := New_List ( Make_Assignment_Statement (Loc, Name => Target, Expression => New_Copy (N))); else Aggr_Code := Build_Array_Aggr_Code (N, Ctype => Ctyp, Index => First_Index (Typ), Into => Target, Scalar_Comp => Is_Scalar_Type (Ctyp)); end if; -- Save the last assignment statement associated with the aggregate -- when building a controlled object. This reference is utilized by -- the finalization machinery when marking an object as successfully -- initialized. if Needs_Finalization (Typ) and then Is_Entity_Name (Target) and then Present (Entity (Target)) and then Ekind_In (Entity (Target), E_Constant, E_Variable) then Set_Last_Aggregate_Assignment (Entity (Target), Last (Aggr_Code)); end if; end; -- If the aggregate is the expression in a declaration, the expanded -- code must be inserted after it. The defining entity might not come -- from source if this is part of an inlined body, but the declaration -- itself will. if Comes_From_Source (Tmp) or else (Nkind (Parent (N)) = N_Object_Declaration and then Comes_From_Source (Parent (N)) and then Tmp = Defining_Entity (Parent (N))) then declare Node_After : constant Node_Id := Next (Parent_Node); begin Insert_Actions_After (Parent_Node, Aggr_Code); if Parent_Kind = N_Object_Declaration then Collect_Initialization_Statements (Obj => Tmp, N => Parent_Node, Node_After => Node_After); end if; end; else Insert_Actions (N, Aggr_Code); end if; -- If the aggregate has been assigned in place, remove the original -- assignment. if Nkind (Parent (N)) = N_Assignment_Statement and then Maybe_In_Place_OK then Rewrite (Parent (N), Make_Null_Statement (Loc)); elsif Nkind (Parent (N)) /= N_Object_Declaration or else Tmp /= Defining_Identifier (Parent (N)) then Rewrite (N, New_Occurrence_Of (Tmp, Loc)); Analyze_And_Resolve (N, Typ); end if; end Expand_Array_Aggregate; ------------------------ -- Expand_N_Aggregate -- ------------------------ procedure Expand_N_Aggregate (N : Node_Id) is begin -- Record aggregate case if Is_Record_Type (Etype (N)) then Expand_Record_Aggregate (N); -- Array aggregate case else -- A special case, if we have a string subtype with bounds 1 .. N, -- where N is known at compile time, and the aggregate is of the -- form (others => 'x'), with a single choice and no expressions, -- and N is less than 80 (an arbitrary limit for now), then replace -- the aggregate by the equivalent string literal (but do not mark -- it as static since it is not). -- Note: this entire circuit is redundant with respect to code in -- Expand_Array_Aggregate that collapses others choices to positional -- form, but there are two problems with that circuit: -- a) It is limited to very small cases due to ill-understood -- interactions with bootstrapping. That limit is removed by -- use of the No_Implicit_Loops restriction. -- b) It incorrectly ends up with the resulting expressions being -- considered static when they are not. For example, the -- following test should fail: -- pragma Restrictions (No_Implicit_Loops); -- package NonSOthers4 is -- B : constant String (1 .. 6) := (others => 'A'); -- DH : constant String (1 .. 8) := B & "BB"; -- X : Integer; -- pragma Export (C, X, Link_Name => DH); -- end; -- But it succeeds (DH looks static to pragma Export) -- To be sorted out ??? if Present (Component_Associations (N)) then declare CA : constant Node_Id := First (Component_Associations (N)); MX : constant := 80; begin if Nkind (First (Choice_List (CA))) = N_Others_Choice and then Nkind (Expression (CA)) = N_Character_Literal and then No (Expressions (N)) then declare T : constant Entity_Id := Etype (N); X : constant Node_Id := First_Index (T); EC : constant Node_Id := Expression (CA); CV : constant Uint := Char_Literal_Value (EC); CC : constant Int := UI_To_Int (CV); begin if Nkind (X) = N_Range and then Compile_Time_Known_Value (Low_Bound (X)) and then Expr_Value (Low_Bound (X)) = 1 and then Compile_Time_Known_Value (High_Bound (X)) then declare Hi : constant Uint := Expr_Value (High_Bound (X)); begin if Hi <= MX then Start_String; for J in 1 .. UI_To_Int (Hi) loop Store_String_Char (Char_Code (CC)); end loop; Rewrite (N, Make_String_Literal (Sloc (N), Strval => End_String)); if CC >= Int (2 ** 16) then Set_Has_Wide_Wide_Character (N); elsif CC >= Int (2 ** 8) then Set_Has_Wide_Character (N); end if; Analyze_And_Resolve (N, T); Set_Is_Static_Expression (N, False); return; end if; end; end if; end; end if; end; end if; -- Not that special case, so normal expansion of array aggregate Expand_Array_Aggregate (N); end if; exception when RE_Not_Available => return; end Expand_N_Aggregate; ------------------------------ -- Expand_N_Delta_Aggregate -- ------------------------------ procedure Expand_N_Delta_Aggregate (N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); Typ : constant Entity_Id := Etype (N); Decl : Node_Id; begin Decl := Make_Object_Declaration (Loc, Defining_Identifier => Make_Temporary (Loc, 'T'), Object_Definition => New_Occurrence_Of (Typ, Loc), Expression => New_Copy_Tree (Expression (N))); if Is_Array_Type (Etype (N)) then Expand_Delta_Array_Aggregate (N, New_List (Decl)); else Expand_Delta_Record_Aggregate (N, New_List (Decl)); end if; end Expand_N_Delta_Aggregate; ---------------------------------- -- Expand_Delta_Array_Aggregate -- ---------------------------------- procedure Expand_Delta_Array_Aggregate (N : Node_Id; Deltas : List_Id) is Loc : constant Source_Ptr := Sloc (N); Temp : constant Entity_Id := Defining_Identifier (First (Deltas)); Assoc : Node_Id; function Generate_Loop (C : Node_Id) return Node_Id; -- Generate a loop containing individual component assignments for -- choices that are ranges, subtype indications, subtype names, and -- iterated component associations. ------------------- -- Generate_Loop -- ------------------- function Generate_Loop (C : Node_Id) return Node_Id is Sl : constant Source_Ptr := Sloc (C); Ix : Entity_Id; begin if Nkind (Parent (C)) = N_Iterated_Component_Association then Ix := Make_Defining_Identifier (Loc, Chars => (Chars (Defining_Identifier (Parent (C))))); else Ix := Make_Temporary (Sl, 'I'); end if; return Make_Loop_Statement (Loc, Iteration_Scheme => Make_Iteration_Scheme (Sl, Loop_Parameter_Specification => Make_Loop_Parameter_Specification (Sl, Defining_Identifier => Ix, Discrete_Subtype_Definition => New_Copy_Tree (C))), Statements => New_List ( Make_Assignment_Statement (Sl, Name => Make_Indexed_Component (Sl, Prefix => New_Occurrence_Of (Temp, Sl), Expressions => New_List (New_Occurrence_Of (Ix, Sl))), Expression => New_Copy_Tree (Expression (Assoc)))), End_Label => Empty); end Generate_Loop; -- Local variables Choice : Node_Id; -- Start of processing for Expand_Delta_Array_Aggregate begin Assoc := First (Component_Associations (N)); while Present (Assoc) loop Choice := First (Choice_List (Assoc)); if Nkind (Assoc) = N_Iterated_Component_Association then while Present (Choice) loop Append_To (Deltas, Generate_Loop (Choice)); Next (Choice); end loop; else while Present (Choice) loop -- Choice can be given by a range, a subtype indication, a -- subtype name, a scalar value, or an entity. if Nkind (Choice) = N_Range or else (Is_Entity_Name (Choice) and then Is_Type (Entity (Choice))) then Append_To (Deltas, Generate_Loop (Choice)); elsif Nkind (Choice) = N_Subtype_Indication then Append_To (Deltas, Generate_Loop (Range_Expression (Constraint (Choice)))); else Append_To (Deltas, Make_Assignment_Statement (Sloc (Choice), Name => Make_Indexed_Component (Sloc (Choice), Prefix => New_Occurrence_Of (Temp, Loc), Expressions => New_List (New_Copy_Tree (Choice))), Expression => New_Copy_Tree (Expression (Assoc)))); end if; Next (Choice); end loop; end if; Next (Assoc); end loop; Insert_Actions (N, Deltas); Rewrite (N, New_Occurrence_Of (Temp, Loc)); end Expand_Delta_Array_Aggregate; ----------------------------------- -- Expand_Delta_Record_Aggregate -- ----------------------------------- procedure Expand_Delta_Record_Aggregate (N : Node_Id; Deltas : List_Id) is Loc : constant Source_Ptr := Sloc (N); Temp : constant Entity_Id := Defining_Identifier (First (Deltas)); Assoc : Node_Id; Choice : Node_Id; begin Assoc := First (Component_Associations (N)); while Present (Assoc) loop Choice := First (Choice_List (Assoc)); while Present (Choice) loop Append_To (Deltas, Make_Assignment_Statement (Sloc (Choice), Name => Make_Selected_Component (Sloc (Choice), Prefix => New_Occurrence_Of (Temp, Loc), Selector_Name => Make_Identifier (Loc, Chars (Choice))), Expression => New_Copy_Tree (Expression (Assoc)))); Next (Choice); end loop; Next (Assoc); end loop; Insert_Actions (N, Deltas); Rewrite (N, New_Occurrence_Of (Temp, Loc)); end Expand_Delta_Record_Aggregate; ---------------------------------- -- Expand_N_Extension_Aggregate -- ---------------------------------- -- If the ancestor part is an expression, add a component association for -- the parent field. If the type of the ancestor part is not the direct -- parent of the expected type, build recursively the needed ancestors. -- If the ancestor part is a subtype_mark, replace aggregate with a decla- -- ration for a temporary of the expected type, followed by individual -- assignments to the given components. procedure Expand_N_Extension_Aggregate (N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); A : constant Node_Id := Ancestor_Part (N); Typ : constant Entity_Id := Etype (N); begin -- If the ancestor is a subtype mark, an init proc must be called -- on the resulting object which thus has to be materialized in -- the front-end if Is_Entity_Name (A) and then Is_Type (Entity (A)) then Convert_To_Assignments (N, Typ); -- The extension aggregate is transformed into a record aggregate -- of the following form (c1 and c2 are inherited components) -- (Exp with c3 => a, c4 => b) -- ==> (c1 => Exp.c1, c2 => Exp.c2, c3 => a, c4 => b) else Set_Etype (N, Typ); if Tagged_Type_Expansion then Expand_Record_Aggregate (N, Orig_Tag => New_Occurrence_Of (Node (First_Elmt (Access_Disp_Table (Typ))), Loc), Parent_Expr => A); -- No tag is needed in the case of a VM else Expand_Record_Aggregate (N, Parent_Expr => A); end if; end if; exception when RE_Not_Available => return; end Expand_N_Extension_Aggregate; ----------------------------- -- Expand_Record_Aggregate -- ----------------------------- procedure Expand_Record_Aggregate (N : Node_Id; Orig_Tag : Node_Id := Empty; Parent_Expr : Node_Id := Empty) is Loc : constant Source_Ptr := Sloc (N); Comps : constant List_Id := Component_Associations (N); Typ : constant Entity_Id := Etype (N); Base_Typ : constant Entity_Id := Base_Type (Typ); Static_Components : Boolean := True; -- Flag to indicate whether all components are compile-time known, -- and the aggregate can be constructed statically and handled by -- the back-end. procedure Build_Back_End_Aggregate; -- Build a proper aggregate to be handled by the back-end function Compile_Time_Known_Composite_Value (N : Node_Id) return Boolean; -- Returns true if N is an expression of composite type which can be -- fully evaluated at compile time without raising constraint error. -- Such expressions can be passed as is to Gigi without any expansion. -- -- This returns true for N_Aggregate with Compile_Time_Known_Aggregate -- set and constants whose expression is such an aggregate, recursively. function Component_Not_OK_For_Backend return Boolean; -- Check for presence of a component which makes it impossible for the -- backend to process the aggregate, thus requiring the use of a series -- of assignment statements. Cases checked for are a nested aggregate -- needing Late_Expansion, the presence of a tagged component which may -- need tag adjustment, and a bit unaligned component reference. -- -- We also force expansion into assignments if a component is of a -- mutable type (including a private type with discriminants) because -- in that case the size of the component to be copied may be smaller -- than the side of the target, and there is no simple way for gigi -- to compute the size of the object to be copied. -- -- NOTE: This is part of the ongoing work to define precisely the -- interface between front-end and back-end handling of aggregates. -- In general it is desirable to pass aggregates as they are to gigi, -- in order to minimize elaboration code. This is one case where the -- semantics of Ada complicate the analysis and lead to anomalies in -- the gcc back-end if the aggregate is not expanded into assignments. function Has_Per_Object_Constraint (L : List_Id) return Boolean; -- Return True if any element of L has Has_Per_Object_Constraint set. -- L should be the Choices component of an N_Component_Association. function Has_Visible_Private_Ancestor (Id : E) return Boolean; -- If any ancestor of the current type is private, the aggregate -- cannot be built in place. We cannot rely on Has_Private_Ancestor, -- because it will not be set when type and its parent are in the -- same scope, and the parent component needs expansion. function Top_Level_Aggregate (N : Node_Id) return Node_Id; -- For nested aggregates return the ultimate enclosing aggregate; for -- non-nested aggregates return N. ------------------------------ -- Build_Back_End_Aggregate -- ------------------------------ procedure Build_Back_End_Aggregate is Comp : Entity_Id; New_Comp : Node_Id; Tag_Value : Node_Id; begin if Nkind (N) = N_Aggregate then -- If the aggregate is static and can be handled by the back-end, -- nothing left to do. if Static_Components then Set_Compile_Time_Known_Aggregate (N); Set_Expansion_Delayed (N, False); end if; end if; -- If no discriminants, nothing special to do if not Has_Discriminants (Typ) then null; -- Case of discriminants present elsif Is_Derived_Type (Typ) then -- For untagged types, non-stored discriminants are replaced with -- stored discriminants, which are the ones that gigi uses to -- describe the type and its components. Generate_Aggregate_For_Derived_Type : declare procedure Prepend_Stored_Values (T : Entity_Id); -- Scan the list of stored discriminants of the type, and add -- their values to the aggregate being built. --------------------------- -- Prepend_Stored_Values -- --------------------------- procedure Prepend_Stored_Values (T : Entity_Id) is Discr : Entity_Id; First_Comp : Node_Id := Empty; begin Discr := First_Stored_Discriminant (T); while Present (Discr) loop New_Comp := Make_Component_Association (Loc, Choices => New_List ( New_Occurrence_Of (Discr, Loc)), Expression => New_Copy_Tree (Get_Discriminant_Value (Discr, Typ, Discriminant_Constraint (Typ)))); if No (First_Comp) then Prepend_To (Component_Associations (N), New_Comp); else Insert_After (First_Comp, New_Comp); end if; First_Comp := New_Comp; Next_Stored_Discriminant (Discr); end loop; end Prepend_Stored_Values; -- Local variables Constraints : constant List_Id := New_List; Discr : Entity_Id; Decl : Node_Id; Num_Disc : Nat := 0; Num_Gird : Nat := 0; -- Start of processing for Generate_Aggregate_For_Derived_Type begin -- Remove the associations for the discriminant of derived type declare First_Comp : Node_Id; begin First_Comp := First (Component_Associations (N)); while Present (First_Comp) loop Comp := First_Comp; Next (First_Comp); if Ekind (Entity (First (Choices (Comp)))) = E_Discriminant then Remove (Comp); Num_Disc := Num_Disc + 1; end if; end loop; end; -- Insert stored discriminant associations in the correct -- order. If there are more stored discriminants than new -- discriminants, there is at least one new discriminant that -- constrains more than one of the stored discriminants. In -- this case we need to construct a proper subtype of the -- parent type, in order to supply values to all the -- components. Otherwise there is one-one correspondence -- between the constraints and the stored discriminants. Discr := First_Stored_Discriminant (Base_Type (Typ)); while Present (Discr) loop Num_Gird := Num_Gird + 1; Next_Stored_Discriminant (Discr); end loop; -- Case of more stored discriminants than new discriminants if Num_Gird > Num_Disc then -- Create a proper subtype of the parent type, which is the -- proper implementation type for the aggregate, and convert -- it to the intended target type. Discr := First_Stored_Discriminant (Base_Type (Typ)); while Present (Discr) loop New_Comp := New_Copy_Tree (Get_Discriminant_Value (Discr, Typ, Discriminant_Constraint (Typ))); Append (New_Comp, Constraints); Next_Stored_Discriminant (Discr); end loop; Decl := Make_Subtype_Declaration (Loc, Defining_Identifier => Make_Temporary (Loc, 'T'), Subtype_Indication => Make_Subtype_Indication (Loc, Subtype_Mark => New_Occurrence_Of (Etype (Base_Type (Typ)), Loc), Constraint => Make_Index_Or_Discriminant_Constraint (Loc, Constraints))); Insert_Action (N, Decl); Prepend_Stored_Values (Base_Type (Typ)); Set_Etype (N, Defining_Identifier (Decl)); Set_Analyzed (N); Rewrite (N, Unchecked_Convert_To (Typ, N)); Analyze (N); -- Case where we do not have fewer new discriminants than -- stored discriminants, so in this case we can simply use the -- stored discriminants of the subtype. else Prepend_Stored_Values (Typ); end if; end Generate_Aggregate_For_Derived_Type; end if; if Is_Tagged_Type (Typ) then -- In the tagged case, _parent and _tag component must be created -- Reset Null_Present unconditionally. Tagged records always have -- at least one field (the tag or the parent). Set_Null_Record_Present (N, False); -- When the current aggregate comes from the expansion of an -- extension aggregate, the parent expr is replaced by an -- aggregate formed by selected components of this expr. if Present (Parent_Expr) and then Is_Empty_List (Comps) then Comp := First_Component_Or_Discriminant (Typ); while Present (Comp) loop -- Skip all expander-generated components if not Comes_From_Source (Original_Record_Component (Comp)) then null; else New_Comp := Make_Selected_Component (Loc, Prefix => Unchecked_Convert_To (Typ, Duplicate_Subexpr (Parent_Expr, True)), Selector_Name => New_Occurrence_Of (Comp, Loc)); Append_To (Comps, Make_Component_Association (Loc, Choices => New_List ( New_Occurrence_Of (Comp, Loc)), Expression => New_Comp)); Analyze_And_Resolve (New_Comp, Etype (Comp)); end if; Next_Component_Or_Discriminant (Comp); end loop; end if; -- Compute the value for the Tag now, if the type is a root it -- will be included in the aggregate right away, otherwise it will -- be propagated to the parent aggregate. if Present (Orig_Tag) then Tag_Value := Orig_Tag; elsif not Tagged_Type_Expansion then Tag_Value := Empty; else Tag_Value := New_Occurrence_Of (Node (First_Elmt (Access_Disp_Table (Typ))), Loc); end if; -- For a derived type, an aggregate for the parent is formed with -- all the inherited components. if Is_Derived_Type (Typ) then declare First_Comp : Node_Id; Parent_Comps : List_Id; Parent_Aggr : Node_Id; Parent_Name : Node_Id; begin -- Remove the inherited component association from the -- aggregate and store them in the parent aggregate First_Comp := First (Component_Associations (N)); Parent_Comps := New_List; while Present (First_Comp) and then Scope (Original_Record_Component (Entity (First (Choices (First_Comp))))) /= Base_Typ loop Comp := First_Comp; Next (First_Comp); Remove (Comp); Append (Comp, Parent_Comps); end loop; Parent_Aggr := Make_Aggregate (Loc, Component_Associations => Parent_Comps); Set_Etype (Parent_Aggr, Etype (Base_Type (Typ))); -- Find the _parent component Comp := First_Component (Typ); while Chars (Comp) /= Name_uParent loop Comp := Next_Component (Comp); end loop; Parent_Name := New_Occurrence_Of (Comp, Loc); -- Insert the parent aggregate Prepend_To (Component_Associations (N), Make_Component_Association (Loc, Choices => New_List (Parent_Name), Expression => Parent_Aggr)); -- Expand recursively the parent propagating the right Tag Expand_Record_Aggregate (Parent_Aggr, Tag_Value, Parent_Expr); -- The ancestor part may be a nested aggregate that has -- delayed expansion: recheck now. if Component_Not_OK_For_Backend then Convert_To_Assignments (N, Typ); end if; end; -- For a root type, the tag component is added (unless compiling -- for the VMs, where tags are implicit). elsif Tagged_Type_Expansion then declare Tag_Name : constant Node_Id := New_Occurrence_Of (First_Tag_Component (Typ), Loc); Typ_Tag : constant Entity_Id := RTE (RE_Tag); Conv_Node : constant Node_Id := Unchecked_Convert_To (Typ_Tag, Tag_Value); begin Set_Etype (Conv_Node, Typ_Tag); Prepend_To (Component_Associations (N), Make_Component_Association (Loc, Choices => New_List (Tag_Name), Expression => Conv_Node)); end; end if; end if; end Build_Back_End_Aggregate; ---------------------------------------- -- Compile_Time_Known_Composite_Value -- ---------------------------------------- function Compile_Time_Known_Composite_Value (N : Node_Id) return Boolean is begin -- If we have an entity name, then see if it is the name of a -- constant and if so, test the corresponding constant value. if Is_Entity_Name (N) then declare E : constant Entity_Id := Entity (N); V : Node_Id; begin if Ekind (E) /= E_Constant then return False; else V := Constant_Value (E); return Present (V) and then Compile_Time_Known_Composite_Value (V); end if; end; -- We have a value, see if it is compile time known else if Nkind (N) = N_Aggregate then return Compile_Time_Known_Aggregate (N); end if; -- All other types of values are not known at compile time return False; end if; end Compile_Time_Known_Composite_Value; ---------------------------------- -- Component_Not_OK_For_Backend -- ---------------------------------- function Component_Not_OK_For_Backend return Boolean is C : Node_Id; Expr_Q : Node_Id; begin if No (Comps) then return False; end if; C := First (Comps); while Present (C) loop -- If the component has box initialization, expansion is needed -- and component is not ready for backend. if Box_Present (C) then return True; end if; if Nkind (Expression (C)) = N_Qualified_Expression then Expr_Q := Expression (Expression (C)); else Expr_Q := Expression (C); end if; -- Return true if the aggregate has any associations for tagged -- components that may require tag adjustment. -- These are cases where the source expression may have a tag that -- could differ from the component tag (e.g., can occur for type -- conversions and formal parameters). (Tag adjustment not needed -- if Tagged_Type_Expansion because object tags are implicit in -- the machine.) if Is_Tagged_Type (Etype (Expr_Q)) and then (Nkind (Expr_Q) = N_Type_Conversion or else (Is_Entity_Name (Expr_Q) and then Ekind (Entity (Expr_Q)) in Formal_Kind)) and then Tagged_Type_Expansion then Static_Components := False; return True; elsif Is_Delayed_Aggregate (Expr_Q) then Static_Components := False; return True; elsif Possible_Bit_Aligned_Component (Expr_Q) then Static_Components := False; return True; elsif Modify_Tree_For_C and then Nkind (C) = N_Component_Association and then Has_Per_Object_Constraint (Choices (C)) then Static_Components := False; return True; elsif Modify_Tree_For_C and then Nkind (Expr_Q) = N_Identifier and then Is_Array_Type (Etype (Expr_Q)) then Static_Components := False; return True; end if; if Is_Elementary_Type (Etype (Expr_Q)) then if not Compile_Time_Known_Value (Expr_Q) then Static_Components := False; end if; elsif not Compile_Time_Known_Composite_Value (Expr_Q) then Static_Components := False; if Is_Private_Type (Etype (Expr_Q)) and then Has_Discriminants (Etype (Expr_Q)) then return True; end if; end if; Next (C); end loop; return False; end Component_Not_OK_For_Backend; ------------------------------- -- Has_Per_Object_Constraint -- ------------------------------- function Has_Per_Object_Constraint (L : List_Id) return Boolean is N : Node_Id := First (L); begin while Present (N) loop if Is_Entity_Name (N) and then Present (Entity (N)) and then Has_Per_Object_Constraint (Entity (N)) then return True; end if; Next (N); end loop; return False; end Has_Per_Object_Constraint; ----------------------------------- -- Has_Visible_Private_Ancestor -- ----------------------------------- function Has_Visible_Private_Ancestor (Id : E) return Boolean is R : constant Entity_Id := Root_Type (Id); T1 : Entity_Id := Id; begin loop if Is_Private_Type (T1) then return True; elsif T1 = R then return False; else T1 := Etype (T1); end if; end loop; end Has_Visible_Private_Ancestor; ------------------------- -- Top_Level_Aggregate -- ------------------------- function Top_Level_Aggregate (N : Node_Id) return Node_Id is Aggr : Node_Id; begin Aggr := N; while Present (Parent (Aggr)) and then Nkind_In (Parent (Aggr), N_Aggregate, N_Component_Association) loop Aggr := Parent (Aggr); end loop; return Aggr; end Top_Level_Aggregate; -- Local variables Top_Level_Aggr : constant Node_Id := Top_Level_Aggregate (N); -- Start of processing for Expand_Record_Aggregate begin -- If the aggregate is to be assigned to an atomic/VFA variable, we have -- to prevent a piecemeal assignment even if the aggregate is to be -- expanded. We create a temporary for the aggregate, and assign the -- temporary instead, so that the back end can generate an atomic move -- for it. if Is_Atomic_VFA_Aggregate (N) then return; -- No special management required for aggregates used to initialize -- statically allocated dispatch tables elsif Is_Static_Dispatch_Table_Aggregate (N) then return; end if; -- Ada 2005 (AI-318-2): We need to convert to assignments if components -- are build-in-place function calls. The assignments will each turn -- into a build-in-place function call. If components are all static, -- we can pass the aggregate to the backend regardless of limitedness. -- Extension aggregates, aggregates in extended return statements, and -- aggregates for C++ imported types must be expanded. if Ada_Version >= Ada_2005 and then Is_Limited_View (Typ) then if not Nkind_In (Parent (N), N_Component_Association, N_Object_Declaration) then Convert_To_Assignments (N, Typ); elsif Nkind (N) = N_Extension_Aggregate or else Convention (Typ) = Convention_CPP then Convert_To_Assignments (N, Typ); elsif not Size_Known_At_Compile_Time (Typ) or else Component_Not_OK_For_Backend or else not Static_Components then Convert_To_Assignments (N, Typ); -- In all other cases, build a proper aggregate to be handled by -- the back-end else Build_Back_End_Aggregate; end if; -- Gigi doesn't properly handle temporaries of variable size so we -- generate it in the front-end elsif not Size_Known_At_Compile_Time (Typ) and then Tagged_Type_Expansion then Convert_To_Assignments (N, Typ); -- An aggregate used to initialize a controlled object must be turned -- into component assignments as the components themselves may require -- finalization actions such as adjustment. elsif Needs_Finalization (Typ) then Convert_To_Assignments (N, Typ); -- Ada 2005 (AI-287): In case of default initialized components we -- convert the aggregate into assignments. elsif Has_Default_Init_Comps (N) then Convert_To_Assignments (N, Typ); -- Check components elsif Component_Not_OK_For_Backend then Convert_To_Assignments (N, Typ); -- If an ancestor is private, some components are not inherited and we -- cannot expand into a record aggregate. elsif Has_Visible_Private_Ancestor (Typ) then Convert_To_Assignments (N, Typ); -- ??? The following was done to compile fxacc00.ads in the ACVCs. Gigi -- is not able to handle the aggregate for Late_Request. elsif Is_Tagged_Type (Typ) and then Has_Discriminants (Typ) then Convert_To_Assignments (N, Typ); -- If the tagged types covers interface types we need to initialize all -- hidden components containing pointers to secondary dispatch tables. elsif Is_Tagged_Type (Typ) and then Has_Interfaces (Typ) then Convert_To_Assignments (N, Typ); -- If some components are mutable, the size of the aggregate component -- may be distinct from the default size of the type component, so -- we need to expand to insure that the back-end copies the proper -- size of the data. However, if the aggregate is the initial value of -- a constant, the target is immutable and might be built statically -- if components are appropriate. elsif Has_Mutable_Components (Typ) and then (Nkind (Parent (Top_Level_Aggr)) /= N_Object_Declaration or else not Constant_Present (Parent (Top_Level_Aggr)) or else not Static_Components) then Convert_To_Assignments (N, Typ); -- If the type involved has bit aligned components, then we are not sure -- that the back end can handle this case correctly. elsif Type_May_Have_Bit_Aligned_Components (Typ) then Convert_To_Assignments (N, Typ); -- When generating C, only generate an aggregate when declaring objects -- since C does not support aggregates in e.g. assignment statements. elsif Modify_Tree_For_C and then not In_Object_Declaration (N) then Convert_To_Assignments (N, Typ); -- In all other cases, build a proper aggregate to be handled by gigi else Build_Back_End_Aggregate; end if; end Expand_Record_Aggregate; ---------------------------- -- Has_Default_Init_Comps -- ---------------------------- function Has_Default_Init_Comps (N : Node_Id) return Boolean is Comps : constant List_Id := Component_Associations (N); C : Node_Id; Expr : Node_Id; begin pragma Assert (Nkind_In (N, N_Aggregate, N_Extension_Aggregate)); if No (Comps) then return False; end if; if Has_Self_Reference (N) then return True; end if; -- Check if any direct component has default initialized components C := First (Comps); while Present (C) loop if Box_Present (C) then return True; end if; Next (C); end loop; -- Recursive call in case of aggregate expression C := First (Comps); while Present (C) loop Expr := Expression (C); if Present (Expr) and then Nkind_In (Expr, N_Aggregate, N_Extension_Aggregate) and then Has_Default_Init_Comps (Expr) then return True; end if; Next (C); end loop; return False; end Has_Default_Init_Comps; -------------------------- -- Is_Delayed_Aggregate -- -------------------------- function Is_Delayed_Aggregate (N : Node_Id) return Boolean is Node : Node_Id := N; Kind : Node_Kind := Nkind (Node); begin if Kind = N_Qualified_Expression then Node := Expression (Node); Kind := Nkind (Node); end if; if not Nkind_In (Kind, N_Aggregate, N_Extension_Aggregate) then return False; else return Expansion_Delayed (Node); end if; end Is_Delayed_Aggregate; --------------------------- -- In_Object_Declaration -- --------------------------- function In_Object_Declaration (N : Node_Id) return Boolean is P : Node_Id := Parent (N); begin while Present (P) loop if Nkind (P) = N_Object_Declaration then return True; end if; P := Parent (P); end loop; return False; end In_Object_Declaration; ---------------------------------------- -- Is_Static_Dispatch_Table_Aggregate -- ---------------------------------------- function Is_Static_Dispatch_Table_Aggregate (N : Node_Id) return Boolean is Typ : constant Entity_Id := Base_Type (Etype (N)); begin return Static_Dispatch_Tables and then Tagged_Type_Expansion and then RTU_Loaded (Ada_Tags) -- Avoid circularity when rebuilding the compiler and then Cunit_Entity (Get_Source_Unit (N)) /= RTU_Entity (Ada_Tags) and then (Typ = RTE (RE_Dispatch_Table_Wrapper) or else Typ = RTE (RE_Address_Array) or else Typ = RTE (RE_Type_Specific_Data) or else Typ = RTE (RE_Tag_Table) or else (RTE_Available (RE_Interface_Data) and then Typ = RTE (RE_Interface_Data)) or else (RTE_Available (RE_Interfaces_Array) and then Typ = RTE (RE_Interfaces_Array)) or else (RTE_Available (RE_Interface_Data_Element) and then Typ = RTE (RE_Interface_Data_Element))); end Is_Static_Dispatch_Table_Aggregate; ----------------------------- -- Is_Two_Dim_Packed_Array -- ----------------------------- function Is_Two_Dim_Packed_Array (Typ : Entity_Id) return Boolean is C : constant Int := UI_To_Int (Component_Size (Typ)); begin return Number_Dimensions (Typ) = 2 and then Is_Bit_Packed_Array (Typ) and then (C = 1 or else C = 2 or else C = 4); end Is_Two_Dim_Packed_Array; -------------------- -- Late_Expansion -- -------------------- function Late_Expansion (N : Node_Id; Typ : Entity_Id; Target : Node_Id) return List_Id is Aggr_Code : List_Id; begin if Is_Array_Type (Etype (N)) then Aggr_Code := Build_Array_Aggr_Code (N => N, Ctype => Component_Type (Etype (N)), Index => First_Index (Typ), Into => Target, Scalar_Comp => Is_Scalar_Type (Component_Type (Typ)), Indexes => No_List); -- Directly or indirectly (e.g. access protected procedure) a record else Aggr_Code := Build_Record_Aggr_Code (N, Typ, Target); end if; -- Save the last assignment statement associated with the aggregate -- when building a controlled object. This reference is utilized by -- the finalization machinery when marking an object as successfully -- initialized. if Needs_Finalization (Typ) and then Is_Entity_Name (Target) and then Present (Entity (Target)) and then Ekind_In (Entity (Target), E_Constant, E_Variable) then Set_Last_Aggregate_Assignment (Entity (Target), Last (Aggr_Code)); end if; return Aggr_Code; end Late_Expansion; ---------------------------------- -- Make_OK_Assignment_Statement -- ---------------------------------- function Make_OK_Assignment_Statement (Sloc : Source_Ptr; Name : Node_Id; Expression : Node_Id) return Node_Id is begin Set_Assignment_OK (Name); return Make_Assignment_Statement (Sloc, Name, Expression); end Make_OK_Assignment_Statement; ----------------------- -- Number_Of_Choices -- ----------------------- function Number_Of_Choices (N : Node_Id) return Nat is Assoc : Node_Id; Choice : Node_Id; Nb_Choices : Nat := 0; begin if Present (Expressions (N)) then return 0; end if; Assoc := First (Component_Associations (N)); while Present (Assoc) loop Choice := First (Choice_List (Assoc)); while Present (Choice) loop if Nkind (Choice) /= N_Others_Choice then Nb_Choices := Nb_Choices + 1; end if; Next (Choice); end loop; Next (Assoc); end loop; return Nb_Choices; end Number_Of_Choices; ------------------------------------ -- Packed_Array_Aggregate_Handled -- ------------------------------------ -- The current version of this procedure will handle at compile time -- any array aggregate that meets these conditions: -- One and two dimensional, bit packed -- Underlying packed type is modular type -- Bounds are within 32-bit Int range -- All bounds and values are static -- Note: for now, in the 2-D case, we only handle component sizes of -- 1, 2, 4 (cases where an integral number of elements occupies a byte). function Packed_Array_Aggregate_Handled (N : Node_Id) return Boolean is Loc : constant Source_Ptr := Sloc (N); Typ : constant Entity_Id := Etype (N); Ctyp : constant Entity_Id := Component_Type (Typ); Not_Handled : exception; -- Exception raised if this aggregate cannot be handled begin -- Handle one- or two dimensional bit packed array if not Is_Bit_Packed_Array (Typ) or else Number_Dimensions (Typ) > 2 then return False; end if; -- If two-dimensional, check whether it can be folded, and transformed -- into a one-dimensional aggregate for the Packed_Array_Impl_Type of -- the original type. if Number_Dimensions (Typ) = 2 then return Two_Dim_Packed_Array_Handled (N); end if; if not Is_Modular_Integer_Type (Packed_Array_Impl_Type (Typ)) then return False; end if; if not Is_Scalar_Type (Component_Type (Typ)) and then Has_Non_Standard_Rep (Component_Type (Typ)) then return False; end if; declare Csiz : constant Nat := UI_To_Int (Component_Size (Typ)); Lo : Node_Id; Hi : Node_Id; -- Bounds of index type Lob : Uint; Hib : Uint; -- Values of bounds if compile time known function Get_Component_Val (N : Node_Id) return Uint; -- Given a expression value N of the component type Ctyp, returns a -- value of Csiz (component size) bits representing this value. If -- the value is non-static or any other reason exists why the value -- cannot be returned, then Not_Handled is raised. ----------------------- -- Get_Component_Val -- ----------------------- function Get_Component_Val (N : Node_Id) return Uint is Val : Uint; begin -- We have to analyze the expression here before doing any further -- processing here. The analysis of such expressions is deferred -- till expansion to prevent some problems of premature analysis. Analyze_And_Resolve (N, Ctyp); -- Must have a compile time value. String literals have to be -- converted into temporaries as well, because they cannot easily -- be converted into their bit representation. if not Compile_Time_Known_Value (N) or else Nkind (N) = N_String_Literal then raise Not_Handled; end if; Val := Expr_Rep_Value (N); -- Adjust for bias, and strip proper number of bits if Has_Biased_Representation (Ctyp) then Val := Val - Expr_Value (Type_Low_Bound (Ctyp)); end if; return Val mod Uint_2 ** Csiz; end Get_Component_Val; -- Here we know we have a one dimensional bit packed array begin Get_Index_Bounds (First_Index (Typ), Lo, Hi); -- Cannot do anything if bounds are dynamic if not Compile_Time_Known_Value (Lo) or else not Compile_Time_Known_Value (Hi) then return False; end if; -- Or are silly out of range of int bounds Lob := Expr_Value (Lo); Hib := Expr_Value (Hi); if not UI_Is_In_Int_Range (Lob) or else not UI_Is_In_Int_Range (Hib) then return False; end if; -- At this stage we have a suitable aggregate for handling at compile -- time. The only remaining checks are that the values of expressions -- in the aggregate are compile-time known (checks are performed by -- Get_Component_Val), and that any subtypes or ranges are statically -- known. -- If the aggregate is not fully positional at this stage, then -- convert it to positional form. Either this will fail, in which -- case we can do nothing, or it will succeed, in which case we have -- succeeded in handling the aggregate and transforming it into a -- modular value, or it will stay an aggregate, in which case we -- have failed to create a packed value for it. if Present (Component_Associations (N)) then Convert_To_Positional (N, Max_Others_Replicate => 64, Handle_Bit_Packed => True); return Nkind (N) /= N_Aggregate; end if; -- Otherwise we are all positional, so convert to proper value declare Lov : constant Int := UI_To_Int (Lob); Hiv : constant Int := UI_To_Int (Hib); Len : constant Nat := Int'Max (0, Hiv - Lov + 1); -- The length of the array (number of elements) Aggregate_Val : Uint; -- Value of aggregate. The value is set in the low order bits of -- this value. For the little-endian case, the values are stored -- from low-order to high-order and for the big-endian case the -- values are stored from high-order to low-order. Note that gigi -- will take care of the conversions to left justify the value in -- the big endian case (because of left justified modular type -- processing), so we do not have to worry about that here. Lit : Node_Id; -- Integer literal for resulting constructed value Shift : Nat; -- Shift count from low order for next value Incr : Int; -- Shift increment for loop Expr : Node_Id; -- Next expression from positional parameters of aggregate Left_Justified : Boolean; -- Set True if we are filling the high order bits of the target -- value (i.e. the value is left justified). begin -- For little endian, we fill up the low order bits of the target -- value. For big endian we fill up the high order bits of the -- target value (which is a left justified modular value). Left_Justified := Bytes_Big_Endian; -- Switch justification if using -gnatd8 if Debug_Flag_8 then Left_Justified := not Left_Justified; end if; -- Switch justfification if reverse storage order if Reverse_Storage_Order (Base_Type (Typ)) then Left_Justified := not Left_Justified; end if; if Left_Justified then Shift := Csiz * (Len - 1); Incr := -Csiz; else Shift := 0; Incr := +Csiz; end if; -- Loop to set the values if Len = 0 then Aggregate_Val := Uint_0; else Expr := First (Expressions (N)); Aggregate_Val := Get_Component_Val (Expr) * Uint_2 ** Shift; for J in 2 .. Len loop Shift := Shift + Incr; Next (Expr); Aggregate_Val := Aggregate_Val + Get_Component_Val (Expr) * Uint_2 ** Shift; end loop; end if; -- Now we can rewrite with the proper value Lit := Make_Integer_Literal (Loc, Intval => Aggregate_Val); Set_Print_In_Hex (Lit); -- Construct the expression using this literal. Note that it is -- important to qualify the literal with its proper modular type -- since universal integer does not have the required range and -- also this is a left justified modular type, which is important -- in the big-endian case. Rewrite (N, Unchecked_Convert_To (Typ, Make_Qualified_Expression (Loc, Subtype_Mark => New_Occurrence_Of (Packed_Array_Impl_Type (Typ), Loc), Expression => Lit))); Analyze_And_Resolve (N, Typ); return True; end; end; exception when Not_Handled => return False; end Packed_Array_Aggregate_Handled; ---------------------------- -- Has_Mutable_Components -- ---------------------------- function Has_Mutable_Components (Typ : Entity_Id) return Boolean is Comp : Entity_Id; begin Comp := First_Component (Typ); while Present (Comp) loop if Is_Record_Type (Etype (Comp)) and then Has_Discriminants (Etype (Comp)) and then not Is_Constrained (Etype (Comp)) then return True; end if; Next_Component (Comp); end loop; return False; end Has_Mutable_Components; ------------------------------ -- Initialize_Discriminants -- ------------------------------ procedure Initialize_Discriminants (N : Node_Id; Typ : Entity_Id) is Loc : constant Source_Ptr := Sloc (N); Bas : constant Entity_Id := Base_Type (Typ); Par : constant Entity_Id := Etype (Bas); Decl : constant Node_Id := Parent (Par); Ref : Node_Id; begin if Is_Tagged_Type (Bas) and then Is_Derived_Type (Bas) and then Has_Discriminants (Par) and then Has_Discriminants (Bas) and then Number_Discriminants (Bas) /= Number_Discriminants (Par) and then Nkind (Decl) = N_Full_Type_Declaration and then Nkind (Type_Definition (Decl)) = N_Record_Definition and then Present (Variant_Part (Component_List (Type_Definition (Decl)))) and then Nkind (N) /= N_Extension_Aggregate then -- Call init proc to set discriminants. -- There should eventually be a special procedure for this ??? Ref := New_Occurrence_Of (Defining_Identifier (N), Loc); Insert_Actions_After (N, Build_Initialization_Call (Sloc (N), Ref, Typ)); end if; end Initialize_Discriminants; ---------------- -- Must_Slide -- ---------------- function Must_Slide (Obj_Type : Entity_Id; Typ : Entity_Id) return Boolean is L1, L2, H1, H2 : Node_Id; begin -- No sliding if the type of the object is not established yet, if it is -- an unconstrained type whose actual subtype comes from the aggregate, -- or if the two types are identical. if not Is_Array_Type (Obj_Type) then return False; elsif not Is_Constrained (Obj_Type) then return False; elsif Typ = Obj_Type then return False; else -- Sliding can only occur along the first dimension Get_Index_Bounds (First_Index (Typ), L1, H1); Get_Index_Bounds (First_Index (Obj_Type), L2, H2); if not Is_OK_Static_Expression (L1) or else not Is_OK_Static_Expression (L2) or else not Is_OK_Static_Expression (H1) or else not Is_OK_Static_Expression (H2) then return False; else return Expr_Value (L1) /= Expr_Value (L2) or else Expr_Value (H1) /= Expr_Value (H2); end if; end if; end Must_Slide; --------------------------------- -- Process_Transient_Component -- --------------------------------- procedure Process_Transient_Component (Loc : Source_Ptr; Comp_Typ : Entity_Id; Init_Expr : Node_Id; Fin_Call : out Node_Id; Hook_Clear : out Node_Id; Aggr : Node_Id := Empty; Stmts : List_Id := No_List) is procedure Add_Item (Item : Node_Id); -- Insert arbitrary node Item into the tree depending on the values of -- Aggr and Stmts. -------------- -- Add_Item -- -------------- procedure Add_Item (Item : Node_Id) is begin if Present (Aggr) then Insert_Action (Aggr, Item); else pragma Assert (Present (Stmts)); Append_To (Stmts, Item); end if; end Add_Item; -- Local variables Hook_Assign : Node_Id; Hook_Decl : Node_Id; Ptr_Decl : Node_Id; Res_Decl : Node_Id; Res_Id : Entity_Id; Res_Typ : Entity_Id; -- Start of processing for Process_Transient_Component begin -- Add the access type, which provides a reference to the function -- result. Generate: -- type Res_Typ is access all Comp_Typ; Res_Typ := Make_Temporary (Loc, 'A'); Set_Ekind (Res_Typ, E_General_Access_Type); Set_Directly_Designated_Type (Res_Typ, Comp_Typ); Add_Item (Make_Full_Type_Declaration (Loc, Defining_Identifier => Res_Typ, Type_Definition => Make_Access_To_Object_Definition (Loc, All_Present => True, Subtype_Indication => New_Occurrence_Of (Comp_Typ, Loc)))); -- Add the temporary which captures the result of the function call. -- Generate: -- Res : constant Res_Typ := Init_Expr'Reference; -- Note that this temporary is effectively a transient object because -- its lifetime is bounded by the current array or record component. Res_Id := Make_Temporary (Loc, 'R'); Set_Ekind (Res_Id, E_Constant); Set_Etype (Res_Id, Res_Typ); -- Mark the transient object as successfully processed to avoid double -- finalization. Set_Is_Finalized_Transient (Res_Id); -- Signal the general finalization machinery that this transient object -- should not be considered for finalization actions because its cleanup -- will be performed by Process_Transient_Component_Completion. Set_Is_Ignored_Transient (Res_Id); Res_Decl := Make_Object_Declaration (Loc, Defining_Identifier => Res_Id, Constant_Present => True, Object_Definition => New_Occurrence_Of (Res_Typ, Loc), Expression => Make_Reference (Loc, New_Copy_Tree (Init_Expr))); Add_Item (Res_Decl); -- Construct all pieces necessary to hook and finalize the transient -- result. Build_Transient_Object_Statements (Obj_Decl => Res_Decl, Fin_Call => Fin_Call, Hook_Assign => Hook_Assign, Hook_Clear => Hook_Clear, Hook_Decl => Hook_Decl, Ptr_Decl => Ptr_Decl); -- Add the access type which provides a reference to the transient -- result. Generate: -- type Ptr_Typ is access all Comp_Typ; Add_Item (Ptr_Decl); -- Add the temporary which acts as a hook to the transient result. -- Generate: -- Hook : Ptr_Typ := null; Add_Item (Hook_Decl); -- Attach the transient result to the hook. Generate: -- Hook := Ptr_Typ (Res); Add_Item (Hook_Assign); -- The original initialization expression now references the value of -- the temporary function result. Generate: -- Res.all Rewrite (Init_Expr, Make_Explicit_Dereference (Loc, Prefix => New_Occurrence_Of (Res_Id, Loc))); end Process_Transient_Component; -------------------------------------------- -- Process_Transient_Component_Completion -- -------------------------------------------- procedure Process_Transient_Component_Completion (Loc : Source_Ptr; Aggr : Node_Id; Fin_Call : Node_Id; Hook_Clear : Node_Id; Stmts : List_Id) is Exceptions_OK : constant Boolean := not Restriction_Active (No_Exception_Propagation); begin pragma Assert (Present (Hook_Clear)); -- Generate the following code if exception propagation is allowed: -- declare -- Abort : constant Boolean := Triggered_By_Abort; -- <or> -- Abort : constant Boolean := False; -- no abort -- E : Exception_Occurrence; -- Raised : Boolean := False; -- begin -- [Abort_Defer;] -- begin -- Hook := null; -- [Deep_]Finalize (Res.all); -- exception -- when others => -- if not Raised then -- Raised := True; -- Save_Occurrence (E, -- Get_Curent_Excep.all.all); -- end if; -- end; -- [Abort_Undefer;] -- if Raised and then not Abort then -- Raise_From_Controlled_Operation (E); -- end if; -- end; if Exceptions_OK then Abort_And_Exception : declare Blk_Decls : constant List_Id := New_List; Blk_Stmts : constant List_Id := New_List; Fin_Stmts : constant List_Id := New_List; Fin_Data : Finalization_Exception_Data; begin -- Create the declarations of the two flags and the exception -- occurrence. Build_Object_Declarations (Fin_Data, Blk_Decls, Loc); -- Generate: -- Abort_Defer; if Abort_Allowed then Append_To (Blk_Stmts, Build_Runtime_Call (Loc, RE_Abort_Defer)); end if; -- Wrap the hook clear and the finalization call in order to trap -- a potential exception. Append_To (Fin_Stmts, Hook_Clear); if Present (Fin_Call) then Append_To (Fin_Stmts, Fin_Call); end if; Append_To (Blk_Stmts, Make_Block_Statement (Loc, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => Fin_Stmts, Exception_Handlers => New_List ( Build_Exception_Handler (Fin_Data))))); -- Generate: -- Abort_Undefer; if Abort_Allowed then Append_To (Blk_Stmts, Build_Runtime_Call (Loc, RE_Abort_Undefer)); end if; -- Reraise the potential exception with a proper "upgrade" to -- Program_Error if needed. Append_To (Blk_Stmts, Build_Raise_Statement (Fin_Data)); -- Wrap everything in a block Append_To (Stmts, Make_Block_Statement (Loc, Declarations => Blk_Decls, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => Blk_Stmts))); end Abort_And_Exception; -- Generate the following code if exception propagation is not allowed -- and aborts are allowed: -- begin -- Abort_Defer; -- Hook := null; -- [Deep_]Finalize (Res.all); -- at end -- Abort_Undefer_Direct; -- end; elsif Abort_Allowed then Abort_Only : declare Blk_Stmts : constant List_Id := New_List; begin Append_To (Blk_Stmts, Build_Runtime_Call (Loc, RE_Abort_Defer)); Append_To (Blk_Stmts, Hook_Clear); if Present (Fin_Call) then Append_To (Blk_Stmts, Fin_Call); end if; Append_To (Stmts, Build_Abort_Undefer_Block (Loc, Stmts => Blk_Stmts, Context => Aggr)); end Abort_Only; -- Otherwise generate: -- Hook := null; -- [Deep_]Finalize (Res.all); else Append_To (Stmts, Hook_Clear); if Present (Fin_Call) then Append_To (Stmts, Fin_Call); end if; end if; end Process_Transient_Component_Completion; --------------------- -- Sort_Case_Table -- --------------------- procedure Sort_Case_Table (Case_Table : in out Case_Table_Type) is L : constant Int := Case_Table'First; U : constant Int := Case_Table'Last; K : Int; J : Int; T : Case_Bounds; begin K := L; while K /= U loop T := Case_Table (K + 1); J := K + 1; while J /= L and then Expr_Value (Case_Table (J - 1).Choice_Lo) > Expr_Value (T.Choice_Lo) loop Case_Table (J) := Case_Table (J - 1); J := J - 1; end loop; Case_Table (J) := T; K := K + 1; end loop; end Sort_Case_Table; ---------------------------- -- Static_Array_Aggregate -- ---------------------------- function Static_Array_Aggregate (N : Node_Id) return Boolean is Bounds : constant Node_Id := Aggregate_Bounds (N); Typ : constant Entity_Id := Etype (N); Comp_Type : constant Entity_Id := Component_Type (Typ); Agg : Node_Id; Expr : Node_Id; Lo : Node_Id; Hi : Node_Id; begin if Is_Tagged_Type (Typ) or else Is_Controlled (Typ) or else Is_Packed (Typ) then return False; end if; if Present (Bounds) and then Nkind (Bounds) = N_Range and then Nkind (Low_Bound (Bounds)) = N_Integer_Literal and then Nkind (High_Bound (Bounds)) = N_Integer_Literal then Lo := Low_Bound (Bounds); Hi := High_Bound (Bounds); if No (Component_Associations (N)) then -- Verify that all components are static integers Expr := First (Expressions (N)); while Present (Expr) loop if Nkind (Expr) /= N_Integer_Literal then return False; end if; Next (Expr); end loop; return True; else -- We allow only a single named association, either a static -- range or an others_clause, with a static expression. Expr := First (Component_Associations (N)); if Present (Expressions (N)) then return False; elsif Present (Next (Expr)) then return False; elsif Present (Next (First (Choice_List (Expr)))) then return False; else -- The aggregate is static if all components are literals, -- or else all its components are static aggregates for the -- component type. We also limit the size of a static aggregate -- to prevent runaway static expressions. if Is_Array_Type (Comp_Type) or else Is_Record_Type (Comp_Type) then if Nkind (Expression (Expr)) /= N_Aggregate or else not Compile_Time_Known_Aggregate (Expression (Expr)) then return False; end if; elsif Nkind (Expression (Expr)) /= N_Integer_Literal then return False; end if; if not Aggr_Size_OK (N, Typ) then return False; end if; -- Create a positional aggregate with the right number of -- copies of the expression. Agg := Make_Aggregate (Sloc (N), New_List, No_List); for I in UI_To_Int (Intval (Lo)) .. UI_To_Int (Intval (Hi)) loop Append_To (Expressions (Agg), New_Copy (Expression (Expr))); -- The copied expression must be analyzed and resolved. -- Besides setting the type, this ensures that static -- expressions are appropriately marked as such. Analyze_And_Resolve (Last (Expressions (Agg)), Component_Type (Typ)); end loop; Set_Aggregate_Bounds (Agg, Bounds); Set_Etype (Agg, Typ); Set_Analyzed (Agg); Rewrite (N, Agg); Set_Compile_Time_Known_Aggregate (N); return True; end if; end if; else return False; end if; end Static_Array_Aggregate; ---------------------------------- -- Two_Dim_Packed_Array_Handled -- ---------------------------------- function Two_Dim_Packed_Array_Handled (N : Node_Id) return Boolean is Loc : constant Source_Ptr := Sloc (N); Typ : constant Entity_Id := Etype (N); Ctyp : constant Entity_Id := Component_Type (Typ); Comp_Size : constant Int := UI_To_Int (Component_Size (Typ)); Packed_Array : constant Entity_Id := Packed_Array_Impl_Type (Base_Type (Typ)); One_Comp : Node_Id; -- Expression in original aggregate One_Dim : Node_Id; -- One-dimensional subaggregate begin -- For now, only deal with cases where an integral number of elements -- fit in a single byte. This includes the most common boolean case. if not (Comp_Size = 1 or else Comp_Size = 2 or else Comp_Size = 4) then return False; end if; Convert_To_Positional (N, Max_Others_Replicate => 64, Handle_Bit_Packed => True); -- Verify that all components are static if Nkind (N) = N_Aggregate and then Compile_Time_Known_Aggregate (N) then null; -- The aggregate may have been reanalyzed and converted already elsif Nkind (N) /= N_Aggregate then return True; -- If component associations remain, the aggregate is not static elsif Present (Component_Associations (N)) then return False; else One_Dim := First (Expressions (N)); while Present (One_Dim) loop if Present (Component_Associations (One_Dim)) then return False; end if; One_Comp := First (Expressions (One_Dim)); while Present (One_Comp) loop if not Is_OK_Static_Expression (One_Comp) then return False; end if; Next (One_Comp); end loop; Next (One_Dim); end loop; end if; -- Two-dimensional aggregate is now fully positional so pack one -- dimension to create a static one-dimensional array, and rewrite -- as an unchecked conversion to the original type. declare Byte_Size : constant Int := UI_To_Int (Component_Size (Packed_Array)); -- The packed array type is a byte array Packed_Num : Nat; -- Number of components accumulated in current byte Comps : List_Id; -- Assembled list of packed values for equivalent aggregate Comp_Val : Uint; -- Integer value of component Incr : Int; -- Step size for packing Init_Shift : Int; -- Endian-dependent start position for packing Shift : Int; -- Current insertion position Val : Int; -- Component of packed array being assembled begin Comps := New_List; Val := 0; Packed_Num := 0; -- Account for endianness. See corresponding comment in -- Packed_Array_Aggregate_Handled concerning the following. if Bytes_Big_Endian xor Debug_Flag_8 xor Reverse_Storage_Order (Base_Type (Typ)) then Init_Shift := Byte_Size - Comp_Size; Incr := -Comp_Size; else Init_Shift := 0; Incr := +Comp_Size; end if; -- Iterate over each subaggregate Shift := Init_Shift; One_Dim := First (Expressions (N)); while Present (One_Dim) loop One_Comp := First (Expressions (One_Dim)); while Present (One_Comp) loop if Packed_Num = Byte_Size / Comp_Size then -- Byte is complete, add to list of expressions Append (Make_Integer_Literal (Sloc (One_Dim), Val), Comps); Val := 0; Shift := Init_Shift; Packed_Num := 0; else Comp_Val := Expr_Rep_Value (One_Comp); -- Adjust for bias, and strip proper number of bits if Has_Biased_Representation (Ctyp) then Comp_Val := Comp_Val - Expr_Value (Type_Low_Bound (Ctyp)); end if; Comp_Val := Comp_Val mod Uint_2 ** Comp_Size; Val := UI_To_Int (Val + Comp_Val * Uint_2 ** Shift); Shift := Shift + Incr; One_Comp := Next (One_Comp); Packed_Num := Packed_Num + 1; end if; end loop; One_Dim := Next (One_Dim); end loop; if Packed_Num > 0 then -- Add final incomplete byte if present Append (Make_Integer_Literal (Sloc (One_Dim), Val), Comps); end if; Rewrite (N, Unchecked_Convert_To (Typ, Make_Qualified_Expression (Loc, Subtype_Mark => New_Occurrence_Of (Packed_Array, Loc), Expression => Make_Aggregate (Loc, Expressions => Comps)))); Analyze_And_Resolve (N); return True; end; end Two_Dim_Packed_Array_Handled; end Exp_Aggr;
kjseefried/coreland-cgbc
Ada
1,776
adb
with Ada.Strings; with CGBC.Bounded_Strings; with Test; procedure T_Bstr_Init_02 is package BS renames CGBC.Bounded_Strings; TC : Test.Context_t; S1 : BS.Bounded_String (8); Caught : Boolean; begin Test.Initialize (Test_Context => TC, Program => "t_bstr_init_02", Test_DB => "TEST_DB", Test_Results => "TEST_RESULTS"); BS.Set_Bounded_String (Target => S1, Source => "ABCD"); Test.Check (TC, 234, BS.Length (S1) = 4, "BS.Length (S1) = 4"); Test.Check (TC, 235, BS.Maximum_Length (S1) = 8, "BS.Maximum_Length (S1) = 8"); BS.Set_Bounded_String (Target => S1, Source => "ABCDEFGH"); Test.Check (TC, 236, BS.Length (S1) = 8, "BS.Length (S1) = 8"); Test.Check (TC, 237, BS.Maximum_Length (S1) = 8, "BS.Maximum_Length (S1) = 8"); begin Caught := False; BS.Set_Bounded_String (Target => S1, Source => "ABCDEFGHI", Drop => Ada.Strings.Error); exception when Ada.Strings.Length_Error => Caught := True; end; Test.Check (TC, 238, Caught, "Caught"); BS.Set_Bounded_String (Target => S1, Source => "ABCDEFGHI", Drop => Ada.Strings.Right); Test.Check (TC, 239, BS.Length (S1) = 8, "BS.Length (S1) = 8"); Test.Check (TC, 240, BS.Maximum_Length (S1) = 8, "BS.Maximum_Length (S1) = 8"); Test.Check (TC, 241, BS.To_String (S1) = "ABCDEFGH", "BS.To_String (S1) = ""ABCDEFGH"""); BS.Set_Bounded_String (Target => S1, Source => "ABCDEFGHI", Drop => Ada.Strings.Left); Test.Check (TC, 242, BS.Length (S1) = 8, "BS.Length (S1) = 8"); Test.Check (TC, 243, BS.Maximum_Length (S1) = 8, "BS.Maximum_Length (S1) = 8"); Test.Check (TC, 244, BS.To_String (S1) = "BCDEFGHI", "BS.To_String (S1) = ""BCDEFGHI"""); end T_Bstr_Init_02;
jscparker/math_packages
Ada
6,526
adb
-- Stnd Binary Rank Test. with text_io; use text_io; with Binary_Rank; with Disorderly.Random; use Disorderly.Random; with Disorderly.Random.Clock_Entropy; with Ada.Numerics.Discrete_Random; with Chi_Gaussian_CDF; procedure rank_tst_1 is type Real is digits 15; Bits_per_Random_Word : constant := 32; pragma Assert (Bits_per_Random_Word > 31 and Bits_per_Random_Word < 62); -- 32 bits for general tests. package Rank_Matrix is new Binary_Rank (No_of_Bits_per_Segment => Bits_per_Random_Word, Segments_per_Vector => 1); -- can't change from 1 use Rank_Matrix; r : Binary_Matrix; Max_Row, Max_Col : constant Matrix_Index := Matrix_Index'Last; -- Matrix_Index goes from 1 .. Bits_per_Vector. -- all array start at 1, since that's the way Marsaglia's diehard does it. -- Notice that we can do sub blocks of the full matrix by changing above. -- VARIABLES FOR CHI-SQUARE TEST: package chi_cdf is new Chi_Gaussian_CDF (Real); --Sample_Size : constant := 2**13; -- for quick demo, 2**12 is min. acceptable. Sample_Size : constant := 2**27; -- 2**27 is good -- Usually, the best way to make the Chi-Square as strong as possible is -- to make the Sample_Size as large as possible. x : Random_Int; Stream_1 : State; Rank : Integer; Outcome_id : Matrix_Index; ave_chi, ave_p, ave_normalized_var_of_p : Real := 0.0; True_Degrees_of_Freedom : constant := 3; subtype Range_of_Possible_Outcomes is Matrix_Index range Max_Col-True_Degrees_of_Freedom .. Max_Col; type Statistical_Data is array (Range_of_Possible_Outcomes) of Real; Observed_Count : Statistical_Data := (others => 0.0); Expected_Count : Statistical_Data := (others => 0.0); Expected_Frequency : constant Statistical_Data := -- FOR 31 bits and greater: -- True_Degrees_of_Freedom : constant := 2; --(0.13363571467, 0.57757619017, 0.28878809515); -- True_Degrees_of_Freedom : constant := 3; (0.00528545025, 0.12835026442, 0.57757619017, 0.28878809515); -- True_Degrees_of_Freedom : constant := 4; --(4.66639518324E-05, 0.0052387863054, 0.1283502644829, -- 0.577576190173205, 0.2887880950866); -- True_Degrees_of_Freedom : constant := 5; -- (9.6962450869E-08, 4.65669893816E-05, 0.0052387863054, -- 0.12835026448293, 0.577576190173205, 0.2887880950866); -- from known analytical distribution (true asymptotically also): -- expected rank_freq -- rank probability -- <=29 0.00528545025 -- 30 0.12835026442 -- 31 0.57757619017 -- 32 0.28878809515 -- -- 58 4.66639518324322E-05 -- 59 5.23878630542589E-03 -- 60 1.28350264482934E-01 -- 61 5.77576190173205E-01 -- 62 2.88788095086602E-01 -- 57 9.69624508687517E-08 -- 58 4.65669893815635E-05 -- 59 5.23878630542589E-03 -- 60 1.28350264482934E-01 -- 61 5.77576190173205E-01 -- 62 2.88788095086602E-01 -- 61 bits: -- -- 56 9.69624508687517E-08 -- 57 4.65669893815635E-05 -- 58 5.23878630542589E-03 -- 59 1.28350264482934E-01 -- 60 5.77576190173205E-01 -- 61 2.88788095086602E-01 -- -- 57 4.66639518324322E-05 and all < 57 -- 58 5.23878630542589E-03 -- 59 1.28350264482934E-01 -- 60 5.77576190173205E-01 -- 61 2.88788095086602E-01 --25 6.05558642701658E-15 --26 4.88352774683776E-11 --27 9.69136088580580E-08 --28 4.65669892297724E-05 --29 5.23878629810739E-03 --30 1.28350264423167E-01 --31 5.77576190173205E-01 --32 2.88788095153841E-01 -------------------- -- Get_Random_Stnd - -------------------- -- Compiler's native random number generator. type Unsigned_Stnd is mod 2**Bits_per_Random_Word; package rnd is new Ada.Numerics.Discrete_Random (Unsigned_Stnd); Stream_Stnd : rnd.Generator; procedure Get_Random_Stnd(X : out Random_Int; S : in rnd.Generator) is begin X := Random_Int (rnd.Random (S)); end Get_Random_Stnd; pragma Inline (Get_Random_Stnd); begin for i in Range_of_Possible_Outcomes loop Expected_Count (i) := Expected_Frequency (i) * Real(Sample_Size); end loop; -- Init array of expected counts: same really for 31 bit to 64 bit nums. -- True_Degrees_of_Freedom : constant := 3; These 4 sum to 1.0 rnd.Reset (Stream_Stnd); -- compiler's PRNG; Initialize the stream even if you don't use it. Clock_Entropy.Reset (Stream_1); -- Init Stream_1 for calls to Get_Random(x, Stream_1); -- do 1 chi-sqr test per Chi_Test_id value: for Chi_Test_id in Long_Integer range 1..2**28 loop -- forever really Observed_Count := (others => 0.0); for Draw_id in Long_Integer range 1 .. Sample_Size loop for Col_id in Matrix_Index range Matrix_Index'First .. Max_Col loop for Seg_id in Segments loop Get_Random_Stnd (X, Stream_Stnd); --Get_Random(X, Stream_1); r(Col_id)(Seg_id) := Unsigned_Segment(X mod 2**Bits_per_Random_Word); end loop; end loop; Get_Rank(r, Max_Row, Max_Col, Rank); --text_io.put(integer'Image(Max_Col - Rank)); if Matrix_Index(Rank) > Range_of_Possible_Outcomes'First then Outcome_id := Matrix_Index(Rank); else Outcome_id := Range_of_Possible_Outcomes'First; end if; Observed_Count(Outcome_id) := Observed_Count(Outcome_id) + 1.0; end loop; declare chi, e, s, normalized_variance_of_p, p_val : Real; Degrees_of_Freedom : constant Real := Real (True_Degrees_of_Freedom); begin chi := 0.0; for Outcome in Range_of_Possible_Outcomes loop e := Expected_Count(Outcome); s := (Observed_Count(Outcome) - e)**2 / e; chi := chi + s; end loop; p_val := chi_cdf.Chi_Squared_CDF (Degrees_of_Freedom, chi); normalized_variance_of_p := (p_val - 0.5)**2 / (0.25/3.0); ave_chi := ave_chi + chi; ave_p := ave_p + p_val; ave_normalized_var_of_p := ave_normalized_var_of_p + normalized_variance_of_p; end; new_line(1); Put ("p-val average (should be 0.5, after 1000's of iterations):"); put (Real'Image (ave_p / Real (Chi_Test_id))); new_line; Put ("p-val variance (should be 1.0, after 1000's of iterations):"); put (Real'Image (ave_normalized_var_of_p / (Real (Chi_Test_id)))); new_line; end loop; end;
stcarrez/ada-wiki
Ada
4,347
adb
----------------------------------------------------------------------- -- wiki-plugins-conditions -- Condition Plugin -- Copyright (C) 2016, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Plugins.Conditions is -- ------------------------------ -- Append the attribute name/value to the condition plugin parameter list. -- ------------------------------ procedure Append (Plugin : in out Condition_Plugin; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString) is begin Attributes.Append (Plugin.Params, Name, Value); end Append; -- ------------------------------ -- Evaluate the condition and return it as a boolean status. -- ------------------------------ function Evaluate (Plugin : in Condition_Plugin; Params : in Wiki.Attributes.Attribute_List) return Boolean is procedure Check (Name : in String; Value : in Wiki.Strings.WString); Result : Boolean := False; Index : Natural := 0; procedure Check (Name : in String; Value : in Wiki.Strings.WString) is pragma Unreferenced (Name); Pos : Wiki.Attributes.Cursor; begin Index := Index + 1; if Index > 1 and then not Result then Pos := Attributes.Find (Plugin.Params, Wiki.Strings.To_String (Value)); Result := Attributes.Has_Element (Pos); end if; end Check; begin Attributes.Iterate (Params, Check'Access); return Result; end Evaluate; -- ------------------------------ -- Get the type of condition (IF, ELSE, ELSIF, END) represented by the plugin. -- ------------------------------ function Get_Condition_Kind (Plugin : in Condition_Plugin; Params : in Wiki.Attributes.Attribute_List) return Condition_Type is pragma Unreferenced (Plugin); Name : constant Strings.WString := Attributes.Get_Attribute (Params, "name"); begin if Name = "if" then return CONDITION_IF; elsif Name = "else" then return CONDITION_ELSE; elsif Name = "elsif" then return CONDITION_ELSIF; elsif Name = "end" then return CONDITION_END; else return CONDITION_IF; end if; end Get_Condition_Kind; -- ------------------------------ -- Evaluate the condition described by the parameters and hide or show the wiki -- content. -- ------------------------------ overriding procedure Expand (Plugin : in out Condition_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in out Plugin_Context) is pragma Unreferenced (Document); Kind : constant Condition_Type := Condition_Plugin'Class (Plugin).Get_Condition_Kind (Params); begin case Kind is when CONDITION_IF => Plugin.Depth := Plugin.Depth + 1; Plugin.Values (Plugin.Depth) := not Condition_Plugin'Class (Plugin).Evaluate (Params); when CONDITION_ELSIF => Plugin.Values (Plugin.Depth) := not Condition_Plugin'Class (Plugin).Evaluate (Params); when CONDITION_ELSE => Plugin.Values (Plugin.Depth) := not Plugin.Values (Plugin.Depth); when CONDITION_END => Plugin.Depth := Plugin.Depth - 1; end case; Context.Previous.Is_Hidden := Plugin.Values (Plugin.Depth); end Expand; end Wiki.Plugins.Conditions;
ZinebZaad/ENSEEIHT
Ada
277
adb
package body Types is function "<"(Gauche: T_Rank; Droit: T_Rank) return Boolean is begin return Gauche.Poid < Droit.Poid; end "<"; function Hachage(Indice: in T_Indice) return Integer is begin return Indice.X; end Hachage; end Types;
burratoo/Acton
Ada
9,435
ads
------------------------------------------------------------------------------------------ -- -- -- OAK PROCESSOR SUPPORT PACKAGE -- -- FREESCALE MPC5544 -- -- -- -- MPC5554.EBI -- -- -- -- Copyright (C) 2010-2021, Patrick Bernardi -- -- -- ------------------------------------------------------------------------------------------ with System.Storage_Elements; use System.Storage_Elements; package MPC5554.EBI with Preelaborate is ---------------------------------------------------------------------------- -- Memory Addresses ---------------------------------------------------------------------------- EBI_Base_Address : constant Integer_Address := 16#C3F8_4000#; MCR_Offset_Address : constant Integer_Address := 16#0000#; TESR_Offset_Address : constant Integer_Address := 16#0008#; BMCR_Offset_Address : constant Integer_Address := 16#000C#; BR0_Offset_Address : constant Integer_Address := 16#0010#; OR0_Offset_Address : constant Integer_Address := 16#0014#; BR1_Offset_Address : constant Integer_Address := 16#0018#; OR1_Offset_Address : constant Integer_Address := 16#001C#; BR2_Offset_Address : constant Integer_Address := 16#0020#; OR2_Offset_Address : constant Integer_Address := 16#0024#; BR3_Offset_Address : constant Integer_Address := 16#0028#; OR3_Offset_Address : constant Integer_Address := 16#002C#; ---------------------------------------------------------------------------- -- Hardware Features ---------------------------------------------------------------------------- type Sixteen_Bit_Address_Type is range 0 .. 16#FFFF#; ---------------------------------------------------------------------------- -- EBI Types --------------------------------------------------------------------------- -- Common Types type Error_Type is (No_Error, Error); type DBM_Type is (S32_Bit, S16_Bit); -- EBI Module Configuration Register (EBI_MCR) type SIZE_Type is (Four_Byte, One_Byte, Two_Byte); type EARP_Type is (MCU, Equal, External); type Module_Configuration_Type is record Size_Enable : Enable_Type; Size : SIZE_Type; Automatic_CLKOUT_Gating_Enable : Enable_Type; External_Master_Mode : Enable_Type; External_Arbitration : Enable_Type; External_Arbitration_Requrest_Priorty : EARP_Type; Module_Disable_Mode : Enable_Type; Data_Bus_Mode : DBM_Type; end record; -- EBI Error Transfer Status Register (EBI_TESR) type Transfer_Error_Status_Type is record Transfer_Error_Ack_Flag : Error_Type; Bus_Monitor_Timeout_Flag : Error_Type; end record; -- EBI Bus Monitor Control Register (EBI_BMCR) type BMT_Type is range 0 .. 255; type Bus_Monitor_Control_Type is record Bus_Monitor_Timing : BMT_Type; Bus_Monitor_Enable : Enable_Type; end record; -- EBI Base Register 0 - 3 (EBI_BRn) type PS_Type is (S32_Bit, S16_Bit); type BL_Type is (Eight_Word, Four_Word); type WEBS_Type is (Write_Enable, Byte_Enable); type Valid_Type is (Invalid, Valid); type TBDIP_Type is (Burst, Before); type Base_Register_Type is record Base_Address : Sixteen_Bit_Address_Type; Port_Size : PS_Type; Burst_Length : BL_Type; Write_Enable_Byte_Select : WEBS_Type; Toggle_Burst_Data_In_Progress : TBDIP_Type; Burst_Inhibit : Enable_Type; Valid_Bit : Valid_Type; end record; -- EBI Option Register (EBI_ORn) type AM_Type is ( AM_512M, AM_256M, AM_128M, AM_64M, AM_32M, AM_16M, AM_8M, AM_4M, AM_2M, AM_1M, AM_512k, AM_256K, AM_128K, AM_64K); type SCY_Type is range 0 .. 2#111#; type BSCY_Type is range 0 .. 3; type Option_Register_Type is record Address_Mask : AM_Type; Cycle_Length : SCY_Type; Burst_Beat_Length_Type : BSCY_Type; end record; ---------------------------------------------------------------------------- -- Hardware Respresentations ---------------------------------------------------------------------------- for Error_Type use (No_Error => 0, Error => 1); for SIZE_Type use (Four_Byte => 2#00#, One_Byte => 2#01#, Two_Byte => 2#10#); for EARP_Type use (MCU => 2#00#, Equal => 2#01#, External => 2#10#); for DBM_Type use (S32_Bit => 0, S16_Bit => 1); for Module_Configuration_Type use record Size_Enable at 0 range 5 .. 5; Size at 0 range 6 .. 7; Automatic_CLKOUT_Gating_Enable at 0 range 16 .. 16; External_Master_Mode at 0 range 17 .. 17; External_Arbitration at 0 range 18 .. 18; External_Arbitration_Requrest_Priorty at 0 range 19 .. 20; Module_Disable_Mode at 0 range 25 .. 25; Data_Bus_Mode at 0 range 31 .. 31; end record; for Transfer_Error_Status_Type use record Transfer_Error_Ack_Flag at 0 range 30 .. 30; Bus_Monitor_Timeout_Flag at 0 range 31 .. 31; end record; for Bus_Monitor_Control_Type use record Bus_Monitor_Timing at 0 range 16 .. 23; Bus_Monitor_Enable at 0 range 24 .. 24; end record; for PS_Type use (S32_Bit => 0, S16_Bit => 1); for BL_Type use (Eight_Word => 0, Four_Word => 1); for WEBS_Type use (Write_Enable => 0, Byte_Enable => 1); for Valid_Type use (Invalid => 0, Valid => 1); for TBDIP_Type use (Burst => 0, Before => 1); for Base_Register_Type use record Base_Address at 0 range 0 .. 16; Port_Size at 0 range 20 .. 20; Burst_Length at 0 range 25 .. 25; Write_Enable_Byte_Select at 0 range 26 .. 26; Toggle_Burst_Data_In_Progress at 0 range 27 .. 27; Burst_Inhibit at 0 range 30 .. 30; Valid_Bit at 0 range 31 .. 31; end record; for AM_Type use (AM_512M => 16#E000#, AM_256M => 16#F000#, AM_128M => 16#F800#, AM_64M => 16#FC00#, AM_32M => 16#FE00#, AM_16M => 16#FF00#, AM_8M => 16#FF80#, AM_4M => 16#FFC0#, AM_2M => 16#FFE0#, AM_1M => 16#FFF0#, AM_512k => 16#FFF8#, AM_256K => 16#FFFC#, AM_128K => 16#FFFE#, AM_64K => 16#FFFF#); for Option_Register_Type use record Address_Mask at 0 range 0 .. 16; Cycle_Length at 0 range 24 .. 27; Burst_Beat_Length_Type at 0 range 29 .. 30; end record; ---------------------------------------------------------------------------- -- EBI Registers ---------------------------------------------------------------------------- pragma Warnings (Off, "*alignment*"); Module_Configuration_Register : Module_Configuration_Type; for Module_Configuration_Register'Address use System'To_Address (EBI_Base_Address + MCR_Offset_Address); Transfer_Error_Status_Register : Transfer_Error_Status_Type; for Transfer_Error_Status_Register'Address use System'To_Address (EBI_Base_Address + TESR_Offset_Address); Bus_Monitor_Control_Register : Bus_Monitor_Control_Type; for Bus_Monitor_Control_Register'Address use System'To_Address (EBI_Base_Address + BMCR_Offset_Address); Base_Register_Bank_0 : Base_Register_Type; for Base_Register_Bank_0'Address use System'To_Address (EBI_Base_Address + BR0_Offset_Address); Option_Register_Bank_0 : Option_Register_Type; for Option_Register_Bank_0'Address use System'To_Address (EBI_Base_Address + OR0_Offset_Address); Base_Register_Bank_1 : Base_Register_Type; for Base_Register_Bank_1'Address use System'To_Address (EBI_Base_Address + BR1_Offset_Address); Option_Register_Bank_1 : Option_Register_Type; for Option_Register_Bank_1'Address use System'To_Address (EBI_Base_Address + OR1_Offset_Address); Base_Register_Bank_2 : Base_Register_Type; for Base_Register_Bank_2'Address use System'To_Address (EBI_Base_Address + BR2_Offset_Address); Option_Register_Bank_2 : Option_Register_Type; for Option_Register_Bank_2'Address use System'To_Address (EBI_Base_Address + OR2_Offset_Address); Base_Register_Bank_3 : Base_Register_Type; for Base_Register_Bank_3'Address use System'To_Address (EBI_Base_Address + BR3_Offset_Address); Option_Register_Bank_3 : Option_Register_Type; for Option_Register_Bank_3'Address use System'To_Address (EBI_Base_Address + OR3_Offset_Address); end MPC5554.EBI;
AdaCore/langkit
Ada
5,522
ads
-- -- Copyright (C) 2014-2022, AdaCore -- SPDX-License-Identifier: Apache-2.0 -- with Ada.Containers; use Ada.Containers; with System; with Langkit_Support.Hashes; use Langkit_Support.Hashes; with Langkit_Support.Lexical_Envs; use Langkit_Support.Lexical_Envs; with Langkit_Support.Token_Data_Handlers; use Langkit_Support.Token_Data_Handlers; with Langkit_Support.Types; use Langkit_Support.Types; -- This package provides common implementation details for Langkit-generated -- libraries. Even though it is not private (to allow Langkit-generated -- libraries to use it), it is not meant to be used beyond this. As such, this -- API is considered unsafe and unstable. package Langkit_Support.Internal.Analysis is -- Bare pointers to library-specific resources. For contexts, units and -- nodes, these correspond to the access types defined in $.Implementation. type Internal_Context is new System.Address; type Internal_Unit is new System.Address; type Internal_Node is new System.Address; No_Internal_Context : constant Internal_Context := Internal_Context (System.Null_Address); No_Internal_Unit : constant Internal_Unit := Internal_Unit (System.Null_Address); No_Internal_Node : constant Internal_Node := Internal_Node (System.Null_Address); type Internal_Node_Metadata is new System.Address; -- The contents and size of the node metadata record is different from one -- Langkit-generated library to another, so this generic API needs to refer -- to it by reference, with ref-counting for lifetime handling. Null -- addresses mean "default metadata", and the language descriptor table -- provides ref-counting primitives. -- As everywhere else, entities are made up of bare nodes and entity -- information, with regular types from Langkit_Support.Lexical_Envs. The -- metadata has a special representation: see above (Internal_Node_Metadata -- type). type Internal_Entity is record Node : Internal_Node; Rebindings : Env_Rebindings; From_Rebound : Boolean; Metadata : Internal_Node_Metadata; end record; function "=" (L, R : Internal_Entity) return Boolean is abstract; -- We hide the equal operator on internal entities, because since null -- metadata can be either null or a pointer to language specific null -- metadata, we generally don't want our implementation to compare the -- whole Internal_Entity, but rather individual fields. No_Internal_Entity : constant Internal_Entity := (No_Internal_Node, null, False, Internal_Node_Metadata (System.Null_Address)); type Internal_Entity_Array is array (Positive range <>) of Internal_Entity; type Internal_Token is record TDH : Token_Data_Handler_Access; Index : Token_Or_Trivia_Index; end record; -- Safety nets keep track of information at "public reference value" -- creation so that later use can check whether the reference is still -- valid (used to ensure memory safety). type Node_Safety_Net is record Context : Internal_Context; Context_Version : Version_Number; -- Analysis context and version number at the time this safety net was -- produced. Unit : Internal_Unit; Unit_Version : Version_Number; -- Analysis unit and unit version at the time this safety net was -- produced. Rebindings_Version : Version_Number; -- Version of the associated rebinding at the time this safety net was -- produced. end record; No_Node_Safety_Net : constant Node_Safety_Net := (No_Internal_Context, 0, No_Internal_Unit, 0, 0); function Create_Node_Safety_Net (Id : Language_Id; Context : Internal_Context; Unit : Internal_Unit; Rebindings : Env_Rebindings) return Node_Safety_Net; -- Return the safety net for a node given its owning context and unit, and -- its rebindings. type Token_Safety_Net is record Context : Internal_Context; Context_Version : Version_Number; -- Analysis context and version number at the time this safety net was -- produced. TDH_Version : Version_Number; -- Version of the token data handler at the time this safety net was -- produced. end record; No_Token_Safety_Net : constant Token_Safety_Net := (No_Internal_Context, 0, 0); -- Contexts, units and token data handlers are implementing with big -- records, at least 256 bytes long, so we can ignore the 8 least -- significant bits of their addresses. Nodes can be much smaller, but -- they are still at least 32 bytes long, so ignore the 5 least significant -- bits of their addresses. function Hash_Context is new Hash_Address (8); function Hash_Unit is new Hash_Address (8); function Hash_Node is new Hash_Address (5); function Hash_TDH is new Hash_Address (8); function Hash (Self : Internal_Context) return Hash_Type is (Hash_Context (System.Address (Self))); function Hash (Self : Internal_Unit) return Hash_Type is (Hash_Unit (System.Address (Self))); function Hash (Self : Internal_Node) return Hash_Type is (Hash_Node (System.Address (Self))); function Hash (Self : Token_Data_Handler_Access) return Hash_Type is (Hash_TDH (if Self = null then System.Null_Address else Self.all'Address)); end Langkit_Support.Internal.Analysis;
twdroeger/ada-awa
Ada
7,721
ads
----------------------------------------------------------------------- -- awa-setup-applications -- Setup and installation -- Copyright (C) 2016, 2017, 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with ASF.Applications.Main; with ASF.Servlets.Faces; with Servlet.Core.Files; with ASF.Requests; with ASF.Responses; with ASF.Server; with ADO.Connections; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Beans.Methods; -- == Setup Procedure Instantiation== -- The setup process is managed by the *Configure* generic procedure. -- The procedure must be instantiated with the application class type and -- the application initialize procedure. -- -- procedure Setup is -- new AWA.Setup.Applications.Configure (MyApp.Application'Class, -- MyApp.Application_Access, -- MyApp.Initialize); -- -- == Setup Operation == -- The *Setup* instantiated operation must then be called with the web container. -- The web container is started first and the *Setup* procedure gets as parameter -- the web container, the application instance to configure, the application name -- and the application context path. -- -- Setup (WS, App, "atlas", MyApp.CONTEXT_PATH) -- -- The operation will install the setup application to handle the setup actions. -- Through the setup actions, the installer will be able to: -- -- * Configure the database (MySQL or SQLite), -- * Configure the Google+ and Facebook OAuth authentication keys, -- * Configure the application name, -- * Configure the mail parameters to be able to send email. -- -- After the setup and configure is finished, the file <tt>.initialized</tt> -- is created in the application directory to indicate the application is -- configured. The next time the *Setup* operation is called, the installation -- process will be skipped. -- -- To run again the installation, remove manually the <tt>.initialized</tt> file. package AWA.Setup.Applications is Empty : constant Util.Beans.Objects.Object := Util.Beans.Objects.To_Object (String '("")); -- The <b>Servlet</b> represents the component that will handle -- an HTTP request received by the server. type Redirect_Servlet is new Servlet.Core.Servlet with null record; overriding procedure Do_Get (Server : in Redirect_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- The configuration state starts in the `CONFIGURING` state and moves to the -- `STARTING` state after the application is configured and it is started. -- Once the application is initialized and registered in the server container, -- the state is changed to `READY`. type Configure_State is (CONFIGURING, STARTING, READY); -- Maintains the state of the configuration between the main task and -- the http configuration requests. protected type State is -- Wait until the configuration is finished. entry Wait_Configuring; -- Wait until the server application is initialized and ready. entry Wait_Ready; -- Set the configuration state. procedure Set (V : in Configure_State); private Value : Configure_State := CONFIGURING; end State; type Application is new ASF.Applications.Main.Application and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased Servlet.Core.Files.File_Servlet; Redirect : aliased Redirect_Servlet; Config : ASF.Applications.Config; Changed : ASF.Applications.Config; Factory : ASF.Applications.Main.Application_Factory; Path : Ada.Strings.Unbounded.Unbounded_String; Database : ADO.Connections.Configuration; Driver : Util.Beans.Objects.Object; Result : Util.Beans.Objects.Object; Root_User : Util.Beans.Objects.Object := Empty; Root_Passwd : Util.Beans.Objects.Object := Empty; Db_Host : Util.Beans.Objects.Object; Db_Port : Util.Beans.Objects.Object; Has_Error : Boolean := False; Status : State; end record; -- Get the value identified by the name. function Get_Value (From : in Application; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. procedure Set_Value (From : in out Application; Name : in String; Value : in Util.Beans.Objects.Object); -- Get the database connection string to be used by the application. function Get_Database_URL (From : in Application) return String; -- Get the command to configure the database. function Get_Configure_Command (From : in Application) return String; -- Configure the database. procedure Configure_Database (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Validate the database configuration parameters. procedure Validate (From : in out Application); -- Save the configuration. procedure Save (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Finish the setup to start the application. procedure Start (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Finish the setup and wait for the application to be started. procedure Finish (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Application) return Util.Beans.Methods.Method_Binding_Array_Access; -- Enter in the application setup procedure Setup (App : in out Application; Config : in String; Server : in out ASF.Server.Container'Class); -- Configure the application by using the setup application, allowing -- the administrator to setup the application database, define the application -- admin parameters. After the configuration is done, register the -- application in the server container and start it. generic type Application_Type (<>) is new ASF.Servlets.Servlet_Registry with private; type Application_Access is access all Application_Type'Class; with procedure Initialize (App : in Application_Access; Config : in ASF.Applications.Config); procedure Configure (Server : in out ASF.Server.Container'Class; App : in Application_Access; Config : in String; URI : in String); end AWA.Setup.Applications;
BrickBot/Bound-T-H8-300
Ada
3,164
adb
-- Options.Interval_Valued (body) -- -- A component of the Bound-T Worst-Case Execution Time Tool. -- ------------------------------------------------------------------------------- -- Copyright (c) 1999 .. 2015 Tidorum Ltd -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- 1. Redistributions of source code must retain the above copyright notice, this -- list of conditions and the following disclaimer. -- 2. Redistributions in binary form must reproduce the above copyright notice, -- this list of conditions and the following disclaimer in the documentation -- and/or other materials provided with the distribution. -- -- 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. -- -- Other modules (files) of this software composition should contain their -- own copyright statements, which may have different copyright and usage -- conditions. The above conditions apply to this file. ------------------------------------------------------------------------------- -- -- $Revision: 1.3 $ -- $Date: 2015/10/24 20:05:50 $ -- -- $Log: options-interval_valued.adb,v $ -- Revision 1.3 2015/10/24 20:05:50 niklas -- Moved to free licence. -- -- Revision 1.2 2013-02-03 12:37:56 niklas -- Using Storage.Bounds.Get. -- -- Revision 1.1 2011-10-18 20:17:06 niklas -- First version, for Toy ALF export. -- with Storage.Bounds.Get; package body Options.Interval_Valued is overriding function Type_And_Default (Option : access Option_T) return String is begin return "Interval, default " & Storage.Bounds.Image (Option.Default); end Type_And_Default; overriding procedure Reset (Option : access Option_T) is begin Option.Value := Storage.Bounds.Universal_Interval; end Reset; overriding procedure Set ( Option : access Option_T; Value : in String) is begin Option.Value := Storage.Bounds.Get.Interval_Value (From => Value); end Set; function Set (Value : Storage.Bounds.Interval_T) return Option_T is begin return (Options.Option_T with Default => Value, Value => Value); end Set; function Value_Of (Option : Option_T) return Storage.Bounds.Interval_T is begin return Option.Value; end Value_Of; end Options.Interval_Valued;
klampworks/hanael
Ada
1,526
adb
with Ada.Characters.Handling; use Ada.Characters.Handling; with Ada.Numerics.Discrete_Random; package body Randomise is -- '0' to '9' subtype Numeric_Rand_Range is Integer range 48..57; package Numeric_Rand is new Ada.Numerics.Discrete_Random(Numeric_Rand_Range); Numeric_Gen : Numeric_Rand.Generator; Numeric_I : Numeric_Rand_Range; -- 'a' to 'z' subtype Alphabetic_Rand_Range is Integer range 97..122; package Alphabetic_Rand is new Ada.Numerics.Discrete_Random( Alphabetic_Rand_Range); Alphabetic_Gen : Alphabetic_Rand.Generator; Alphabetic_I : Alphabetic_Rand_Range; New_Char : Character; procedure Randomise_String(S : in out R_String.Bounded_String) is begin for C in R_String.To_String(S)'Range loop case R_String.Element(S, C) is when '0'..'9' => Numeric_I := Numeric_Rand.Random(Numeric_Gen); New_Char := Character'Val(Numeric_I); R_String.Replace_Element(S, C, New_Char); when 'a'..'z' => Alphabetic_I := Alphabetic_Rand.Random(Alphabetic_Gen); New_Char := Character'Val(Alphabetic_I); R_String.Replace_Element(S, C, New_Char); when 'A'..'Z' => Alphabetic_I := Alphabetic_Rand.Random(Alphabetic_Gen); New_Char := To_Upper(Character'Val(Alphabetic_I)); R_String.Replace_Element(S, C, New_Char); when others => null; end case; end loop; end Randomise_String; begin Numeric_Rand.Reset(Numeric_Gen); Alphabetic_Rand.Reset(Alphabetic_Gen); end Randomise;
zhmu/ananas
Ada
587
adb
package body Opt13_Pkg is subtype Index_Type is Natural range 0 .. 16; type Arr is array (Index_Type range <>) of Integer; type Rec is record F1, F2, F3 : Float; N : Natural; B1, B2 : Boolean; F4 : Float; end record; type Data (D : Index_Type) is record A : Arr (1 .. D); R : Rec; end record; Zero : constant Rec := (0.0, 0.0, 0.0, 0, False, False, 0.0); procedure Allocate (T : out My_Type) is begin T := new Data (Index_Type'last); T.R := Zero; for I in 1 .. T.A'last loop N := 1; end loop; end; end Opt13_Pkg;
stcarrez/dynamo
Ada
2,172
ads
----------------------------------------------------------------------- -- gen-artifacts-yaml -- Yaml database model files -- Copyright (C) 2018, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- 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 Gen.Model.Packages; package Gen.Artifacts.Yaml is -- ------------------------------ -- Yaml artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Project : in out Gen.Model.Projects.Project_Definition'Class; Context : in out Generator'Class); -- Read the UML/XMI model file. procedure Read_Model (Handler : in out Artifact; File : in String; Model : in out Gen.Model.Packages.Model_Definition; Context : in out Generator'Class); -- Save the model in a YAML file. procedure Save_Model (Handler : in Artifact; Path : in String; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); private type Artifact is new Gen.Artifacts.Artifact with null record; end Gen.Artifacts.Yaml;
luk9400/nsi
Ada
193
adb
with Ada.Text_IO; with Bubble; procedure Main is A : Bubble.Arr := (2, 1, 3, 7); begin Bubble.Sort(A); for I in A'Range loop Ada.Text_IO.Put_Line(A(I)'Image); end loop; end Main;
godunko/adawebui
Ada
3,516
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Web Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2018-2020, Vadim Godunko <[email protected]> -- -- 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: 5903 $ $Date: 2018-12-26 22:07:33 +0300 (Wed, 26 Dec 2018) $ ------------------------------------------------------------------------------ with Web.UI.Widgets.Spin_Boxes.Integers; package Web.UI.Integer_Spin_Boxes renames Web.UI.Widgets.Spin_Boxes.Integers;
sondrehf/Sanntid
Ada
3,986
adb
with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Numerics.Float_Random; use Ada.Text_IO, Ada.Integer_Text_IO, Ada.Numerics.Float_Random; procedure exercise7 is Count_Failed : exception; -- Exception to be raised when counting fails Gen : Generator; -- Random number generator protected type Transaction_Manager (N : Positive) is entry Finished; function Commit return Boolean; procedure Signal_Abort; private Finished_Gate_Open : Boolean := False; Aborted : Boolean := False; Should_Commit : Boolean := True; end Transaction_Manager; protected body Transaction_Manager is entry Finished when Finished_Gate_Open or Finished'Count = N is begin ------------------------------------------ -- PART 3: Complete the exit protocol here -- First participant enters if Finished'Count = N-1 then Finished_Gate_Open := True; Should_Commit := not Aborted; end if; -- Last participant enters if Finished'Count = 0 then Finished_Gate_Open := False; Aborted := False; end if; ------------------------------------------ end Finished; procedure Signal_Abort is begin Aborted := True; end Signal_Abort; function Commit return Boolean is begin return Should_Commit; end Commit; end Transaction_Manager; function Unreliable_Slow_Add (x : Integer) return Integer is Error_Rate : Constant := 0.15; -- (between 0 and 1) begin ------------------------------------------- -- PART 1: Create the transaction work here -- hvilke verdier for konstantene? if Random(Gen) > Error_Rate then delay Duration(Random(Gen)*4.0); return x + 10; else delay Duration(Random(Gen)*0.5); raise Count_Failed; end if; ------------------------------------------- end Unreliable_Slow_Add; task type Transaction_Worker (Initial : Integer; Manager : access Transaction_Manager); task body Transaction_Worker is Num : Integer := Initial; Prev : Integer := Num; Round_Num : Integer := 0; begin Put_Line ("Worker" & Integer'Image(Initial) & " started"); loop Put_Line ("Worker" & Integer'Image(Initial) & " started round" & Integer'Image(Round_Num)); Round_Num := Round_Num + 1; --------------------------------------- -- PART 2: Do the transaction work here begin Num := Unreliable_Slow_Add(Num); exception when Count_Failed => Manager.Signal_Abort; end; Manager.Finished; --------------------------------------- if Manager.Commit = True then Put_Line (" Worker" & Integer'Image(Initial) & " comitting" & Integer'Image(Num)); else Put_Line (" Worker" & Integer'Image(Initial) & " reverting from" & Integer'Image(Num) & " to" & Integer'Image(Prev)); ------------------------------------------- -- PART 2: Roll back to previous value here Num := Prev; ------------------------------------------- end if; Prev := Num; delay 0.5; end loop; end Transaction_Worker; Manager : aliased Transaction_Manager (3); Worker_1 : Transaction_Worker (0, Manager'Access); Worker_2 : Transaction_Worker (1, Manager'Access); Worker_3 : Transaction_Worker (2, Manager'Access); begin Reset(Gen); -- Seed the random number generator end exercise7;
AdaCore/libadalang
Ada
5,991
ads
-- Copyright (C) 2014-2022, AdaCore -- SPDX-License-Identifier: Apache-2.0 -- -- This package provides the capability to automatically discover the layout -- of source files in an Ada project, given a list of files, or a file name -- pattern and a list of directories. -- -- It is useful in order to easily run Libadalang on a complex project that -- does not have its own GPR project file. with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; private with Ada.Containers.Hashed_Maps; with GNAT.Regexp; with GNAT.Regpat; with GNATCOLL.VFS; with Langkit_Support.Symbols; with Libadalang.Analysis; use Libadalang.Analysis; with Libadalang.Common; use Libadalang.Common; package Libadalang.Auto_Provider is use Support.Text; Default_Source_Filename_Pattern : constant GNAT.Regpat.Pattern_Matcher := GNAT.Regpat.Compile ("\.(ad.|a|spc|bdy)$"); Default_Source_Filename_Regexp : constant GNAT.Regexp.Regexp := GNAT.Regexp.Compile (".*\.(ad.|a|spc|bdy)"); -- Default matchers for Ada source filenames. They match most usual file -- extensions used for Ada sources: ``.ads``, ``.adb``, ``.ada``, ``.spc``, -- ``.bdy``, etc. function Find_Files (Name_Pattern : GNAT.Regpat.Pattern_Matcher := Default_Source_Filename_Pattern; Directories : GNATCOLL.VFS.File_Array) return GNATCOLL.VFS.File_Array_Access; -- Return the list of absolute file names for all regular files in the -- given ``Directories`` whose name match the given regular expression -- ``Name_Pattern``. The result is dynamically allocated, so the caller -- must free it when done with it. function Find_Files_Regexp (Name_Pattern : GNAT.Regexp.Regexp := Default_Source_Filename_Regexp; Directories : GNATCOLL.VFS.File_Array) return GNATCOLL.VFS.File_Array_Access; -- Like ``Find_Files``, but works on GNAT.Regexp patterns. -- -- Note: this function is not an overload, so that calls such as -- ``Find_Files (Directories => D);`` are not ambiguous. type Auto_Unit_Provider is new Libadalang.Analysis.Unit_Provider_Interface with private; -- Unit provider for a given list of files overriding function Get_Unit_Filename (Provider : Auto_Unit_Provider; Name : Text_Type; Kind : Analysis_Unit_Kind) return String; --% no-document: True overriding procedure Get_Unit_Location (Provider : Auto_Unit_Provider; Name : Text_Type; Kind : Analysis_Unit_Kind; Filename : in out Unbounded_String; PLE_Root_Index : in out Natural); --% no-document: True overriding function Get_Unit (Provider : Auto_Unit_Provider; Context : Analysis_Context'Class; Name : Text_Type; Kind : Analysis_Unit_Kind; Charset : String := ""; Reparse : Boolean := False) return Analysis_Unit'Class; --% no-document: True overriding procedure Get_Unit_And_PLE_Root (Provider : Auto_Unit_Provider; Context : Analysis_Context'Class; Name : Text_Type; Kind : Analysis_Unit_Kind; Charset : String := ""; Reparse : Boolean := False; Unit : in out Analysis_Unit'Class; PLE_Root_Index : in out Natural); --% no-document: True overriding procedure Release (Provider : in out Auto_Unit_Provider); --% no-document: True function Create_Auto_Provider (Input_Files : GNATCOLL.VFS.File_Array; Charset : String := Default_Charset) return Auto_Unit_Provider; -- Return a unit provider that knows which compilation units are to be -- found in the given list of source files. -- -- This knowledge is built trying to parse all given ``Input_Files`` as Ada -- source files and listing the compilation units found there. Files that -- cannot be parsed properly are discarded. If two compilation units are -- found for the same unit, the first that is found in ``Input_Files`` is -- taken and the other ones are discarded. -- -- Source files are decoded using the given ``Charset``. -- -- .. todo:: Find a way to report discarded source files/compilation units. function Create_Auto_Provider_Reference (Input_Files : GNATCOLL.VFS.File_Array; Charset : String := Default_Charset) return Unit_Provider_Reference; -- Wrapper around ``Create_Auto_Provider`` as a shortcut to create a unit -- provider reference. -- --% belongs-to: Auto_Unit_Provider private use GNATCOLL.VFS; use Langkit_Support.Symbols; type Filename_And_PLE_Root is record Filename : Unbounded_String; PLE_Root_Index : Positive; end record; package Unit_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Symbol_Type, Element_Type => Filename_And_PLE_Root, Hash => Hash, Equivalent_Keys => "="); type Auto_Unit_Provider is new Libadalang.Analysis.Unit_Provider_Interface with record Keys : Symbol_Table; Mapping : Unit_Maps.Map; end record; type Auto_Unit_Provider_Access is access all Auto_Unit_Provider; function As_Key (Name : Text_Type; Kind : Analysis_Unit_Kind; Provider : Auto_Unit_Provider) return Symbol_Type; -- Given a compilation unit name and a kind (body? spec?), return a -- (unique) key for the unit to file mapping. procedure Create_Auto_Provider (Provider : out Auto_Unit_Provider; Input_Files : GNATCOLL.VFS.File_Array; Charset : String := Default_Charset); -- Helper for the Create_Auto_Provider functions function Create_Auto_Provider_Reference (Input_Files : GNATCOLL.VFS.File_Array; Charset : String := Default_Charset) return Unit_Provider_Reference is (Create_Unit_Provider_Reference (Create_Auto_Provider (Input_Files, Charset))); end Libadalang.Auto_Provider;
gitter-badger/libAnne
Ada
2,886
ads
with Containers.Stacks; generic type Fixed_Type is delta <>; with function Image(Value : Fixed_Type) return String is <>; with function Wide_Image(Value : Fixed_Type) return Wide_String is <>; with function Wide_Wide_Image(Value : Fixed_Type) return Wide_Wide_String is <>; package Containers.Fixed_Stacks with Preelaborate is package Base_Stack is new Containers.Stacks(Fixed_Type); --Please ignore this use Base_Stack; type Stack is new Base_Stack.Stack with null record; procedure Add(Self : in out Stack) with Pre => Self.Length >= 2; --Add the top two numbers on the stack, and push the result back onto the stack procedure Add(Self : in out Stack; Value : in Fixed_Type) with Pre => Self.Length >= 1; --Add the top number on the stack with the specified value, and push the result back onto the stack procedure Subtract(Self : in out Stack) with Pre => Self.Length >= 2; --Subtract the top two numbers on the stack, and push the result back onto the stack procedure Sub(Self : in out Stack) renames Subtract; --Subtract the top two numbers on the stack, and push the result back onto the stack procedure Subtract(Self : in out Stack; Value : in Fixed_Type) with Pre => Self.Length >= 1; --Subtract the specified value from the top number of the stack, and push the result back onto the stack procedure Sub(Self : in out Stack; Value : in Fixed_Type) renames Subtract; --Subtract the specified value from the top number of the stack and push the result back onto the stack procedure Multiply(Self : in out Stack) with Pre => Self.Length >= 2; --Multiply the top two numbers on the stack, and push the result back onto the stack procedure Mul(Self : in out Stack) renames Multiply; --Multiply the top two numbers on the stack, and push the result back onto the stack procedure Multiply(Self : in out Stack; Value : in Fixed_Type) with Pre => Self.Length >= 1; --Multiply the top number on the stack with the specified value, and push the result back onto the stack procedure Mul(Self : in out Stack; Value : in Fixed_Type) renames Multiply; --Multiply the top number on the stack with the specified value, and push the result back onto the stack procedure Divide(Self : in out Stack) with Pre => Self.Length >= 2; --Divide the top two numbers on the stack, and push the result back onto the stack procedure Div(Self : in out Stack) renames Divide; --Divide the top two numbers on the stack, and push the result back onto the stack procedure Divide(Self : in out Stack; Value : in Fixed_Type) with Pre => Self.Length >= 1; --Divide the top number on the stack by the specified value, and push the result back onto the stack procedure Div(Self : in out Stack; Value : in Fixed_Type) renames Divide; --Divide the top number on the stack by the specified value, and push the result back onto the stack end Containers.Fixed_Stacks;
JeremyGrosser/Ada_Drivers_Library
Ada
1,931
ads
-- This package was generated by the Ada_Drivers_Library project wizard script package ADL_Config is Architecture : constant String := "ARM"; -- From board definition Board : constant String := "STM32F407_Discovery"; -- From command line CPU_Core : constant String := "ARM Cortex-M4F"; -- From mcu definition Device_Family : constant String := "STM32F4"; -- From board definition Device_Name : constant String := "STM32F407VGTx"; -- From board definition Has_Ravenscar_Full_Runtime : constant String := "True"; -- From board definition Has_Ravenscar_SFP_Runtime : constant String := "True"; -- From board definition Has_ZFP_Runtime : constant String := "False"; -- From board definition High_Speed_External_Clock : constant := 8000000; -- From board definition Max_Mount_Name_Length : constant := 128; -- From default value Max_Mount_Points : constant := 2; -- From default value Max_Path_Length : constant := 1024; -- From default value Number_Of_Interrupts : constant := 0; -- From default value Runtime_Name : constant String := "ravenscar-sfp-stm32f4"; -- From default value Runtime_Name_Suffix : constant String := "stm32f4"; -- From board definition Runtime_Profile : constant String := "ravenscar-sfp"; -- From command line Use_Startup_Gen : constant Boolean := False; -- From command line Vendor : constant String := "STMicro"; -- From board definition end ADL_Config;
zhmu/ananas
Ada
3,168
ads
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- B I N D O . A U G M E N T O R S -- -- -- -- S p e c -- -- -- -- Copyright (C) 2019-2022, 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 enhance the library graph, which -- reflects source dependencies between units, with information obtained from -- the invocation graph, which reflects all activations of tasks, calls, and -- instantiations within units. with Bindo.Graphs; use Bindo.Graphs; use Bindo.Graphs.Invocation_Graphs; use Bindo.Graphs.Library_Graphs; package Bindo.Augmentors is ------------------------------ -- Library_Graph_Augmentors -- ------------------------------ package Library_Graph_Augmentors is procedure Augment_Library_Graph (Inv_Graph : Invocation_Graph); -- Augment the library graph of Inv_Graph with information from -- invocation graph Inv_Graph as follows: -- -- 1) Traverse the invocation graph starting from each elaboration -- procedure of unit Root. -- -- 2) Each time the traversal transitions from one unit into another -- unit Curr, add an invocation edge between predecessor Curr and -- successor Root in the library graph. -- -- 3) Do the above steps for all units with an elaboration procedure. end Library_Graph_Augmentors; end Bindo.Augmentors;
pdaxrom/Kino2
Ada
4,343
adb
------------------------------------------------------------------------------ -- -- -- GNAT ncurses Binding -- -- -- -- Terminal_Interface.Curses.Forms.Form_User_Data -- -- -- -- B O D Y -- -- -- ------------------------------------------------------------------------------ -- Copyright (c) 1998 Free Software Foundation, Inc. -- -- -- -- 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, distribute with modifications, 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 ABOVE 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. -- -- -- -- Except as contained in this notice, the name(s) of the above copyright -- -- holders shall not be used in advertising or otherwise to promote the -- -- sale, use or other dealings in this Software without prior written -- -- authorization. -- ------------------------------------------------------------------------------ -- Author: Juergen Pfeifer, 1996 -- Contact: http://www.familiepfeifer.de/Contact.aspx?Lang=en -- Version Control: -- $Revision: 1.11 $ -- Binding Version 01.00 ------------------------------------------------------------------------------ -- | -- |===================================================================== -- | man page form__userptr.3x -- |===================================================================== -- | with Terminal_Interface.Curses.Aux; use Terminal_Interface.Curses.Aux; package body Terminal_Interface.Curses.Forms.Form_User_Data is use type Interfaces.C.int; -- | -- | -- | procedure Set_User_Data (Frm : in Form; Data : in User_Access) is function Set_Form_Userptr (Frm : Form; Data : User_Access) return C_Int; pragma Import (C, Set_Form_Userptr, "set_form_userptr"); Res : constant Eti_Error := Set_Form_Userptr (Frm, Data); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_User_Data; -- | -- | -- | function Get_User_Data (Frm : in Form) return User_Access is function Form_Userptr (Frm : Form) return User_Access; pragma Import (C, Form_Userptr, "form_userptr"); begin return Form_Userptr (Frm); end Get_User_Data; procedure Get_User_Data (Frm : in Form; Data : out User_Access) is begin Data := Get_User_Data (Frm); end Get_User_Data; end Terminal_Interface.Curses.Forms.Form_User_Data;
reznikmm/matreshka
Ada
3,684
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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$ ------------------------------------------------------------------------------ with XML.DOM.Attributes; package ODF.DOM.Svg_Slope_Attributes is pragma Preelaborate; type ODF_Svg_Slope_Attribute is limited interface and XML.DOM.Attributes.DOM_Attribute; type ODF_Svg_Slope_Attribute_Access is access all ODF_Svg_Slope_Attribute'Class with Storage_Size => 0; end ODF.DOM.Svg_Slope_Attributes;
zhmu/ananas
Ada
255
adb
-- { dg-do run } -- { dg-options "-gnatVa" } with Range_Check3_Pkg; use Range_Check3_Pkg; procedure Range_Check3 is Ptr : Array_Access; begin Ptr := Allocate; raise Program_Error; exception when Constraint_Error => null; end Range_Check3;
OneWingedShark/Byron
Ada
190
ads
Pragma Ada_2012; Pragma Assertion_Policy( Check ); With Lexington.Token_Vector_Pkg; -- Generate based integer literals. Procedure Lexington.Aux.P15(Data : in out Token_Vector_Pkg.Vector);
VitalijBondarenko/Formatted_Output_NG
Ada
5,816
adb
------------------------------------------------------------------------------ -- -- -- File: -- -- formatted_output-integer_output.adb -- -- -- -- Description: -- -- Formatted_Output.Integer_Output generic package body -- -- -- -- Author: -- -- Eugene Nonko, [email protected] -- -- -- -- Revision history: -- -- 27/01/99 - original -- -- 16/03/99 - added support for justification characters -- -- -- ------------------------------------------------------------------------------ with Ada.Text_IO, Ada.Strings, Ada.Strings.Fixed, Ada.Strings.Unbounded; use Ada.Text_IO, Ada.Strings, Ada.Strings.Fixed, Ada.Strings.Unbounded; package body Formatted_Output.Integer_Output is package Item_Type_IO is new Integer_IO (Item_Type); use Item_Type_IO; function Format (Value : Item_Type; Initial_Width : Integer; Leading_Zero : Boolean; Base : Integer; Justification : Alignment) return String is Img : String (1 .. Maximal_Item_Length); Width, Real_Width : Integer; Pre_First, Last, Current : Natural; begin -- Format Put (Img, Value, Base); if Base = 10 then Last := Maximal_Item_Length; else Last := Maximal_Item_Length - 1; end if; Pre_First := Last; while Img (Pre_First) /= ' ' and then Img (Pre_First) /= '#' loop Pre_First := Pre_First - 1; end loop; if Value < 0 and then Base /= 10 then Img (Pre_First) := '-'; Pre_First := Pre_First - 1; end if; Real_Width := Last - Pre_First; if Initial_Width < Real_Width then Width := Real_Width; else Width := Initial_Width; end if; declare S : String (1 .. Width); begin Move (Img (Pre_First + 1 .. Last), S, Justify => Justification, Pad => Filler); if Leading_Zero then if Value < 0 then S (1) := '-'; Current := 2; else Current := 1; end if; while S (Current) = Filler or else S (Current) = '-' loop S (Current) := '0'; Current := Current + 1; end loop; end if; return S; end; end Format; function "&" (Fmt : Format_Type; Value : Item_Type) return Format_Type is Command_Start : constant Integer := Scan_To_Percent_Sign (Fmt); Leading_Zero : Boolean := False; Width : Integer := 0; Digit_Occured, Justification_Changed : Boolean := False; Justification : Alignment := Right; Fmt_Copy : Unbounded_String; begin -- "&" if Command_Start /= 0 then Fmt_Copy := Unbounded_String (Fmt); for I in Command_Start + 1 .. Length (Fmt_Copy) loop case Element (Fmt_Copy, I) is when 'd' => Replace_Slice (Fmt_Copy, Command_Start, I, Format (Value, Width, Leading_Zero, 10, Justification)); return Format_Type (Fmt_Copy); when 'x' => Replace_Slice (Fmt_Copy, Command_Start, I, Format (Value, Width, Leading_Zero, 16, Justification)); return Format_Type (Fmt_Copy); when 'o' => Replace_Slice (Fmt_Copy, Command_Start, I, Format (Value, Width, Leading_Zero, 8, Justification)); return Format_Type (Fmt_Copy); when 'b' => Replace_Slice (Fmt_Copy, Command_Start, I, Format (Value, Width, Leading_Zero, 2, Justification)); return Format_Type (Fmt_Copy); when '-' | '+' | '*' => if Justification_Changed or else Digit_Occured then raise Format_Error; end if; Justification_Changed := True; case Element (Fmt_Copy, I) is when '-' => Justification := Left; when '+' => Justification := Right; when '*' => Justification := Center; when others => null; end case; when '0' .. '9' => Digit_Occured := True; if Width = 0 and then Element (Fmt_Copy, I) = '0' then Leading_Zero := True; else Width := Width * 10 + Character'Pos (Element (Fmt_Copy, I)) - Character'Pos ('0'); end if; when others => raise Format_Error; end case; end loop; end if; raise Format_Error; end "&"; end Formatted_Output.Integer_Output;
charlie5/lace
Ada
1,125
ads
with openGL.Font, openGL.Geometry; package openGL.Model.sphere.textured -- -- Models a textured sphere. -- is type Item is new Model.sphere.item with private; type View is access all Item'Class; --------- --- Forge -- function new_Sphere (Radius : in Real; lat_Count : in Positive := 26; long_Count : in Positive := 52; Image : in asset_Name := null_Asset; is_Skysphere : in Boolean := False) return View; -------------- --- Attributes -- overriding function to_GL_Geometries (Self : access Item; Textures : access Texture.name_Map_of_texture'Class; Fonts : in Font.font_id_Map_of_font) return Geometry.views; private type Item is new Model.sphere.item with record Image : asset_Name := null_Asset; -- Usually a mercator projection to be mapped onto the sphere. is_Skysphere : Boolean := False; end record; end openGL.Model.sphere.textured;
ficorax/PortAudioAda
Ada
1,337
ads
with PortAudioAda.Thin; use PortAudioAda.Thin; generic type Frame; type User_Data is private; with function Pre_Processing (frameIn : Frame; data : User_Data) return Frame; with function Post_Processing (frameIn : Frame; data : User_Data) return Frame; package Generic_Callback is type Pre_Callback is access function (frameIn : Frame; data : User_Data) return Frame; type Post_Callback is access function (frameIn : Frame; data : User_Data) return Frame; function PAA_Open_Stream (stream : access PaStream_Ptr; inputParameters : access PaStreamParameters; outputParameters : access PaStreamParameters; sampleRate : Long_Float; framesPerBuffer : Long_Integer; streamFlags : PaStreamFlags; pre : Pre_Callback; post : Post_Callback; userData : User_Data) return PaError; end Generic_Callback;
caqg/linux-home
Ada
48,969
adb
-- Abstract : -- -- Support Emacs Ada mode and gpr-query minor mode queries about -- GNAT projects and cross reference data -- -- Copyright (C) 2014 - 2022 Free Software Foundation All Rights Reserved. -- -- This program is free software; you can redistribute it and/or -- modify it under terms of the GNU General Public License as -- published by the Free Software Foundation; either version 3, or (at -- your option) any later version. This program is distributed in the -- hope that it will be useful, but WITHOUT ANY WARRANTY; without even -- the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -- PURPOSE. See the GNU General Public License for more details. You -- should have received a copy of the GNU General Public License -- distributed with this program; see file COPYING. If not, write to -- the Free Software Foundation, 51 Franklin Street, Suite 500, Boston, -- MA 02110-1335, USA. pragma License (GPL); with Ada.Characters.Handling; with Ada.Command_Line; with Ada.Directories; with Ada.Environment_Variables; with Ada.Exceptions.Traceback; with Ada.IO_Exceptions; with Ada.Strings.Fixed; with Ada.Strings.Unbounded; with Ada.Text_IO; with GNAT.Command_Line; with GNAT.Directory_Operations; with GNAT.OS_Lib; with GNAT.Strings; with GNAT.Traceback.Symbolic; with GNATCOLL.Arg_Lists; with GNATCOLL.Paragraph_Filling; with GNATCOLL.Projects; with GNATCOLL.SQL.Exec; with GNATCOLL.SQL.Sqlite; with GNATCOLL.Traces; with GNATCOLL.Utils; with GNATCOLL.VFS; with GNATCOLL.VFS_Utils; with GNATCOLL.Xref; procedure Gpr_Query is use all type GNATCOLL.VFS.File_Array; use GNATCOLL; Version : constant String := "3"; -- Changes once per release when the API (commands and responses) -- changes; must match gpr-query.el gpr-query-protocol-version Me : constant GNATCOLL.Traces.Trace_Handle := GNATCOLL.Traces.Create ("gpr_query"); -- See gnatcoll-xref.adb for xref traces. DB_Error : exception; Invalid_Command : exception; function "+" (Item : in Ada.Strings.Unbounded.Unbounded_String) return String renames Ada.Strings.Unbounded.To_String; function "+" (Item : in String) return Ada.Strings.Unbounded.Unbounded_String renames Ada.Strings.Unbounded.To_Unbounded_String; function "+" (Item : in GNATCOLL.VFS.Filesystem_String) return String is begin return String (Item); end "+"; procedure Process_Line (Line : String); -- Process a full line of commands. -- Raise Invalid_Command when the command is invalid. function Get_Entity (Arg : String) return GNATCOLL.Xref.Entity_Information; -- Return the entity matching the "name:file:line[:column]" argument type My_Xref_Database is new GNATCOLL.Xref.Xref_Database with null record; -- Derived so we can override Image to output full paths Short_File_Names : Boolean; -- set by each command that calls Image -- Full_File_Names_Arg : constant String := "full_file_names"; Short_File_Names_Arg : constant String := "short_file_names"; overriding function Image (Self : My_Xref_Database; File : GNATCOLL.VFS.Virtual_File) return String; function Image (Self : GNATCOLL.Xref.Entity_Information) return String; -- Return a display version of the argument Xref : aliased My_Xref_Database; Env : GNATCOLL.Projects.Project_Environment_Access; Tree : aliased GNATCOLL.Projects.Project_Tree; Source_Search_Path : GNATCOLL.VFS.File_Array_Access; Previous_Progress : Natural := 0; Progress_Reporter : access procedure (Current, Total : Integer) := null; -- Subprogram specs for subprograms used before bodies procedure Check_Arg_Count (Args : in GNATCOLL.Arg_Lists.Arg_List; Expected : in Integer); procedure Dump (Curs : in out GNATCOLL.Xref.Entities_Cursor'Class); procedure Dump (Refs : in out GNATCOLL.Xref.References_Cursor'Class; Controlling_Type_Name : in String := ""); procedure Dump_Local (Refs : in out GNATCOLL.Xref.References_Cursor'Class; Local_File_Name : in String); -- Display the results of a query procedure Put (Item : GNATCOLL.VFS.File_Array); generic with function Compute (Self : in GNATCOLL.Xref.Xref_Database'Class; Entity : in GNATCOLL.Xref.Entity_Information) return GNATCOLL.Xref.Entity_Information; procedure Process_Command_Single (Args : GNATCOLL.Arg_Lists.Arg_List); -- Get the entity identified by Args, which must contain a single -- argument. Then call Compute, and output the result. -- -- Appropriate for queries that return a single entity result. procedure Process_Command_Single (Args : GNATCOLL.Arg_Lists.Arg_List) is use GNATCOLL.Arg_Lists; use GNATCOLL.Xref; Entity : Entity_Information; Comp : Entity_Information; begin Check_Arg_Count (Args, 2); Short_File_Names := Nth_Arg (Args, 2) = Short_File_Names_Arg; Entity := Get_Entity (Nth_Arg (Args, 1)); Comp := Compute (Xref, Entity); if Comp /= No_Entity then Ada.Text_IO.Put_Line (Image (Comp)); end if; end Process_Command_Single; generic with procedure Compute (Self : in GNATCOLL.Xref.Xref_Database'Class; Entity : in GNATCOLL.Xref.Entity_Information; Cursor : out GNATCOLL.Xref.Entities_Cursor'Class); procedure Process_Command_Multiple (Args : GNATCOLL.Arg_Lists.Arg_List); procedure Process_Command_Multiple (Args : GNATCOLL.Arg_Lists.Arg_List) is use GNATCOLL.Arg_Lists; use GNATCOLL.Xref; Entity : Entity_Information; Descendants : Recursive_Entities_Cursor; -- Apparently a generic formal parameter cannot match a subprogram access type, so we need this: procedure Do_Compute (Self : in GNATCOLL.Xref.Xref_Database'Class; Entity : in GNATCOLL.Xref.Entity_Information; Cursor : out GNATCOLL.Xref.Entities_Cursor'Class) is begin Compute (Self, Entity, Cursor); end Do_Compute; begin Check_Arg_Count (Args, 2); Short_File_Names := Nth_Arg (Args, 2) = Short_File_Names_Arg; Entity := Get_Entity (Nth_Arg (Args, 1)); Recursive (Self => Xref'Unchecked_Access, Entity => Entity, Compute => Do_Compute'Unrestricted_Access, Cursor => Descendants); Dump (Descendants); end Process_Command_Multiple; -- Command procedures; Args is the command line. -- -- Infrastructure commands procedure Process_Help (Args : GNATCOLL.Arg_Lists.Arg_List); procedure Process_Refresh (Args : GNATCOLL.Arg_Lists.Arg_List); procedure Process_DB_Name (Args : GNATCOLL.Arg_Lists.Arg_List); -- Queries; alphabetical procedure Process_Complete (Args : GNATCOLL.Arg_Lists.Arg_List); procedure Process_Overridden is new Process_Command_Single (GNATCOLL.Xref.Overrides); procedure Process_Overriding is new Process_Command_Multiple (GNATCOLL.Xref.Overridden_By); procedure Process_Parent_Types is new Process_Command_Multiple (GNATCOLL.Xref.Parent_Types); procedure Process_Project_Path (Args : GNATCOLL.Arg_Lists.Arg_List); procedure Process_Refs (Args : GNATCOLL.Arg_Lists.Arg_List); procedure Process_Tree_Defs (Args : GNATCOLL.Arg_Lists.Arg_List); procedure Process_Tree_Refs (Args : GNATCOLL.Arg_Lists.Arg_List); procedure Process_Source_Dirs (Args : GNATCOLL.Arg_Lists.Arg_List); type Command_Descr is record Name : GNAT.Strings.String_Access; Args : GNAT.Strings.String_Access; Help : GNAT.Strings.String_Access; Handler : not null access procedure (Args : GNATCOLL.Arg_Lists.Arg_List); end record; Commands : constant array (Natural range <>) of Command_Descr := ((new String'("help"), new String'("[command or variable name]"), new String'("Display the list of commands and their syntax."), Process_Help'Access), (new String'("refresh"), null, new String'("Refresh the contents of the xref database."), Process_Refresh'Access), (new String'("db_name"), null, new String'("Report the root name of the database files."), Process_DB_Name'Access), -- queries (new String'("complete"), new String'("pattern"), new String'("Names that complete the pattern."), Process_Complete'Access), (new String'("overridden"), new String'("name:file:line[:column] {full_file_names | short_file_names}"), new String'("The entity that is overridden by the parameter"), Process_Overridden'Access), (new String'("overriding"), new String'("name:file:line[:column] {full_file_names | short_file_names}"), new String'("The entities that override the parameter"), Process_Overriding'Access), (new String'("parent_types"), new String'("name:file:line[:column] {full_file_names | short_file_names}"), new String'("The parent types of the entity."), Process_Parent_Types'Access), (new String'("project_path"), null, new String'("The project search path."), Process_Project_Path'Access), (new String'("refs"), new String'("name:file:line[:column] {global | local_only} {full_file_names | short_file_names}"), new String'("All known references to the entity."), Process_Refs'Access), (new String'("tree_defs"), new String'("name:file[:line[:column]] {full_file_names | short_file_names}"), new String' ("All known references to the entity, and to child types or overridden/overriding operations."), Process_Tree_Defs'Access), (new String'("tree_refs"), new String'("name:file:line[:column] {full_file_names | short_file_names}"), new String' ("All known references to the entity, and to parent/child types or overridden/overriding operations."), Process_Tree_Refs'Access), (new String'("source_dirs"), null, new String'("The project source directories, recursively."), Process_Source_Dirs'Access)); -- Parsed command line info Cmdline : GNAT.Command_Line.Command_Line_Configuration; ALI_Encoding : aliased GNAT.Strings.String_Access := new String'(""); Commands_From_Switch : aliased GNAT.Strings.String_Access; DB_Name : aliased GNAT.Strings.String_Access := new String'("gpr_query.db"); Force_Refresh : aliased Boolean; Gpr_Config_File : aliased GNAT.Strings.String_Access; Nightly_DB_Name : aliased GNAT.Strings.String_Access; Project_File_Name : aliased GNAT.Strings.String_Access; Show_Progress : aliased Boolean; Traces_Config_File : aliased GNAT.Strings.String_Access; ---------- -- Procedure bodies, alphabetical procedure Check_Arg_Count (Args : in GNATCOLL.Arg_Lists.Arg_List; Expected : in Integer) is Count : constant Integer := GNATCOLL.Arg_Lists.Args_Length (Args); begin if Count /= Expected then raise Invalid_Command with "Invalid number of arguments" & Integer'Image (Count) & "; expecting" & Integer'Image (Expected); end if; end Check_Arg_Count; procedure Display_Progress (Current, Total : Integer) is Now : constant Integer := Integer (Float'Floor (Float (Current) / Float (Total) * 100.0)); begin if Now /= Previous_Progress then Ada.Text_IO.Put_Line ("completed" & Current'Img & " out of" & Total'Img & " (" & GNATCOLL.Utils.Image (Now, Min_Width => 0) & "%)..."); Previous_Progress := Now; end if; end Display_Progress; procedure Dump (Curs : in out GNATCOLL.Xref.Entities_Cursor'Class) is use GNATCOLL.Xref; begin while Curs.Has_Element loop Ada.Text_IO.Put_Line (Image (Curs.Element)); Curs.Next; end loop; end Dump; procedure Dump (Refs : in out GNATCOLL.Xref.References_Cursor'Class; Controlling_Type_Name : in String := "") is use GNATCOLL.Xref; begin while Has_Element (Refs) loop declare Ref : constant Entity_Reference := Refs.Element; begin Ada.Text_IO.Put_Line (Xref.Image (Ref) & " (" & (if Controlling_Type_Name'Length = 0 then "" else Controlling_Type_Name & "; ") & (+Ref.Kind) & ")"); end; Next (Refs); end loop; end Dump; procedure Dump_Local (Refs : in out GNATCOLL.Xref.References_Cursor'Class; Local_File_Name : in String) is use GNATCOLL.Xref; begin while Has_Element (Refs) loop declare Ref : constant Entity_Reference := Refs.Element; begin if Local_File_Name = "" or else Local_File_Name = Ref.File.Display_Base_Name then Ada.Text_IO.Put_Line (Xref.Image (Ref) & " (" & (+Ref.Kind) & ")"); end if; end; Next (Refs); end loop; end Dump_Local; function Get_Entity (Arg : String) return GNATCOLL.Xref.Entity_Information is use GNAT.Directory_Operations; use GNATCOLL.Xref; Words : GNAT.Strings.String_List_Access := GNATCOLL.Utils.Split (Arg, On => ':'); Ref : GNATCOLL.Xref.Entity_Reference; begin case Words'Length is when 4 => Ref := Xref.Get_Entity (Name => Words (Words'First).all, File => Format_Pathname (Style => UNIX, Path => Words (Words'First + 1).all), Project => GNATCOLL.Projects.No_Project, Line => Integer'Value (Words (Words'First + 2).all), Column => Visible_Column (Integer'Value (Words (Words'First + 3).all))); when 3 => -- No column; assume good enough for a precise match Ref := Xref.Get_Entity (Name => Words (Words'First).all, File => Format_Pathname (Style => UNIX, Path => Words (Words'First + 1).all), Project => GNATCOLL.Projects.No_Project, Line => Integer'Value (Words (Words'First + 2).all)); when 2 => -- No line or column; error. GNAT.Strings.Free (Words); raise Invalid_Command with "Invalid parameter '" & Arg & "', expecting name:file:line[:column]]"; when others => -- No file, or bad args. -- -- Xref.Get_Entity treats 'File => ""' as searching for pre-defined entities such as "Integer". -- -- To search for a name in all files, use "complete" command. GNAT.Strings.Free (Words); raise Invalid_Command with "Invalid parameter '" & Arg & "', expecting name:file:line[:column]]"; end case; GNAT.Strings.Free (Words); if Ref.Entity = GNATCOLL.Xref.No_Entity then Ada.Text_IO.Put_Line ("Error: entity not found '" & Arg & "'"); elsif GNATCOLL.Xref.Is_Fuzzy_Match (Ref.Entity) then Ada.Text_IO.Put_Line ("warning: fuzzy match for the entity"); end if; return Ref.Entity; end Get_Entity; overriding function Image (Self : My_Xref_Database; File : GNATCOLL.VFS.Virtual_File) return String is pragma Unreferenced (Self); begin if Short_File_Names then return File.Display_Base_Name; else return File.Display_Full_Name; end if; end Image; function Image (Self : GNATCOLL.Xref.Entity_Information) return String is use GNATCOLL.Xref; begin if Self = No_Entity then return "Unknown entity"; else declare Decl : constant Entity_Declaration := Xref.Declaration (Self); begin if Is_Predefined_Entity (Decl) then return "predefined entity: " & (+Decl.Name); else return Xref.Image (Decl.Location); end if; end; end if; end Image; procedure Process_DB_Name (Args : GNATCOLL.Arg_Lists.Arg_List) is pragma Unreferenced (Args); begin Ada.Text_IO.Put_Line (DB_Name.all); end Process_DB_Name; procedure Process_Help (Args : GNATCOLL.Arg_Lists.Arg_List) is use Ada.Text_IO; use GNATCOLL.Arg_Lists; use type GNAT.Strings.String_Access; begin for C in Commands'Range loop if Args_Length (Args) <= 0 -- Empty_Command_Line returns -1 or else Nth_Arg (Args, 1) = Commands (C).Name.all then Put (" " & Commands (C).Name.all); if Commands (C).Args = null then New_Line; else Put_Line (" " & Commands (C).Args.all); end if; Put (Ada.Strings.Unbounded.To_String (GNATCOLL.Paragraph_Filling.Knuth_Fill (Commands (C).Help.all, Max_Line_Length => 70, Line_Prefix => " "))); end if; end loop; New_Line; Put_Line ("'exit' to quit"); end Process_Help; procedure Process_Line (Line : String) is Expr : GNAT.Strings.String_List_Access; begin if Ada.Strings.Fixed.Trim (Line, Ada.Strings.Both) = "" then return; end if; Expr := GNATCOLL.Utils.Split (Line, On => ';'); for C in Expr'Range loop if Ada.Strings.Fixed.Trim (Expr (C).all, Ada.Strings.Both) = "" then null; else declare use GNATCOLL.Arg_Lists; List : constant Arg_List := Parse_String (Expr (C).all, Mode => Separate_Args); Cmd : constant String := Ada.Characters.Handling.To_Lower (Get_Command (List)); Found : Boolean := False; begin for Co in Commands'Range loop if Commands (Co).Name.all = Cmd then Commands (Co).Handler (List); Found := True; exit; end if; end loop; if not Found then raise Invalid_Command with "Invalid command: '" & Cmd & "'"; end if; end; end if; end loop; GNAT.Strings.Free (Expr); end Process_Line; function Get_Parameters (Entity : GNATCOLL.Xref.Entity_Information) return String is use Ada.Strings.Unbounded; use GNATCOLL.Xref; Params : Parameters_Cursor := GNATCOLL.Xref.Parameters (Xref, Entity); Result : Unbounded_String; Need_Paren : Boolean := True; begin loop exit when not Has_Element (Params); Result := Result & ((if Need_Paren then (if Length (Result) > 0 then " (" else "(") else ", ") & Xref.Declaration (Element (Params).Parameter).Name); Need_Paren := False; Next (Params); end loop; if not Need_Paren then Result := Result & ")"; end if; return +Result; end Get_Parameters; procedure Process_Complete (Args : GNATCOLL.Arg_Lists.Arg_List) is use Ada.Text_IO; use GNATCOLL.Arg_Lists; use GNATCOLL.Xref; Prefix : constant String := Nth_Arg (Args, 1); Matches : Entities_Cursor; Count : Integer := 0; begin Short_File_Names := False; -- First count all matches, so Emacs can show progress Xref.From_Prefix (Prefix, Is_Partial => True, Cursor => Matches); loop exit when not Has_Element (Matches); Count := @ + 1; Next (Matches); end loop; Ada.Text_IO.Put_Line ("element count" & Count'Image); Xref.From_Prefix (Prefix, Is_Partial => True, Cursor => Matches); loop exit when not Has_Element (Matches); declare Decl : constant Entity_Declaration := Xref.Declaration (Element (Matches)); begin Put (Xref.Qualified_Name (Element (Matches))); if Decl.Flags.Is_Subprogram then Ada.Text_IO.Put (Get_Parameters (Decl.Location.Entity)); end if; end; Ada.Text_IO.Put_Line (" " & Image (Element (Matches))); Next (Matches); end loop; end Process_Complete; procedure Process_Project_Path (Args : GNATCOLL.Arg_Lists.Arg_List) is pragma Unreferenced (Args); Dirs : constant GNATCOLL.VFS.File_Array := GNATCOLL.Projects.Predefined_Project_Path (Env.all); begin Short_File_Names := False; Put (Dirs); end Process_Project_Path; procedure Process_Refresh (Args : GNATCOLL.Arg_Lists.Arg_List) is pragma Unreferenced (Args); begin Parse_All_LI_Files (Self => Xref, Project => Tree.Root_Project, Parse_Runtime_Files => False, Show_Progress => Progress_Reporter, ALI_Encoding => ALI_Encoding.all, From_DB_Name => Nightly_DB_Name.all, To_DB_Name => DB_Name.all, Force_Refresh => Force_Refresh); end Process_Refresh; procedure Process_Refs (Args : GNATCOLL.Arg_Lists.Arg_List) is use GNATCOLL.Arg_Lists; begin Check_Arg_Count (Args, 3); -- entity, local/global, full/short Short_File_Names := Nth_Arg (Args, 3) = Short_File_Names_Arg; declare use GNATCOLL.Xref; Entity : constant Entity_Information := Get_Entity (Nth_Arg (Args, 1)); Refs : References_Cursor; begin Xref.References (Entity, Refs); if Nth_Arg (Args, 2) = "local_only" then -- Xref doesn't let us get the full file name of Entity (sigh) declare use Ada.Strings.Fixed; First : constant Integer := 1 + Index (Nth_Arg (Args, 1), ":"); Last : constant Integer := -1 + Index (Nth_Arg (Args, 1), ":", First); Local_File_Name : constant String := Nth_Arg (Args, 1) (First .. Last); begin Dump_Local (Refs, Local_File_Name); end; else Dump (Refs); end if; end; end Process_Refs; function Has_Op (Entity : in GNATCOLL.Xref.Entity_Information; Primitive_Op_Name : in String := "") return Boolean is use GNATCOLL.Xref; Ops : Entities_Cursor; begin Xref.Methods (Entity, Ops); loop exit when not Has_Element (Ops); if Primitive_Op_Name = +Xref.Declaration (Element (Ops)).Name then return True; end if; Next (Ops); end loop; return False; end Has_Op; function Root_Parent_Type (Entity : in GNATCOLL.Xref.Entity_Information; Primitive_Op_Name : in String := "") return GNATCOLL.Xref.Entity_Information is use GNATCOLL.Xref; Result : Entity_Information := Entity; Parents : Entities_Cursor; begin loop Xref.Parent_Types (Result, Parents); -- There is more than one parent when the type inherits interfaces. -- We assume the first parent is a non-interface (if there is one), -- and ignore the rest. exit when (not Parents.Has_Element) or else (Primitive_Op_Name'Length > 0 and then not Has_Op (Parents.Element, Primitive_Op_Name)); Result := Parents.Element; end loop; return Result; end Root_Parent_Type; procedure All_Child_Types (Entity : in GNATCOLL.Xref.Entity_Information; Cursor : in out GNATCOLL.Xref.Recursive_Entities_Cursor) is begin GNATCOLL.Xref.Recursive (Self => Xref'Unchecked_Access, Entity => Entity, Compute => GNATCOLL.Xref.Child_Types'Access, Cursor => Cursor); end All_Child_Types; function Controlling_Type (Entity : in GNATCOLL.Xref.Entity_Information) return GNATCOLL.Xref.Entity_Information is use GNATCOLL.Xref; -- Method_Of returns a derived type if the subprogram is not -- overridden for the child; the type we want is the non-child; the -- last item in Controlling_Types. Types : Entities_Cursor; Result : Entity_Information := No_Entity; begin Xref.Method_Of (Entity, Types); loop exit when not Has_Element (Types); Result := Types.Element; Next (Types); end loop; return Result; end Controlling_Type; procedure Dump_Decl (Decl : in GNATCOLL.Xref.Entity_Declaration; Annotation : in String := "") is begin Ada.Text_IO.Put_Line (Xref.Image (Decl.Location) & " (" & (+Decl.Name) & " " & (if Annotation'Length = 0 then "" else Annotation & " ") & (+Decl.Kind) & ")"); end Dump_Decl; procedure Dump_Ref (Ref : in GNATCOLL.Xref.Entity_Reference; Annotation : in String := "") is begin Ada.Text_IO.Put_Line (Xref.Image (Ref) & " (" & (+Xref.Declaration (Ref.Entity).Name) & " " & (if Annotation'Length = 0 then "" else Annotation & " ") & (+Ref.Kind) & ")"); end Dump_Ref; procedure Dump_Entity (Entity : in GNATCOLL.Xref.Entity_Information; Controlling_Type_Name : in String := "") is use Ada.Strings.Unbounded; use GNATCOLL.Xref; Spec_Decl : constant Entity_Declaration := Xref.Declaration (Entity); Body_Decls : References_Cursor; Parameters : Unbounded_String; begin if Controlling_Type_Name'Length > 0 then Parameters := +Controlling_Type_Name & ";"; end if; if Spec_Decl.Flags.Is_Subprogram then Parameters := Parameters & Get_Parameters (Spec_Decl.Location.Entity); end if; Xref.Bodies (Entity, Body_Decls); if not Has_Element (Body_Decls) then Dump_Decl (Spec_Decl, +Parameters); else declare use all type GNATCOLL.VFS.Virtual_File; First_Body_Ref : constant Entity_Reference := Body_Decls.Element; begin if First_Body_Ref.File = Spec_Decl.Location.File and First_Body_Ref.Line = Spec_Decl.Location.Line and First_Body_Ref.Column = Spec_Decl.Location.Column then Ada.Text_IO.Put_Line (Xref.Image (First_Body_Ref) & " (" & (+Spec_Decl.Name) & " " & (if Length (Parameters) = 0 then "" else +Parameters & " ") & (+Spec_Decl.Kind) & "/" & (+First_Body_Ref.Kind) & ")"); else Dump_Decl (Spec_Decl, +Parameters); Dump_Ref (First_Body_Ref, +Parameters); end if; end; Next (Body_Decls); loop exit when not Has_Element (Body_Decls); Dump_Ref (Body_Decls.Element, +Parameters); Next (Body_Decls); end loop; end if; end Dump_Entity; procedure Process_Tree_Defs (Args : GNATCOLL.Arg_Lists.Arg_List) is -- "tree_defs" <name:loc> {short_file_names | full_file_names} use GNATCOLL.Arg_Lists; use GNATCOLL.Xref; Words : GNAT.Strings.String_List_Access := GNATCOLL.Utils.Split (Nth_Arg (Args, 1), On => ':'); Root_Parent : Entity_Information; procedure One_Entity (Orig_Entity : in Entity_Information; No_Children : in Boolean := False) is Orig_Decl : constant Entity_Declaration := Xref.Declaration (Orig_Entity); Orig_Short_Name : constant String := +Orig_Decl.Name; procedure Dump_Method (Type_Entity : in GNATCOLL.Xref.Entity_Information; Primitive_Op_Name : in String) is Type_Name : constant String := Xref.Qualified_Name (Type_Entity); Ops : Entities_Cursor; begin Xref.Methods (Type_Entity, Ops); loop exit when not Has_Element (Ops); declare Method_Name : constant String := +Xref.Declaration (Element (Ops)).Name; begin if Primitive_Op_Name = Method_Name then -- IMPROVEME: if the method is inherited but not overridden, use the -- type location. Dump_Entity (Element (Ops), Type_Name); end if; end; Next (Ops); end loop; end Dump_Method; procedure Dump_Entities (Entities : in out Recursive_Entities_Cursor) is begin loop exit when not Has_Element (Entities); if Orig_Decl.Flags.Is_Subprogram then Dump_Method (Entities.Element, Primitive_Op_Name => Orig_Short_Name); else Dump_Entity (Entities.Element); end if; Next (Entities); end loop; end Dump_Entities; begin if Orig_Decl.Flags.Is_Type then -- It is tempting to find the highest ancestor type here, then show -- all types derived from that. But in Ada, that root ancestor is -- often Ada.Finalization.[Limited_]Controlled (or some similar root -- type), so the tree is much larger than we really want. So we just -- show all children of the given type; the user can then climb the -- tree if they want to enlarge it. This also allows the user to -- choose which anscestor to examine when there is more than one, -- with interfaces. Root_Parent := Orig_Entity; elsif Orig_Decl.Flags.Is_Subprogram then declare Controlling : constant Entity_Information := Controlling_Type (Orig_Entity); begin if Controlling = No_Entity then -- Not a primitive subprogram Dump_Entity (Orig_Entity); return; else if No_Children then Root_Parent := Controlling; -- for type name else -- Here we find the highest ancestor type that has this method. -- gnatcoll.xref does not let us get the type of each parameter, so -- we can't match profiles, just names. Root_Parent := Root_Parent_Type (Controlling, Primitive_Op_Name => Orig_Short_Name); end if; end if; end; else -- Something else (variable, package, ...) Dump_Decl (Orig_Decl); return; end if; if No_Children then if Orig_Decl.Flags.Is_Type then Dump_Entity (Orig_Entity); else Dump_Entity (Orig_Entity, Controlling_Type_Name => Xref.Qualified_Name (Root_Parent)); end if; else declare Child_Types : Recursive_Entities_Cursor; begin -- "Child_Types" includes generic formal parameters (ie -- gen_run_wisi_lr_parse.ads Parse_Data_Type) in addition to the -- actual parameters. All_Child_Types (Root_Parent, Child_Types); if Orig_Decl.Flags.Is_Type then Dump_Entity (Root_Parent); else Dump_Method (Root_Parent, +Orig_Decl.Name); end if; Dump_Entities (Child_Types); end; end if; end One_Entity; use GNAT.Directory_Operations; begin Short_File_Names := Nth_Arg (Args, 2) = Short_File_Names_Arg; case Words'Length is when 3 | 4 => One_Entity (Xref.Get_Entity (Name => Words (Words'First).all, File => Format_Pathname (Style => UNIX, Path => Words (Words'First + 1).all), Project => GNATCOLL.Projects.No_Project, Line => Integer'Value (Words (Words'First + 2).all), Column => (if Words'Length = 4 then Visible_Column (Integer'Value (Words (Words'First + 3).all)) else -1)) -- No column; assume good enough for a precise match .Entity); when 2 => -- No line or column; find all matching names in file declare use GNATCOLL.VFS; Multiple : Entities_Cursor; Orig_File : constant Virtual_File := Locate_Regular_File (File_Name => +Words (Words'First + 1).all, Path => Source_Search_Path.all); Orig_File_Name : constant Filesystem_String := Full_Name (Orig_File); begin From_Prefix (Xref, Words (Words'First).all, Is_Partial => False, Cursor => Multiple); loop exit when not Has_Element (Multiple); declare Decl : constant Entity_Declaration := Xref.Declaration (Element (Multiple)); function Check_Body_File return Boolean is Bodies : References_Cursor; begin Xref.Bodies (Decl.Location.Entity, Bodies); loop exit when not Has_Element (Bodies); declare Ref : Entity_Reference renames Element (Bodies); begin if Orig_File_Name = Full_Name (Ref.File) then return True; end if; end; Next (Bodies); end loop; return False; end Check_Body_File; begin if Orig_File_Name = Full_Name (Decl.Location.File) or else Check_Body_File then One_Entity (Element (Multiple), No_Children => True); end if; end; Next (Multiple); end loop; end; when others => -- No file or bad arg. GNAT.Strings.Free (Words); raise Invalid_Command with "Invalid parameter '" & Nth_Arg (Args, 1) & "', expecting name:file:[line[:column]]"; end case; end Process_Tree_Defs; procedure Process_Tree_Refs (Args : GNATCOLL.Arg_Lists.Arg_List) is -- "tree_refs" <name:loc> {short_file_names | full_file_names} use GNATCOLL.Arg_Lists; use GNATCOLL.Xref; Orig_Entity : constant Entity_Information := Get_Entity (Nth_Arg (Args, 1)); Orig_Decl : constant Entity_Declaration := Xref.Declaration (Orig_Entity); Root_Parent : Entity_Information; procedure Dump_Type (Type_Entity : in Entity_Information) is Methods : Entities_Cursor; begin if Orig_Decl.Flags.Is_Subprogram then Xref.Methods (Type_Entity, Methods); loop exit when not Has_Element (Methods); declare Method_Name : constant String := +Xref.Declaration (Methods.Element).Name; Refs : References_Cursor; begin if Method_Name = +Orig_Decl.Name then Xref.References (Methods.Element, Refs); Dump (Refs, +Xref.Declaration (Type_Entity).Name); end if; end; Next (Methods); end loop; else Dump_Entity (Type_Entity); end if; end Dump_Type; procedure Dump_Types (Types : in out Recursive_Entities_Cursor) is begin loop exit when not Has_Element (Types); Dump_Type (Types.Element); Next (Types); end loop; end Dump_Types; begin Short_File_Names := Nth_Arg (Args, 2) = Short_File_Names_Arg; if Orig_Decl.Flags.Is_Type then -- See comment in Process_Tree_Defs Root_Parent := Orig_Entity; elsif Orig_Decl.Flags.Is_Subprogram then declare Controlling : constant Entity_Information := Controlling_Type (Orig_Entity); begin if Controlling = No_Entity then -- Not a primitive subprogram declare Refs : References_Cursor; begin Xref.References (Orig_Entity, Refs); Dump (Refs); return; end; else Root_Parent := Root_Parent_Type (Controlling, Primitive_Op_Name => +Orig_Decl.Name); end if; end; else -- A variable declare Refs : References_Cursor; begin Xref.References (Orig_Entity, Refs); Dump (Refs); return; end; end if; declare Child_Types : Recursive_Entities_Cursor; begin All_Child_Types (Root_Parent, Child_Types); Dump_Type (Root_Parent); Dump_Types (Child_Types); end; end Process_Tree_Refs; procedure Process_Source_Dirs (Args : GNATCOLL.Arg_Lists.Arg_List) is pragma Unreferenced (Args); begin Put (Source_Search_Path.all); end Process_Source_Dirs; procedure Put (Item : GNATCOLL.VFS.File_Array) is use GNATCOLL.VFS; begin for I in Item'Range loop Ada.Text_IO.Put_Line (+Full_Name (Item (I))); end loop; end Put; ---------- -- SQL error reporting type SQL_Error_Reporter is new GNATCOLL.SQL.Exec.Error_Reporter with null record; overriding procedure On_Error (Self : in out SQL_Error_Reporter; Connection : access GNATCOLL.SQL.Exec.Database_Connection_Record'Class; Message : in String) is pragma Unreferenced (Self, Connection); begin Ada.Text_IO.Put_Line ("gpr_query: sql error on create database: " & Message); end On_Error; -- For some reason, gnat community 2020 doesn't like this: -- overriding procedure On_Warning -- (Self : in out SQL_Error_Reporter; -- Connection : access GNATCOLL.SQL.Exec.Database_Connection_Record'Class; -- Message : in String) -- is begin -- Ada.Text_IO.Put_Line ("gpr_query: sql warning on create database: " & Message); -- end On_Warning; Error_Reporter : aliased SQL_Error_Reporter; begin Ada.Text_IO.Put_Line ("version: " & Version); declare use GNAT.Command_Line; begin Set_Usage (Cmdline, Help => "Query project info and cross-references on source code. See ada-mode docs for more help."); -- Switch variable alphabetic order Define_Switch (Cmdline, Output => ALI_Encoding'Access, Long_Switch => "--encoding=", Switch => "-e=", Help => "The character encoding used for source and ALI files"); Define_Switch (Cmdline, Output => Commands_From_Switch'Access, Switch => "-c:", Long_Switch => "--command=", Help => "Execute the commands from ARG, and exit"); Define_Switch (Cmdline, Output => DB_Name'Access, Long_Switch => "--db=", Help => "Specifies the name of the database file (or ':memory:')"); Define_Switch (Cmdline, Output => Force_Refresh'Access, Long_Switch => "--force_refresh", Help => "Force rebuilding the database."); Define_Switch (Cmdline, Output => Gpr_Config_File'Access, Long_Switch => "--autoconf=", Help => "Specify the gpr configuration file (.cgpr)"); Define_Switch (Cmdline, Output => Nightly_DB_Name'Access, Long_Switch => "--nightlydb=", Help => "Specifies the name of a prebuilt database"); Define_Switch (Cmdline, Output => Project_File_Name'Access, Switch => "-P:", Long_Switch => "--project=", Help => "Load the given project (mandatory)"); Define_Switch (Cmdline, Output => Show_Progress'Access, Long_Switch => "--display_progress", Switch => "-d", Help => "Show progress as LI files are parsed"); Define_Switch (Cmdline, Output => Traces_Config_File'Access, Long_Switch => "--tracefile=", Help => "Specify a traces configuration file, set projects lib verbose. File should contain ""gpr_query=yes"""); Getopt (Cmdline, Callback => null); exception when Exit_From_Command_Line => -- from "--help" return; end; if Project_File_Name.all = "" then Ada.Text_IO.Put_Line ("No project file specified"); GNAT.Command_Line.Display_Help (Cmdline); return; end if; -- Only trace if user specifies --tracefile if Traces_Config_File.all /= "" and then GNAT.OS_Lib.Is_Regular_File (Traces_Config_File.all) then GNATCOLL.Traces.Parse_Config_File (Filename => Traces_Config_File.all, Force_Activation => False); GNATCOLL.Traces.Trace (Me, "trace enabled"); end if; GNATCOLL.Projects.Initialize (Env); -- for register_default_language if Gpr_Config_File.all /= "" and then GNAT.OS_Lib.Is_Regular_File (Gpr_Config_File.all) then Env.Set_Config_File (GNATCOLL.VFS.Create_From_UTF8 (GNAT.OS_Lib.Normalize_Pathname (Name => Gpr_Config_File.all, Directory => GNAT.Directory_Operations.Get_Current_Dir))); else -- Apparently Ada language extensions are already registered (sigh) Env.Register_Default_Language_Extension (Language_Name => "C", Default_Spec_Suffix => ".h", Default_Body_Suffix => ".c"); Env.Register_Default_Language_Extension (Language_Name => "C++", Default_Spec_Suffix => ".hh", Default_Body_Suffix => ".cpp"); end if; declare use Ada.Environment_Variables; use Ada.Text_IO; use GNATCOLL.VFS; use GNATCOLL.VFS_Utils; Gpr_Project_Path : constant String := (if Exists ("GPR_PROJECT_PATH") then Ada.Directories.Current_Directory & GNAT.OS_Lib.Path_Separator & Value ("GPR_PROJECT_PATH") else Ada.Directories.Current_Directory); Path : constant Virtual_File := -- must be an absolute file name (if Is_Absolute_Path (+Project_File_Name.all) then Create_From_UTF8 (Project_File_Name.all, Normalize => True) else Locate_Regular_File (+Project_File_Name.all, From_Path (+Gpr_Project_Path))); begin GNATCOLL.Traces.Trace (Me, "GPR_PROJECT_PATH " & Gpr_Project_Path); if not Path.Is_Regular_File then declare Path : constant File_Array := From_Path (+Gpr_Project_Path); begin Put_Line (Project_File_Name.all & ": not found on path:"); for P of Path loop Put_Line (+Full_Name (P)); end loop; end; Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; GNATCOLL.Traces.Trace (Me, "project file " & (+Path.Full_Name)); if Show_Progress then Progress_Reporter := Display_Progress'Unrestricted_Access; end if; begin -- Recompute_View => True registers all the source files -- (among other things), so we will know that a .[ag]li -- belongs to this project Tree.Load (Path, Env, Errors => Ada.Text_IO.Put_Line'Access, Recompute_View => True); exception when GNATCOLL.Projects.Invalid_Project => Ada.Text_IO.Put_Line ("project search path:"); Put (GNATCOLL.Projects.Predefined_Project_Path (Env.all)); raise GNATCOLL.Projects.Invalid_Project with +Path.Full_Name & ": invalid project"; end; end; if DB_Name.all /= ":memory:" then declare use GNATCOLL.VFS; N : constant String := DB_Name.all; Temp : Virtual_File := Tree.Root_Project.Object_Dir; Dir2 : Virtual_File; begin GNAT.Strings.Free (DB_Name); -- If the project does not have an object directory, create -- the database in the directory containing the project file. if Temp = No_File then Temp := Tree.Root_Project.Project_Path.Dir; end if; Temp := Create_From_Base (Base_Dir => Temp.Full_Name.all, Base_Name => +N); Dir2 := Create (Temp.Dir_Name); if not Dir2.Is_Directory then Dir2.Make_Dir (Recursive => True); end if; DB_Name := new String'(Temp.Display_Full_Name); end; end if; declare -- Error if DB_Name does not exist but is in a read-only directory. -- The Errors parameter to Sqlite.Setup does not help here; it -- reports no error. Ada.Directories does not support a "writeable" -- query. use Ada.Directories; begin if DB_Name.all = ":memory:" then null; elsif Exists (DB_Name.all) then -- If this is read-only, we assume it is up to date and the user is -- just browsing. null; else declare use GNATCOLL.VFS; Dir_Name : constant String := Containing_Directory (DB_Name.all); Dir_File : constant Virtual_File := Create (Filesystem_String (Dir_Name)); begin if Is_Writable (Dir_File) then null; else raise DB_Error with "database file '" & DB_Name.all & "' does not exist, and directory is not writeable"; end if; end; end if; end; declare use type GNAT.Strings.String_Access; Error : GNAT.Strings.String_Access; begin GNATCOLL.Traces.Trace (Me, "using database " & DB_Name.all); Setup_DB (Self => Xref, Tree => Tree'Unchecked_Access, DB => GNATCOLL.SQL.Sqlite.Setup (Database => DB_Name.all, Errors => Error_Reporter'Unchecked_Access), Error => Error); if Error /= null then -- old db schema raise DB_Error with Error.all; end if; end; Process_Refresh (GNATCOLL.Arg_Lists.Empty_Command_Line); Source_Search_Path := new GNATCOLL.VFS.File_Array' (GNATCOLL.Projects.Source_Dirs (Project => Tree.Root_Project, Recursive => True) & GNATCOLL.Projects.Predefined_Source_Path (Env.all)); if Commands_From_Switch.all /= "" then Process_Line (Commands_From_Switch.all); return; end if; loop Ada.Text_IO.Put (">>> "); declare Input : constant String := Ada.Text_IO.Get_Line; begin exit when Input = "exit"; Process_Line (Input); exception when E : Invalid_Command => Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); Process_Help (GNATCOLL.Arg_Lists.Empty_Command_Line); end; end loop; exception when Ada.IO_Exceptions.End_Error => null; when E : GNATCOLL.Projects.Invalid_Project => Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); when E : DB_Error => Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); when E : Invalid_Command => Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); Process_Help (GNATCOLL.Arg_Lists.Empty_Command_Line); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); when GNAT.Command_Line.Invalid_Switch => GNAT.Command_Line.Display_Help (Cmdline); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); when E : others => Ada.Text_IO.Put_Line ("Unexpected exception"); Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Information (E)); Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (Ada.Exceptions.Traceback.Tracebacks (E))); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end Gpr_Query;
DrenfongWong/tkm-rpc
Ada
1,288
adb
with Tkmrpc.Servers.Ike; with Tkmrpc.Results; with Tkmrpc.Request.Ike.Isa_Sign.Convert; with Tkmrpc.Response.Ike.Isa_Sign.Convert; package body Tkmrpc.Operation_Handlers.Ike.Isa_Sign is ------------------------------------------------------------------------- procedure Handle (Req : Request.Data_Type; Res : out Response.Data_Type) is Specific_Req : Request.Ike.Isa_Sign.Request_Type; Specific_Res : Response.Ike.Isa_Sign.Response_Type; begin Specific_Res := Response.Ike.Isa_Sign.Null_Response; Specific_Req := Request.Ike.Isa_Sign.Convert.From_Request (S => Req); if Specific_Req.Data.Isa_Id'Valid and Specific_Req.Data.Lc_Id'Valid and Specific_Req.Data.Init_Message.Size'Valid then Servers.Ike.Isa_Sign (Result => Specific_Res.Header.Result, Isa_Id => Specific_Req.Data.Isa_Id, Lc_Id => Specific_Req.Data.Lc_Id, Init_Message => Specific_Req.Data.Init_Message, Signature => Specific_Res.Data.Signature); Res := Response.Ike.Isa_Sign.Convert.To_Response (S => Specific_Res); else Res.Header.Result := Results.Invalid_Parameter; end if; end Handle; end Tkmrpc.Operation_Handlers.Ike.Isa_Sign;
PThierry/ewok-kernel
Ada
10,158
ads
-- -- Copyright 2018 The wookey project team <[email protected]> -- - Ryad Benadjila -- - Arnauld Michelizza -- - Mathieu Renard -- - Philippe Thierry -- - Philippe Trebuchet -- -- 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 ewok.tasks_shared; use ewok.tasks_shared; with ewok.devices_shared; use ewok.devices_shared; with ewok.ipc; with ewok.exported.dma; with ewok.dma_shared; with soc; with soc.layout; package ewok.tasks with spark_mode => on is subtype t_task_name is string (1 .. 10); type t_task_state is ( -- No task in this slot TASK_STATE_EMPTY, -- Task can be elected by the scheduler with its standard priority -- or an ISR is ready for execution TASK_STATE_RUNNABLE, -- Force the scheduler to choose that task TASK_STATE_FORCED, -- Pending syscall. Task can't be scheduled. TASK_STATE_SVC_BLOCKED, -- An ISR is finished TASK_STATE_ISR_DONE, -- Task currently has nothing to do, not schedulable TASK_STATE_IDLE, -- Task is sleeping TASK_STATE_SLEEPING, -- Task is deeply sleeping TASK_STATE_SLEEPING_DEEP, -- Task has generated an exception (memory fault, etc.), not -- schedulable anymore TASK_STATE_FAULT, -- Task has return from its main() function. Yet its ISR handlers can -- still be executed if needed TASK_STATE_FINISHED, -- Task has emitted a blocking send() and is waiting for the -- receiver to emit a recv() TASK_STATE_IPC_SEND_BLOCKED, -- Task has emitted a blocking recv() and is waiting for a message TASK_STATE_IPC_RECV_BLOCKED, -- Task has emitted a blocking send() and is waiting an -- acknowledgement after the message has been received TASK_STATE_IPC_WAIT_ACK, -- Task has entered in a critical section. Related ISRs can't be executed TASK_STATE_LOCKED); type t_task_type is (-- Kernel task TASK_TYPE_KERNEL, -- User task, being executed in user mode, with restricted access TASK_TYPE_USER); type t_main_context is record frame_a : ewok.t_stack_frame_access := NULL; end record; type t_isr_context is record entry_point : system_address := 0; device_id : ewok.devices_shared.t_device_id := ID_DEV_UNUSED; sched_policy : ewok.tasks_shared.t_scheduling_post_isr := ISR_STANDARD; frame_a : ewok.t_stack_frame_access := NULL; end record; -- -- Tasks -- MAX_DEVS_PER_TASK : constant := 10; MAX_DMAS_PER_TASK : constant := 8; MAX_INTERRUPTS_PER_TASK : constant := 8; MAX_DMA_SHM_PER_TASK : constant := 4; type t_registered_dma_index_list is array (unsigned_32 range <>) of ewok.dma_shared.t_user_dma_index with default_component_value => ewok.dma_shared.ID_DMA_UNUSED; type t_dma_shm_info_list is array (unsigned_32 range <>) of ewok.exported.dma.t_dma_shm_info; type t_device is record device_id : ewok.devices_shared.t_device_id := ID_DEV_UNUSED; mounted : boolean := false; end record; type t_device_list is array (unsigned_8 range <>) of t_device; type t_ipc_endpoint_id_list is array (ewok.tasks_shared.t_task_id) of ewok.ipc.t_extended_endpoint_id with default_component_value => ewok.ipc.ID_ENDPOINT_UNUSED; type t_task is record name : t_task_name := " "; entry_point : system_address := 0; ttype : t_task_type := TASK_TYPE_USER; mode : t_task_mode := TASK_MODE_MAINTHREAD; id : ewok.tasks_shared.t_task_id := ID_UNUSED; slot : unsigned_8 := 0; -- 1: first slot (0: unused) num_slots : unsigned_8 := 0; prio : unsigned_8 := 0; #if CONFIG_KERNEL_DOMAIN domain : unsigned_8 := 0; #end if; #if CONFIG_KERNEL_SCHED_DEBUG count : unsigned_32 := 0; force_count : unsigned_32 := 0; isr_count : unsigned_32 := 0; #end if; num_dma_shms : unsigned_32 range 0 .. MAX_DMA_SHM_PER_TASK := 0; dma_shm : t_dma_shm_info_list (1 .. MAX_DMA_SHM_PER_TASK); num_dma_id : unsigned_32 range 0 .. MAX_DMAS_PER_TASK := 0; dma_id : t_registered_dma_index_list (1 .. MAX_DMAS_PER_TASK); num_devs : unsigned_8 range 0 .. MAX_DEVS_PER_TASK := 0; devices : t_device_list (1 .. MAX_DEVS_PER_TASK); init_done : boolean := false; data_slot_start : system_address := 0; data_slot_end : system_address := 0; txt_slot_start : system_address := 0; txt_slot_end : system_address := 0; stack_bottom : system_address := 0; stack_top : system_address := 0; stack_size : unsigned_16 := 0; state : t_task_state := TASK_STATE_EMPTY; isr_state : t_task_state := TASK_STATE_EMPTY; ipc_endpoint_id : t_ipc_endpoint_id_list; ctx : aliased t_main_context; isr_ctx : aliased t_isr_context; end record; type t_task_array is array (t_task_id range <>) of aliased t_task; ------------- -- Globals -- ------------- -- The list of the running tasks tasks_list : t_task_array (ID_APP1 .. ID_KERNEL); softirq_task_name : aliased t_task_name := "SOFTIRQ" & " "; idle_task_name : aliased t_task_name := "IDLE" & " "; --------------- -- Functions -- --------------- pragma assertion_policy (pre => IGNORE, post => IGNORE, assert => IGNORE); procedure idle_task with no_return; procedure finished_task with no_return; -- create various task's stack -- preconditions : -- Here we check that generated headers, defining stack address and -- program counter of various stack are valid for the currently -- supported SoC. This is a sanitizing function for generated files. procedure create_stack (sp : in system_address; pc : in system_address; params : in ewok.t_parameters; frame_a : out ewok.t_stack_frame_access) with -- precondition 1 : stack pointer must be in RAM pre => ( (sp >= soc.layout.USER_RAM_BASE and sp <= (soc.layout.USER_RAM_BASE + soc.layout.USER_RAM_SIZE)) or (sp >= soc.layout.KERNEL_RAM_BASE and sp <= (soc.layout.KERNEL_RAM_BASE + soc.layout.KERNEL_RAM_SIZE)) ) and ( -- precondition 2 : program counter must be in flash pc >= soc.layout.FLASH_BASE and pc <= soc.layout.FLASH_BASE + soc.layout.FLASH_SIZE ), global => ( in_out => tasks_list ); procedure set_default_values (tsk : out t_task); procedure init_softirq_task; procedure init_idle_task; procedure init_apps; function is_real_user (id : ewok.tasks_shared.t_task_id) return boolean; #if CONFIG_KERNEL_DOMAIN function get_domain (id : in ewok.tasks_shared.t_task_id) return unsigned_8 with inline; #end if; function get_task_id (name : t_task_name) return ewok.tasks_shared.t_task_id; procedure set_state (id : ewok.tasks_shared.t_task_id; mode : t_task_mode; state : t_task_state) with inline; function get_state (id : ewok.tasks_shared.t_task_id; mode : t_task_mode) return t_task_state with inline; function get_mode (id : in ewok.tasks_shared.t_task_id) return t_task_mode with inline, global => null; procedure set_mode (id : in ewok.tasks_shared.t_task_id; mode : in ewok.tasks_shared.t_task_mode) with inline, global => ( in_out => tasks_list ); function is_ipc_waiting (id : in ewok.tasks_shared.t_task_id) return boolean; -- Set return value inside a syscall -- Note: mode must be defined as a task can do a syscall while in ISR mode -- or in THREAD mode procedure set_return_value (id : in ewok.tasks_shared.t_task_id; mode : in t_task_mode; val : in unsigned_32) with inline; procedure task_init with global => null; function is_init_done (id : ewok.tasks_shared.t_task_id) return boolean; procedure append_device (id : in ewok.tasks_shared.t_task_id; dev_id : in ewok.devices_shared.t_device_id; descriptor : out unsigned_8; success : out boolean) with post => (if success = false then descriptor = 0 else descriptor > 0 and descriptor < tasks_list(id).devices'last); procedure remove_device (id : in ewok.tasks_shared.t_task_id; dev_descriptor : in unsigned_8); function is_mounted (id : in ewok.tasks_shared.t_task_id; dev_descriptor : in unsigned_8) return boolean; procedure mount_device (id : in ewok.tasks_shared.t_task_id; dev_descriptor : in unsigned_8; success : out boolean); procedure unmount_device (id : in ewok.tasks_shared.t_task_id; dev_descriptor : in unsigned_8; success : out boolean); end ewok.tasks;
mapcode-foundation/mapcode-ada
Ada
4,194
adb
-- ----------------------------------------------------------------------------- -- Copyright (C) 2003-2019 Stichting Mapcode Foundation (http://www.mapcode.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_Conversion; -- Suppress warning than System.Bit_Ops is an internal GNAT unit -- thus not portable pragma Warnings (Off, "* is an internal GNAT unit"); with System.Bit_Ops; pragma Warnings (On, "* is an internal GNAT unit"); with Interfaces; package body Mapcode_Utils.Bits is function To_Unsigned_32 is new Ada.Unchecked_Conversion (Source => Integer, Target => Interfaces.Unsigned_32); function To_Integer is new Ada.Unchecked_Conversion (Source => Interfaces.Unsigned_32, Target => Integer); function To_Unsigned_64 is new Ada.Unchecked_Conversion (Source => Ll_Integer, Target => Interfaces.Unsigned_64); function To_Ll_Integer is new Ada.Unchecked_Conversion (Source => Interfaces.Unsigned_64, Target => Ll_Integer); -- Integer function "And" (Left, Right : Integer) return Integer is Res : Integer; begin System.Bit_Ops.Bit_And (Left'Address, Left'Size, Right'Address, Right'Size, Res'Address); return Res; end "And"; function "Or" (Left, Right : Integer) return Integer is Res : Integer; begin System.Bit_Ops.Bit_Or (Left'Address, Left'Size, Right'Address, Right'Size, Res'Address); return Res; end "Or"; function "Xor" (Left, Right : Integer) return Integer is Res : Integer; begin System.Bit_Ops.Bit_Xor (Left'Address, Left'Size, Right'Address, Right'Size, Res'Address); return Res; end "Xor"; function "Not" (Val : Integer) return Integer is Res : Integer; begin System.Bit_Ops.Bit_Not (Val'Address, Val'Size, Res'Address); return Res; end "Not"; function Shl (Val : Integer; Bits : Integer) return Integer is (To_Integer(Interfaces.Shift_Left(To_Unsigned_32(Val), Bits))); function Shr (Val : Integer; Bits : Integer) return Integer is (To_Integer(Interfaces.Shift_Right(To_Unsigned_32(Val), Bits))); -- Long_Long_Integer function "And" (Left, Right : Ll_Integer) return Ll_Integer is Res : Ll_Integer; begin System.Bit_Ops.Bit_And (Left'Address, Left'Size, Right'Address, Right'Size, Res'Address); return Res; end "And"; function "Or" (Left, Right : Ll_Integer) return Ll_Integer is Res : Ll_Integer; begin System.Bit_Ops.Bit_Or (Left'Address, Left'Size, Right'Address, Right'Size, Res'Address); return Res; end "Or"; function "Xor" (Left, Right : Ll_Integer) return Ll_Integer is Res : Ll_Integer; begin System.Bit_Ops.Bit_Xor (Left'Address, Left'Size, Right'Address, Right'Size, Res'Address); return Res; end "Xor"; function "Not" (Val : Ll_Integer) return Ll_Integer is Res : Ll_Integer; begin System.Bit_Ops.Bit_Not (Val'Address, Val'Size, Res'Address); return Res; end "Not"; function Shl (Val : Ll_Integer; Bits : Integer) return Ll_Integer is (To_Ll_Integer(Interfaces.Shift_Left (To_Unsigned_64(Val), Bits))); function Shr (Val : Ll_Integer; Bits : Integer) return Ll_Integer is (To_Ll_Integer(Interfaces.Shift_Right (To_Unsigned_64(Val), Bits))); end Mapcode_Utils.Bits;
charlie5/cBound
Ada
1,909
ads
-- This file is generated by SWIG. Please do not modify by hand. -- with Interfaces; with swig; with Interfaces.C; with Interfaces.C.Pointers; package xcb.xcb_alloc_color_planes_reply_t is -- Item -- type Item is record response_type : aliased Interfaces.Unsigned_8; pad0 : aliased Interfaces.Unsigned_8; sequence : aliased Interfaces.Unsigned_16; length : aliased Interfaces.Unsigned_32; pixels_len : aliased Interfaces.Unsigned_16; pad1 : aliased swig.int8_t_Array (0 .. 1); red_mask : aliased Interfaces.Unsigned_32; green_mask : aliased Interfaces.Unsigned_32; blue_mask : aliased Interfaces.Unsigned_32; pad2 : aliased swig.int8_t_Array (0 .. 7); end record; -- Item_Array -- type Item_Array is array (Interfaces.C .size_t range <>) of aliased xcb.xcb_alloc_color_planes_reply_t .Item; -- Pointer -- package C_Pointers is new Interfaces.C.Pointers (Index => Interfaces.C.size_t, Element => xcb.xcb_alloc_color_planes_reply_t.Item, Element_Array => xcb.xcb_alloc_color_planes_reply_t.Item_Array, Default_Terminator => (others => <>)); subtype Pointer is C_Pointers.Pointer; -- Pointer_Array -- type Pointer_Array is array (Interfaces.C .size_t range <>) of aliased xcb.xcb_alloc_color_planes_reply_t .Pointer; -- Pointer_Pointer -- package C_Pointer_Pointers is new Interfaces.C.Pointers (Index => Interfaces.C.size_t, Element => xcb.xcb_alloc_color_planes_reply_t.Pointer, Element_Array => xcb.xcb_alloc_color_planes_reply_t.Pointer_Array, Default_Terminator => null); subtype Pointer_Pointer is C_Pointer_Pointers.Pointer; end xcb.xcb_alloc_color_planes_reply_t;
zhmu/ananas
Ada
2,913
ads
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S Y S T E M . F A T _ L F L T -- -- -- -- S p e c -- -- -- -- Copyright (C) 1992-2022, 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. -- -- -- ------------------------------------------------------------------------------ -- This package contains an instantiation of the floating-point attribute -- runtime routines for the type Long_Float. with System.Fat_Gen; package System.Fat_LFlt is pragma Pure; -- Note the only entity from this package that is accessed by Rtsfind -- is the name of the package instantiation. Entities within this package -- (i.e. the individual floating-point attribute routines) are accessed -- by name using selected notation. package Attr_Long_Float is new System.Fat_Gen (Long_Float); end System.Fat_LFlt;
msrLi/portingSources
Ada
798
adb
-- Copyright 2013-2014 Free Software Foundation, Inc. -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. with Const; use Const; procedure Foo is begin raise Aint_Global_GDB_E; end Foo;
ytomino/vampire
Ada
147
ads
-- The Village of Vampire by YT, このソースコードはNYSLです procedure Tabula.Users.Load ( Name : in String; Info : in out User_Info);
AdaCore/gpr
Ada
100
adb
with GNAT.IO; with p8_0; procedure p8 is begin GNAT.IO.Put_Line (p8_0.p8_0_0 (111)'Img); end p8;
Heziode/lsystem-editor
Ada
2,057
ads
------------------------------------------------------------------------------- -- LSE -- L-System Editor -- Author: Heziode -- -- License: -- MIT License -- -- Copyright (c) 2018 Quentin Dauprat (Heziode) <[email protected]> -- -- 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 LSE.Model.IO.Drawing_Area.Drawing_Area_Ptr; use LSE.Model.IO.Drawing_Area.Drawing_Area_Ptr; -- @description -- This package provide a drawing area factory -- package LSE.Model.IO.Drawing_Area_Factory is -- Make the drawing area -- @param Value Type of the drawing area -- @param Path Path where to save the L-System drawed procedure Make (This : out LSE.Model.IO.Drawing_Area.Drawing_Area_Ptr.Holder; Value : String; Path : String); private -- Available drawing areas (export format) type Available_Export is (PS); end LSE.Model.IO.Drawing_Area_Factory;
NCommander/dnscatcher
Ada
3,222
ads
-- Copyright 2019 Michael Casadevall <[email protected]> -- -- 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 DNSCatcher.DNS.Processor.Packet; use DNSCatcher.DNS.Processor.Packet; -- @summary -- RData Unknown_Parser is a catch-all for any RRTypes that do not have -- specific handling in this package. It exists to prevent crashes and to -- store these rrtypes in a generic form as a failsafe. -- -- @description -- The unknown packet parser is the last resort used by the RData package. -- Aside from the generic Type and TTL values, the unknown handler simply -- contains a binary representation of a given class -- package DNSCatcher.DNS.Processor.RData.Unknown_Parser is -- Unknown RData Type type Parsed_Unknown_RData is new DNSCatcher.DNS.Processor.RData.Parsed_RData with private; type Parsed_Unknown_RData_Access is access all Parsed_Unknown_RData; -- Converts a RR record to logicial representation -- -- @value This -- Class object -- -- @value DNS_Header -- DNS Packet Header -- -- @value Parsed_RR -- Any parsed Resource Record from Processor.Packet -- procedure From_Parsed_RR (This : in out Parsed_Unknown_RData; DNS_Header : DNS_Packet_Header; Parsed_RR : Parsed_DNS_Resource_Record); -- Represents RData as a String for debug logging -- -- @value This -- Class object -- -- @returns -- String saying "UNKNOWN" -- function RData_To_String (This : in Parsed_Unknown_RData) return String; -- Represents the resource record packet as a whole as a string -- -- @value This -- Class object -- -- @returns -- String that states "UNKNOWN" -- function Print_Packet (This : in Parsed_Unknown_RData) return String; -- Frees and deallocates the class object -- -- @value This -- Class object to deallocate -- procedure Delete (This : in out Parsed_Unknown_RData); private type Parsed_Unknown_RData is new DNSCatcher.DNS.Processor.RData .Parsed_RData with record RData : Unbounded_String; end record; end DNSCatcher.DNS.Processor.RData.Unknown_Parser;
reznikmm/matreshka
Ada
3,402
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Web Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2012, Vadim Godunko <[email protected]> -- -- 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 Web_Services is pragma Pure; end Web_Services;
ZinebZaad/ENSEEIHT
Ada
9,470
adb
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with SDA_Exceptions; use SDA_Exceptions; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; --! Les Unbounded_String ont une capacité variable, contrairement au String --! pour lesquelles une capacité doit être fixée. with LCA; procedure Test_LCA is package LCA_String_Integer is new LCA (T_Cle => Unbounded_String, T_Donnee => Integer); use LCA_String_Integer; -- Retourner une chaîne avec des guillemets autour de S function Avec_Guillemets (S: Unbounded_String) return String is begin return '"' & To_String (S) & '"'; end; -- Utiliser & entre String à gauche et Unbounded_String à droite. Des -- guillemets sont ajoutées autour de la Unbounded_String -- Il s'agit d'un masquage de l'opérteur & défini dans Strings.Unbounded function "&" (Left: String; Right: Unbounded_String) return String is begin return Left & Avec_Guillemets (Right); end; -- Surcharge l'opérateur unaire "+" pour convertir une String -- en Unbounded_String. -- Cette astuce permet de simplifier l'initialisation -- de cles un peu plus loin. function "+" (Item : in String) return Unbounded_String renames To_Unbounded_String; -- Afficher une Unbounded_String et un entier. procedure Afficher (S : in Unbounded_String; N: in Integer) is begin Put (Avec_Guillemets (S)); Put (" : "); Put (N, 1); New_Line; end Afficher; -- Afficher la Sda. procedure Afficher is new Pour_Chaque (Afficher); Nb_Cles : constant Integer := 7; Cles : constant array (1..Nb_Cles) of Unbounded_String := (+"un", +"deux", +"trois", +"quatre", +"cinq", +"quatre-vingt-dix-neuf", +"vingt-et-un"); Inconnu : constant Unbounded_String := To_Unbounded_String ("Inconnu"); Donnees : constant array (1..Nb_Cles) of Integer := (1, 2, 3, 4, 5, 99, 21); Somme_Donnees : constant Integer := 135; Somme_Donnees_Len4 : constant Integer := 7; -- somme si Length (Cle) = 4 Somme_Donnees_Q: constant Integer := 103; -- somme si initiale de Cle = 'q' -- Initialiser l'annuaire avec les Donnees et Cles ci-dessus. -- Attention, c'est à l'appelant de libérer la mémoire associée en -- utilisant Vider. -- Si Bavard est vrai, les insertions sont tracées (affichées). procedure Construire_Exemple_Sujet (Annuaire : out T_LCA; Bavard: Boolean := False) is begin Initialiser (Annuaire); pragma Assert (Est_Vide (Annuaire)); pragma Assert (Taille (Annuaire) = 0); for I in 1..Nb_Cles loop Enregistrer (Annuaire, Cles (I), Donnees (I)); if Bavard then Put_Line ("Après insertion de la clé " & Cles (I)); Afficher (Annuaire); New_Line; else null; end if; pragma Assert (not Est_Vide (Annuaire)); pragma Assert (Taille (Annuaire) = I); for J in 1..I loop pragma Assert (La_Donnee (Annuaire, Cles (J)) = Donnees (J)); end loop; for J in I+1..Nb_Cles loop pragma Assert (not Cle_Presente (Annuaire, Cles (J))); end loop; end loop; end Construire_Exemple_Sujet; procedure Tester_Exemple_Sujet is Annuaire : T_LCA; begin Construire_Exemple_Sujet (Annuaire, True); Vider (Annuaire); end Tester_Exemple_Sujet; -- Tester suppression en commençant par les derniers éléments ajoutés procedure Tester_Supprimer_Inverse is Annuaire : T_LCA; begin Put_Line ("=== Tester_Supprimer_Inverse..."); New_Line; Construire_Exemple_Sujet (Annuaire); for I in reverse 1..Nb_Cles loop Supprimer (Annuaire, Cles (I)); Put_Line ("Après suppression de " & Cles (I) & " :"); Afficher (Annuaire); New_Line; for J in 1..I-1 loop pragma Assert (Cle_Presente (Annuaire, Cles (J))); pragma Assert (La_Donnee (Annuaire, Cles (J)) = Donnees (J)); end loop; for J in I..Nb_Cles loop pragma Assert (not Cle_Presente (Annuaire, Cles (J))); end loop; end loop; Vider (Annuaire); end Tester_Supprimer_Inverse; -- Tester suppression en commençant les les premiers éléments ajoutés procedure Tester_Supprimer is Annuaire : T_LCA; begin Put_Line ("=== Tester_Supprimer..."); New_Line; Construire_Exemple_Sujet (Annuaire); for I in 1..Nb_Cles loop Put_Line ("Suppression de " & Cles (I) & " :"); Supprimer (Annuaire, Cles (I)); Afficher (Annuaire); New_Line; for J in 1..I loop pragma Assert (not Cle_Presente (Annuaire, Cles (J))); end loop; for J in I+1..Nb_Cles loop pragma Assert (Cle_Presente (Annuaire, Cles (J))); pragma Assert (La_Donnee (Annuaire, Cles (J)) = Donnees (J)); end loop; end loop; Vider (Annuaire); end Tester_Supprimer; procedure Tester_Supprimer_Un_Element is -- Tester supprimer sur un élément, celui à Indice dans Cles. procedure Tester_Supprimer_Un_Element (Indice: in Integer) is Annuaire : T_LCA; begin Construire_Exemple_Sujet (Annuaire); Put_Line ("Suppression de " & Cles (Indice) & " :"); Supprimer (Annuaire, Cles (Indice)); Afficher (Annuaire); New_Line; for J in 1..Nb_Cles loop if J = Indice then pragma Assert (not Cle_Presente (Annuaire, Cles (J))); else pragma Assert (Cle_Presente (Annuaire, Cles (J))); end if; end loop; Vider (Annuaire); end Tester_Supprimer_Un_Element; begin Put_Line ("=== Tester_Supprimer_Un_Element..."); New_Line; for I in 1..Nb_Cles loop Tester_Supprimer_Un_Element (I); end loop; end Tester_Supprimer_Un_Element; procedure Tester_Remplacer_Un_Element is -- Tester enregistrer sur un élément présent, celui à Indice dans Cles. procedure Tester_Remplacer_Un_Element (Indice: in Integer; Nouveau: in Integer) is Annuaire : T_LCA; begin Construire_Exemple_Sujet (Annuaire); Put_Line ("Remplacement de " & Cles (Indice) & " par " & Integer'Image(Nouveau) & " :"); enregistrer (Annuaire, Cles (Indice), Nouveau); Afficher (Annuaire); New_Line; for J in 1..Nb_Cles loop pragma Assert (Cle_Presente (Annuaire, Cles (J))); if J = Indice then pragma Assert (La_Donnee (Annuaire, Cles (J)) = Nouveau); else pragma Assert (La_Donnee (Annuaire, Cles (J)) = Donnees (J)); end if; end loop; Vider (Annuaire); end Tester_Remplacer_Un_Element; begin Put_Line ("=== Tester_Remplacer_Un_Element..."); New_Line; for I in 1..Nb_Cles loop Tester_Remplacer_Un_Element (I, 0); null; end loop; end Tester_Remplacer_Un_Element; procedure Tester_Supprimer_Erreur is Annuaire : T_LCA; begin begin Put_Line ("=== Tester_Supprimer_Erreur..."); New_Line; Construire_Exemple_Sujet (Annuaire); Supprimer (Annuaire, Inconnu); exception when Cle_Absente_Exception => null; when others => pragma Assert (False); end; Vider (Annuaire); end Tester_Supprimer_Erreur; procedure Tester_La_Donnee_Erreur is Annuaire : T_LCA; Inutile: Integer; begin begin Put_Line ("=== Tester_Supprimer_Erreur..."); New_Line; Construire_Exemple_Sujet (Annuaire); Inutile := La_Donnee (Annuaire, Inconnu); exception when Cle_Absente_Exception => null; when others => pragma Assert (False); end; Vider (Annuaire); end Tester_La_Donnee_Erreur; procedure Tester_Pour_chaque is Annuaire : T_LCA; Somme: Integer; procedure Sommer (Cle: Unbounded_String; Donnee: Integer) is begin Put (" + "); Put (Donnee, 2); New_Line; Somme := Somme + Donnee; end; procedure Sommer is new Pour_Chaque (Sommer); begin Put_Line ("=== Tester_Pour_Chaque..."); New_Line; Construire_Exemple_Sujet(Annuaire); Somme := 0; Sommer (Annuaire); pragma Assert (Somme = Somme_Donnees); Vider(Annuaire); New_Line; end Tester_Pour_chaque; procedure Tester_Pour_chaque_Somme_Si_Cle_Commence_Par_Q is Annuaire : T_LCA; Somme: Integer; procedure Sommer_Cle_Commence_Par_Q (Cle: Unbounded_String; Donnee: Integer) is begin if To_String (Cle) (1) = 'q' then Put (" + "); Put (Donnee, 2); New_Line; Somme := Somme + Donnee; else null; end if; end; procedure Sommer is new Pour_Chaque (Sommer_Cle_Commence_Par_Q); begin Put_Line ("=== Tester_Pour_Chaque_Somme_Si_Cle_Commence_Par_Q..."); New_Line; Construire_Exemple_Sujet(Annuaire); Somme := 0; Sommer (Annuaire); pragma Assert (Somme = Somme_Donnees_Q); Vider(Annuaire); New_Line; end Tester_Pour_chaque_Somme_Si_Cle_Commence_Par_Q; procedure Tester_Pour_chaque_Somme_Len4_Erreur is Annuaire : T_LCA; Somme: Integer; procedure Sommer_Len4_Erreur (Cle: Unbounded_String; Donnee: Integer) is Nouvelle_Exception: Exception; begin if Length (Cle) = 4 then Put (" + "); Put (Donnee, 2); New_Line; Somme := Somme + Donnee; else raise Nouvelle_Exception; end if; end; procedure Sommer is new Pour_Chaque (Sommer_Len4_Erreur); begin Put_Line ("=== Tester_Pour_Chaque_Somme_Len4_Erreur..."); New_Line; Construire_Exemple_Sujet(Annuaire); Somme := 0; Sommer (Annuaire); pragma Assert (Somme = Somme_Donnees_Len4); Vider(Annuaire); New_Line; end Tester_Pour_chaque_Somme_Len4_Erreur; begin Tester_Exemple_Sujet; Tester_Supprimer_Inverse; Tester_Supprimer; Tester_Supprimer_Un_Element; Tester_Remplacer_Un_Element; Tester_Supprimer_Erreur; Tester_La_Donnee_Erreur; Tester_Pour_chaque; Tester_Pour_chaque_Somme_Si_Cle_Commence_Par_Q; Tester_Pour_chaque_Somme_Len4_Erreur; Put_Line ("Fin des tests : OK."); end Test_LCA;
sungyeon/drake
Ada
2,118
adb
with Ada.Exception_Identification.From_Here; with System.Native_Credentials; with System.Zero_Terminated_Strings; with C.errno; with C.stdint; package body System.Native_Directories.Volumes is use Ada.Exception_Identification.From_Here; use type File_Size; use type C.signed_int; use type C.size_t; use type C.stdint.uint32_t; -- implementation function Is_Assigned (FS : File_System) return Boolean is begin return FS.Statistics.f_version /= 0; end Is_Assigned; procedure Get (Name : String; FS : aliased out File_System) is C_Name : C.char_array ( 0 .. Name'Length * Zero_Terminated_Strings.Expanding); begin Zero_Terminated_Strings.To_C (Name, C_Name (0)'Access); if C.sys.mount.statfs (C_Name (0)'Access, FS.Statistics'Access) < 0 then Raise_Exception (Named_IO_Exception_Id (C.errno.errno)); end if; end Get; function Size (FS : File_System) return File_Size is begin return File_Size (FS.Statistics.f_blocks) * File_Size (FS.Statistics.f_bsize); end Size; function Free_Space (FS : File_System) return File_Size is begin return File_Size (FS.Statistics.f_bfree) * File_Size (FS.Statistics.f_bsize); end Free_Space; function Owner (FS : File_System) return String is begin return Native_Credentials.User_Name (FS.Statistics.f_owner); end Owner; function Format_Name (FS : File_System) return String is begin return Zero_Terminated_Strings.Value ( FS.Statistics.f_fstypename (0)'Access); end Format_Name; function Directory (FS : File_System) return String is begin return Zero_Terminated_Strings.Value ( FS.Statistics.f_mntonname (0)'Access); end Directory; function Device (FS : File_System) return String is begin return Zero_Terminated_Strings.Value ( FS.Statistics.f_mntfromname (0)'Access); end Device; function Identity (FS : File_System) return File_System_Id is begin return FS.Statistics.f_fsid; end Identity; end System.Native_Directories.Volumes;
thorstel/Advent-of-Code-2018
Ada
2,281
adb
with Ada.Containers.Vectors; use Ada.Containers; with Ada.Text_IO; use Ada.Text_IO; procedure Day14 is package Natural_Vectors is new Vectors (Index_Type => Natural, Element_Type => Natural); Score_Board : Natural_Vectors.Vector; Part2_Goal : Natural_Vectors.Vector; Part2_Goal_Index : Natural := 0; Input : constant Natural := 165061; Elf1 : Natural := 0; Elf2 : Natural := 1; procedure Mix_Recipes is Sum : constant Natural := Score_Board (Elf1) + Score_Board (Elf2); Recipe1 : constant Natural := Sum / 10; Recipe2 : constant Natural := Sum mod 10; begin if Sum >= 10 then Score_Board.Append (Recipe1); end if; Score_Board.Append (Recipe2); Elf1 := (Elf1 + Score_Board (Elf1) + 1) mod Natural (Score_Board.Length); Elf2 := (Elf2 + Score_Board (Elf2) + 1) mod Natural (Score_Board.Length); end Mix_Recipes; begin -- Part 1 Score_Board.Append (3); Score_Board.Append (7); while Natural (Score_Board.Length) < (Input + 10) loop Mix_Recipes; end loop; Put ("Part 1 ="); for I in Input .. (Input + 9) loop Put (Natural'Image (Score_Board (I))); end loop; Put_Line (""); -- Part 2 Part2_Goal.Append (1); Part2_Goal.Append (6); Part2_Goal.Append (5); Part2_Goal.Append (0); Part2_Goal.Append (6); Part2_Goal.Append (1); Score_Board.Clear; Score_Board.Reserve_Capacity (2500000); Score_Board.Append (3); Score_Board.Append (7); Elf1 := 0; Elf2 := 1; Infinite_Loop : loop declare End_Index : constant Natural := Natural (Score_Board.Length); begin Mix_Recipes; for I in End_Index .. Natural (Score_Board.Length) - 1 loop if Score_Board (I) = Part2_Goal (Part2_Goal_Index) then Part2_Goal_Index := Part2_Goal_Index + 1; else Part2_Goal_Index := 0; end if; if Part2_Goal_Index = Natural (Part2_Goal.Length) then Put_Line ("Part 2 =" & Natural'Image (I - (Part2_Goal_Index - 1))); exit Infinite_Loop; end if; end loop; end; end loop Infinite_Loop; end Day14;
zertovitch/zip-ada
Ada
585
adb
with Ada.Text_IO; procedure Show_License (file : Ada.Text_IO.File_Type; source_with_license : String) is use Ada.Text_IO; begin New_Line (file); Put_Line (file, "| This software is free and open-source."); Put_Line (file, "| It is provided ""as is"", WITHOUT WARRANTY OF ANY KIND."); Put_Line (file, "| For the full license wording, see the header (copyright & MIT license)"); Put_Line (file, "| appearing on top of this software's source files."); Put_Line (file, "| In doubt, check the file: " & source_with_license); New_Line (file); end Show_License;
reznikmm/matreshka
Ada
4,726
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This class represents an instance of an Association, in the same way that -- Element represents an instance of a Class. ------------------------------------------------------------------------------ with AMF.CMOF.Associations; with AMF.Elements; with AMF.Links; package AMF.Internals.AMF_Links is type AMF_Link_Proxy is limited new AMF.Links.Link with record Id : AMF.Internals.AMF_Link; end record; type AMF_Link_Proxy_Access is access all AMF_Link_Proxy'Class; overriding function Get_Association (Self : not null access constant AMF_Link_Proxy) return not null AMF.CMOF.Associations.CMOF_Association_Access; -- This is the Association of which the Link is an instance. overriding function Get_First_End (Self : not null access constant AMF_Link_Proxy) return not null AMF.Elements.Element_Access; -- This is the Element associated with the first end of the Association. overriding function Get_Second_End (Self : not null access constant AMF_Link_Proxy) return not null AMF.Elements.Element_Access; -- This is the Element associated with the second end of the Association. overriding procedure Delete (Self : not null access constant AMF_Link_Proxy); -- Deletes the Link. This may leave the same elements associated by other -- links for this Association. end AMF.Internals.AMF_Links;
stcarrez/babel
Ada
2,684
ads
----------------------------------------------------------------------- -- babel-streams-cached -- Cached stream management -- Copyright (C) 2014, 2015 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- 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. ----------------------------------------------------------------------- -- == Cached Stream == -- The <tt>Babel.Streams.Cached</tt> package provides a cached stream where the whole -- stream is read in one or several stream buffers. package Babel.Streams.Cached is type Stream_Type is new Babel.Streams.Stream_Type with private; type Stream_Access is access all Stream_Type'Class; -- Load the file stream into the cache and use the buffer pool to obtain more buffers -- for the cache. procedure Load (Stream : in out Stream_Type; File : in out Babel.Streams.Stream_Type'Class; Pool : in out Babel.Files.Buffers.Buffer_Pool); -- Read the data stream as much as possible and return the result in a buffer. -- The buffer is owned by the stream and need not be released. The same buffer may -- or may not be returned by the next <tt>Read</tt> operation. -- A null buffer is returned when the end of the data stream is reached. overriding procedure Read (Stream : in out Stream_Type; Buffer : out Babel.Files.Buffers.Buffer_Access); -- Write the buffer in the data stream. overriding procedure Write (Stream : in out Stream_Type; Buffer : in Babel.Files.Buffers.Buffer_Access); -- Prepare to read again the data stream from the beginning. overriding procedure Rewind (Stream : in out Stream_Type); private type Stream_Type is new Babel.Streams.Stream_Type with record Input : Babel.Streams.Stream_Access; Output : Babel.Streams.Stream_Access; Buffers : Babel.Files.Buffers.Buffer_Access_Vector; Current : Babel.Files.Buffers.Buffer_Access_Cursor; end record; -- Release the buffers associated with the cache. overriding procedure Finalize (Stream : in out Stream_Type); end Babel.Streams.Cached;
reznikmm/matreshka
Ada
5,825
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Localization, Internationalization, Globalization for Ada -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014-2016, Vadim Godunko <[email protected]> -- -- 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$ ------------------------------------------------------------------------------ private with Ada.Containers.Vectors; with Ada.Streams; private with League.JSON.Arrays; with League.JSON.Documents; private with League.JSON.Objects; with League.JSON.Values; with League.Strings; package League.JSON.Streams is pragma Preelaborate; type JSON_Stream is new Ada.Streams.Root_Stream_Type with private; procedure Start_Object (Self : not null access JSON_Stream'Class); procedure End_Object (Self : not null access JSON_Stream'Class); procedure Start_Array (Self : not null access JSON_Stream'Class); procedure End_Array (Self : not null access JSON_Stream'Class); function End_Of_Array (Self : not null access JSON_Stream'Class) return Boolean; -- Returns True when there are no array elements to be read. procedure Key (Self : not null access JSON_Stream'Class; Key : League.Strings.Universal_String); function Get_JSON_Document (Self : not null access JSON_Stream'Class) return League.JSON.Documents.JSON_Document; procedure Set_JSON_Document (Self : not null access JSON_Stream'Class; Data : League.JSON.Documents.JSON_Document); function Read (Self : in out JSON_Stream'Class) return League.JSON.Values.JSON_Value; -- Reads current value and updates stream's position. procedure Write (Self : in out JSON_Stream'Class; Item : League.JSON.Values.JSON_Value); -- Writes value into the stream and updates stream's position. private type State_Kinds is (Array_State, Object_State); type State (Kind : State_Kinds := Array_State) is record Modified : Boolean := False; case Kind is when Array_State => Current_Array : League.JSON.Arrays.JSON_Array; Index : Positive := 1; when Object_State => Current_Object : League.JSON.Objects.JSON_Object; Key : League.Strings.Universal_String; end case; end record; package State_Vectors is new Ada.Containers.Vectors (Positive, State); type JSON_Stream is new Ada.Streams.Root_Stream_Type with record Current : State; Stack : State_Vectors.Vector; end record; overriding procedure Read (Stream : in out JSON_Stream; Item : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); overriding procedure Write (Stream : in out JSON_Stream; Item : Ada.Streams.Stream_Element_Array); end League.JSON.Streams;
reznikmm/matreshka
Ada
3,840
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2012-2013, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This file is generated, don't edit it. ------------------------------------------------------------------------------ with AMF.OCL.Literal_Exps; package AMF.OCL.Invalid_Literal_Exps is pragma Preelaborate; type OCL_Invalid_Literal_Exp is limited interface and AMF.OCL.Literal_Exps.OCL_Literal_Exp; type OCL_Invalid_Literal_Exp_Access is access all OCL_Invalid_Literal_Exp'Class; for OCL_Invalid_Literal_Exp_Access'Storage_Size use 0; end AMF.OCL.Invalid_Literal_Exps;
reznikmm/matreshka
Ada
6,353
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Localization, Internationalization, Globalization for Ada -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2013, Vadim Godunko <[email protected]> -- -- 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$ ------------------------------------------------------------------------------ -- Code related to LZMA compression method. with Interfaces; with Ada.Streams; package Matreshka.Filters.LZMA is pragma Preelaborate; type XZ_Magic_Bytes is array (Ada.Streams.Stream_Element_Offset range 1 .. 6) of Ada.Streams.Stream_Element; type XZ_Stream_Header is record Magic : XZ_Magic_Bytes; Flags : Interfaces.Unsigned_16; CRC32 : Interfaces.Unsigned_32; end record; type XZ_Block_Header is record Header_Size : Ada.Streams.Stream_Element_Offset; Flags : Interfaces.Unsigned_8; Compressed_Size : Interfaces.Unsigned_64; Uncompressed_Size : Interfaces.Unsigned_64; Filter_Id : Interfaces.Unsigned_8; Filter_Prop : Interfaces.Unsigned_8; Padding_1 : Interfaces.Unsigned_8; Padding_2 : Interfaces.Unsigned_8; Padding_3 : Interfaces.Unsigned_8; CRC32 : Interfaces.Unsigned_32; Dictionary_Size : Ada.Streams.Stream_Element_Offset; end record; -- function Has_Compressed_Size (Self : XZ_Block_Header) return Boolean; -- function Has_Uncompressed_Size (Self : XZ_Block_Header) return Boolean; type XZ_Packet_Header is record Control_Byte : Interfaces.Unsigned_8; Last_Packet : Boolean; Dictionary_Reset : Boolean; Compressed_Chunk : Boolean; State_Reset : Boolean; Properties_Reset : Boolean; Compressed_Size : Ada.Streams.Stream_Element_Offset; Uncompressed_Size : Ada.Streams.Stream_Element_Offset; end record; -- This enum is used to track which LZMA symbols have occurred most recently -- and in which order. This information is used to predict the next symbol. -- -- Symbols: -- - Literal: One 8-bit byte -- - Match: Repeat a chunk of data at some distance -- - Long repeat: Multi-byte match at a recently seen distance -- - Short repeat: One-byte repeat at a recently seen distance -- -- The symbol names are in from STATE_oldest_older_previous. REP means -- either short or long repeated match, and NONLIT means any non-literal. type State is (STATE_LIT_LIT, STATE_MATCH_LIT_LIT, STATE_REP_LIT_LIT, STATE_SHORTREP_LIT_LIT, STATE_MATCH_LIT, STATE_REP_LIT, STATE_SHORTREP_LIT, STATE_LIT_MATCH, STATE_LIT_LONGREP, STATE_LIT_SHORTREP, STATE_NONLIT_MATCH, STATE_NONLIT_REP); subtype Literal_State is State range STATE_LIT_LIT .. STATE_SHORTREP_LIT; type Packet_Name is (Lit, Match, Short_Rep, Long_Rep); -- Maximum number of position states. A position state is the lowest pb -- number of bits of the current uncompressed offset. In some places there -- are different sets of probabilities for different position states. POS_STATES_BITS : constant := 4; POS_STATES_MAX : constant := 2 ** POS_STATES_BITS; -- (1 << 4) use type Ada.Streams.Stream_Element_Count; type Position_State_Index is mod POS_STATES_MAX; end Matreshka.Filters.LZMA;
stcarrez/ada-security
Ada
3,588
ads
----------------------------------------------------------------------- -- security-auth-oauth -- OAuth based authentication -- Copyright (C) 2013, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- 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 Security.OAuth.Clients; private package Security.Auth.OAuth is -- ------------------------------ -- OAuth Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OAuth authorization process. type Manager is abstract new Security.Auth.Manager with private; -- Initialize the authentication realm. overriding procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Provider : in String := PROVIDER_OPENID); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- Read the XRDS document from the URI and initialize the OpenID provider end point. -- (See OpenID Section 7.3 Discovery) overriding procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) overriding procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. overriding function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result overriding procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the OAuth access token and retrieve information about the user. procedure Verify_Access_Token (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Token : in Security.OAuth.Clients.Access_Token_Access; Result : in out Authentication) is abstract; private type Manager is abstract new Security.Auth.Manager with record Return_To : Unbounded_String; Realm : Unbounded_String; Scope : Unbounded_String; Issuer : Unbounded_String; App : Security.OAuth.Clients.Application; end record; end Security.Auth.OAuth;
charlie5/lace
Ada
1,535
ads
with freetype_c.Pointers; package freetype_c.pointer_Pointers is use freetype_c.Pointers; type FT_UShort_Pointer_Pointer is access all FT_UShort_Pointer; type FT_Int_Pointer_Pointer is access all FT_Int_Pointer; type FT_UInt_Pointer_Pointer is access all FT_UInt_Pointer; type FT_Long_Pointer_Pointer is access all FT_Long_Pointer; type FT_ULong_Pointer_Pointer is access all FT_ULong_Pointer; type FT_Fixed_Pointer_Pointer is access all FT_Fixed_Pointer; type FT_Pos_Pointer_Pointer is access all FT_Pos_Pointer; type FT_Error_Pointer_Pointer is access all FT_Error_Pointer; type FT_Encoding_Pointer_Pointer is access all FT_Encoding_Pointer; type FT_F26Dot6_Pointer_Pointer is access all FT_F26Dot6_Pointer; type FT_Int32_Pointer_Pointer is access all FT_Int32_Pointer; type FT_UInt32_Pointer_Pointer is access all FT_UInt32_Pointer; type FT_Render_Mode_Pointer_Pointer is access all FT_Render_Mode_Pointer; type FT_Outline_Pointer_Pointer is access all FT_Outline_Pointer; type FT_LibraryRec_Pointer_Pointer is access all FT_LibraryRec_Pointer; type FT_GlyphSlotRec_Pointer_Pointer is access all FT_GlyphSlotRec_Pointer; type FT_FaceRec_Pointer_Pointer is access all FT_FaceRec_Pointer; type FT_Kerning_Mode_Pointer_Pointer is access all FT_Kerning_Mode_Pointer; type FT_SizeRec_Pointer_Pointer is access all FT_SizeRec_Pointer; end freetype_c.pointer_Pointers;
reznikmm/matreshka
Ada
3,734
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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$ ------------------------------------------------------------------------------ with XML.DOM.Attributes; package ODF.DOM.Draw_Guide_Overhang_Attributes is pragma Preelaborate; type ODF_Draw_Guide_Overhang_Attribute is limited interface and XML.DOM.Attributes.DOM_Attribute; type ODF_Draw_Guide_Overhang_Attribute_Access is access all ODF_Draw_Guide_Overhang_Attribute'Class with Storage_Size => 0; end ODF.DOM.Draw_Guide_Overhang_Attributes;
flyx/OpenGLAda
Ada
1,708
ads
-- part of OpenGLAda, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "COPYING" with Interfaces.C; package GL is pragma Preelaborate; package C renames Interfaces.C; ----------------------------------------------------------------------------- -- Basics -- ----------------------------------------------------------------------------- -- this is an OpenGLAda-specific procedure that must be called once at -- startup and loads all function pointers for post-1.1 OpenGL functionality. -- it is idempotent (i.e. can be called multiple times without further -- effect). procedure Init; procedure Flush; procedure Finish; -- index types for vectors and matrices type Index_Homogeneous is (X, Y, Z, W); subtype Index_3D is Index_Homogeneous range X .. Z; subtype Index_2D is Index_Homogeneous range X .. Y; -- raised when a function that is not available for the current context -- is called. Feature_Not_Supported_Exception : exception; -- raised when OpenGLAda does not support a certain OpenGL feature -- (either because it's too new and has not yet been wrapped, or because -- it's so deprecated that you shouldn't use it anyway) Not_Implemented_Exception : exception; private ----------------------------------------------------------------------------- -- Internal functions -- ----------------------------------------------------------------------------- procedure Raise_Exception_On_OpenGL_Error; pragma Inline (Raise_Exception_On_OpenGL_Error); end GL;
persan/A-gst
Ada
10,865
ads
pragma Ada_2005; pragma Style_Checks (Off); pragma Warnings (Off); with Interfaces.C; use Interfaces.C; with GLIB; -- with GStreamer.GST_Low_Level.glibconfig_h; with glib; with glib.Values; with System; package GStreamer.GST_Low_Level.gstreamer_0_10_gst_rtp_gstrtppayloads_h is GST_RTP_PAYLOAD_G723_63 : constant := 16; -- gst/rtp/gstrtppayloads.h:110 GST_RTP_PAYLOAD_G723_53 : constant := 17; -- gst/rtp/gstrtppayloads.h:111 GST_RTP_PAYLOAD_TS48 : constant := 18; -- gst/rtp/gstrtppayloads.h:112 GST_RTP_PAYLOAD_TS41 : constant := 19; -- gst/rtp/gstrtppayloads.h:113 GST_RTP_PAYLOAD_G723_63_STRING : aliased constant String := "16" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:115 GST_RTP_PAYLOAD_G723_53_STRING : aliased constant String := "17" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:116 GST_RTP_PAYLOAD_TS48_STRING : aliased constant String := "18" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:117 GST_RTP_PAYLOAD_TS41_STRING : aliased constant String := "19" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:118 GST_RTP_PAYLOAD_PCMU_STRING : aliased constant String := "0" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:123 GST_RTP_PAYLOAD_1016_STRING : aliased constant String := "1" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:124 GST_RTP_PAYLOAD_G721_STRING : aliased constant String := "2" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:125 GST_RTP_PAYLOAD_GSM_STRING : aliased constant String := "3" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:126 GST_RTP_PAYLOAD_G723_STRING : aliased constant String := "4" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:127 GST_RTP_PAYLOAD_DVI4_8000_STRING : aliased constant String := "5" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:128 GST_RTP_PAYLOAD_DVI4_16000_STRING : aliased constant String := "6" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:129 GST_RTP_PAYLOAD_LPC_STRING : aliased constant String := "7" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:130 GST_RTP_PAYLOAD_PCMA_STRING : aliased constant String := "8" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:131 GST_RTP_PAYLOAD_G722_STRING : aliased constant String := "9" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:132 GST_RTP_PAYLOAD_L16_STEREO_STRING : aliased constant String := "10" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:133 GST_RTP_PAYLOAD_L16_MONO_STRING : aliased constant String := "11" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:134 GST_RTP_PAYLOAD_QCELP_STRING : aliased constant String := "12" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:135 GST_RTP_PAYLOAD_CN_STRING : aliased constant String := "13" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:136 GST_RTP_PAYLOAD_MPA_STRING : aliased constant String := "14" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:137 GST_RTP_PAYLOAD_G728_STRING : aliased constant String := "15" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:138 GST_RTP_PAYLOAD_DVI4_11025_STRING : aliased constant String := "16" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:139 GST_RTP_PAYLOAD_DVI4_22050_STRING : aliased constant String := "17" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:140 GST_RTP_PAYLOAD_G729_STRING : aliased constant String := "18" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:141 GST_RTP_PAYLOAD_CELLB_STRING : aliased constant String := "25" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:143 GST_RTP_PAYLOAD_JPEG_STRING : aliased constant String := "26" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:144 GST_RTP_PAYLOAD_NV_STRING : aliased constant String := "28" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:145 GST_RTP_PAYLOAD_H261_STRING : aliased constant String := "31" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:147 GST_RTP_PAYLOAD_MPV_STRING : aliased constant String := "32" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:148 GST_RTP_PAYLOAD_MP2T_STRING : aliased constant String := "33" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:149 GST_RTP_PAYLOAD_H263_STRING : aliased constant String := "34" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:150 GST_RTP_PAYLOAD_DYNAMIC_STRING : aliased constant String := "[96, 127]" & ASCII.NUL; -- gst/rtp/gstrtppayloads.h:152 -- arg-macro: function GST_RTP_PAYLOAD_IS_DYNAMIC (pt) -- return (pt) >= 96 and then (pt) <= 127; -- GStreamer -- * Copyright (C) <2007> Wim Taymans <[email protected]> -- * -- * gstrtppayloads.h: various helper functions to deal with RTP payload -- * types. -- * -- * This library is free software; you can redistribute it and/or -- * modify it under the terms of the GNU Library 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 -- * Library General Public License for more details. -- * -- * You should have received a copy of the GNU Library 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. -- --* -- * GstRTPPayload: -- * @GST_RTP_PAYLOAD_PCMU: ITU-T G.711. mu-law audio (RFC 3551) -- * @GST_RTP_PAYLOAD_1016: RFC 3551 says reserved -- * @GST_RTP_PAYLOAD_G721: RFC 3551 says reserved -- * @GST_RTP_PAYLOAD_GSM: GSM audio -- * @GST_RTP_PAYLOAD_G723: ITU G.723.1 audio -- * @GST_RTP_PAYLOAD_DVI4_8000: IMA ADPCM wave type (RFC 3551) -- * @GST_RTP_PAYLOAD_DVI4_16000: IMA ADPCM wave type (RFC 3551) -- * @GST_RTP_PAYLOAD_LPC: experimental linear predictive encoding -- * @GST_RTP_PAYLOAD_PCMA: ITU-T G.711 A-law audio (RFC 3551) -- * @GST_RTP_PAYLOAD_G722: ITU-T G.722 (RFC 3551) -- * @GST_RTP_PAYLOAD_L16_STEREO: stereo PCM -- * @GST_RTP_PAYLOAD_L16_MONO: mono PCM -- * @GST_RTP_PAYLOAD_QCELP: EIA & TIA standard IS-733 -- * @GST_RTP_PAYLOAD_CN: Comfort Noise (RFC 3389) -- * @GST_RTP_PAYLOAD_MPA: Audio MPEG 1-3. -- * @GST_RTP_PAYLOAD_G728: ITU-T G.728 Speech coder (RFC 3551) -- * @GST_RTP_PAYLOAD_DVI4_11025: IMA ADPCM wave type (RFC 3551) -- * @GST_RTP_PAYLOAD_DVI4_22050: IMA ADPCM wave type (RFC 3551) -- * @GST_RTP_PAYLOAD_G729: ITU-T G.729 Speech coder (RFC 3551) -- * @GST_RTP_PAYLOAD_CELLB: See RFC 2029 -- * @GST_RTP_PAYLOAD_JPEG: ISO Standards 10918-1 and 10918-2 (RFC 2435) -- * @GST_RTP_PAYLOAD_NV: nv encoding by Ron Frederick -- * @GST_RTP_PAYLOAD_H261: ITU-T Recommendation H.261 (RFC 2032) -- * @GST_RTP_PAYLOAD_MPV: Video MPEG 1 & 2 (RFC 2250) -- * @GST_RTP_PAYLOAD_MP2T: MPEG-2 transport stream (RFC 2250) -- * @GST_RTP_PAYLOAD_H263: Video H263 (RFC 2190) -- * -- * -- * Standard predefined fixed payload types. -- * -- * The official list is at: -- * http://www.iana.org/assignments/rtp-parameters -- * -- * Audio: -- * reserved: 19 -- * unassigned: 20-23, -- * -- * Video: -- * unassigned: 24, 27, 29, 30, 35-71, 77-95 -- * Reserved for RTCP conflict avoidance: 72-76 -- -- Audio: -- RFC 3551 says reserved -- RFC 3551 says reserved -- Video: -- BOTH subtype GstRTPPayload is unsigned; GST_RTP_PAYLOAD_PCMU : constant GstRTPPayload := 0; GST_RTP_PAYLOAD_1016 : constant GstRTPPayload := 1; GST_RTP_PAYLOAD_G721 : constant GstRTPPayload := 2; GST_RTP_PAYLOAD_GSM : constant GstRTPPayload := 3; GST_RTP_PAYLOAD_G723 : constant GstRTPPayload := 4; GST_RTP_PAYLOAD_DVI4_8000 : constant GstRTPPayload := 5; GST_RTP_PAYLOAD_DVI4_16000 : constant GstRTPPayload := 6; GST_RTP_PAYLOAD_LPC : constant GstRTPPayload := 7; GST_RTP_PAYLOAD_PCMA : constant GstRTPPayload := 8; GST_RTP_PAYLOAD_G722 : constant GstRTPPayload := 9; GST_RTP_PAYLOAD_L16_STEREO : constant GstRTPPayload := 10; GST_RTP_PAYLOAD_L16_MONO : constant GstRTPPayload := 11; GST_RTP_PAYLOAD_QCELP : constant GstRTPPayload := 12; GST_RTP_PAYLOAD_CN : constant GstRTPPayload := 13; GST_RTP_PAYLOAD_MPA : constant GstRTPPayload := 14; GST_RTP_PAYLOAD_G728 : constant GstRTPPayload := 15; GST_RTP_PAYLOAD_DVI4_11025 : constant GstRTPPayload := 16; GST_RTP_PAYLOAD_DVI4_22050 : constant GstRTPPayload := 17; GST_RTP_PAYLOAD_G729 : constant GstRTPPayload := 18; GST_RTP_PAYLOAD_CELLB : constant GstRTPPayload := 25; GST_RTP_PAYLOAD_JPEG : constant GstRTPPayload := 26; GST_RTP_PAYLOAD_NV : constant GstRTPPayload := 28; GST_RTP_PAYLOAD_H261 : constant GstRTPPayload := 31; GST_RTP_PAYLOAD_MPV : constant GstRTPPayload := 32; GST_RTP_PAYLOAD_MP2T : constant GstRTPPayload := 33; GST_RTP_PAYLOAD_H263 : constant GstRTPPayload := 34; -- gst/rtp/gstrtppayloads.h:107 -- backward compatibility -- Defining the above as strings, to make the declaration of pad_templates -- * easier. So if please keep these synchronized with the above. -- --* -- * GST_RTP_PAYLOAD_IS_DYNAMIC: -- * @pt: a payload type -- * -- * Check if @pt is a dynamic payload type. -- type GstRTPPayloadInfo; --subtype GstRTPPayloadInfo is u_GstRTPPayloadInfo; -- gst/rtp/gstrtppayloads.h:162 --* -- * GstRTPPayloadInfo: -- * @payload_type: payload type, -1 means dynamic -- * @media: the media type(s), usually "audio", "video", "application", "text", -- * "message". -- * @encoding_name: the encoding name of @pt -- * @clock_rate: default clock rate, 0 = unknown/variable -- * @encoding_parameters: encoding parameters. For audio this is the number of -- * channels. NULL = not applicable. -- * @bitrate: the bitrate of the media. 0 = unknown/variable. -- * -- * Structure holding default payload type information. -- type GstRTPPayloadInfo is record payload_type : aliased GLIB.guint8; -- gst/rtp/gstrtppayloads.h:179 media : access GLIB.gchar; -- gst/rtp/gstrtppayloads.h:180 encoding_name : access GLIB.gchar; -- gst/rtp/gstrtppayloads.h:181 clock_rate : aliased GLIB.guint; -- gst/rtp/gstrtppayloads.h:182 encoding_parameters : access GLIB.gchar; -- gst/rtp/gstrtppayloads.h:183 bitrate : aliased GLIB.guint; -- gst/rtp/gstrtppayloads.h:184 end record; pragma Convention (C_Pass_By_Copy, GstRTPPayloadInfo); -- gst/rtp/gstrtppayloads.h:177 function gst_rtp_payload_info_for_pt (payload_type : GLIB.guint8) return access constant GstRTPPayloadInfo; -- gst/rtp/gstrtppayloads.h:187 pragma Import (C, gst_rtp_payload_info_for_pt, "gst_rtp_payload_info_for_pt"); function gst_rtp_payload_info_for_name (media : access GLIB.gchar; encoding_name : access GLIB.gchar) return access constant GstRTPPayloadInfo; -- gst/rtp/gstrtppayloads.h:188 pragma Import (C, gst_rtp_payload_info_for_name, "gst_rtp_payload_info_for_name"); end GStreamer.GST_Low_Level.gstreamer_0_10_gst_rtp_gstrtppayloads_h;
zhmu/ananas
Ada
353
adb
-- { dg-do compile } -- { dg-options "-gnatVa" } procedure Range_Check7 is type Short is range -32768 .. 32767; type Int is range -2 ** 31 .. 2 ** 31 - 1; subtype Nat is Int range 0 .. Int'Last; type Ptr is access all Short; procedure Proc (P : Ptr) is N : constant Nat := Nat (P.all); begin null; end; begin null; end;
charlesdaniels/libagar
Ada
2,176
ads
with Agar; with Agar.Object; with Agar.Data_Source; with System.Address_To_Access_Conversions; with Interfaces.C; -- -- Example of an Agar object class called "Animal". -- package Animal is package OBJ renames Agar.Object; package DS renames Agar.Data_Source; package C renames Interfaces.C; use type C.int; use type C.C_float; use type C.double; Success : constant C.int := 0; Error : constant C.int := -1; ----------------------- -- Class Description -- ----------------------- type Ecological_Group_t is (Undefined, Carnivore, Herbivore, Omnivore, Detritivore, Parasite); type Animal_Class is limited record Class : OBJ.Class; -- Agar(Object) -> Animal -- more fields -- Ecological_Group : Ecological_Group_t; Description : String (1 .. 200); end record with Convention => C; type Animal_Class_Access is access all Animal_Class with Convention => C; --------------------- -- Object Instance -- --------------------- type Animal is limited record Object : OBJ.Object; -- Agar(Object) -> Animal -- more fields -- Age : Interfaces.Unsigned_8; Exp : Interfaces.Unsigned_16; Name : String (1 .. 20); Bio : String (1 .. 100); X : C.double; Y : C.double; Z : C.double; end record with Convention => C; type Animal_Access is access all Animal with Convention => C; package C_cls is new System.Address_To_Access_Conversions (Animal_Class); Generic_Object_Class : OBJ.Class_Access := null; Animal_Object_Class : C_cls.Object_Pointer := null; function Create_Class return OBJ.Class_Not_Null_Access; procedure Destroy_Class; procedure Init (Object : OBJ.Object_Access) with Convention => C; procedure Destroy (Object : OBJ.Object_Access) with Convention => C; function Load (Object : OBJ.Object_Access; Source : DS.Data_Source_Access; Version : OBJ.Version_Access) return C.int with Convention => C; function Save (Object : OBJ.Object_Access; Dest : DS.Data_Source_Access) return C.int with Convention => C; end Animal;
AdaCore/Ada_Drivers_Library
Ada
5,479
adb
------------------------------------------------------------------------------ -- -- -- Copyright (C) 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 nRF51.Tasks; with nRF51.Events; with nRF51.Radio; use nRF51.Radio; with nRF51.Clock; use nRF51.Clock; with Bluetooth_Low_Energy.Packets; use Bluetooth_Low_Energy.Packets; with Bluetooth_Low_Energy; use Bluetooth_Low_Energy; with Bluetooth_Low_Energy.Beacon; use Bluetooth_Low_Energy.Beacon; with HAL; use HAL; package body Beacon is Current_Adv_Channel : BLE_Advertising_Channel_Number := 37; Beacon_Packet : BLE_Packet; ---------------------- -- Initialize_Radio -- ---------------------- procedure Initialize_Radio is Beacon_UUID : constant BLE_UUID := Make_UUID ((1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)); begin Beacon_Packet := Make_Beacon_Packet (MAC => (16#A1#, 16#AD#, 16#A1#, 16#AD#, 16#A1#, 16#AD#), UUID => Beacon_UUID, Major => 0, Minor => 0, Power => 0); -- Setup high frequency clock for BLE transmission Set_High_Freq_Source (HFCLK_RC); Start_High_Freq; while not High_Freq_Running loop null; end loop; -- Setup radio module for BLE Setup_For_Bluetooth_Low_Energy; -- Set BLE advertising address Set_Logic_Addresses (Base0 => 16#89_BE_D6_00#, Base1 => 16#00_00_00_00#, Base_Length_In_Byte => 3, AP0 => 16#8E#, AP1 => 16#00#, AP2 => 16#00#, AP3 => 16#00#, AP4 => 16#00#, AP5 => 16#00#, AP6 => 16#00#, AP7 => 16#00#); -- Select logic address Set_TX_Address (0); -- Transmission power Set_Power (Zero_Dbm); -- Enable shortcuts for easier radio operation Enable_Shortcut (Ready_To_Start); Enable_Shortcut (End_To_Disable); end Initialize_Radio; ------------------------ -- Send_Beacon_Packet -- ------------------------ procedure Send_Beacon_Packet is begin Configure_Whitening (True, UInt6 (Current_Adv_Channel)); Set_Frequency (Radio_Frequency_MHz (Channel_Frequency (Current_Adv_Channel))); if Current_Adv_Channel /= BLE_Advertising_Channel_Number'Last then Current_Adv_Channel := Current_Adv_Channel + 1; else Current_Adv_Channel := BLE_Advertising_Channel_Number'First; end if; -- Set TX packet address Set_Packet (Memory_Address (Beacon_Packet)); -- Clear all events nRF51.Events.Clear (nRF51.Events.Radio_DISABLED); nRF51.Events.Clear (nRF51.Events.Radio_ADDRESS); nRF51.Events.Clear (nRF51.Events.Radio_PAYLOAD); nRF51.Events.Clear (nRF51.Events.Radio_END); -- Start transmission nRF51.Tasks.Trigger (nRF51.Tasks.Radio_TXEN); -- Wait for end of transmission while not nRF51.Events.Triggered (nRF51.Events.Radio_DISABLED) loop null; end loop; end Send_Beacon_Packet; end Beacon;
AdaCore/libadalang
Ada
77
adb
with Pkg_1.A; procedure Foo is begin pragma Test (Pkg_1.A.Bar); end Foo;
sungyeon/drake
Ada
104
ads
pragma License (Unrestricted); with Ada.IO_Exceptions; package IO_Exceptions renames Ada.IO_Exceptions;
1Crazymoney/LearnAda
Ada
212
adb
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Text_IO; use Ada.Text_IO; with Mat; -- use Mat; procedure paros is N : Natural; begin Get( N ); Put( Boolean'image(Mat.isEven(N))); end paros;
AdaCore/gpr
Ada
20
ads
package R is end R;
usainzg/EHU
Ada
5,607
adb
with Ada.Integer_Text_IO, Ada.Text_IO; use Ada.Integer_Text_IO, Ada.Text_IO; with Listas; with Es_Abundante; with Crear_Sublista_4Primos; with Crear_Sublista_Pares; with Listas_Enteros; procedure Probar_Listas is procedure Crear_Sublista_3Abundantes is new Listas_Enteros.Crear_Sublista(Cuantos => 3, Filtro => Es_Abundante); procedure Escribir_Contenido(L: in out Listas_Enteros.Lista; Lista: String) is N: Integer; begin -- Contenido de L1 con los 10 primeros enteros Put_Line("El contenido de la Lista "&Lista&" es:"); Put("===> "); while not Listas_Enteros.Es_Vacia(L) loop Listas_Enteros.Obtener_Primero(L, N); Put(N,2); Put(" "); Listas_Enteros.Borrar_Primero(L); end loop; New_Line; New_Line; end Escribir_Contenido; procedure Escribir_Contenidos(L1: in out Listas_Enteros.Lista; L1s: String; L2: in out Listas_Enteros.Lista; L2s: String) is N1, N2: Integer; begin Put_Line("===> El contenido de las Listas "&L1s&" y "&L2s&" es:"); while not Listas_Enteros.Es_Vacia(L1) loop Listas_Enteros.Obtener_Primero(L1, N1); Listas_Enteros.Obtener_Primero(L2, N2); Put(N1, 4); Put(" -- "); Put(N2, 4); New_Line; Listas_Enteros.Borrar_Primero(L1); Listas_Enteros.Borrar_Primero(L2); end loop; end Escribir_Contenidos; L1, L1p, L2, L3, L4, L2p, Lp1, Lp2, L3primos, L4abudantes : Listas_Enteros.Lista; N, N1, N2 : Integer; begin -- Crear lista de enteros L1 con los 10 primeros enteros Put("===> Creando L1 ..."); Listas_Enteros.Crear_Vacia(L1); for I in 1..10 loop Listas_Enteros.Colocar(L1, I); if Listas_Enteros.Esta(L1, I) then Put(I, 0); Put(" "); else Put("NO"); Put(I, 0); Put(" "); end if; end loop; Crear_Sublista_Pares(L1, L1p); -- Los pares de L1 New_Line; New_Line; -- Crear lista de enteros L2 con los enteros desde el 11 al 23 Put("===> Creando L2 ..."); Listas_Enteros.Crear_Vacia(L2); for I in 11..23 loop Listas_Enteros.Colocar(L2, I); if Listas_Enteros.Esta(L2, I) then Put(I, 0); Put(" "); else Put("NO"); Put(I, 0); Put(" "); end if; end loop; Crear_Sublista_Pares(L2, L2p); -- Los pares de L2 New_Line; New_Line; Put("===> Creando L3 ..."); Listas_Enteros.Crear_Vacia(L3); for I in 11..23 loop Listas_Enteros.Colocar(L3, I); if Listas_Enteros.Esta(L3, I) then Put(I, 0); Put(" "); else Put("NO"); Put(I, 0); Put(" "); end if; end loop; --Crear_Sublista_4Primos(L3, L3primos); -- Los pares de L2 New_Line; New_Line; Put("===> Creando L4 ..."); Listas_Enteros.Crear_Vacia(L4); for I in 11..23 loop Listas_Enteros.Colocar(L4, I); if Listas_Enteros.Esta(L4, I) then Put(I, 0); Put(" "); else Put("NO"); Put(I, 0); Put(" "); end if; end loop; Crear_Sublista_3Abundantes(L4, L4abudantes); -- Los pares de L2 New_Line; New_Line; -- Contenido de L1 con los 10 primeros enteros Put("===> "); Escribir_Contenido(L1, "L1"); -- Contenido de L2 con los 10 primeros enteros Put("===> "); Escribir_Contenido(L2, "L2"); Put("===> "); Escribir_Contenido(L3, "L3"); Put("===> "); Escribir_Contenido(L3primos, "L3primos"); Put("===> "); Escribir_Contenido(L4, "L4"); Put("===> "); Escribir_Contenido(L4abudantes, "L4abudantes"); -- Crear lista de enteros pares Lp con los 5 primeros pares del 2 al 8 Listas_Enteros.Crear_Vacia(Lp1); N:= 2; while N<=10 loop Listas_Enteros.Colocar(Lp1, N); N:= N+2; end loop; -- Trataremos las listas de pares L1p y Lp1 if Listas_Enteros.Igual(Lp1, L1p) then Put_Line("La lista Lp1 y la obtenida como sublista de pares L1p son iguales"); Escribir_Contenidos(L1p, "L1p", Lp1, "Lp1"); else Put_Line("La lista Lp1 y la obtenida como sublista de pares L1p NO son iguales"); -- Contenido de L1p Put("===> "); Escribir_Contenido(L1p, "L1p"); end if; New_Line; New_Line; -- Trataremos las listas de pares L2p y Lp2 Listas_Enteros.Copiar(Lp2, L2p); if Listas_Enteros.Igual(Lp2, L2p) then Put_Line("La lista Lp2 y la obtenida como copia L2p son iguales"); Escribir_Contenidos(L2p, "L2p", Lp2, "Lp2"); else Put_Line("La lista Lp2 y la obtenida como copia L2p NO son iguales"); -- Contenido de L2p Put("===> "); Escribir_Contenido(L2p, "L2p"); end if; end Probar_Listas;
sf17k/sdlada
Ada
3,081
ads
-------------------------------------------------------------------------------------------------------------------- -- Copyright (c) 2014-2015 Luke A. Guest -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely, subject to the following restrictions: -- -- 1. The origin of this software must not be misrepresented; you must not -- claim that you wrote the original software. If you use this software -- in a product, an acknowledgment in the product documentation would be -- appreciated but is not required. -- -- 2. Altered source versions must be plainly marked as such, and must not be -- misrepresented as being the original software. -- -- 3. This notice may not be removed or altered from any source -- distribution. -------------------------------------------------------------------------------------------------------------------- -- SDL.Video.Rectangles -- -- Rectangle bounding areas. -------------------------------------------------------------------------------------------------------------------- with Interfaces.C; package SDL.Video.Rectangles is package C renames Interfaces.C; Rectangle_Error : exception; type Size is record Width : C.int; Height : C.int; end record with Convention => C; type Size_Arrays is array (C.size_t range <>) of aliased Size with Convention => C; type Point is record X : C.int; Y : C.int; end record with Convention => C; type Point_Arrays is array (C.size_t range <>) of aliased Point with Convention => C; type Line_Segment is record Start : Point; Finish : Point; end record with Convention => C; type Line_Arrays is array (C.size_t range <>) of aliased Line_Segment with Convention => C; type Rectangle is record X : C.int; Y : C.int; Width : C.int; height : C.int; end record with Convention => C; Null_Rectangle : constant Rectangle := (others => 0); type Rectangle_Arrays is array (C.size_t range <>) of aliased Rectangle with Convention => C; type Rectangle_Access is access all Rectangle with Convention => C; function Enclose (Points : in Point_Arrays; Clip : in Rectangle; Enclosed : out Rectangle) return Boolean; procedure Enclose (Points : in Point_Arrays; Enclosed : out Rectangle); function Has_Intersected (A, B : in Rectangle) return Boolean; function Intersects (A, B : in Rectangle; Intersection : out Rectangle) return Boolean; function Clip_To (Clip_Area : in Rectangle; Line : in out Line_Segment) return Boolean; function Union (A, B : in Rectangle) return Rectangle; end SDL.Video.Rectangles;
kjseefried/coreland-cgbc
Ada
520
adb
with BOHT_Support; with CGBC; with Test; procedure T_BOHT_01 is TC : Test.Context_t; package BST4 renames BOHT_Support.String_Tables4; use type CGBC.Count_Type; begin Test.Initialize (Test_Context => TC, Program => "t_boht_01", Test_DB => "TEST_DB", Test_Results => "TEST_RESULTS"); Test.Check (Test_Context => TC, Test => 400, Condition => BST4.Length (BOHT_Support.Map) = 0, Statement => "BST4.Length (BOHT_Support.Map) = 0"); end T_BOHT_01;
redparavoz/ada-wiki
Ada
29,890
ads
-- Generated by gen-ada-entities.pl latin1.ent symbol.ent special.ent private package Wiki.Parsers.Html.Entities is pragma Preelaborate; AELIG_NAME : aliased constant String := "AElig"; AACUTE_NAME : aliased constant String := "Aacute"; ACIRC_NAME : aliased constant String := "Acirc"; AGRAVE_NAME : aliased constant String := "Agrave"; ALPHA_NAME : aliased constant String := "Alpha"; ARING_NAME : aliased constant String := "Aring"; ATILDE_NAME : aliased constant String := "Atilde"; AUML_NAME : aliased constant String := "Auml"; BETA_NAME : aliased constant String := "Beta"; CCEDIL_NAME : aliased constant String := "Ccedil"; CHI_NAME : aliased constant String := "Chi"; DAGGER_NAME : aliased constant String := "Dagger"; DELTA_NAME : aliased constant String := "Delta"; ETH_NAME : aliased constant String := "ETH"; EACUTE_NAME : aliased constant String := "Eacute"; ECIRC_NAME : aliased constant String := "Ecirc"; EGRAVE_NAME : aliased constant String := "Egrave"; EPSILON_NAME : aliased constant String := "Epsilon"; ETA_NAME : aliased constant String := "Eta"; EUML_NAME : aliased constant String := "Euml"; GAMMA_NAME : aliased constant String := "Gamma"; IACUTE_NAME : aliased constant String := "Iacute"; ICIRC_NAME : aliased constant String := "Icirc"; IGRAVE_NAME : aliased constant String := "Igrave"; IOTA_NAME : aliased constant String := "Iota"; IUML_NAME : aliased constant String := "Iuml"; KAPPA_NAME : aliased constant String := "Kappa"; LAMBDA_NAME : aliased constant String := "Lambda"; MU_NAME : aliased constant String := "Mu"; NTILDE_NAME : aliased constant String := "Ntilde"; NU_NAME : aliased constant String := "Nu"; OELIG_NAME : aliased constant String := "OElig"; OACUTE_NAME : aliased constant String := "Oacute"; OCIRC_NAME : aliased constant String := "Ocirc"; OGRAVE_NAME : aliased constant String := "Ograve"; OMEGA_NAME : aliased constant String := "Omega"; OMICRON_NAME : aliased constant String := "Omicron"; OSLASH_NAME : aliased constant String := "Oslash"; OTILDE_NAME : aliased constant String := "Otilde"; OUML_NAME : aliased constant String := "Ouml"; PHI_NAME : aliased constant String := "Phi"; PI_NAME : aliased constant String := "Pi"; PRIME_NAME : aliased constant String := "Prime"; PSI_NAME : aliased constant String := "Psi"; RHO_NAME : aliased constant String := "Rho"; SCARON_NAME : aliased constant String := "Scaron"; SIGMA_NAME : aliased constant String := "Sigma"; THORN_NAME : aliased constant String := "THORN"; TAU_NAME : aliased constant String := "Tau"; THETA_NAME : aliased constant String := "Theta"; UACUTE_NAME : aliased constant String := "Uacute"; UCIRC_NAME : aliased constant String := "Ucirc"; UGRAVE_NAME : aliased constant String := "Ugrave"; UPSILON_NAME : aliased constant String := "Upsilon"; UUML_NAME : aliased constant String := "Uuml"; XI_NAME : aliased constant String := "Xi"; YACUTE_NAME : aliased constant String := "Yacute"; YUML_NAME : aliased constant String := "Yuml"; ZETA_NAME : aliased constant String := "Zeta"; N59_NAME : aliased constant String := "aacute"; N60_NAME : aliased constant String := "acirc"; ACUTE_NAME : aliased constant String := "acute"; N62_NAME : aliased constant String := "aelig"; N63_NAME : aliased constant String := "agrave"; ALEFSYM_NAME : aliased constant String := "alefsym"; N65_NAME : aliased constant String := "alpha"; AMP_NAME : aliased constant String := "amp"; AND_NAME : aliased constant String := "and"; ANG_NAME : aliased constant String := "ang"; APOS_NAME : aliased constant String := "apos"; N70_NAME : aliased constant String := "aring"; ASYMP_NAME : aliased constant String := "asymp"; N72_NAME : aliased constant String := "atilde"; N73_NAME : aliased constant String := "auml"; BDQUO_NAME : aliased constant String := "bdquo"; N75_NAME : aliased constant String := "beta"; BRVBAR_NAME : aliased constant String := "brvbar"; BULL_NAME : aliased constant String := "bull"; CAP_NAME : aliased constant String := "cap"; N79_NAME : aliased constant String := "ccedil"; CEDIL_NAME : aliased constant String := "cedil"; CENT_NAME : aliased constant String := "cent"; N82_NAME : aliased constant String := "chi"; CIRC_NAME : aliased constant String := "circ"; CLUBS_NAME : aliased constant String := "clubs"; CONG_NAME : aliased constant String := "cong"; COPY_NAME : aliased constant String := "copy"; CRARR_NAME : aliased constant String := "crarr"; CUP_NAME : aliased constant String := "cup"; CURREN_NAME : aliased constant String := "curren"; DARR_NAME : aliased constant String := "dArr"; N91_NAME : aliased constant String := "dagger"; N92_NAME : aliased constant String := "darr"; DEG_NAME : aliased constant String := "deg"; N94_NAME : aliased constant String := "delta"; DIAMS_NAME : aliased constant String := "diams"; DIVIDE_NAME : aliased constant String := "divide"; N97_NAME : aliased constant String := "eacute"; N98_NAME : aliased constant String := "ecirc"; N99_NAME : aliased constant String := "egrave"; EMPTY_NAME : aliased constant String := "empty"; EMSP_NAME : aliased constant String := "emsp"; ENSP_NAME : aliased constant String := "ensp"; N103_NAME : aliased constant String := "epsilon"; EQUIV_NAME : aliased constant String := "equiv"; N105_NAME : aliased constant String := "eta"; N106_NAME : aliased constant String := "eth"; N107_NAME : aliased constant String := "euml"; EURO_NAME : aliased constant String := "euro"; EXIST_NAME : aliased constant String := "exist"; FNOF_NAME : aliased constant String := "fnof"; FORALL_NAME : aliased constant String := "forall"; FRAC12_NAME : aliased constant String := "frac12"; FRAC14_NAME : aliased constant String := "frac14"; FRAC34_NAME : aliased constant String := "frac34"; FRASL_NAME : aliased constant String := "frasl"; N116_NAME : aliased constant String := "gamma"; GE_NAME : aliased constant String := "ge"; GT_NAME : aliased constant String := "gt"; HARR_NAME : aliased constant String := "hArr"; N120_NAME : aliased constant String := "harr"; HEARTS_NAME : aliased constant String := "hearts"; HELLIP_NAME : aliased constant String := "hellip"; N123_NAME : aliased constant String := "iacute"; N124_NAME : aliased constant String := "icirc"; IEXCL_NAME : aliased constant String := "iexcl"; N126_NAME : aliased constant String := "igrave"; IMAGE_NAME : aliased constant String := "image"; INFIN_NAME : aliased constant String := "infin"; INT_NAME : aliased constant String := "int"; N130_NAME : aliased constant String := "iota"; IQUEST_NAME : aliased constant String := "iquest"; ISIN_NAME : aliased constant String := "isin"; N133_NAME : aliased constant String := "iuml"; N134_NAME : aliased constant String := "kappa"; LARR_NAME : aliased constant String := "lArr"; N136_NAME : aliased constant String := "lambda"; LANG_NAME : aliased constant String := "lang"; LAQUO_NAME : aliased constant String := "laquo"; N139_NAME : aliased constant String := "larr"; LCEIL_NAME : aliased constant String := "lceil"; LDQUO_NAME : aliased constant String := "ldquo"; LE_NAME : aliased constant String := "le"; LFLOOR_NAME : aliased constant String := "lfloor"; LOWAST_NAME : aliased constant String := "lowast"; LOZ_NAME : aliased constant String := "loz"; LRM_NAME : aliased constant String := "lrm"; LSAQUO_NAME : aliased constant String := "lsaquo"; LSQUO_NAME : aliased constant String := "lsquo"; LT_NAME : aliased constant String := "lt"; MACR_NAME : aliased constant String := "macr"; MDASH_NAME : aliased constant String := "mdash"; MICRO_NAME : aliased constant String := "micro"; MIDDOT_NAME : aliased constant String := "middot"; MINUS_NAME : aliased constant String := "minus"; N155_NAME : aliased constant String := "mu"; NABLA_NAME : aliased constant String := "nabla"; NBSP_NAME : aliased constant String := "nbsp"; NDASH_NAME : aliased constant String := "ndash"; NE_NAME : aliased constant String := "ne"; NI_NAME : aliased constant String := "ni"; NOT_NAME : aliased constant String := "not"; NOTIN_NAME : aliased constant String := "notin"; NSUB_NAME : aliased constant String := "nsub"; N164_NAME : aliased constant String := "ntilde"; N165_NAME : aliased constant String := "nu"; N166_NAME : aliased constant String := "oacute"; N167_NAME : aliased constant String := "ocirc"; N168_NAME : aliased constant String := "oelig"; N169_NAME : aliased constant String := "ograve"; OLINE_NAME : aliased constant String := "oline"; N171_NAME : aliased constant String := "omega"; N172_NAME : aliased constant String := "omicron"; OPLUS_NAME : aliased constant String := "oplus"; OR_NAME : aliased constant String := "or"; ORDF_NAME : aliased constant String := "ordf"; ORDM_NAME : aliased constant String := "ordm"; N177_NAME : aliased constant String := "oslash"; N178_NAME : aliased constant String := "otilde"; OTIMES_NAME : aliased constant String := "otimes"; N180_NAME : aliased constant String := "ouml"; PARA_NAME : aliased constant String := "para"; PART_NAME : aliased constant String := "part"; PERMIL_NAME : aliased constant String := "permil"; PERP_NAME : aliased constant String := "perp"; N185_NAME : aliased constant String := "phi"; N186_NAME : aliased constant String := "pi"; PIV_NAME : aliased constant String := "piv"; PLUSMN_NAME : aliased constant String := "plusmn"; POUND_NAME : aliased constant String := "pound"; N190_NAME : aliased constant String := "prime"; PROD_NAME : aliased constant String := "prod"; PROP_NAME : aliased constant String := "prop"; N193_NAME : aliased constant String := "psi"; QUOT_NAME : aliased constant String := "quot"; RARR_NAME : aliased constant String := "rArr"; RADIC_NAME : aliased constant String := "radic"; RANG_NAME : aliased constant String := "rang"; RAQUO_NAME : aliased constant String := "raquo"; N199_NAME : aliased constant String := "rarr"; RCEIL_NAME : aliased constant String := "rceil"; RDQUO_NAME : aliased constant String := "rdquo"; REAL_NAME : aliased constant String := "real"; REG_NAME : aliased constant String := "reg"; RFLOOR_NAME : aliased constant String := "rfloor"; N205_NAME : aliased constant String := "rho"; RLM_NAME : aliased constant String := "rlm"; RSAQUO_NAME : aliased constant String := "rsaquo"; RSQUO_NAME : aliased constant String := "rsquo"; SBQUO_NAME : aliased constant String := "sbquo"; N210_NAME : aliased constant String := "scaron"; SDOT_NAME : aliased constant String := "sdot"; SECT_NAME : aliased constant String := "sect"; SHY_NAME : aliased constant String := "shy"; N214_NAME : aliased constant String := "sigma"; SIGMAF_NAME : aliased constant String := "sigmaf"; SIM_NAME : aliased constant String := "sim"; SPADES_NAME : aliased constant String := "spades"; SUB_NAME : aliased constant String := "sub"; SUBE_NAME : aliased constant String := "sube"; SUM_NAME : aliased constant String := "sum"; SUP_NAME : aliased constant String := "sup"; SUP1_NAME : aliased constant String := "sup1"; SUP2_NAME : aliased constant String := "sup2"; SUP3_NAME : aliased constant String := "sup3"; SUPE_NAME : aliased constant String := "supe"; SZLIG_NAME : aliased constant String := "szlig"; N227_NAME : aliased constant String := "tau"; THERE4_NAME : aliased constant String := "there4"; N229_NAME : aliased constant String := "theta"; THETASYM_NAME : aliased constant String := "thetasym"; THINSP_NAME : aliased constant String := "thinsp"; N232_NAME : aliased constant String := "thorn"; TILDE_NAME : aliased constant String := "tilde"; TIMES_NAME : aliased constant String := "times"; TRADE_NAME : aliased constant String := "trade"; UARR_NAME : aliased constant String := "uArr"; N237_NAME : aliased constant String := "uacute"; N238_NAME : aliased constant String := "uarr"; N239_NAME : aliased constant String := "ucirc"; N240_NAME : aliased constant String := "ugrave"; UML_NAME : aliased constant String := "uml"; UPSIH_NAME : aliased constant String := "upsih"; N243_NAME : aliased constant String := "upsilon"; N244_NAME : aliased constant String := "uuml"; WEIERP_NAME : aliased constant String := "weierp"; N246_NAME : aliased constant String := "xi"; N247_NAME : aliased constant String := "yacute"; YEN_NAME : aliased constant String := "yen"; N249_NAME : aliased constant String := "yuml"; N250_NAME : aliased constant String := "zeta"; ZWJ_NAME : aliased constant String := "zwj"; ZWNJ_NAME : aliased constant String := "zwnj"; type String_Access is access constant String; type Keyword_Array is array (Positive range 1 .. 253) of String_Access; type Char_Array is array (Positive range 1 .. 253) of Wide_Wide_Character; Keywords : constant Keyword_Array := ( AELIG_NAME'Access, AACUTE_NAME'Access, ACIRC_NAME'Access, AGRAVE_NAME'Access, ALPHA_NAME'Access, ARING_NAME'Access, ATILDE_NAME'Access, AUML_NAME'Access, BETA_NAME'Access, CCEDIL_NAME'Access, CHI_NAME'Access, DAGGER_NAME'Access, DELTA_NAME'Access, ETH_NAME'Access, EACUTE_NAME'Access, ECIRC_NAME'Access, EGRAVE_NAME'Access, EPSILON_NAME'Access, ETA_NAME'Access, EUML_NAME'Access, GAMMA_NAME'Access, IACUTE_NAME'Access, ICIRC_NAME'Access, IGRAVE_NAME'Access, IOTA_NAME'Access, IUML_NAME'Access, KAPPA_NAME'Access, LAMBDA_NAME'Access, MU_NAME'Access, NTILDE_NAME'Access, NU_NAME'Access, OELIG_NAME'Access, OACUTE_NAME'Access, OCIRC_NAME'Access, OGRAVE_NAME'Access, OMEGA_NAME'Access, OMICRON_NAME'Access, OSLASH_NAME'Access, OTILDE_NAME'Access, OUML_NAME'Access, PHI_NAME'Access, PI_NAME'Access, PRIME_NAME'Access, PSI_NAME'Access, RHO_NAME'Access, SCARON_NAME'Access, SIGMA_NAME'Access, THORN_NAME'Access, TAU_NAME'Access, THETA_NAME'Access, UACUTE_NAME'Access, UCIRC_NAME'Access, UGRAVE_NAME'Access, UPSILON_NAME'Access, UUML_NAME'Access, XI_NAME'Access, YACUTE_NAME'Access, YUML_NAME'Access, ZETA_NAME'Access, N59_NAME'Access, N60_NAME'Access, ACUTE_NAME'Access, N62_NAME'Access, N63_NAME'Access, ALEFSYM_NAME'Access, N65_NAME'Access, AMP_NAME'Access, AND_NAME'Access, ANG_NAME'Access, APOS_NAME'Access, N70_NAME'Access, ASYMP_NAME'Access, N72_NAME'Access, N73_NAME'Access, BDQUO_NAME'Access, N75_NAME'Access, BRVBAR_NAME'Access, BULL_NAME'Access, CAP_NAME'Access, N79_NAME'Access, CEDIL_NAME'Access, CENT_NAME'Access, N82_NAME'Access, CIRC_NAME'Access, CLUBS_NAME'Access, CONG_NAME'Access, COPY_NAME'Access, CRARR_NAME'Access, CUP_NAME'Access, CURREN_NAME'Access, DARR_NAME'Access, N91_NAME'Access, N92_NAME'Access, DEG_NAME'Access, N94_NAME'Access, DIAMS_NAME'Access, DIVIDE_NAME'Access, N97_NAME'Access, N98_NAME'Access, N99_NAME'Access, EMPTY_NAME'Access, EMSP_NAME'Access, ENSP_NAME'Access, N103_NAME'Access, EQUIV_NAME'Access, N105_NAME'Access, N106_NAME'Access, N107_NAME'Access, EURO_NAME'Access, EXIST_NAME'Access, FNOF_NAME'Access, FORALL_NAME'Access, FRAC12_NAME'Access, FRAC14_NAME'Access, FRAC34_NAME'Access, FRASL_NAME'Access, N116_NAME'Access, GE_NAME'Access, GT_NAME'Access, HARR_NAME'Access, N120_NAME'Access, HEARTS_NAME'Access, HELLIP_NAME'Access, N123_NAME'Access, N124_NAME'Access, IEXCL_NAME'Access, N126_NAME'Access, IMAGE_NAME'Access, INFIN_NAME'Access, INT_NAME'Access, N130_NAME'Access, IQUEST_NAME'Access, ISIN_NAME'Access, N133_NAME'Access, N134_NAME'Access, LARR_NAME'Access, N136_NAME'Access, LANG_NAME'Access, LAQUO_NAME'Access, N139_NAME'Access, LCEIL_NAME'Access, LDQUO_NAME'Access, LE_NAME'Access, LFLOOR_NAME'Access, LOWAST_NAME'Access, LOZ_NAME'Access, LRM_NAME'Access, LSAQUO_NAME'Access, LSQUO_NAME'Access, LT_NAME'Access, MACR_NAME'Access, MDASH_NAME'Access, MICRO_NAME'Access, MIDDOT_NAME'Access, MINUS_NAME'Access, N155_NAME'Access, NABLA_NAME'Access, NBSP_NAME'Access, NDASH_NAME'Access, NE_NAME'Access, NI_NAME'Access, NOT_NAME'Access, NOTIN_NAME'Access, NSUB_NAME'Access, N164_NAME'Access, N165_NAME'Access, N166_NAME'Access, N167_NAME'Access, N168_NAME'Access, N169_NAME'Access, OLINE_NAME'Access, N171_NAME'Access, N172_NAME'Access, OPLUS_NAME'Access, OR_NAME'Access, ORDF_NAME'Access, ORDM_NAME'Access, N177_NAME'Access, N178_NAME'Access, OTIMES_NAME'Access, N180_NAME'Access, PARA_NAME'Access, PART_NAME'Access, PERMIL_NAME'Access, PERP_NAME'Access, N185_NAME'Access, N186_NAME'Access, PIV_NAME'Access, PLUSMN_NAME'Access, POUND_NAME'Access, N190_NAME'Access, PROD_NAME'Access, PROP_NAME'Access, N193_NAME'Access, QUOT_NAME'Access, RARR_NAME'Access, RADIC_NAME'Access, RANG_NAME'Access, RAQUO_NAME'Access, N199_NAME'Access, RCEIL_NAME'Access, RDQUO_NAME'Access, REAL_NAME'Access, REG_NAME'Access, RFLOOR_NAME'Access, N205_NAME'Access, RLM_NAME'Access, RSAQUO_NAME'Access, RSQUO_NAME'Access, SBQUO_NAME'Access, N210_NAME'Access, SDOT_NAME'Access, SECT_NAME'Access, SHY_NAME'Access, N214_NAME'Access, SIGMAF_NAME'Access, SIM_NAME'Access, SPADES_NAME'Access, SUB_NAME'Access, SUBE_NAME'Access, SUM_NAME'Access, SUP_NAME'Access, SUP1_NAME'Access, SUP2_NAME'Access, SUP3_NAME'Access, SUPE_NAME'Access, SZLIG_NAME'Access, N227_NAME'Access, THERE4_NAME'Access, N229_NAME'Access, THETASYM_NAME'Access, THINSP_NAME'Access, N232_NAME'Access, TILDE_NAME'Access, TIMES_NAME'Access, TRADE_NAME'Access, UARR_NAME'Access, N237_NAME'Access, N238_NAME'Access, N239_NAME'Access, N240_NAME'Access, UML_NAME'Access, UPSIH_NAME'Access, N243_NAME'Access, N244_NAME'Access, WEIERP_NAME'Access, N246_NAME'Access, N247_NAME'Access, YEN_NAME'Access, N249_NAME'Access, N250_NAME'Access, ZWJ_NAME'Access, ZWNJ_NAME'Access); Mapping : constant Char_Array := ( Wide_Wide_Character'Val (198), Wide_Wide_Character'Val (193), Wide_Wide_Character'Val (194), Wide_Wide_Character'Val (192), Wide_Wide_Character'Val (913), Wide_Wide_Character'Val (197), Wide_Wide_Character'Val (195), Wide_Wide_Character'Val (196), Wide_Wide_Character'Val (914), Wide_Wide_Character'Val (199), Wide_Wide_Character'Val (935), Wide_Wide_Character'Val (8225), Wide_Wide_Character'Val (916), Wide_Wide_Character'Val (208), Wide_Wide_Character'Val (201), Wide_Wide_Character'Val (202), Wide_Wide_Character'Val (200), Wide_Wide_Character'Val (917), Wide_Wide_Character'Val (919), Wide_Wide_Character'Val (203), Wide_Wide_Character'Val (915), Wide_Wide_Character'Val (205), Wide_Wide_Character'Val (206), Wide_Wide_Character'Val (204), Wide_Wide_Character'Val (921), Wide_Wide_Character'Val (207), Wide_Wide_Character'Val (922), Wide_Wide_Character'Val (923), Wide_Wide_Character'Val (924), Wide_Wide_Character'Val (209), Wide_Wide_Character'Val (925), Wide_Wide_Character'Val (338), Wide_Wide_Character'Val (211), Wide_Wide_Character'Val (212), Wide_Wide_Character'Val (210), Wide_Wide_Character'Val (937), Wide_Wide_Character'Val (927), Wide_Wide_Character'Val (216), Wide_Wide_Character'Val (213), Wide_Wide_Character'Val (214), Wide_Wide_Character'Val (934), Wide_Wide_Character'Val (928), Wide_Wide_Character'Val (8243), Wide_Wide_Character'Val (936), Wide_Wide_Character'Val (929), Wide_Wide_Character'Val (352), Wide_Wide_Character'Val (931), Wide_Wide_Character'Val (222), Wide_Wide_Character'Val (932), Wide_Wide_Character'Val (920), Wide_Wide_Character'Val (218), Wide_Wide_Character'Val (219), Wide_Wide_Character'Val (217), Wide_Wide_Character'Val (933), Wide_Wide_Character'Val (220), Wide_Wide_Character'Val (926), Wide_Wide_Character'Val (221), Wide_Wide_Character'Val (376), Wide_Wide_Character'Val (918), Wide_Wide_Character'Val (225), Wide_Wide_Character'Val (226), Wide_Wide_Character'Val (180), Wide_Wide_Character'Val (230), Wide_Wide_Character'Val (224), Wide_Wide_Character'Val (8501), Wide_Wide_Character'Val (945), Wide_Wide_Character'Val (38), Wide_Wide_Character'Val (8743), Wide_Wide_Character'Val (8736), Wide_Wide_Character'Val (39), Wide_Wide_Character'Val (229), Wide_Wide_Character'Val (8776), Wide_Wide_Character'Val (227), Wide_Wide_Character'Val (228), Wide_Wide_Character'Val (8222), Wide_Wide_Character'Val (946), Wide_Wide_Character'Val (166), Wide_Wide_Character'Val (8226), Wide_Wide_Character'Val (8745), Wide_Wide_Character'Val (231), Wide_Wide_Character'Val (184), Wide_Wide_Character'Val (162), Wide_Wide_Character'Val (967), Wide_Wide_Character'Val (710), Wide_Wide_Character'Val (9827), Wide_Wide_Character'Val (8773), Wide_Wide_Character'Val (169), Wide_Wide_Character'Val (8629), Wide_Wide_Character'Val (8746), Wide_Wide_Character'Val (164), Wide_Wide_Character'Val (8659), Wide_Wide_Character'Val (8224), Wide_Wide_Character'Val (8595), Wide_Wide_Character'Val (176), Wide_Wide_Character'Val (948), Wide_Wide_Character'Val (9830), Wide_Wide_Character'Val (247), Wide_Wide_Character'Val (233), Wide_Wide_Character'Val (234), Wide_Wide_Character'Val (232), Wide_Wide_Character'Val (8709), Wide_Wide_Character'Val (8195), Wide_Wide_Character'Val (8194), Wide_Wide_Character'Val (949), Wide_Wide_Character'Val (8801), Wide_Wide_Character'Val (951), Wide_Wide_Character'Val (240), Wide_Wide_Character'Val (235), Wide_Wide_Character'Val (8364), Wide_Wide_Character'Val (8707), Wide_Wide_Character'Val (402), Wide_Wide_Character'Val (8704), Wide_Wide_Character'Val (189), Wide_Wide_Character'Val (188), Wide_Wide_Character'Val (190), Wide_Wide_Character'Val (8260), Wide_Wide_Character'Val (947), Wide_Wide_Character'Val (8805), Wide_Wide_Character'Val (62), Wide_Wide_Character'Val (8660), Wide_Wide_Character'Val (8596), Wide_Wide_Character'Val (9829), Wide_Wide_Character'Val (8230), Wide_Wide_Character'Val (237), Wide_Wide_Character'Val (238), Wide_Wide_Character'Val (161), Wide_Wide_Character'Val (236), Wide_Wide_Character'Val (8465), Wide_Wide_Character'Val (8734), Wide_Wide_Character'Val (8747), Wide_Wide_Character'Val (953), Wide_Wide_Character'Val (191), Wide_Wide_Character'Val (8712), Wide_Wide_Character'Val (239), Wide_Wide_Character'Val (954), Wide_Wide_Character'Val (8656), Wide_Wide_Character'Val (955), Wide_Wide_Character'Val (9001), Wide_Wide_Character'Val (171), Wide_Wide_Character'Val (8592), Wide_Wide_Character'Val (8968), Wide_Wide_Character'Val (8220), Wide_Wide_Character'Val (8804), Wide_Wide_Character'Val (8970), Wide_Wide_Character'Val (8727), Wide_Wide_Character'Val (9674), Wide_Wide_Character'Val (8206), Wide_Wide_Character'Val (8249), Wide_Wide_Character'Val (8216), Wide_Wide_Character'Val (60), Wide_Wide_Character'Val (175), Wide_Wide_Character'Val (8212), Wide_Wide_Character'Val (181), Wide_Wide_Character'Val (183), Wide_Wide_Character'Val (8722), Wide_Wide_Character'Val (956), Wide_Wide_Character'Val (8711), Wide_Wide_Character'Val (160), Wide_Wide_Character'Val (8211), Wide_Wide_Character'Val (8800), Wide_Wide_Character'Val (8715), Wide_Wide_Character'Val (172), Wide_Wide_Character'Val (8713), Wide_Wide_Character'Val (8836), Wide_Wide_Character'Val (241), Wide_Wide_Character'Val (957), Wide_Wide_Character'Val (243), Wide_Wide_Character'Val (244), Wide_Wide_Character'Val (339), Wide_Wide_Character'Val (242), Wide_Wide_Character'Val (8254), Wide_Wide_Character'Val (969), Wide_Wide_Character'Val (959), Wide_Wide_Character'Val (8853), Wide_Wide_Character'Val (8744), Wide_Wide_Character'Val (170), Wide_Wide_Character'Val (186), Wide_Wide_Character'Val (248), Wide_Wide_Character'Val (245), Wide_Wide_Character'Val (8855), Wide_Wide_Character'Val (246), Wide_Wide_Character'Val (182), Wide_Wide_Character'Val (8706), Wide_Wide_Character'Val (8240), Wide_Wide_Character'Val (8869), Wide_Wide_Character'Val (966), Wide_Wide_Character'Val (960), Wide_Wide_Character'Val (982), Wide_Wide_Character'Val (177), Wide_Wide_Character'Val (163), Wide_Wide_Character'Val (8242), Wide_Wide_Character'Val (8719), Wide_Wide_Character'Val (8733), Wide_Wide_Character'Val (968), Wide_Wide_Character'Val (34), Wide_Wide_Character'Val (8658), Wide_Wide_Character'Val (8730), Wide_Wide_Character'Val (9002), Wide_Wide_Character'Val (187), Wide_Wide_Character'Val (8594), Wide_Wide_Character'Val (8969), Wide_Wide_Character'Val (8221), Wide_Wide_Character'Val (8476), Wide_Wide_Character'Val (174), Wide_Wide_Character'Val (8971), Wide_Wide_Character'Val (961), Wide_Wide_Character'Val (8207), Wide_Wide_Character'Val (8250), Wide_Wide_Character'Val (8217), Wide_Wide_Character'Val (8218), Wide_Wide_Character'Val (353), Wide_Wide_Character'Val (8901), Wide_Wide_Character'Val (167), Wide_Wide_Character'Val (173), Wide_Wide_Character'Val (963), Wide_Wide_Character'Val (962), Wide_Wide_Character'Val (8764), Wide_Wide_Character'Val (9824), Wide_Wide_Character'Val (8834), Wide_Wide_Character'Val (8838), Wide_Wide_Character'Val (8721), Wide_Wide_Character'Val (8835), Wide_Wide_Character'Val (185), Wide_Wide_Character'Val (178), Wide_Wide_Character'Val (179), Wide_Wide_Character'Val (8839), Wide_Wide_Character'Val (223), Wide_Wide_Character'Val (964), Wide_Wide_Character'Val (8756), Wide_Wide_Character'Val (952), Wide_Wide_Character'Val (977), Wide_Wide_Character'Val (8201), Wide_Wide_Character'Val (254), Wide_Wide_Character'Val (732), Wide_Wide_Character'Val (215), Wide_Wide_Character'Val (8482), Wide_Wide_Character'Val (8657), Wide_Wide_Character'Val (250), Wide_Wide_Character'Val (8593), Wide_Wide_Character'Val (251), Wide_Wide_Character'Val (249), Wide_Wide_Character'Val (168), Wide_Wide_Character'Val (978), Wide_Wide_Character'Val (965), Wide_Wide_Character'Val (252), Wide_Wide_Character'Val (8472), Wide_Wide_Character'Val (958), Wide_Wide_Character'Val (253), Wide_Wide_Character'Val (165), Wide_Wide_Character'Val (255), Wide_Wide_Character'Val (950), Wide_Wide_Character'Val (8205), Wide_Wide_Character'Val (8204)); end Wiki.Parsers.Html.Entities;
reznikmm/matreshka
Ada
9,712
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Web Framework -- -- -- -- Tools Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2012-2013, Vadim Godunko <[email protected]> -- -- 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$ ------------------------------------------------------------------------------ with League.Strings; with WSDL.AST.Messages; pragma Unreferenced (WSDL.AST.Messages); -- GNAT Pro 7.2.0w (20130423): package is needed to access to type's -- components. with WSDL.AST.Operations; pragma Unreferenced (WSDL.AST.Operations); -- GNAT Pro 7.2.0w (20130423): package is needed to access to type's -- components. with WSDL.Constants; package body WSDL.Analyzer is use WSDL.Constants; ------------------------------- -- Enter_Interface_Operation -- ------------------------------- overriding procedure Enter_Interface_Operation (Self : in out Analyzer; Node : not null WSDL.AST.Interface_Operation_Access; Control : in out WSDL.Iterators.Traverse_Control) is pragma Unreferenced (Self); pragma Unreferenced (Control); use type League.Strings.Universal_String; use type WSDL.AST.Interface_Message_Access; Input_Message : WSDL.AST.Interface_Message_Access; Output_Message : WSDL.AST.Interface_Message_Access; begin if Node.Message_Exchange_Pattern.IRI = In_Out_MEP then -- InOutComposition-2015: "The in-out message exchange pattern -- consists of exactly two messages, in order, as follows: -- -- 1. A message: -- -- - indicated by a Interface Message Reference component whose -- {message label} is "In" and {direction} is "in" -- -- - received from some node N -- -- 2. A message: -- -- - indicated by a Interface Message Reference component whose -- {message label} is "Out" and {direction} is "out" -- -- - sent to node N" -- Lookup for input and output messages. Check whether only one -- message for each direction is specified. for Message_Node of Node.Interface_Message_References loop case Message_Node.Direction is when WSDL.AST.In_Message => if Input_Message /= null then -- InOutComposition-2015: Only one input message can be -- specified in this MEP. raise Program_Error; end if; Input_Message := Message_Node; when WSDL.AST.Out_Message => if Output_Message /= null then -- InOutComposition-2015: Only one output message can be -- specified in this MEP. raise Program_Error; end if; Output_Message := Message_Node; end case; end loop; -- Check whether input message is specified. if Input_Message = null then -- InOutComposition-2015: Input message must be specified for this -- MEP. raise Program_Error; end if; -- Check label of the message. It can be empty, because MEP has only -- one input message. if not Input_Message.Message_Label.Is_Empty and Input_Message.Message_Label /= In_Label then -- InOutComposition-2015: Input message must have label 'In' or -- doesn't have label. raise Program_Error; end if; -- Check whether output message is specified. if Output_Message = null then -- InOutComposition-2015: Input message must be specified for this -- MEP. raise Program_Error; end if; -- Check label of the message. It can be empty, because MEP has only -- one output message. if not Output_Message.Message_Label.Is_Empty and Output_Message.Message_Label /= Out_Label then -- InOutComposition-2015: Output message must have label 'Out' or -- doesn't have label. raise Program_Error; end if; elsif Node.Message_Exchange_Pattern.IRI = Robust_In_Only_MEP then -- RobustInOnlyComposition-2013: "The robust-in-only message exchange -- pattern consists of exactly one message as follows: -- -- 1. A message: -- -- - indicated by a Interface Message Reference component whose -- {message label} is "In" and {direction} is "in" -- -- - received from some node N" -- Lookup for input message. Check whether only one -- input message is specified. for Message_Node of Node.Interface_Message_References loop case Message_Node.Direction is when WSDL.AST.In_Message => if Input_Message /= null then -- RobustInOnlyComposition-2013: Only one input message -- can be specified in this MEP. raise Program_Error; end if; Input_Message := Message_Node; when WSDL.AST.Out_Message => -- RobustInOnlyComposition-2013: Output messages can't be -- specified for this MEP. -- -- XXX Must never be happen when MessageLabel-1033 will be -- implemented (check will be done by parser). raise Program_Error; end case; end loop; -- Check whether input message is specified. if Input_Message = null then -- RobustInOnlyComposition-2013: Input message must be specified -- for this MEP. raise Program_Error; end if; -- Check label of the message. It can be empty, because MEP has only -- one input message. if not Input_Message.Message_Label.Is_Empty and Input_Message.Message_Label /= In_Label then -- RobustInOnlyComposition-2013: Input message must have label -- 'In' or doesn't have label. raise Program_Error; end if; else raise Program_Error; end if; end Enter_Interface_Operation; -------------- -- Set_Root -- -------------- procedure Set_Root (Self : in out Analyzer'Class; Root : WSDL.AST.Description_Access) is begin Self.Root := Root; end Set_Root; end WSDL.Analyzer;
stcarrez/dynamo
Ada
14,294
adb
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- M L I B . T G T -- -- -- -- B o d y -- -- -- -- Copyright (C) 2001-2010, 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. 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. -- -- -- ------------------------------------------------------------------------------ with MLib.Fil; with Prj.Com; with MLib.Tgt.Specific; pragma Warnings (Off, MLib.Tgt.Specific); -- MLib.Tgt.Specific is with'ed only for elaboration purposes package body MLib.Tgt is --------------------- -- Archive_Builder -- --------------------- function Archive_Builder return String is begin return Archive_Builder_Ptr.all; end Archive_Builder; ----------------------------- -- Archive_Builder_Default -- ----------------------------- function Archive_Builder_Default return String is begin return "ar"; end Archive_Builder_Default; ----------------------------- -- Archive_Builder_Options -- ----------------------------- function Archive_Builder_Options return String_List_Access is begin return Archive_Builder_Options_Ptr.all; end Archive_Builder_Options; ------------------------------------- -- Archive_Builder_Options_Default -- ------------------------------------- function Archive_Builder_Options_Default return String_List_Access is begin return new String_List'(1 => new String'("cr")); end Archive_Builder_Options_Default; ------------------------------------ -- Archive_Builder_Append_Options -- ------------------------------------ function Archive_Builder_Append_Options return String_List_Access is begin return Archive_Builder_Append_Options_Ptr.all; end Archive_Builder_Append_Options; -------------------------------------------- -- Archive_Builder_Append_Options_Default -- -------------------------------------------- function Archive_Builder_Append_Options_Default return String_List_Access is begin return new String_List'(1 => new String'("q")); end Archive_Builder_Append_Options_Default; ----------------- -- Archive_Ext -- ----------------- function Archive_Ext return String is begin return Archive_Ext_Ptr.all; end Archive_Ext; ------------------------- -- Archive_Ext_Default -- ------------------------- function Archive_Ext_Default return String is begin return "a"; end Archive_Ext_Default; --------------------- -- Archive_Indexer -- --------------------- function Archive_Indexer return String is begin return Archive_Indexer_Ptr.all; end Archive_Indexer; ----------------------------- -- Archive_Indexer_Default -- ----------------------------- function Archive_Indexer_Default return String is begin return "ranlib"; end Archive_Indexer_Default; ----------------------------- -- Archive_Indexer_Options -- ----------------------------- function Archive_Indexer_Options return String_List_Access is begin return Archive_Indexer_Options_Ptr.all; end Archive_Indexer_Options; ------------------------------------- -- Archive_Indexer_Options_Default -- ------------------------------------- function Archive_Indexer_Options_Default return String_List_Access is begin return new String_List (1 .. 0); end Archive_Indexer_Options_Default; --------------------------- -- Build_Dynamic_Library -- --------------------------- procedure Build_Dynamic_Library (Ofiles : Argument_List; Options : Argument_List; Interfaces : Argument_List; Lib_Filename : String; Lib_Dir : String; Symbol_Data : Symbol_Record; Driver_Name : Name_Id := No_Name; Lib_Version : String := ""; Auto_Init : Boolean := False) is begin Build_Dynamic_Library_Ptr (Ofiles, Options, Interfaces, Lib_Filename, Lib_Dir, Symbol_Data, Driver_Name, Lib_Version, Auto_Init); end Build_Dynamic_Library; ------------------------------ -- Default_Symbol_File_Name -- ------------------------------ function Default_Symbol_File_Name return String is begin return Default_Symbol_File_Name_Ptr.all; end Default_Symbol_File_Name; -------------------------------------- -- Default_Symbol_File_Name_Default -- -------------------------------------- function Default_Symbol_File_Name_Default return String is begin return ""; end Default_Symbol_File_Name_Default; ------------- -- DLL_Ext -- ------------- function DLL_Ext return String is begin return DLL_Ext_Ptr.all; end DLL_Ext; --------------------- -- DLL_Ext_Default -- --------------------- function DLL_Ext_Default return String is begin return "so"; end DLL_Ext_Default; ---------------- -- DLL_Prefix -- ---------------- function DLL_Prefix return String is begin return DLL_Prefix_Ptr.all; end DLL_Prefix; ------------------------ -- DLL_Prefix_Default -- ------------------------ function DLL_Prefix_Default return String is begin return "lib"; end DLL_Prefix_Default; -------------------- -- Dynamic_Option -- -------------------- function Dynamic_Option return String is begin return Dynamic_Option_Ptr.all; end Dynamic_Option; ---------------------------- -- Dynamic_Option_Default -- ---------------------------- function Dynamic_Option_Default return String is begin return "-shared"; end Dynamic_Option_Default; ------------------- -- Is_Object_Ext -- ------------------- function Is_Object_Ext (Ext : String) return Boolean is begin return Is_Object_Ext_Ptr (Ext); end Is_Object_Ext; --------------------------- -- Is_Object_Ext_Default -- --------------------------- function Is_Object_Ext_Default (Ext : String) return Boolean is begin return Ext = ".o"; end Is_Object_Ext_Default; -------------- -- Is_C_Ext -- -------------- function Is_C_Ext (Ext : String) return Boolean is begin return Is_C_Ext_Ptr (Ext); end Is_C_Ext; ---------------------- -- Is_C_Ext_Default -- ---------------------- function Is_C_Ext_Default (Ext : String) return Boolean is begin return Ext = ".c"; end Is_C_Ext_Default; -------------------- -- Is_Archive_Ext -- -------------------- function Is_Archive_Ext (Ext : String) return Boolean is begin return Is_Archive_Ext_Ptr (Ext); end Is_Archive_Ext; ---------------------------- -- Is_Archive_Ext_Default -- ---------------------------- function Is_Archive_Ext_Default (Ext : String) return Boolean is begin return Ext = ".a"; end Is_Archive_Ext_Default; ------------- -- Libgnat -- ------------- function Libgnat return String is begin return Libgnat_Ptr.all; end Libgnat; --------------------- -- Libgnat_Default -- --------------------- function Libgnat_Default return String is begin return "libgnat.a"; end Libgnat_Default; ------------------------ -- Library_Exists_For -- ------------------------ function Library_Exists_For (Project : Project_Id; In_Tree : Project_Tree_Ref) return Boolean is begin return Library_Exists_For_Ptr (Project, In_Tree); end Library_Exists_For; -------------------------------- -- Library_Exists_For_Default -- -------------------------------- function Library_Exists_For_Default (Project : Project_Id; In_Tree : Project_Tree_Ref) return Boolean is pragma Unreferenced (In_Tree); begin if not Project.Library then Prj.Com.Fail ("INTERNAL ERROR: Library_Exists_For called " & "for non library project"); return False; else declare Lib_Dir : constant String := Get_Name_String (Project.Library_Dir.Display_Name); Lib_Name : constant String := Get_Name_String (Project.Library_Name); begin if Project.Library_Kind = Static then return Is_Regular_File (Lib_Dir & Directory_Separator & "lib" & Fil.Append_To (Lib_Name, Archive_Ext)); else return Is_Regular_File (Lib_Dir & Directory_Separator & DLL_Prefix & Fil.Append_To (Lib_Name, DLL_Ext)); end if; end; end if; end Library_Exists_For_Default; --------------------------- -- Library_File_Name_For -- --------------------------- function Library_File_Name_For (Project : Project_Id; In_Tree : Project_Tree_Ref) return File_Name_Type is begin return Library_File_Name_For_Ptr (Project, In_Tree); end Library_File_Name_For; ----------------------------------- -- Library_File_Name_For_Default -- ----------------------------------- function Library_File_Name_For_Default (Project : Project_Id; In_Tree : Project_Tree_Ref) return File_Name_Type is pragma Unreferenced (In_Tree); begin if not Project.Library then Prj.Com.Fail ("INTERNAL ERROR: Library_File_Name_For called " & "for non library project"); return No_File; else declare Lib_Name : constant String := Get_Name_String (Project.Library_Name); begin if Project.Library_Kind = Static then Name_Len := 3; Name_Buffer (1 .. Name_Len) := "lib"; Add_Str_To_Name_Buffer (Fil.Append_To (Lib_Name, Archive_Ext)); else Name_Len := 0; Add_Str_To_Name_Buffer (DLL_Prefix); Add_Str_To_Name_Buffer (Fil.Append_To (Lib_Name, DLL_Ext)); end if; return Name_Find; end; end if; end Library_File_Name_For_Default; -------------------------------------- -- Library_Major_Minor_Id_Supported -- -------------------------------------- function Library_Major_Minor_Id_Supported return Boolean is begin return Library_Major_Minor_Id_Supported_Ptr.all; end Library_Major_Minor_Id_Supported; ---------------------------------------------- -- Library_Major_Minor_Id_Supported_Default -- ---------------------------------------------- function Library_Major_Minor_Id_Supported_Default return Boolean is begin return True; end Library_Major_Minor_Id_Supported_Default; ---------------- -- Object_Ext -- ---------------- function Object_Ext return String is begin return Object_Ext_Ptr.all; end Object_Ext; ------------------------ -- Object_Ext_Default -- ------------------------ function Object_Ext_Default return String is begin return "o"; end Object_Ext_Default; ---------------- -- PIC_Option -- ---------------- function PIC_Option return String is begin return PIC_Option_Ptr.all; end PIC_Option; ------------------------ -- PIC_Option_Default -- ------------------------ function PIC_Option_Default return String is begin return "-fPIC"; end PIC_Option_Default; ----------------------------------------------- -- Standalone_Library_Auto_Init_Is_Supported -- ----------------------------------------------- function Standalone_Library_Auto_Init_Is_Supported return Boolean is begin return Standalone_Library_Auto_Init_Is_Supported_Ptr.all; end Standalone_Library_Auto_Init_Is_Supported; ------------------------------------------------------- -- Standalone_Library_Auto_Init_Is_Supported_Default -- ------------------------------------------------------- function Standalone_Library_Auto_Init_Is_Supported_Default return Boolean is begin return True; end Standalone_Library_Auto_Init_Is_Supported_Default; --------------------------- -- Support_For_Libraries -- --------------------------- function Support_For_Libraries return Library_Support is begin return Support_For_Libraries_Ptr.all; end Support_For_Libraries; ----------------------------------- -- Support_For_Libraries_Default -- ----------------------------------- function Support_For_Libraries_Default return Library_Support is begin return Full; end Support_For_Libraries_Default; end MLib.Tgt;
onox/sdlada
Ada
2,507
ads
-------------------------------------------------------------------------------------------------------------------- -- Copyright (c) 2013-2018 Luke A. Guest -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely, subject to the following restrictions: -- -- 1. The origin of this software must not be misrepresented; you must not -- claim that you wrote the original software. If you use this software -- in a product, an acknowledgment in the product documentation would be -- appreciated but is not required. -- -- 2. Altered source versions must be plainly marked as such, and must not be -- misrepresented as being the original software. -- -- 3. This notice may not be removed or altered from any source -- distribution. -------------------------------------------------------------------------------------------------------------------- -- SDL.Video.Surfaces.Makers -- -- Functions to create surface objects. -------------------------------------------------------------------------------------------------------------------- package SDL.Video.Surfaces.Makers is procedure Create (Self : in out Surface; Size : in SDL.Sizes; BPP : in Pixel_Depths; Red_Mask : in Colour_Masks; Blue_Mask : in Colour_Masks; Green_Mask : in Colour_Masks; Alpha_Mask : in Colour_Masks); -- TODO: This is likely a temporary place for this. It's likely I will add a Streams package. -- procedure Create (Self : in out Surface; File_Name : in String); private function Get_Internal_Surface (Self : in Surface) return Internal_Surface_Pointer with Export => True, Convention => Ada; -- Create a surface from an internal pointer, this pointer will be owned by something else, so we don't delete it. function Make_Surface_From_Pointer (S : in Internal_Surface_Pointer; Owns : in Boolean := False) return Surface with Export => True, Convention => Ada; -- TODO: SDL_ConvertSurface -- TODO: SDL_ConvertSurfaceFormat -- TODO: SDL_CreateRGBSurfaceFrom end SDL.Video.Surfaces.Makers;
burratoo/Acton
Ada
8,479
ads
------------------------------------------------------------------------------------------ -- -- -- ACTON PROCESSOR SUPPORT PACKAGE -- -- -- -- ATMEL.AT91SAM7S.PIO -- -- -- -- Copyright (C) 2014-2021, Patrick Bernardi -- -- -- ------------------------------------------------------------------------------------------ with Interfaces; use Interfaces; with System; use System; package Atmel.AT91SAM7S.PIO with Preelaborate is -------------------------- -- PIO Memory Addresses -- -------------------------- PIO_Base_Address : constant := 16#FFFF_F400#; PER_Offset_Address : constant := 16#0000#; PDR_Offset_Address : constant := 16#0004#; PSR_Offset_Address : constant := 16#0008#; OER_Offset_Address : constant := 16#0010#; ODR_Offset_Address : constant := 16#0014#; OSR_Offset_Address : constant := 16#0018#; IFER_Offset_Address : constant := 16#0020#; IFDR_Offset_Address : constant := 16#0024#; IFSR_Offset_Address : constant := 16#0028#; SODR_Offset_Address : constant := 16#0030#; CODR_Offset_Address : constant := 16#0034#; ODSR_Offset_Address : constant := 16#0038#; PDSR_Offset_Address : constant := 16#003C#; IER_Offset_Address : constant := 16#0040#; IDR_Offset_Address : constant := 16#0044#; IMR_Offset_Address : constant := 16#0048#; ISR_Offset_Address : constant := 16#004C#; MDER_Offset_Address : constant := 16#0050#; MDDR_Offset_Address : constant := 16#0054#; MDSR_Offset_Address : constant := 16#0058#; PUDR_Offset_Address : constant := 16#0060#; PUER_Offset_Address : constant := 16#0064#; PUSR_Offset_Address : constant := 16#0068#; ASR_Offset_Address : constant := 16#0070#; BSR_Offset_Address : constant := 16#0074#; ABSR_Offset_Address : constant := 16#0078#; OWER_Offset_Address : constant := 16#00A0#; OWDR_Offset_Address : constant := 16#00A4#; OWSR_Offset_Address : constant := 16#00A8#; ----------------------- -- Hardware Features -- ----------------------- --------------- -- PIO Types -- --------------- type Active_Status_Type is (Inactive, Active); type Output_Status_Type is (Pure_Input, Output_Enabled); type Change_Type is (No_Change, Change_Occured); type Select_Type is (No_Change, Use_Peripheral); type Peripheral_Assigment_Type is (A, B); type Enable_Set is array (PIO_Lines) of Enable_No_Change_Type with Pack, Size => Register_Size, Alignment => 4; type Disable_Set is array (PIO_Lines) of Disable_No_Change_Type with Pack, Size => Register_Size, Alignment => 4; type Active_Status_Set is array (PIO_Lines) of Active_Status_Type with Pack, Size => Register_Size, Alignment => 4; type Output_Status_Set is array (PIO_Lines) of Output_Status_Type with Pack, Size => Register_Size, Alignment => 4; type Enabled_Set is array (PIO_Lines) of Enabled_Type with Pack, Size => Register_Size, Alignment => 4; type Binary_Set is array (PIO_Lines) of Boolean with Pack, Size => Register_Size, Alignment => 4; type Change_Set is array (PIO_Lines) of Change_Type with Pack, Size => Register_Size, Alignment => 4; type Select_Set is array (PIO_Lines) of Select_Type with Pack, Size => Register_Size, Alignment => 4; type Peripheral_Assigment_Set is array (PIO_Lines) of Peripheral_Assigment_Type with Pack, Size => Register_Size, Alignment => 4; ------------------------------ -- Hardware Representations -- ------------------------------ for Active_Status_Type use (Inactive => 0, Active => 1); for Output_Status_Type use (Pure_Input => 0, Output_Enabled => 1); for Change_Type use (No_Change => 0, Change_Occured => 1); for Select_Type use (No_Change => 0, Use_Peripheral => 1); for Peripheral_Assigment_Type use (A => 0, B => 1); ------------------- -- PIO Registers -- ------------------- PIO_Enable_Register : Enable_Set with Address => System'To_Address (PIO_Base_Address + PER_Offset_Address); PIO_Disable_Register : Disable_Set with Address => System'To_Address (PIO_Base_Address + PDR_Offset_Address); PIO_Status_Register : Active_Status_Set with Address => System'To_Address (PIO_Base_Address + PSR_Offset_Address); Output_Enable_Register : Enable_Set with Address => System'To_Address (PIO_Base_Address + OER_Offset_Address); Output_Disable_Register : Disable_Set with Address => System'To_Address (PIO_Base_Address + ODR_Offset_Address); Output_Status_Register : Output_Status_Set with Address => System'To_Address (PIO_Base_Address + OSR_Offset_Address); Input_Filter_Enable_Register : Enable_Set with Address => System'To_Address (PIO_Base_Address + IFER_Offset_Address); Input_Filter_Disable_Register : Disable_Set with Address => System'To_Address (PIO_Base_Address + IFDR_Offset_Address); Input_Filter_Status_Register : Enabled_Set with Address => System'To_Address (PIO_Base_Address + IFSR_Offset_Address); Set_Output_Data_Register : Enable_Set with Address => System'To_Address (PIO_Base_Address + SODR_Offset_Address); Clear_Output_Data_Register : Enable_Set with Address => System'To_Address (PIO_Base_Address + CODR_Offset_Address); Output_Data_Status_Register : Binary_Set with Address => System'To_Address (PIO_Base_Address + ODSR_Offset_Address); Output_Data_Status_Register_Word : Unsigned_32 with Address => System'To_Address (PIO_Base_Address + ODSR_Offset_Address); Pin_Data_Status_Register : Binary_Set with Address => System'To_Address (PIO_Base_Address + PDSR_Offset_Address); Pin_Data_Status_Register_Word : Unsigned_32 with Address => System'To_Address (PIO_Base_Address + PDSR_Offset_Address); Interrupt_Enable_Register : Enable_Set with Address => System'To_Address (PIO_Base_Address + IER_Offset_Address); Interrupt_Disable_Register : Disable_Set with Address => System'To_Address (PIO_Base_Address + IDR_Offset_Address); Interrupt_Mask_Register : Enabled_Set with Address => System'To_Address (PIO_Base_Address + IMR_Offset_Address); Interrupt_Status_Register : Change_Set with Address => System'To_Address (PIO_Base_Address + ISR_Offset_Address); Multi_Driver_Enable_Register : Enable_Set with Address => System'To_Address (PIO_Base_Address + MDER_Offset_Address); Multi_Driver_Disable_Register : Disable_Set with Address => System'To_Address (PIO_Base_Address + MDDR_Offset_Address); Multi_Driver_Status_Register : Enabled_Set with Address => System'To_Address (PIO_Base_Address + MDSR_Offset_Address); Pull_Up_Disable_Register : Disable_Set with Address => System'To_Address (PIO_Base_Address + PUDR_Offset_Address); Pull_Up_Enable_Register : Enable_Set with Address => System'To_Address (PIO_Base_Address + PUER_Offset_Address); Pull_Up_Status_Register : Enabled_Set with Address => System'To_Address (PIO_Base_Address + PUER_Offset_Address); Peripheral_A_Select_Register : Select_Set with Address => System'To_Address (PIO_Base_Address + ASR_Offset_Address); Peripheral_B_Select_Register : Select_Set with Address => System'To_Address (PIO_Base_Address + BSR_Offset_Address); Peripheral_Status_Register : Peripheral_Assigment_Type with Address => System'To_Address (PIO_Base_Address + ABSR_Offset_Address); Output_Write_Enable_Register : Enable_Set with Address => System'To_Address (PIO_Base_Address + OWER_Offset_Address); Output_Write_Disable_Register : Disable_Set with Address => System'To_Address (PIO_Base_Address + OWDR_Offset_Address); Output_Write_Status_Register : Enabled_Set with Address => System'To_Address (PIO_Base_Address + OWSR_Offset_Address); end Atmel.AT91SAM7S.PIO;
danva994/AdaSDL2
Ada
915
adb
package body SDL.Mixer is procedure SDL_MIXER_VERSION (X : access SDL_version) is begin X.major := SDL_MIXER_MAJOR_VERSION; X.minor := SDL_MIXER_MINOR_VERSION; X.patch := SDL_MIXER_PATCHLEVEL; end SDL_MIXER_VERSION; function Mix_LoadWAV (file : C.char_array) return access Mix_Chunk is begin return Mix_LoadWAV_RW (SDL_RWFromFile (file, C.To_C ("rb")), 1); end Mix_LoadWAV; function Mix_PlayChannel (channel : C.int; chunk : access Mix_Chunk; loops : C.int) return C.int is begin return Mix_PlayChannelTimed (channel, chunk, loops, -1); end Mix_PlayChannel; function Mix_FadeInChannel (channel : C.int; chunk : access Mix_Chunk; loops : C.int; ms : C.int) return C.int is begin return Mix_FadeInChannelTimed (channel, chunk, loops, ms, -1); end Mix_FadeInChannel; end SDL.Mixer;
godunko/adagl
Ada
3,328
ads
------------------------------------------------------------------------------ -- -- -- Ada binding for OpenGL/WebGL -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2016-2018, Vadim Godunko <[email protected]> -- -- 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. -- -- -- ------------------------------------------------------------------------------ with WebAPI.WebGL.Textures; package OpenGL.Textures.Internals is pragma Preelaborate; function Get_WebGL_Texture (Self : OpenGL_Texture'Class) return WebAPI.WebGL.Textures.WebGL_Texture_Access; end OpenGL.Textures.Internals;
reznikmm/matreshka
Ada
4,093
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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$ ------------------------------------------------------------------------------ with ODF.DOM.Db_Data_Source_Setting_Type_Attributes; package Matreshka.ODF_Db.Data_Source_Setting_Type_Attributes is type Db_Data_Source_Setting_Type_Attribute_Node is new Matreshka.ODF_Db.Abstract_Db_Attribute_Node and ODF.DOM.Db_Data_Source_Setting_Type_Attributes.ODF_Db_Data_Source_Setting_Type_Attribute with null record; overriding function Create (Parameters : not null access Matreshka.DOM_Attributes.Attribute_L2_Parameters) return Db_Data_Source_Setting_Type_Attribute_Node; overriding function Get_Local_Name (Self : not null access constant Db_Data_Source_Setting_Type_Attribute_Node) return League.Strings.Universal_String; end Matreshka.ODF_Db.Data_Source_Setting_Type_Attributes;
onox/orka
Ada
8,530
adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2020 onox <[email protected]> -- -- 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.Numerics.Generic_Elementary_Functions; with GL.Barriers; with GL.Compute; with GL.Toggles; with GL.Types; with Orka.Rendering.Drawing; with Orka.Rendering.Programs.Modules; with Orka.Rendering.Textures; package body Orka.Rendering.Effects.Filters is package EF is new Ada.Numerics.Generic_Elementary_Functions (Float_64); function Gaussian_Kernel (Radius : Size) return Float_32_Array is Sigma : constant Float_64 := ((Float_64 (Radius) - 1.0) * 0.5 - 1.0) * 0.3 + 0.8; Denominator : constant Float_64 := EF.Sqrt (2.0 * Ada.Numerics.Pi * Sigma ** 2); Kernel : Float_64_Array (0 .. Radius); Sum : Float_64 := 0.0; begin for Index in Kernel'Range loop Kernel (Index) := EF.Exp (-Float_64 (Index**2) / (2.0 * Sigma ** 2)) / Denominator; Sum := Sum + Kernel (Index) * (if Index > 0 then 2.0 else 1.0); -- Kernel array only stores the positive side of the curve, but -- we need to compute the area of the whole curve for normalization end loop; -- Normalize the weights to prevent the image from becoming darker for Index in Kernel'Range loop Kernel (Index) := Kernel (Index) / Sum; end loop; declare -- Use bilinear texture filtering hardware [1]. -- -- Weight (t1, t2) = Weight (t1) + Weight (t2) -- -- offset (t1) * weight (t1) + offset (t2) * weight (t2) -- Offset (t1, t2) = ----------------------------------------------------- -- weight (t1, t2) -- -- [1] http://rastergrid.com/blog/2010/09/efficient-gaussian-blur-with-linear-sampling/ Weights : Float_32_Array (0 .. Radius / 2); Offsets : Float_32_Array (0 .. Radius / 2); begin Weights (Weights'First) := Float_32 (Kernel (Weights'First)); Offsets (Offsets'First) := 0.0; -- Weights for Index in Weights'First + 1 .. Weights'Last loop declare T1 : constant Size := Index * 2 - 1; T2 : constant Size := Index * 2; begin Weights (Index) := Float_32 (Kernel (T1) + Kernel (T2)); end; end loop; -- Offsets for Index in Offsets'First + 1 .. Offsets'Last loop declare T1 : constant Size := Index * 2 - 1; T2 : constant Size := Index * 2; W12 : constant Float_32 := Weights (Index); begin if W12 > 0.0 then Offsets (Index) := Float_32 ((Float_64 (T1) * Kernel (T1) + Float_64 (T2) * Kernel (T2)) / Float_64 (W12)); else Offsets (Index) := 0.0; end if; end; end loop; return Offsets & Weights; end; end Gaussian_Kernel; function Create_Filter (Location : Resources.Locations.Location_Ptr; Subject : GL.Objects.Textures.Texture; Kernel : Float_32_Array) return Separable_Filter is use all type LE.Texture_Kind; pragma Assert (Subject.Kind = LE.Texture_Rectangle); use Rendering.Buffers; use Rendering.Framebuffers; use Rendering.Programs; Width : constant Size := Subject.Width (0); Height : constant Size := Subject.Height (0); begin return Result : Separable_Filter := (Buffer_Weights => Create_Buffer ((others => False), Kernel), Program_Blur => Create_Program (Modules.Module_Array' (Modules.Create_Module (Location, VS => "oversized-triangle.vert"), Modules.Create_Module (Location, FS => "effects/blur.frag"))), Framebuffer_H => Create_Framebuffer (Width, Height), Framebuffer_V => Create_Framebuffer (Width, Height), Texture_H => Subject, others => <>) do Result.Uniform_Horizontal := Result.Program_Blur.Uniform ("horizontal"); Result.Texture_V.Allocate_Storage (Subject); Result.Framebuffer_H.Attach (Result.Texture_H); Result.Framebuffer_V.Attach (Result.Texture_V); end return; end Create_Filter; procedure Render (Object : in out Separable_Filter; Passes : Positive := 1) is use all type Orka.Rendering.Buffers.Indexed_Buffer_Target; begin GL.Toggles.Disable (GL.Toggles.Depth_Test); Object.Program_Blur.Use_Program; Object.Buffer_Weights.Bind (Shader_Storage, 0); for Pass in 1 .. Passes loop -- Horizontal pass: Texture_H => Texture_V Object.Uniform_Horizontal.Set_Boolean (True); Orka.Rendering.Textures.Bind (Object.Texture_H, Orka.Rendering.Textures.Texture, 0); Object.Framebuffer_V.Use_Framebuffer; Orka.Rendering.Drawing.Draw (GL.Types.Triangles, 0, 3); -- Vertical pass: Texture_V => Texture_H Object.Uniform_Horizontal.Set_Boolean (False); Orka.Rendering.Textures.Bind (Object.Texture_V, Orka.Rendering.Textures.Texture, 0); Object.Framebuffer_H.Use_Framebuffer; Orka.Rendering.Drawing.Draw (GL.Types.Triangles, 0, 3); end loop; GL.Toggles.Enable (GL.Toggles.Depth_Test); end Render; ----------------------------------------------------------------------------- function Create_Filter (Location : Resources.Locations.Location_Ptr; Subject : GL.Objects.Textures.Texture; Radius : Size) return Moving_Average_Filter is use all type LE.Texture_Kind; pragma Assert (Subject.Kind = LE.Texture_Rectangle); use Rendering.Programs; Width : constant Size := Subject.Width (0); Height : constant Size := Subject.Height (0); begin return Result : Moving_Average_Filter := (Program_Blur => Create_Program (Modules.Create_Module (Location, CS => "effects/moving-average-blur.comp")), Texture_H => Subject, others => <>) do Result.Uniform_Horizontal := Result.Program_Blur.Uniform ("horizontal"); Result.Program_Blur.Uniform ("radius").Set_Int (Radius); Result.Texture_V.Allocate_Storage (Subject); declare Work_Group_Size : constant Float_32 := Float_32 (Result.Program_Blur.Compute_Work_Group_Size (X)); begin Result.Columns := Unsigned_32 (Float_32'Ceiling (Float_32 (Width) / Work_Group_Size)); Result.Rows := Unsigned_32 (Float_32'Ceiling (Float_32 (Height) / Work_Group_Size)); end; end return; end Create_Filter; procedure Render (Object : in out Moving_Average_Filter; Passes : Positive := 2) is begin Object.Program_Blur.Use_Program; for Pass in 1 .. Passes loop -- Horizontal pass: Texture_H => Texture_V Object.Uniform_Horizontal.Set_Boolean (True); Orka.Rendering.Textures.Bind (Object.Texture_H, Orka.Rendering.Textures.Texture, 0); Orka.Rendering.Textures.Bind (Object.Texture_V, Orka.Rendering.Textures.Image, 1); GL.Compute.Dispatch_Compute (X => Object.Rows); GL.Barriers.Memory_Barrier ((Shader_Image_Access | Texture_Fetch => True, others => False)); -- Vertical pass: Texture_V => Texture_H Object.Uniform_Horizontal.Set_Boolean (False); Orka.Rendering.Textures.Bind (Object.Texture_V, Orka.Rendering.Textures.Texture, 0); Orka.Rendering.Textures.Bind (Object.Texture_H, Orka.Rendering.Textures.Image, 1); GL.Compute.Dispatch_Compute (X => Object.Columns); GL.Barriers.Memory_Barrier ((Shader_Image_Access | Texture_Fetch => True, others => False)); end loop; end Render; end Orka.Rendering.Effects.Filters;
ph0sph8/amass
Ada
1,426
ads
-- Copyright 2017 Jeff Foley. All rights reserved. -- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. local json = require("json") name = "ZETAlytics" type = "api" function start() setratelimit(5) end function vertical(ctx, domain) if (api == nil or api.key == "") then return end local resp local vurl = buildurl(domain) -- Check if the response data is in the graph database if (api.ttl ~= nil and api.ttl > 0) then resp = obtain_response(vurl, api.ttl) end if (resp == nil or resp == "") then local err resp, err = request({ url=vurl, headers={['Content-Type']="application/json"}, }) if (err ~= nil and err ~= "") then return end if (api.ttl ~= nil and api.ttl > 0) then cache_response(vurl, resp) end end local d = json.decode(resp) if (d == nil or #(d.results) == 0) then return end for i, r in pairs(d.results) do sendnames(ctx, r.qname) end end function buildurl(domain) return "https://zonecruncher.com/api/v1/subdomains?q=" .. domain .. "&token=" .. api.key end function sendnames(ctx, content) local names = find(content, subdomainre) if names == nil then return end for i, v in pairs(names) do newname(ctx, v) end end
AdaCore/libadalang
Ada
150
adb
procedure Test_Derived_Discrete is type B is new Integer; C : B := B'First; pragma Test_Statement; begin null; end Test_Derived_Discrete;
zhmu/ananas
Ada
2,086
ads
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- G N A T N A M E -- -- -- -- S p e c -- -- -- -- Copyright (C) 2001-2022, 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. -- -- -- ------------------------------------------------------------------------------ -- Tool for dealing with source files with arbitrary naming conventions. -- It either creates a configuration pragmas file, or updates or creates -- a project file. procedure Gnatname;
wiremoons/apass
Ada
4,363
adb
------------------------------------------------------------------------------- -- BUILD FILE : apass -- -- Description : A CLI password generator written in Ada. -- -- Author : Simon Rowe <[email protected]> -- -- License : MIT Open Source. -- ------------------------------------------------------------------------------- with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Command_Line; use Ada.Command_Line; -- use local packages with Password_Manager; with Cmd_Flags; procedure Apass is -------------------------- -- MAIN -------------------------- Full_Password_Str : Unbounded_String := Null_Unbounded_String; Total_Passwords : Integer := 3; Number_Of_Words : constant Integer := 3; begin -- print info on how to compile a 'release' version pragma Debug (Put_Line (Standard_Error, "[DEBUG] build a 'release' version with: gprclean && gprbuild -XBUILD=release")); -- Check if any command line options were used and if they are they will be executed -- and then the program can exit here if Cmd_Flags.Command_Line_Flags_Exist then Set_Exit_Status (Success); pragma Debug (Put_Line (Standard_Error, "[DEBUG] exit with 'success'.")); return; -- exit as flags found and executed else -- Set_Exit_Status (Failure); -- failed as no database found -- pragma Debug (Put_Line (Standard_Error, "[DEBUG] exit with 'failure'.")); Put_Line ("Program 'apass' running..."); Put_Line ("Total words available to construct passwords: " & Password_Manager.Total_Words); Put_Line ("Number of suggested passwords per group:" & Integer'Image (Total_Passwords)); Put_Line ("Number of words to use per password string:" & Integer'Image (Number_Of_Words)); New_Line (1); -- output of mixed lowercase with two punctuation marks and two random numbers surrounding the string while Total_Passwords > 0 loop Full_Password_Str := To_Unbounded_String (Password_Manager.Get_Random_Number); --Full_Password_Str := Full_Password_Str & To_Unbounded_String (Password_Manager.Get_Random_Mark); Append (Full_Password_Str, To_Unbounded_String (Password_Manager.Get_Random_Mark)); Append (Full_Password_Str, To_Unbounded_String (Password_Manager.Basic_Password (Number_Of_Words))); Append (Full_Password_Str, To_Unbounded_String (Password_Manager.Get_Random_Mark)); Append (Full_Password_Str, To_Unbounded_String (Password_Manager.Get_Random_Number)); Password_Manager.Print_Password (To_String (Full_Password_Str)); Total_Passwords := Total_Passwords - 1; end loop; Put_Line (" "); New_Line (1); Total_Passwords := 3; -- output of mixed lowercase with two punctuation marks and two random numbers surrounding the string while Total_Passwords > 0 loop Full_Password_Str := To_Unbounded_String (Password_Manager.Basic_Password (Number_Of_Words)); Append (Full_Password_Str, To_Unbounded_String (Password_Manager.Get_Random_Mark)); Append (Full_Password_Str, To_Unbounded_String (Password_Manager.Get_Random_Number)); Password_Manager.Print_Password (To_String (Full_Password_Str)); Total_Passwords := Total_Passwords - 1; end loop; Put_Line (" "); New_Line (1); Total_Passwords := 3; -- output of mixed lowercase with two punctuation marks and two random numbers surrounding the string while Total_Passwords > 0 loop Full_Password_Str := To_Unbounded_String (Password_Manager.Capitilised_Password (Number_Of_Words)); Append (Full_Password_Str, To_Unbounded_String (Password_Manager.Get_Random_Mark)); Append (Full_Password_Str, To_Unbounded_String (Password_Manager.Get_Random_Number)); Password_Manager.Print_Password (To_String (Full_Password_Str)); Total_Passwords := Total_Passwords - 1; end loop; Put_Line (" "); end if; Set_Exit_Status (Success); pragma Debug (Put_Line (Standard_Error, "[DEBUG] exit with 'success'.")); return; -- exit as flags found and executed end Apass;
MinimSecure/unum-sdk
Ada
1,023
adb
-- Copyright 2015-2016 Free Software Foundation, Inc. -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. procedure Foo is function F (C : Character) return Integer is begin return Character'Pos (C); end F; function F (I : Integer) return Integer is begin return -I; end F; I1 : constant Integer := F ('A'); -- BREAK I2 : constant Integer := F (1); begin null; end Foo;
AdaCore/gpr
Ada
1,609
adb
-- -- Copyright (C) 2019-2023, AdaCore -- -- SPDX-License-Identifier: Apache-2.0 -- with Ada.Directories; with Ada.Strings.Fixed; with Ada.Text_IO; with GPR2.Context; with GPR2.Log; with GPR2.Project.View; with GPR2.Project.Tree; procedure Main is use Ada; use GPR2; use GPR2.Project; Projects : constant array (1 .. 3) of String (1 .. 1) := ("a", "b", "c"); begin for P of Projects loop declare Prj : Project.Tree.Object; Ctx : Context.Object; begin Project.Tree.Load (Prj, Create (Filename_Type (P)), Ctx); Text_IO.Put_Line ("All good, no message."); exception when GPR2.Project_Error => if Prj.Has_Messages then Text_IO.Put_Line ("Messages found:"); for C in Prj.Log_Messages.Iterate (False, False, True, True, True) loop declare Mes : constant String := Log.Element (C).Format; F : constant Natural := Strings.Fixed.Index (Mes, "imports "); L : constant Natural := Strings.Fixed.Index (Mes, "/limited-refs"); begin if F /= 0 and then L /= 0 then Text_IO.Put_Line (Mes (1 .. F + 7) & Mes (L .. Mes'Last)); else Text_IO.Put_Line (Mes); end if; end; end loop; end if; end; end loop; end Main;
reznikmm/matreshka
Ada
4,752
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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$ ------------------------------------------------------------------------------ with Matreshka.DOM_Documents; with Matreshka.ODF_String_Constants; with ODF.DOM.Iterators; with ODF.DOM.Visitors; package body Matreshka.ODF_Table.Source_Cell_Range_Addresses_Attributes is ------------ -- Create -- ------------ overriding function Create (Parameters : not null access Matreshka.DOM_Attributes.Attribute_L2_Parameters) return Table_Source_Cell_Range_Addresses_Attribute_Node is begin return Self : Table_Source_Cell_Range_Addresses_Attribute_Node do Matreshka.ODF_Table.Constructors.Initialize (Self'Unchecked_Access, Parameters.Document, Matreshka.ODF_String_Constants.Table_Prefix); end return; end Create; -------------------- -- Get_Local_Name -- -------------------- overriding function Get_Local_Name (Self : not null access constant Table_Source_Cell_Range_Addresses_Attribute_Node) return League.Strings.Universal_String is pragma Unreferenced (Self); begin return Matreshka.ODF_String_Constants.Source_Cell_Range_Addresses_Attribute; end Get_Local_Name; begin Matreshka.DOM_Documents.Register_Attribute (Matreshka.ODF_String_Constants.Table_URI, Matreshka.ODF_String_Constants.Source_Cell_Range_Addresses_Attribute, Table_Source_Cell_Range_Addresses_Attribute_Node'Tag); end Matreshka.ODF_Table.Source_Cell_Range_Addresses_Attributes;
jorge-real/TTS-Ravenscar
Ada
146
ads
package Use_CPU is procedure Work (Amount_MS : in Natural) with Inline; -- Amount of time in ms, truncated to tens of ms end Use_CPU;
jrmarino/AdaBase
Ada
409
ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../../License.txt private with Ada.Finalization; package AdaBase.Statement is pragma Pure; type Base_Pure is abstract tagged private; private package FIN renames Ada.Finalization; type Base_Pure is abstract new FIN.Controlled with record null; end record; end AdaBase.Statement;
charlie5/lace
Ada
20,310
adb
with openGL.Geometry.colored, openGL.Primitive.indexed, float_Math.Geometry.d2.Hexagon, ada.Containers.hashed_Maps, ada.unchecked_Deallocation; package body openGL.Model.hex_grid is -------- -- Forge -- function new_Grid (heights_Asset : in asset_Name; Heights : in height_Map_view; Color : in lucid_Color := (palette.White, Opaque)) return View is the_Model : constant View := new Item' (Model.item with heights_Asset => heights_Asset, Heights => Heights, Color => +Color); begin the_Model.set_Bounds; return the_Model; end new_Grid; overriding procedure destroy (Self : in out Item) is procedure deallocate is new ada.unchecked_Deallocation (height_Map, height_Map_view); begin destroy (Model.item (Self)); deallocate (Self.Heights); end destroy; ------------- -- Attributes -- package hexagon_Geometry renames Geometry_2d.Hexagon; -- site_Map_of_vertex_Id -- function Hash (From : in Geometry_2d.Site) return ada.Containers.Hash_type is use ada.Containers; type Fix is delta 0.00_1 range 0.0 .. 1000.0; cell_Size : constant Fix := 0.5; grid_Width : constant := 10; begin return Hash_type (Fix (From (1)) / cell_Size) + Hash_type (Fix (From (2)) / cell_Size) * grid_Width; end Hash; function Equivalent (S1, S2 : Geometry_2d.Site) return Boolean is Tolerance : constant := 0.1; begin return abs (S2 (1) - S1 (1)) < Tolerance and abs (S2 (2) - S1 (2)) < Tolerance; end Equivalent; type Coordinates_array is array (Index_t range <>) of hexagon_Geometry.Coordinates; type hex_Vertex is record shared_Hexes : Coordinates_array (1 .. 3); shared_Count : Index_t := 0; Site : Geometry_3d.Site; end record; type hex_Vertices is array (Index_t range <>) of hex_Vertex; package site_Maps_of_vertex_Id is new ada.Containers.hashed_Maps (Key_type => Geometry_2d.Site, Element_type => Index_t, Hash => Hash, equivalent_Keys => Equivalent, "=" => "="); overriding function to_GL_Geometries (Self : access Item; Textures : access Texture.name_Map_of_texture'Class; Fonts : in Font.font_id_Map_of_font) return Geometry.views is pragma Unreferenced (Textures, Fonts); use Geometry, Geometry.colored, Geometry_2d; site_Map_of_vertex_Id : site_Maps_of_vertex_Id.Map; next_free_vertex_Id : Index_t := 0; function fetch_Id (S : in geometry_2d.Site) return Index_t is use site_Maps_of_vertex_Id; C : constant Cursor := site_Map_of_vertex_Id.Find (S); begin if has_Element (C) then return Element (C); else next_free_vertex_Id := @ + 1; site_Map_of_vertex_Id.insert (S, next_free_vertex_Id); return next_free_vertex_Id; end if; end fetch_Id; Heights : height_Map_view renames Self.Heights; row_Count : constant Index_t := Heights'Length (1); col_Count : constant Index_t := Heights'Length (2); the_Grid : constant hexagon_Geometry.Grid := Hexagon.to_Grid (Rows => Positive (row_Count), Cols => Positive (col_Count), circumRadius => 1.0); zigzag_Count : constant Index_t := col_Count + 1; first_zigzag_vertex_Count : constant Index_t := row_Count * 2 + 1; mid_zigzag_vertex_Count : constant Index_t := row_Count * 2 + 2; last_zigzag_vertex_Count : constant Index_t := row_Count * 2 + 1; zigzags_vertex_Count : constant Index_t := first_zigzag_vertex_Count + (mid_zigzag_vertex_Count) * (zigzag_Count - 2) + last_zigzag_vertex_Count; zigzag_joiner_vertex_Count : constant Index_t := col_Count * 2; vertex_Count : constant Index_t := zigzags_vertex_Count + zigzag_joiner_vertex_Count; hex_Vertices : hex_Grid.hex_Vertices (1 .. zigzags_vertex_Count); zigzags_indices_Count : constant long_Index_t := long_Index_t (vertex_Count); gl_Vertices : aliased Geometry.colored.Vertex_array (1 .. vertex_Count); hex_Count : constant long_Index_t := long_Index_t (col_Count * row_Count * 2); zigzags_Indices : aliased Indices (1 .. zigzags_indices_Count); tops_Indices : aliased Indices (1 .. hex_Count + long_Index_t (col_Count * 2)); zigzags_Geometry : constant Geometry.colored.view := Geometry.colored.new_Geometry; tops_Geometry : constant Geometry.colored.view := Geometry.colored.new_Geometry; min_Site : Site := [Real'Last, Real'Last, Real'Last]; max_Site : Site := [Real'First, Real'First, Real'First]; begin find_shared_Hexes_per_Vertex: begin for Row in 1 .. row_Count loop for Col in 1 .. col_Count loop for Which in hexagon_Geometry.vertex_Id loop declare use hexagon_Geometry; Site : constant Geometry_2d.Site := vertex_Site (the_Grid, hex_Id => [Positive (Row), Positive (Col)], Which => Which); vertex_Id : constant Index_t := fetch_Id (S => Site); the_Vertex : hex_Vertex renames hex_Vertices (vertex_Id); C : constant Index_t := the_Vertex.shared_Count + 1; begin the_Vertex.shared_Count := C; the_Vertex.shared_Hexes (C) := [Positive (Row), Positive (Col)]; the_Vertex.Site := [Site (1), 0.0, Site (2)]; end; end loop; end loop; end loop; end find_shared_Hexes_per_Vertex; set_Height_for_each_Vertex: begin for Row in 1 .. row_Count loop for Col in 1 .. col_Count loop for Which in hexagon_Geometry.vertex_Id loop declare use hexagon_Geometry; Site : constant Geometry_2d.Site := vertex_Site (the_Grid, hex_Id => [Positive (Row), Positive (Col)], Which => Which); Height : Real := 0.0; vertex_Id : constant Index_t := fetch_Id (S => Site); the_Vertex : hex_Vertex renames hex_Vertices (vertex_Id); begin for Each in 1 .. the_Vertex.shared_Count loop Height := Height + Heights (Row, Col); end loop; Height := Height / Real (the_Vertex.shared_Count); the_Vertex.Site := [Site (1), Height, Site (2)]; min_Site := [Real'Min (min_Site (1), the_Vertex.Site (1)), Real'Min (min_Site (2), the_Vertex.Site (2)), Real'Min (min_Site (3), the_Vertex.Site (3))]; max_Site := [Real'Max (min_Site (1), the_Vertex.Site (1)), Real'Max (min_Site (2), the_Vertex.Site (2)), Real'Max (min_Site (3), the_Vertex.Site (3))]; end; end loop; end loop; end loop; end set_Height_for_each_Vertex; set_GL_Vertices: declare Center : constant Site := [(max_Site (1) - min_Site (1)) / 2.0, (max_Site (2) - min_Site (2)) / 2.0, (max_Site (3) - min_Site (3)) / 2.0]; vertex_Id : Index_t := 0; Color : constant rgba_Color := Self.Color; begin --- Add hex vertices. -- for i in hex_Vertices'Range loop vertex_Id := vertex_Id + 1; gl_Vertices (vertex_Id).Site := hex_Vertices (vertex_Id).Site - Center; gl_Vertices (vertex_Id).Color := Color; end loop; --- Add joiner vertices. -- for i in 1 .. col_Count loop declare use hexagon_Geometry; Site : Geometry_2d.Site := vertex_Site (the_Grid, hex_Id => [Row => Positive (row_Count), Col => Positive (i)], Which => 3); hex_vertex_Id : Index_t := fetch_Id (Site); begin vertex_Id := vertex_Id + 1; gl_Vertices (vertex_Id) := (Site => hex_Vertices (hex_vertex_Id).Site - Center, Color => (Primary => Color.Primary, Alpha => 0)); Site := vertex_Site (the_Grid, hex_Id => [Row => 1, Col => Positive (i)], Which => 6); hex_vertex_Id := fetch_Id (Site); vertex_Id := vertex_Id + 1; gl_Vertices (vertex_Id) := (Site => hex_Vertices (hex_vertex_Id).Site - Center, Color => (Primary => Color.Primary, Alpha => 0)); end; end loop; end set_GL_Vertices; set_zigzags_GL_Indices: declare Cursor : long_Index_t := 0; joiners_vertex_Id : Index_t := zigzags_vertex_Count; procedure add_zigzag_Vertex (Row, Col : in Positive; hex_Vertex : in Hexagon.vertex_Id) is use hexagon_Geometry; Site : constant Geometry_2d.Site := vertex_Site (the_Grid, hex_Id => [Row, Col], Which => hex_Vertex); begin Cursor := Cursor + 1; zigzags_Indices (Cursor) := fetch_Id (S => Site); end add_zigzag_Vertex; procedure add_joiner_vertex_Pair is begin Cursor := Cursor + 1; joiners_vertex_Id := joiners_vertex_Id + 1; zigzags_Indices (Cursor) := joiners_vertex_Id; Cursor := Cursor + 1; joiners_vertex_Id := joiners_vertex_Id + 1; zigzags_Indices (Cursor) := joiners_vertex_Id; end add_joiner_vertex_Pair; begin --- Fist zigzag -- add_zigzag_Vertex (Row => 1, Col => 1, hex_Vertex => 5); for Row in 1 .. Positive (row_Count) loop add_zigzag_Vertex (Row, Col => 1, hex_Vertex => 4); add_zigzag_Vertex (Row, Col => 1, hex_Vertex => 3); end loop; add_joiner_vertex_Pair; --- Middles zigzags -- for zz in 2 .. Positive (zigzag_Count) - 1 loop declare odd_Zigzag : constant Boolean := zz mod 2 = 1; begin if odd_Zigzag then add_zigzag_Vertex (Row => 1, Col => Positive (zz), hex_Vertex => 5); else -- Even zigzag. add_zigzag_Vertex (Row => 1, Col => Positive (zz - 1), hex_Vertex => 6); end if; for Row in 1 .. Positive (row_Count) loop if odd_Zigzag then add_zigzag_Vertex (Row, Col => zz, hex_Vertex => 4); add_zigzag_Vertex (Row, Col => zz, hex_Vertex => 3); if Row = Positive (row_Count) -- Last row. then add_zigzag_Vertex (Row, Col => zz - 1, hex_Vertex => 2); end if; else -- Even zigzag. add_zigzag_Vertex (Row, Col => zz, hex_Vertex => 5); add_zigzag_Vertex (Row, Col => zz, hex_Vertex => 4); if Row = Positive (row_Count) -- Last row. then add_zigzag_Vertex (Row, Col => zz, hex_Vertex => 3); end if; end if; end loop; end; add_joiner_vertex_Pair; end loop; --- Last zigzag -- add_zigzag_Vertex (Row => 1, Col => Positive (col_Count), hex_Vertex => 6); for Row in 1 .. Positive (row_Count) loop add_zigzag_Vertex (Row, Positive (col_Count), hex_Vertex => 1); add_zigzag_Vertex (Row, Positive (col_Count), hex_Vertex => 2); end loop; end set_zigzags_GL_Indices; zigzags_Geometry.is_Transparent (False); zigzags_Geometry.Vertices_are (gl_Vertices); set_tops_GL_Indices: declare Cursor : long_Index_t := 0; begin for Col in 1 .. col_Count loop for Row in 1 .. row_Count loop declare use hexagon_Geometry; Site : Geometry_2d.Site := vertex_Site (the_Grid, hex_Id => [Positive (Row), Positive (Col)], Which => 5); begin Cursor := Cursor + 1; tops_Indices (Cursor) := fetch_Id (Site); Site := vertex_Site (the_Grid, hex_Id => [Positive (Row), Positive (Col)], Which => 6); Cursor := Cursor + 1; tops_Indices (Cursor) := fetch_Id (Site); if Row = row_Count -- Last row, so do bottoms. then Site := vertex_Site (the_Grid, hex_Id => [Positive (Row), Positive (Col)], Which => 3); Cursor := Cursor + 1; tops_Indices (Cursor) := fetch_Id (Site); Site := vertex_Site (the_Grid, hex_Id => [Positive (Row), Positive (Col)], Which => 2); Cursor := Cursor + 1; tops_Indices (Cursor) := fetch_Id (Site); end if; end; end loop; end loop; end set_tops_GL_Indices; tops_Geometry.is_Transparent (False); tops_Geometry.Vertices_are (gl_Vertices); add_zigzag_Geometry: declare the_Primitive : constant Primitive.indexed.view := Primitive.indexed.new_Primitive (Primitive.line_Strip, zigzags_Indices); begin zigzags_Geometry.add (Primitive.view (the_Primitive)); end add_zigzag_Geometry; add_tops_Geometry: declare the_Primitive : constant Primitive.indexed.view := Primitive.indexed.new_Primitive (Primitive.Lines, tops_Indices); begin tops_Geometry.add (Primitive.view (the_Primitive)); end add_tops_Geometry; return [1 => Geometry.view (zigzags_Geometry), 2 => Geometry.view ( tops_Geometry)]; end to_GL_Geometries; -- TODO: This is an approximation based on a rectangular grid. -- Do a correct calculation based on the hexagon grid vertices. -- overriding procedure set_Bounds (Self : in out Item) is Heights : height_Map_view renames Self.Heights; row_Count : constant Index_t := Heights'Length (1) - 1; col_Count : constant Index_t := Heights'Length (2) - 1; vertex_Count : constant Index_t := Heights'Length (1) * Heights'Length (2); the_Sites : aliased Sites (1 .. vertex_Count); the_Bounds : openGL.Bounds := null_Bounds; begin set_Sites: declare vert_Id : Index_t := 0; the_height_Range : constant Vector_2 := height_Extent (Heights.all); Middle : constant Real := (the_height_Range (1) + the_height_Range (2)) / 2.0; begin for Row in 1 .. row_Count + 1 loop for Col in 1 .. col_Count + 1 loop vert_Id := vert_Id + 1; the_Sites (vert_Id) := [Real (Col) - Real (col_Count) / 2.0 - 1.0, Heights (Row, Col) - Middle, Real (Row) - Real (row_Count) / 2.0 - 1.0]; the_Bounds.Box.Lower (1) := Real'Min (the_Bounds.Box.Lower (1), the_Sites (vert_Id) (1)); the_Bounds.Box.Lower (2) := Real'Min (the_Bounds.Box.Lower (2), the_Sites (vert_Id) (2)); the_Bounds.Box.Lower (3) := Real'Min (the_Bounds.Box.Lower (3), the_Sites (vert_Id) (3)); the_Bounds.Box.Upper (1) := Real'Max (the_Bounds.Box.Upper (1), the_Sites (vert_Id) (1)); the_Bounds.Box.Upper (2) := Real'Max (the_Bounds.Box.Upper (2), the_Sites (vert_Id) (2)); the_Bounds.Box.Upper (3) := Real'Max (the_Bounds.Box.Upper (3), the_Sites (vert_Id) (3)); the_Bounds.Ball := Real'Max (the_Bounds.Ball, abs (the_Sites (vert_Id))); end loop; end loop; the_Bounds.Ball := the_Bounds.Ball * 1.1; -- TODO: Why the '* 1.1' ? end set_Sites; Self.Bounds := the_Bounds; end set_Bounds; end openGL.Model.hex_grid;
AdaCore/langkit
Ada
1,348
adb
with Ada.Text_IO; use Ada.Text_IO; with Langkit_Support.Text; use Langkit_Support.Text; with Libfoolang.Analysis; use Libfoolang.Analysis; with Libfoolang.Common; use Libfoolang.Common; with Libfoolang.Rewriting; use Libfoolang.Rewriting; with Process_Apply; procedure Rewrite_Lists is Ctx : constant Analysis_Context := Create_Context; U : constant Analysis_Unit := Get_From_Buffer (Ctx, "main.txt", Buffer => ""); RH : Rewriting_Handle := Start_Rewriting (Ctx); N : constant Node_Rewriting_Handle := Handle (Root (U)); function Create_Def (Name, Lit : Text_Type) return Node_Rewriting_Handle; ---------------- -- Create_Def -- ---------------- function Create_Def (Name, Lit : Text_Type) return Node_Rewriting_Handle is begin return Create_Def (RH, Create_Token_Node (RH, Foo_Name, Name), No_Node_Rewriting_Handle, Create_Token_Node (RH, Foo_Literal, Lit)); end Create_Def; begin Insert_Child (N, 1, Create_Def ("a", "1")); Append_Child (N, Create_Def ("b", "2")); Append_Child (N, Create_Def ("c", "3")); Remove_Child (N, 2); Put_Line ("Applying the diff..."); Process_Apply (RH); Root (U).Print (Show_Slocs => False); Put_Line ("rewrite_lists.adb: Done."); end Rewrite_Lists;
reznikmm/matreshka
Ada
6,277
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Localization, Internationalization, Globalization for Ada -- -- -- -- Tools Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2009, Vadim Godunko <[email protected]> -- -- 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$ ------------------------------------------------------------------------------ with Ada.Text_IO; package body Segments_Readers is use Ada.Strings.Unbounded; LDML_Tag : constant String := "ldml"; Identity_Tag : constant String := "identity"; Version_Tag : constant String := "version"; Generation_Tag : constant String := "generation"; Language_Tag : constant String := "language"; Segmentations_Tag : constant String := "segmentations"; Segmentation_Tag : constant String := "segmentation"; Variables_Tag : constant String := "variables"; Variable_Tag : constant String := "variable"; Segment_Rules_Tag : constant String := "segmentRules"; Rule_Tag : constant String := "rule"; Id_Attribute : constant String := "id"; -- function "+" (Right : String) return Unbounded_String -- renames To_Unbounded_String; ---------------- -- Characters -- ---------------- overriding procedure Characters (Self : in out Segments_Reader; Ch : Unicode.CES.Byte_Sequence) is begin Append (Self.C, Ch); end Characters; ----------------- -- End_Element -- ----------------- overriding procedure End_Element (Self : in out Segments_Reader; Namespace_URI : Unicode.CES.Byte_Sequence := ""; Local_Name : Unicode.CES.Byte_Sequence := ""; Qname : Unicode.CES.Byte_Sequence := "") is begin if Local_Name = Variable_Tag or else Local_Name = Rule_Tag then Ada.Text_IO.Put_Line (To_String (Self.C)); end if; end End_Element; ------------------- -- Start_Element -- ------------------- overriding procedure Start_Element (Self : in out Segments_Reader; Namespace_URI : Unicode.CES.Byte_Sequence := ""; Local_Name : Unicode.CES.Byte_Sequence := ""; Qname : Unicode.CES.Byte_Sequence := ""; Attrs : Sax.Attributes.Attributes'Class) is begin if Local_Name = LDML_Tag then null; elsif Local_Name = Identity_Tag then null; elsif Local_Name = Version_Tag then null; elsif Local_Name = Generation_Tag then null; elsif Local_Name = Language_Tag then null; elsif Local_Name = Segmentations_Tag then null; elsif Local_Name = Segmentation_Tag then null; elsif Local_Name = Variables_Tag then null; elsif Local_Name = Variable_Tag then Ada.Text_IO.Put (Attrs.Get_Value (Id_Attribute) & " := "); Self.C := Null_Unbounded_String; elsif Local_Name = Segment_Rules_Tag then null; elsif Local_Name = Rule_Tag then Ada.Text_IO.Put (Attrs.Get_Value (Id_Attribute) & " => "); Self.C := Null_Unbounded_String; else Ada.Text_IO.Put_Line (Local_Name); raise Program_Error; end if; end Start_Element; end Segments_Readers;
zhmu/ananas
Ada
7,841
ads
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- S Y S T E M -- -- -- -- S p e c -- -- (VxWorks 7.x PPC64 Kernel) -- -- -- -- Copyright (C) 1992-2022, Free Software Foundation, Inc. -- -- -- -- This specification is derived from the Ada Reference Manual for use with -- -- GNAT. The copyright notice above, and the license provisions that follow -- -- apply solely to the contents of the part following the private keyword. -- -- -- -- 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. -- -- -- ------------------------------------------------------------------------------ -- This is the VxWorks 7.x version of this package for PPC64 Kernel package System is pragma Pure; -- Note that we take advantage of the implementation permission to make -- this unit Pure instead of Preelaborable; see RM 13.7.1(15). In Ada -- 2005, this is Pure in any case (AI-362). pragma No_Elaboration_Code_All; -- Allow the use of that restriction in units that WITH this unit type Name is (SYSTEM_NAME_GNAT); System_Name : constant Name := SYSTEM_NAME_GNAT; -- System-Dependent Named Numbers Min_Int : constant := -2 ** (Standard'Max_Integer_Size - 1); Max_Int : constant := 2 ** (Standard'Max_Integer_Size - 1) - 1; Max_Binary_Modulus : constant := 2 ** Standard'Max_Integer_Size; Max_Nonbinary_Modulus : constant := 2 ** Integer'Size - 1; Max_Base_Digits : constant := Long_Long_Float'Digits; Max_Digits : constant := Long_Long_Float'Digits; Max_Mantissa : constant := Standard'Max_Integer_Size - 1; Fine_Delta : constant := 2.0 ** (-Max_Mantissa); Tick : constant := 1.0 / 60.0; -- Storage-related Declarations type Address is private; pragma Preelaborable_Initialization (Address); Null_Address : constant Address; Storage_Unit : constant := 8; Word_Size : constant := 64; Memory_Size : constant := 2 ** 64; -- Address comparison function "<" (Left, Right : Address) return Boolean; function "<=" (Left, Right : Address) return Boolean; function ">" (Left, Right : Address) return Boolean; function ">=" (Left, Right : Address) return Boolean; function "=" (Left, Right : Address) return Boolean; pragma Import (Intrinsic, "<"); pragma Import (Intrinsic, "<="); pragma Import (Intrinsic, ">"); pragma Import (Intrinsic, ">="); pragma Import (Intrinsic, "="); -- Other System-Dependent Declarations type Bit_Order is (High_Order_First, Low_Order_First); Default_Bit_Order : constant Bit_Order := High_Order_First; pragma Warnings (Off, Default_Bit_Order); -- kill constant condition warning -- Priority-related Declarations (RM D.1) -- Ada priorities are mapped to VxWorks priorities using the following -- transformation: 255 - Ada Priority -- Ada priorities are used as follows: -- 256 is reserved for the VxWorks kernel -- 248 - 255 correspond to hardware interrupt levels 0 .. 7 -- 247 is a catchall default "interrupt" priority for signals, -- allowing higher priority than normal tasks, but lower than -- hardware priority levels. Protected Object ceilings can -- override these values. -- 246 is used by the Interrupt_Manager task Max_Priority : constant Positive := 245; Max_Interrupt_Priority : constant Positive := 255; subtype Any_Priority is Integer range 0 .. 255; subtype Priority is Any_Priority range 0 .. 245; subtype Interrupt_Priority is Any_Priority range 246 .. 255; Default_Priority : constant Priority := 122; private type Address is mod Memory_Size; Null_Address : constant Address := 0; -------------------------------------- -- System Implementation Parameters -- -------------------------------------- -- These parameters provide information about the target that is used -- by the compiler. They are in the private part of System, where they -- can be accessed using the special circuitry in the Targparm unit -- whose source should be consulted for more detailed descriptions -- of the individual switch values. Backend_Divide_Checks : constant Boolean := False; Backend_Overflow_Checks : constant Boolean := True; Command_Line_Args : constant Boolean := False; Configurable_Run_Time : constant Boolean := False; Denorm : constant Boolean := True; Duration_32_Bits : constant Boolean := False; Exit_Status_Supported : constant Boolean := True; Machine_Overflows : constant Boolean := False; Machine_Rounds : constant Boolean := True; Preallocated_Stacks : constant Boolean := False; Signed_Zeros : constant Boolean := True; Stack_Check_Default : constant Boolean := False; Stack_Check_Probes : constant Boolean := True; Stack_Check_Limits : constant Boolean := False; Support_Aggregates : constant Boolean := True; Support_Composite_Assign : constant Boolean := True; Support_Composite_Compare : constant Boolean := True; Support_Long_Shifts : constant Boolean := True; Always_Compatible_Rep : constant Boolean := False; Suppress_Standard_Library : constant Boolean := False; Use_Ada_Main_Program_Name : constant Boolean := True; Frontend_Exceptions : constant Boolean := False; ZCX_By_Default : constant Boolean := True; Executable_Extension : constant String := ".out"; end System;
procrastiraptor/euler
Ada
1,283
adb
with Ada.Integer_Text_IO; with Ada.Unchecked_Deallocation; procedure Euler14 is Max_Start: constant Positive := 999_999; subtype Start_Type is Positive range 1 .. Max_Start; type Memo is array (Start_Type) of Natural; type Memo_Ptr is access Memo; procedure Free is new Ada.Unchecked_Deallocation(Memo, Memo_Ptr); Collatz: Memo_Ptr := new Memo'(1 => 1, others => 0); type Intermediate is range 1 .. 2 ** 60; function Chain_Length(Start: Intermediate) return Positive is Next: constant Intermediate := (if Start mod 2 = 0 then Start / 2 else 3 * Start + 1); begin if Start <= Intermediate(Start_Type'Last) then declare S: constant Start_Type := Start_Type(Start); begin if Collatz(S) = 0 then Collatz(S) := 1 + Chain_Length(Next); end if; return Collatz(S); end; else return 1 + Chain_Length(Next); end if; end Chain_Length; Max, Curr: Natural := 0; Best: Start_Type; begin for I in Start_Type'Range loop Curr := Chain_Length(Intermediate(I)); if Curr > Max then Max := Curr; Best := I; end if; end loop; Ada.Integer_Text_IO.Put(Best); Free(Collatz); end Euler14;
tum-ei-rcs/StratoX
Ada
21,517
adb
with MPU6000.Register; use MPU6000.Register; with Ada.Unchecked_Conversion; --with Config.Software; package body MPU6000.Driver with SPARK_Mode, Refined_State => (State => Is_Init) is READ_FLAG : constant Byte := Byte( 2#1000_0000# ); -- Public procedures and functions ------------------ -- MPU6000_Test -- ------------------ function Test return Boolean is begin return Is_Init; end Test; -- Private procedures and functions -------------------------------- -- Evaluate_Self_Test -- -------------------------------- function Evaluate_Self_Test (Low : Float; High : Float; Value : Float; Debug_String : String) return Boolean is pragma Unreferenced (Debug_String); ret : Boolean; begin if Value not in Low .. High then ret := False; else ret := True; end if; return ret; end Evaluate_Self_Test; --------------------------- -- Read_Register -- --------------------------- procedure Read_Register (Reg_Addr : Byte; Data : in out Data_Type) with SPARK_Mode => Off -- SPARK: subtype constraint for Data_RX cannot depend on Data'Length is Data_TX : constant Data_Type := (Reg_Addr + READ_FLAG) & Data; Data_RX : Data_Type (1 .. Data'Length + 1) := (others => Byte(0)); begin HIL.SPI.transceive(HIL.SPI.MPU6000, Data_TX, Data_RX ); -- send the amount of bytes that should be read Data := Data_RX(2 .. Data_RX'Length); end Read_Register; ----------------------------------- -- Read_Byte_At_Register -- ----------------------------------- procedure Read_Byte_At_Register (Reg_Addr : Byte; Data : in out Byte) is Data_RX : Data_Type := (1 .. 2 => Byte( 0 ) ); begin --HIL.SPI.write(HIL.SPI.MPU6000, (1 => Reg_Addr) ); HIL.SPI.transceive(HIL.SPI.MPU6000, (1 => (Reg_Addr + READ_FLAG), 2 => Data), Data_RX ); Data := Data_RX(2); end Read_Byte_At_Register; ---------------------------------- -- Read_Bit_At_Register -- ---------------------------------- procedure Read_Bit_At_Register (Reg_Addr : Byte; Bit_Pos : Unsigned_8_Bit_Index; Bit_Value : out Boolean) is Register_Value : Byte := Byte (0); begin Read_Byte_At_Register (Reg_Addr, Register_Value); Bit_Value := (if (Register_Value and Shift_Left (1, Bit_Pos)) /= 0 then True else False); end Read_Bit_At_Register; ---------------------------- -- Write_Register -- ---------------------------- procedure Write_Register (Reg_Addr : Byte; Data : Data_Type) is Data_TX : constant Data_Type := Reg_Addr & Data; begin HIL.SPI.write(HIL.SPI.MPU6000, Data_TX); end Write_Register; ------------------------------------ -- Write_Byte_At_Register -- ------------------------------------ procedure Write_Byte_At_Register (Reg_Addr : Byte; Data : Byte) is Data_TX : constant Data_Type := (1 => Reg_Addr) & Data; begin HIL.SPI.write(HIL.SPI.MPU6000, Data_TX); end Write_Byte_At_Register; ----------------------------------- -- Write_Bit_At_Register -- ----------------------------------- procedure Write_Bit_At_Register (Reg_Addr : Byte; Bit_Pos : Unsigned_8_Bit_Index; Bit_Value : Boolean) is Register_Value : Byte := Byte( 0 ); begin Read_Byte_At_Register (Reg_Addr, Register_Value); Register_Value := (if Bit_Value then Register_Value or (Shift_Left (1, Bit_Pos)) else Register_Value and not (Shift_Left (1, Bit_Pos))); Write_Byte_At_Register (Reg_Addr, Register_Value); end Write_Bit_At_Register; ------------------------------------ -- Write_Bits_At_Register -- ------------------------------------ procedure Write_Bits_At_Register (Reg_Addr : Byte; Start_Bit_Pos : Unsigned_8_Bit_Index; Data : Byte; Length : Unsigned_8_Bit_Index) is Register_Value : Byte := Byte (0); Mask : Byte; Data_Aux : Byte := Data; begin Read_Byte_At_Register (Reg_Addr, Register_Value); Mask := Shift_Left ((Shift_Left (1, Length) - 1), Start_Bit_Pos - Length + 1); Data_Aux := Shift_Left (Data_Aux, Start_Bit_Pos - Length + 1); Data_Aux := Data_Aux and Mask; Register_Value := Register_Value and not Mask; Register_Value := Register_Value or Data_Aux; Write_Byte_At_Register (Reg_Addr, Register_Value); end Write_Bits_At_Register; -------------------------------------- -- Fuse_Low_And_High_Register_Parts -- -------------------------------------- function Fuse_Low_And_High_Register_Parts (High : Byte; Low : Byte) return Integer_16 is ------------------------- -- Unsigned_16_To_Integer_16 -- ------------------------- function Unsigned_16_To_Integer_16 is new Ada.Unchecked_Conversion (Unsigned_16, Integer_16); Register : Unsigned_16; begin Register := Shift_Left (Unsigned_16 (High), 8); Register := Register or Unsigned_16 (Low); return Unsigned_16_To_Integer_16 (Register); end Fuse_Low_And_High_Register_Parts; ------------------------------ -- MPU6000_Set_Clock_Source -- ------------------------------ procedure Set_Clock_Source (Clock_Source : MPU6000_Clock_Source) with SPARK_Mode => Off -- not allowed: Enum'Rep is begin Write_Bits_At_Register (Reg_Addr => MPU6000_RA_PWR_MGMT_1, Start_Bit_Pos => MPU6000_PWR1_CLKSEL_BIT, Data => MPU6000_Clock_Source'Enum_Rep (Clock_Source), Length => MPU6000_PWR1_CLKSEL_LENGTH); end Set_Clock_Source; --------------------------- -- MPU6000_Set_DLPF_Mode -- --------------------------- procedure Set_DLPF_Mode (DLPF_Mode : MPU6000_DLPF_Bandwidth_Mode) with SPARK_Mode => Off -- not allowed: Enum'Rep is begin Write_Bits_At_Register (Reg_Addr => MPU6000_RA_CONFIG, Start_Bit_Pos => MPU6000_CFG_DLPF_CFG_BIT, Data => MPU6000_DLPF_Bandwidth_Mode'Enum_Rep (DLPF_Mode), Length => MPU6000_CFG_DLPF_CFG_LENGTH); end Set_DLPF_Mode; --------------------------------------- -- MPU6000_Set_Full_Scale_Gyro_Range -- --------------------------------------- procedure Set_Full_Scale_Gyro_Range (FS_Range : MPU6000_FS_Gyro_Range) with SPARK_Mode => Off -- not allowed: Enum'Rep is begin Write_Bits_At_Register (Reg_Addr => MPU6000_RA_GYRO_CONFIG, Start_Bit_Pos => MPU6000_GCONFIG_FS_SEL_BIT, Data => MPU6000_FS_Gyro_Range'Enum_Rep (FS_Range), Length => MPU6000_GCONFIG_FS_SEL_LENGTH); end Set_Full_Scale_Gyro_Range; ---------------------------------------- -- MPU6000_Set_Full_Scale_Accel_Range -- ---------------------------------------- procedure Set_Full_Scale_Accel_Range (FS_Range : MPU6000_FS_Accel_Range) with SPARK_Mode => Off -- not allowed: Enum'Rep is begin Write_Bits_At_Register (Reg_Addr => MPU6000_RA_ACCEL_CONFIG, Start_Bit_Pos => MPU6000_ACONFIG_AFS_SEL_BIT, Data => MPU6000_FS_Accel_Range'Enum_Rep (FS_Range), Length => MPU6000_ACONFIG_AFS_SEL_LENGTH); end Set_Full_Scale_Accel_Range; ------------------------------------ -- MPU6000_Set_I2C_Bypass_Enabled -- ------------------------------------ procedure Set_I2C_Bypass_Enabled (Value : Boolean) is begin Write_Bit_At_Register (Reg_Addr => MPU6000_RA_INT_PIN_CFG, Bit_Pos => MPU6000_INTCFG_I2C_BYPASS_EN_BIT, Bit_Value => Value); end Set_I2C_Bypass_Enabled; ----------------------------- -- MPU6000_Set_Int_Enabled -- ----------------------------- procedure Set_Int_Enabled (Value : Boolean) is begin -- Full register byte for all interrupts, for quick reading. -- Each bit should be set 0 for disabled, 1 for enabled. if Value then Write_Byte_At_Register (Reg_Addr => MPU6000_RA_INT_ENABLE, Data => 16#FF#); else Write_Byte_At_Register (Reg_Addr => MPU6000_RA_INT_ENABLE, Data => 16#00#); end if; end Set_Int_Enabled; ---------------------- -- MPU6000_Set_Rate -- ---------------------- procedure Set_Rate (Rate_Div : Byte) is begin Write_Byte_At_Register (Reg_Addr => MPU6000_RA_SMPLRT_DIV, Data => Rate_Div); end Set_Rate; ------------------------------- -- MPU6000_Set_Sleep_Enabled -- ------------------------------- procedure Set_Sleep_Enabled (Value : Boolean) is begin Write_Bit_At_Register (Reg_Addr => MPU6000_RA_PWR_MGMT_1, Bit_Pos => MPU6000_PWR1_SLEEP_BIT, Bit_Value => Value); end Set_Sleep_Enabled; ------------------------------------- -- MPU6000_Set_Temp_Sensor_Enabled -- ------------------------------------- procedure Set_Temp_Sensor_Enabled (Value : Boolean) is begin -- True value for this bit actually disables it. Write_Bit_At_Register (Reg_Addr => MPU6000_RA_PWR_MGMT_1, Bit_Pos => MPU6000_PWR1_TEMP_DIS_BIT, Bit_Value => not Value); end Set_Temp_Sensor_Enabled; ------------------------------------- -- MPU6000_Get_Temp_Sensor_Enabled -- ------------------------------------- procedure Get_Temp_Sensor_Enabled (ret : out Boolean) is bit : Boolean; begin Read_Bit_At_Register (Reg_Addr => MPU6000_RA_PWR_MGMT_1, Bit_Pos => MPU6000_PWR1_TEMP_DIS_BIT, Bit_Value => bit); -- False value for this bit means that it is enabled ret := not bit; end Get_Temp_Sensor_Enabled; -------------------------- -- MPU6000_Get_Motion_6 -- -------------------------- procedure Get_Motion_6 (Acc_X : out Integer_16; Acc_Y : out Integer_16; Acc_Z : out Integer_16; Gyro_X : out Integer_16; Gyro_Y : out Integer_16; Gyro_Z : out Integer_16) is Raw_Data : Data_Type (1 .. 14) := (others => 0); begin Read_Register (Reg_Addr => MPU6000_RA_ACCEL_XOUT_H, Data => Raw_Data); Acc_X := Fuse_Low_And_High_Register_Parts (Raw_Data (1), Raw_Data (2)); Acc_Y := Fuse_Low_And_High_Register_Parts (Raw_Data (3), Raw_Data (4)); Acc_Z := Fuse_Low_And_High_Register_Parts (Raw_Data (5), Raw_Data (6)); Gyro_X := Fuse_Low_And_High_Register_Parts (Raw_Data (9), Raw_Data (10)); Gyro_Y := Fuse_Low_And_High_Register_Parts (Raw_Data (11), Raw_Data (12)); Gyro_Z := Fuse_Low_And_High_Register_Parts (Raw_Data (13), Raw_Data (14)); end Get_Motion_6; ----------------------------- -- MPU6000_Test_Connection -- ----------------------------- procedure Test_Connection (success : out Boolean) is Who_Am_I : Byte := Byte( 0 ); begin Read_Byte_At_Register (Reg_Addr => MPU6000_RA_WHO_AM_I, Data => Who_Am_I); success := Who_Am_I = MPU6000_DEVICE_ID; end Test_Connection; ----------------------- -- MPU6000_Self_Test -- ----------------------- procedure Self_Test (Test_Status : out Boolean) is data : Byte := 0; begin Read_Byte_At_Register (MPU6000_RA_WHO_AM_I, data); Test_Status := data = 16#68#; end Self_Test; procedure Self_Test_Extended (Test_Status : out Boolean) is subtype Integer_32_Array_3 is Integer_32_Array (1 .. 3); subtype Integer_32_Array_6 is Integer_32_Array (1 .. 6); subtype Float_Array_3 is Float_Array (1 .. 3); Raw_Data : Data_Type (1 .. 6) := (others => 0); Saved_Reg : Data_Type (1 .. 4) := (others => 0); Self_Test : Data_Type (1 .. 6) := (others => 0); Acc_Avg : Integer_32_Array_3 := (others => 0); Gyro_Avg : Integer_32_Array_3 := (others => 0); Acc_ST_Avg : Integer_32_Array_3 := (others => 0); Gyro_ST_Avg : Integer_32_Array_3 := (others => 0); Factory_Trim : Integer_32_Array_6 := (others => 0); Acc_Diff : Float_Array_3; Gyro_Diff : Float_Array_3; FS : constant Natural := 0; begin -- Save old configuration Read_Byte_At_Register (MPU6000_RA_SMPLRT_DIV, Saved_Reg (1)); Read_Byte_At_Register (MPU6000_RA_CONFIG, Saved_Reg (2)); Read_Byte_At_Register (MPU6000_RA_GYRO_CONFIG, Saved_Reg (3)); Read_Byte_At_Register (MPU6000_RA_ACCEL_CONFIG, Saved_Reg (4)); -- Write test configuration Write_Byte_At_Register (MPU6000_RA_SMPLRT_DIV, 16#00#); Write_Byte_At_Register (MPU6000_RA_CONFIG, 16#02#); Write_Byte_At_Register (MPU6000_RA_GYRO_CONFIG, Shift_Left (1, FS)); Write_Byte_At_Register (MPU6000_RA_ACCEL_CONFIG, Shift_Left (1, FS)); -- Get average current values of gyro and accelerometer for I in 1 .. 200 loop Read_Register (MPU6000_RA_ACCEL_XOUT_H, Raw_Data); Acc_Avg (1) := Acc_Avg (1) + Integer_32 (Fuse_Low_And_High_Register_Parts (Raw_Data (1), Raw_Data (2))); Acc_Avg (2) := Acc_Avg (2) + Integer_32 (Fuse_Low_And_High_Register_Parts (Raw_Data (3), Raw_Data (4))); Acc_Avg (3) := Acc_Avg (3) + Integer_32 (Fuse_Low_And_High_Register_Parts (Raw_Data (5), Raw_Data (6))); Read_Register (MPU6000_RA_GYRO_XOUT_H, Raw_Data); Gyro_Avg (1) := Gyro_Avg (1) + Integer_32 (Fuse_Low_And_High_Register_Parts (Raw_Data (1), Raw_Data (2))); Gyro_Avg (2) := Gyro_Avg (2) + Integer_32 (Fuse_Low_And_High_Register_Parts (Raw_Data (3), Raw_Data (4))); Gyro_Avg (3) := Gyro_Avg (3) + Integer_32 (Fuse_Low_And_High_Register_Parts (Raw_Data (5), Raw_Data (6))); end loop; -- Get average of 200 values and store as average current readings for I in Integer_32_Array_3'Range loop Acc_Avg (I) := Acc_Avg (I) / 200; Gyro_Avg (I) := Gyro_Avg (I) / 200; end loop; -- Configure the acceleromter for self test Write_Byte_At_Register (MPU6000_RA_ACCEL_CONFIG, 16#E0#); Write_Byte_At_Register (MPU6000_RA_GYRO_CONFIG, 16#E0#); -- Delay a while to let the device stabilize declare now : Ada.Real_Time.Time := Clock; begin delay until now + Milliseconds (25); end; -- Get average self-test values of gyro and accelerometer for I in 1 .. 200 loop Read_Register (MPU6000_RA_ACCEL_XOUT_H, Raw_Data); Acc_ST_Avg (1) := Acc_ST_Avg (1) + Integer_32 (Fuse_Low_And_High_Register_Parts (Raw_Data (1), Raw_Data (2))); Acc_ST_Avg (2) := Acc_ST_Avg (2) + Integer_32 (Fuse_Low_And_High_Register_Parts (Raw_Data (3), Raw_Data (4))); Acc_ST_Avg (3) := Acc_ST_Avg (3) + Integer_32 (Fuse_Low_And_High_Register_Parts (Raw_Data (5), Raw_Data (6))); Read_Register (MPU6000_RA_GYRO_XOUT_H, Raw_Data); Gyro_ST_Avg (1) := Gyro_ST_Avg (1) + Integer_32 (Fuse_Low_And_High_Register_Parts (Raw_Data (1), Raw_Data (2))); Gyro_ST_Avg (2) := Gyro_ST_Avg (2) + Integer_32 (Fuse_Low_And_High_Register_Parts (Raw_Data (3), Raw_Data (4))); Gyro_ST_Avg (3) := Gyro_ST_Avg (3) + Integer_32 (Fuse_Low_And_High_Register_Parts (Raw_Data (5), Raw_Data (6))); end loop; -- Get average of 200 values and store as average self-test readings for I in Integer_32_Array_3'Range loop Acc_ST_Avg (I) := Acc_ST_Avg (I) / 200; Gyro_ST_Avg (I) := Gyro_ST_Avg (I) / 200; end loop; -- Configure the gyro and accelerometer for normal operation Write_Byte_At_Register (MPU6000_RA_ACCEL_CONFIG, 16#00#); Write_Byte_At_Register (MPU6000_RA_GYRO_CONFIG, 16#00#); -- Delay a while to let the device stabilize declare now : Ada.Real_Time.Time := Clock; begin delay until now + Milliseconds (25); end; -- Retrieve Accelerometer and Gyro Factory Self - Test Code From USR_Reg Read_Byte_At_Register (MPU6000_RA_SELF_TEST_X, Self_Test (1)); Read_Byte_At_Register (MPU6000_RA_SELF_TEST_Y, Self_Test (2)); Read_Byte_At_Register (MPU6000_RA_SELF_TEST_Z, Self_Test (3)); Read_Byte_At_Register (MPU6000_RA_SELF_TEST_X, Self_Test (4)); Read_Byte_At_Register (MPU6000_RA_SELF_TEST_Y, Self_Test (5)); Read_Byte_At_Register (MPU6000_RA_SELF_TEST_Z, Self_Test (6)); for I in 1 .. 6 loop if Self_Test (I) /= 0 then Factory_Trim (I) := Integer_32 (MPU6000_ST_TB (Integer (Self_Test (I)))); else Factory_Trim (I) := 0; end if; end loop; -- Report results as a ratio of (STR - FT)/FT; the change from -- Factory Trim of the Self - Test Response -- To get percent, must multiply by 100 declare AFT, GFT : Float; begin for I in 1 .. 3 loop AFT := Float (Factory_Trim (I)); GFT := Float (Factory_Trim (I + 3)); if AFT /= 0.0 then Acc_Diff (I) := 100.0 * (Float (Acc_ST_Avg (I) - Acc_Avg (I) - Factory_Trim (I)) / AFT); else Acc_Diff (I) := 0.0; end if; if GFT /= 0.0 then Gyro_Diff (I) := 100.0 * (Float (Gyro_ST_Avg (I) - Gyro_Avg (I) - Factory_Trim (I + 3)) / GFT); else Gyro_Diff (I) := 0.0; end if; end loop; end; -- Restore old configuration Write_Byte_At_Register (MPU6000_RA_SMPLRT_DIV, Saved_Reg (1)); Write_Byte_At_Register (MPU6000_RA_CONFIG, Saved_Reg (2)); Write_Byte_At_Register (MPU6000_RA_GYRO_CONFIG, Saved_Reg (3)); Write_Byte_At_Register (MPU6000_RA_ACCEL_CONFIG, Saved_Reg (4)); -- Check result Test_Status := Evaluate_Self_Test (MPU6000_ST_GYRO_LOW, MPU6000_ST_GYRO_HIGH, Gyro_Diff (1), "gyro X"); Test_Status := Test_Status and Evaluate_Self_Test (MPU6000_ST_GYRO_LOW, MPU6000_ST_GYRO_HIGH, Gyro_Diff (2), "gyro Y"); Test_Status := Test_Status and Evaluate_Self_Test (MPU6000_ST_GYRO_LOW, MPU6000_ST_GYRO_HIGH, Gyro_Diff (3), "gyro Z"); Test_Status := Test_Status and Evaluate_Self_Test (MPU6000_ST_ACCEL_LOW, MPU6000_ST_ACCEL_HIGH, Acc_Diff (1), "acc X"); Test_Status := Test_Status and Evaluate_Self_Test (MPU6000_ST_ACCEL_LOW, MPU6000_ST_ACCEL_HIGH, Acc_Diff (2), "acc Y"); Test_Status := Test_Status and Evaluate_Self_Test (MPU6000_ST_ACCEL_LOW, MPU6000_ST_ACCEL_HIGH, Acc_Diff (3), "acc Z"); end Self_Test_Extended; ------------------- -- MPU6000_Reset -- ------------------- procedure Reset is begin Write_Bit_At_Register (Reg_Addr => MPU6000_RA_PWR_MGMT_1, Bit_Pos => MPU6000_PWR1_DEVICE_RESET_BIT, Bit_Value => True); end Reset; ------------------ -- MPU6000_Init -- ------------------ procedure Init is begin if Is_Init then return; end if; -- Wait for MPU6000 startup delay until MPU6000_STARTUP_TIME_MS; -- Wake-Up Write_Bit_At_Register(MPU6000_RA_PWR_MGMT_1, MPU6000_PWR1_SLEEP_BIT, False); declare now : constant Ada.Real_Time.Time := Clock; begin delay until now + Milliseconds (10); end; -- Disable I2C Write_Bit_At_Register(MPU6000_RA_USER_CTRL, MPU6000_USERCTRL_I2C_IF_DIS_BIT, True); -- set Clock Set_Clock_Source(Z_Gyro_Clk); -- set sample rate -- Sample Rate = Gyroscope Output Rate / (1 + SMPLRT_DIV) -- Gyroscope Output Rate = (if DLPF = enabled then 1kHz else 8kHz) Set_Rate( Byte( 19 ) ); -- 50Hz -- set digital low pass filter (DLPF) Set_DLPF_Mode(MPU6000_DLPF_BW_20); -- Determine the device's I2C address (FIXME: why? this is SPI) declare hypothetical_i2c_address : constant HIL.Byte := Shift_Left (MPU6000_ADDRESS_AD0_HIGH, 1); begin null; end; -- Delay to wait for the state initialization of SCL and SDA declare now : constant Ada.Real_Time.Time := Clock; begin delay until now + Milliseconds (5); end; end Init; end MPU6000.Driver;
reznikmm/slimp
Ada
3,672
adb
-- Copyright (c) 2019 Maxim Reznik <[email protected]> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with Ada.Calendar; with Ada.Text_IO; with League.String_Vectors; with Slim.Messages.cont; -- with Slim.Players.Displays; package body Slim.Players.Play_Radio_Visiters is ---------- -- DSCO -- ---------- overriding procedure DSCO (Self : in out Visiter; Message : not null access Slim.Messages.DSCO.DSCO_Message) is pragma Unreferenced (Message); use type Ada.Calendar.Time; Player : Players.Player renames Self.Player.all; begin -- got disconnection on the data channel Player.State := (Idle, Ada.Calendar.Clock - 60.0, Player.First_Menu); end DSCO; ---------- -- META -- ---------- overriding procedure META (Self : in out Visiter; Message : not null access Slim.Messages.META.META_Message) is Player : Players.Player renames Self.Player.all; Text : League.Strings.Universal_String := Message.Value; Prefix : constant Wide_Wide_String := "StreamTitle='"; Suffix : constant Wide_Wide_String := "';"; begin if Text.Starts_With (Prefix) then Text := Text.Tail_From (Prefix'Length + 1); end if; if Text.Ends_With (Suffix) then Text := Text.Head_To (Text.Length - Suffix'Length); end if; Player.State.Play_State.Current_Song := Text; Slim.Players.Common_Play_Visiters.Update_Display (Player); end META; ---------- -- RESP -- ---------- overriding procedure RESP (Self : in out Visiter; Message : not null access Slim.Messages.RESP.RESP_Message) is List : constant League.String_Vectors.Universal_String_Vector := Message.Headers; Player : Players.Player renames Self.Player.all; Line : League.Strings.Universal_String; Metaint_Header : constant Wide_Wide_String := "icy-metaint:"; Metaint : Natural := 0; Cont : Slim.Messages.cont.Cont_Message; begin for J in 1 .. List.Length loop Line := List.Element (J); if Line.Starts_With (Metaint_Header) then Line := Line.Tail_From (Metaint_Header'Length + 1); begin Metaint := Natural'Wide_Wide_Value (Line.To_Wide_Wide_String); exception when Constraint_Error => null; end; exit; end if; end loop; Cont.Set_Metaint (Metaint); Write_Message (Player.Socket, Cont); end RESP; ---------- -- STAT -- ---------- overriding procedure STAT (Self : in out Visiter; Message : not null access Slim.Messages.STAT.STAT_Message) is Player : Players.Player renames Self.Player.all; begin Player.WiFi := Message.WiFi_Level; if Message.Event (1 .. 3) /= "STM" then return; elsif not Player.State.Play_State.Current_Song.Is_Empty then null; elsif Message.Event = "STMc" then Player.State.Play_State.Current_Song.Clear; Player.State.Play_State.Current_Song.Append ("Connecting..."); elsif Message.Event = "STMe" then Player.State.Play_State.Current_Song.Clear; Player.State.Play_State.Current_Song.Append ("Connected"); end if; Slim.Players.Common_Play_Visiters.Update_Display (Player); if Message.Event /= "STMt" then Ada.Text_IO.Put_Line (Message.Event); end if; end STAT; end Slim.Players.Play_Radio_Visiters;
sungyeon/drake
Ada
652
ads
pragma License (Unrestricted); -- implementation unit required by compiler package System.Tasking.Async_Delays is -- required for select delay then abort by compiler (s-parame.ads) type Delay_Block is null record; -- required for select delay then abort by compiler (s-parame.ads) function Enqueue_Duration ( T : Duration; D : not null access Delay_Block) return Boolean; -- required for select delay then abort by compiler (s-parame.ads) procedure Cancel_Async_Delay (D : not null access Delay_Block); function Timed_Out (D : not null access Delay_Block) return Boolean; end System.Tasking.Async_Delays;
reznikmm/matreshka
Ada
8,984
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011-2012, Vadim Godunko <[email protected]> -- -- 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$ ------------------------------------------------------------------------------ with AMF.Elements; with AMF.Internals.Element_Collections; with AMF.Internals.Helpers; with AMF.Internals.Tables.UML_Attributes; with AMF.Visitors.UML_Iterators; with AMF.Visitors.UML_Visitors; package body AMF.Internals.UML_Exception_Handlers is ------------------- -- Enter_Element -- ------------------- overriding procedure Enter_Element (Self : not null access constant UML_Exception_Handler_Proxy; Visitor : in out AMF.Visitors.Abstract_Visitor'Class; Control : in out AMF.Visitors.Traverse_Control) is begin if Visitor in AMF.Visitors.UML_Visitors.UML_Visitor'Class then AMF.Visitors.UML_Visitors.UML_Visitor'Class (Visitor).Enter_Exception_Handler (AMF.UML.Exception_Handlers.UML_Exception_Handler_Access (Self), Control); end if; end Enter_Element; ------------------- -- Leave_Element -- ------------------- overriding procedure Leave_Element (Self : not null access constant UML_Exception_Handler_Proxy; Visitor : in out AMF.Visitors.Abstract_Visitor'Class; Control : in out AMF.Visitors.Traverse_Control) is begin if Visitor in AMF.Visitors.UML_Visitors.UML_Visitor'Class then AMF.Visitors.UML_Visitors.UML_Visitor'Class (Visitor).Leave_Exception_Handler (AMF.UML.Exception_Handlers.UML_Exception_Handler_Access (Self), Control); end if; end Leave_Element; ------------------- -- Visit_Element -- ------------------- overriding procedure Visit_Element (Self : not null access constant UML_Exception_Handler_Proxy; Iterator : in out AMF.Visitors.Abstract_Iterator'Class; Visitor : in out AMF.Visitors.Abstract_Visitor'Class; Control : in out AMF.Visitors.Traverse_Control) is begin if Iterator in AMF.Visitors.UML_Iterators.UML_Iterator'Class then AMF.Visitors.UML_Iterators.UML_Iterator'Class (Iterator).Visit_Exception_Handler (Visitor, AMF.UML.Exception_Handlers.UML_Exception_Handler_Access (Self), Control); end if; end Visit_Element; ------------------------- -- Get_Exception_Input -- ------------------------- overriding function Get_Exception_Input (Self : not null access constant UML_Exception_Handler_Proxy) return AMF.UML.Object_Nodes.UML_Object_Node_Access is begin return AMF.UML.Object_Nodes.UML_Object_Node_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.UML_Attributes.Internal_Get_Exception_Input (Self.Element))); end Get_Exception_Input; ------------------------- -- Set_Exception_Input -- ------------------------- overriding procedure Set_Exception_Input (Self : not null access UML_Exception_Handler_Proxy; To : AMF.UML.Object_Nodes.UML_Object_Node_Access) is begin AMF.Internals.Tables.UML_Attributes.Internal_Set_Exception_Input (Self.Element, AMF.Internals.Helpers.To_Element (AMF.Elements.Element_Access (To))); end Set_Exception_Input; ------------------------ -- Get_Exception_Type -- ------------------------ overriding function Get_Exception_Type (Self : not null access constant UML_Exception_Handler_Proxy) return AMF.UML.Classifiers.Collections.Set_Of_UML_Classifier is begin return AMF.UML.Classifiers.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Exception_Type (Self.Element))); end Get_Exception_Type; ---------------------- -- Get_Handler_Body -- ---------------------- overriding function Get_Handler_Body (Self : not null access constant UML_Exception_Handler_Proxy) return AMF.UML.Executable_Nodes.UML_Executable_Node_Access is begin return AMF.UML.Executable_Nodes.UML_Executable_Node_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.UML_Attributes.Internal_Get_Handler_Body (Self.Element))); end Get_Handler_Body; ---------------------- -- Set_Handler_Body -- ---------------------- overriding procedure Set_Handler_Body (Self : not null access UML_Exception_Handler_Proxy; To : AMF.UML.Executable_Nodes.UML_Executable_Node_Access) is begin AMF.Internals.Tables.UML_Attributes.Internal_Set_Handler_Body (Self.Element, AMF.Internals.Helpers.To_Element (AMF.Elements.Element_Access (To))); end Set_Handler_Body; ------------------------ -- Get_Protected_Node -- ------------------------ overriding function Get_Protected_Node (Self : not null access constant UML_Exception_Handler_Proxy) return AMF.UML.Executable_Nodes.UML_Executable_Node_Access is begin return AMF.UML.Executable_Nodes.UML_Executable_Node_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.UML_Attributes.Internal_Get_Protected_Node (Self.Element))); end Get_Protected_Node; ------------------------ -- Set_Protected_Node -- ------------------------ overriding procedure Set_Protected_Node (Self : not null access UML_Exception_Handler_Proxy; To : AMF.UML.Executable_Nodes.UML_Executable_Node_Access) is begin AMF.Internals.Tables.UML_Attributes.Internal_Set_Protected_Node (Self.Element, AMF.Internals.Helpers.To_Element (AMF.Elements.Element_Access (To))); end Set_Protected_Node; end AMF.Internals.UML_Exception_Handlers;
reznikmm/matreshka
Ada
6,455
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Web Framework -- -- -- -- Tools Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2015, Vadim Godunko <[email protected]> -- -- 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$ ------------------------------------------------------------------------------ with Asis.Declarations; with Asis.Definitions; package body Properties.Definitions.Enumeration_Type is ---------- -- Code -- ---------- function Code (Engine : access Engines.Contexts.Context; Element : Asis.Expression; Name : Engines.Text_Property) return League.Strings.Universal_String is pragma Unreferenced (Engine, Name); List : constant Asis.Declaration_List := Asis.Definitions.Enumeration_Literal_Declarations (Element); Text : League.Strings.Universal_String; begin Text.Append ("{"); for J in List'Range loop declare Image : constant Wide_String := Asis.Declarations.Defining_Name_Image (Asis.Declarations.Names (List (J)) (1)); Name : constant League.Strings.Universal_String := League.Strings.From_UTF_16_Wide_String (Image); begin Text.Append ("'"); Text.Append (Name.To_Lowercase); Text.Append ("' : '"); Text.Append (Name.To_Uppercase); if J = List'Last then Text.Append ("'"); else Text.Append ("', "); end if; end; end loop; Text.Append ("};"); return Text; end Code; ---------------- -- Initialize -- ---------------- function Initialize (Engine : access Engines.Contexts.Context; Element : Asis.Expression; Name : Engines.Text_Property) return League.Strings.Universal_String is pragma Unreferenced (Engine, Element, Name); begin return League.Strings.To_Universal_String ("undefined"); end Initialize; -------------------- -- Is_Simple_Type -- -------------------- function Is_Simple_Type (Engine : access Engines.Contexts.Context; Element : Asis.Definition; Name : Engines.Boolean_Property) return Boolean is pragma Unreferenced (Engine, Element, Name); begin return True; end Is_Simple_Type; ----------- -- Lower -- ----------- function Lower (Engine : access Engines.Contexts.Context; Element : Asis.Expression; Name : Engines.Text_Property) return League.Strings.Universal_String is pragma Unreferenced (Name); List : constant Asis.Declaration_List := Asis.Definitions.Enumeration_Literal_Declarations (Element); begin return Engine.Text.Get_Property (Asis.Declarations.Names (List (List'First)) (1), Engines.Code); end Lower; ----------- -- Upper -- ----------- function Upper (Engine : access Engines.Contexts.Context; Element : Asis.Expression; Name : Engines.Text_Property) return League.Strings.Universal_String is pragma Unreferenced (Name); List : constant Asis.Declaration_List := Asis.Definitions.Enumeration_Literal_Declarations (Element); begin return Engine.Text.Get_Property (Asis.Declarations.Names (List (List'Last)) (1), Engines.Code); end Upper; end Properties.Definitions.Enumeration_Type;
sungyeon/drake
Ada
769
ads
pragma License (Unrestricted); -- Ada 2012 generic type Cursor; with function Has_Element (Position : Cursor) return Boolean; pragma Unreferenced (Has_Element); package Ada.Iterator_Interfaces is pragma Pure; type Forward_Iterator is limited interface; pragma No_Tagged_Streams (Forward_Iterator); function First (Object : Forward_Iterator) return Cursor is abstract; function Next (Object : Forward_Iterator; Position : Cursor) return Cursor is abstract; type Reversible_Iterator is limited interface and Forward_Iterator; function Last (Object : Reversible_Iterator) return Cursor is abstract; function Previous (Object : Reversible_Iterator; Position : Cursor) return Cursor is abstract; end Ada.Iterator_Interfaces;
stcarrez/hyperion
Ada
9,897
adb
-- Hyperion API -- Hyperion Monitoring API The monitoring agent is first registered so that the server knows it as well as its security key. Each host are then registered by a monitoring agent. -- -- The version of the OpenAPI document: 1.0.0 -- Contact: [email protected] -- -- NOTE: This package is auto generated by OpenAPI-Generator 4.1.0-SNAPSHOT. -- https://openapi-generator.tech -- Do not edit the class manually. package body Hyperion.Rest.Models is use Swagger.Streams; procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in InlineObject1_Type) is begin Into.Start_Entity (Name); Into.Write_Entity ("name", Value.Name); Into.Write_Entity ("ip", Value.Ip); Into.Write_Entity ("hostKey", Value.Host_Key); Into.Write_Entity ("agentKey", Value.Agent_Key); Into.Write_Entity ("agentId", Value.Agent_Id); Into.End_Entity (Name); end Serialize; procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in InlineObject1_Type_Vectors.Vector) is begin Into.Start_Array (Name); for Item of Value loop Serialize (Into, "", Item); end loop; Into.End_Array (Name); end Serialize; procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out InlineObject1_Type) is Object : Swagger.Value_Type; begin Swagger.Streams.Deserialize (From, Name, Object); Swagger.Streams.Deserialize (Object, "name", Value.Name); Swagger.Streams.Deserialize (Object, "ip", Value.Ip); Swagger.Streams.Deserialize (Object, "hostKey", Value.Host_Key); Swagger.Streams.Deserialize (Object, "agentKey", Value.Agent_Key); Swagger.Streams.Deserialize (Object, "agentId", Value.Agent_Id); end Deserialize; procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out InlineObject1_Type_Vectors.Vector) is List : Swagger.Value_Array_Type; Item : InlineObject1_Type; begin Value.Clear; Swagger.Streams.Deserialize (From, Name, List); for Data of List loop Deserialize (Data, "", Item); Value.Append (Item); end loop; end Deserialize; procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in Dataset_Type) is begin Into.Start_Entity (Name); Serialize (Into, "id", Value.Id); Into.Write_Entity ("name", Value.Name); Into.Write_Entity ("label", Value.Label); Into.End_Entity (Name); end Serialize; procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in Dataset_Type_Vectors.Vector) is begin Into.Start_Array (Name); for Item of Value loop Serialize (Into, "", Item); end loop; Into.End_Array (Name); end Serialize; procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out Dataset_Type) is Object : Swagger.Value_Type; begin Swagger.Streams.Deserialize (From, Name, Object); Swagger.Streams.Deserialize (Object, "id", Value.Id); Swagger.Streams.Deserialize (Object, "name", Value.Name); Swagger.Streams.Deserialize (Object, "label", Value.Label); end Deserialize; procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out Dataset_Type_Vectors.Vector) is List : Swagger.Value_Array_Type; Item : Dataset_Type; begin Value.Clear; Swagger.Streams.Deserialize (From, Name, List); for Data of List loop Deserialize (Data, "", Item); Value.Append (Item); end loop; end Deserialize; procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in InlineObject_Type) is begin Into.Start_Entity (Name); Into.Write_Entity ("name", Value.Name); Into.Write_Entity ("ip", Value.Ip); Into.Write_Entity ("agentKey", Value.Agent_Key); Into.End_Entity (Name); end Serialize; procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in InlineObject_Type_Vectors.Vector) is begin Into.Start_Array (Name); for Item of Value loop Serialize (Into, "", Item); end loop; Into.End_Array (Name); end Serialize; procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out InlineObject_Type) is Object : Swagger.Value_Type; begin Swagger.Streams.Deserialize (From, Name, Object); Swagger.Streams.Deserialize (Object, "name", Value.Name); Swagger.Streams.Deserialize (Object, "ip", Value.Ip); Swagger.Streams.Deserialize (Object, "agentKey", Value.Agent_Key); end Deserialize; procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out InlineObject_Type_Vectors.Vector) is List : Swagger.Value_Array_Type; Item : InlineObject_Type; begin Value.Clear; Swagger.Streams.Deserialize (From, Name, List); for Data of List loop Deserialize (Data, "", Item); Value.Append (Item); end loop; end Deserialize; procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in Agent_Type) is begin Into.Start_Entity (Name); Serialize (Into, "id", Value.Id); Into.Write_Entity ("name", Value.Name); Into.Write_Entity ("ip", Value.Ip); Into.Write_Entity ("create_date", Value.Create_Date); Into.Write_Entity ("key", Value.Key); Into.Write_Entity ("status", Value.Status); Into.End_Entity (Name); end Serialize; procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in Agent_Type_Vectors.Vector) is begin Into.Start_Array (Name); for Item of Value loop Serialize (Into, "", Item); end loop; Into.End_Array (Name); end Serialize; procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out Agent_Type) is Object : Swagger.Value_Type; begin Swagger.Streams.Deserialize (From, Name, Object); Swagger.Streams.Deserialize (Object, "id", Value.Id); Swagger.Streams.Deserialize (Object, "name", Value.Name); Swagger.Streams.Deserialize (Object, "ip", Value.Ip); Deserialize (Object, "create_date", Value.Create_Date); Swagger.Streams.Deserialize (Object, "key", Value.Key); Swagger.Streams.Deserialize (Object, "status", Value.Status); end Deserialize; procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out Agent_Type_Vectors.Vector) is List : Swagger.Value_Array_Type; Item : Agent_Type; begin Value.Clear; Swagger.Streams.Deserialize (From, Name, List); for Data of List loop Deserialize (Data, "", Item); Value.Append (Item); end loop; end Deserialize; procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in Host_Type) is begin Into.Start_Entity (Name); Serialize (Into, "id", Value.Id); Into.Write_Entity ("name", Value.Name); Into.Write_Entity ("ip", Value.Ip); Into.Write_Entity ("create_date", Value.Create_Date); Into.Write_Entity ("done_date", Value.Done_Date); Into.Write_Entity ("status", Value.Status); Into.End_Entity (Name); end Serialize; procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in Host_Type_Vectors.Vector) is begin Into.Start_Array (Name); for Item of Value loop Serialize (Into, "", Item); end loop; Into.End_Array (Name); end Serialize; procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out Host_Type) is Object : Swagger.Value_Type; begin Swagger.Streams.Deserialize (From, Name, Object); Swagger.Streams.Deserialize (Object, "id", Value.Id); Swagger.Streams.Deserialize (Object, "name", Value.Name); Swagger.Streams.Deserialize (Object, "ip", Value.Ip); Deserialize (Object, "create_date", Value.Create_Date); Deserialize (Object, "done_date", Value.Done_Date); Swagger.Streams.Deserialize (Object, "status", Value.Status); end Deserialize; procedure Deserialize (From : in Swagger.Value_Type; Name : in String; Value : out Host_Type_Vectors.Vector) is List : Swagger.Value_Array_Type; Item : Host_Type; begin Value.Clear; Swagger.Streams.Deserialize (From, Name, List); for Data of List loop Deserialize (Data, "", Item); Value.Append (Item); end loop; end Deserialize; end Hyperion.Rest.Models;
reznikmm/matreshka
Ada
6,137
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011, Vadim Godunko <[email protected]> -- -- 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$ ------------------------------------------------------------------------------ with AMF.Internals.UML_Packageable_Elements; with AMF.UML.Value_Specifications; package AMF.Internals.UML_Value_Specifications is type UML_Value_Specification_Proxy is abstract limited new AMF.Internals.UML_Packageable_Elements.UML_Packageable_Element_Proxy and AMF.UML.Value_Specifications.UML_Value_Specification with null record; overriding function Boolean_Value (Self : not null access constant UML_Value_Specification_Proxy) return AMF.Optional_Boolean; -- Operation ValueSpecification::booleanValue. -- -- The query booleanValue() gives a single Boolean value when one can be -- computed. overriding function Integer_Value (Self : not null access constant UML_Value_Specification_Proxy) return AMF.Optional_Integer; -- Operation ValueSpecification::integerValue. -- -- The query integerValue() gives a single Integer value when one can be -- computed. overriding function Is_Computable (Self : not null access constant UML_Value_Specification_Proxy) return Boolean; -- Operation ValueSpecification::isComputable. -- -- The query isComputable() determines whether a value specification can -- be computed in a model. This operation cannot be fully defined in OCL. -- A conforming implementation is expected to deliver true for this -- operation for all value specifications that it can compute, and to -- compute all of those for which the operation is true. A conforming -- implementation is expected to be able to compute the value of all -- literals. overriding function Is_Null (Self : not null access constant UML_Value_Specification_Proxy) return Boolean; -- Operation ValueSpecification::isNull. -- -- The query isNull() returns true when it can be computed that the value -- is null. overriding function Real_Value (Self : not null access constant UML_Value_Specification_Proxy) return AMF.Optional_Real; -- Operation ValueSpecification::realValue. -- -- The query realValue() gives a single Real value when one can be -- computed. overriding function String_Value (Self : not null access constant UML_Value_Specification_Proxy) return AMF.Optional_String; -- Operation ValueSpecification::stringValue. -- -- The query stringValue() gives a single String value when one can be -- computed. overriding function Unlimited_Value (Self : not null access constant UML_Value_Specification_Proxy) return AMF.Optional_Unlimited_Natural; -- Operation ValueSpecification::unlimitedValue. -- -- The query unlimitedValue() gives a single UnlimitedNatural value when -- one can be computed. end AMF.Internals.UML_Value_Specifications;