content stringlengths 23 1.05M |
|---|
generic
type T is mod <>;
package Offmt_Lib.Fmt_Data.Unsigned_Generic is
subtype Parent is Fmt_Data.Instance;
type Instance
is new Parent with private;
overriding
procedure From_Frame (This : in out Instance;
Frame : in out Data_Frame);
overriding
function Format (This : Instance;
Kind : Format_Kind)
return String;
overriding
procedure Put (This : Instance;
Kind : Format_Kind);
function Value (This : Instance) return T;
private
type Instance
is new Parent with record
Val : T;
Loaded : Boolean := False;
end record;
end Offmt_Lib.Fmt_Data.Unsigned_Generic;
|
-- Standard Ada library specification
-- Copyright (c) 2004-2016 AXE Consultants
-- Copyright (c) 2004, 2005, 2006 Ada-Europe
-- Copyright (c) 2000 The MITRE Corporation, Inc.
-- Copyright (c) 1992, 1993, 1994, 1995 Intermetrics, Inc.
-- SPDX-License-Identifier: BSD-3-Clause and LicenseRef-AdaReferenceManual
---------------------------------------------------------------------------
package System.Multiprocessors is
pragma Preelaborate(Multiprocessors);
type CPU_Range is range 0 .. implementation_defined;
Not_A_Specific_CPU : constant CPU_Range := 0;
subtype CPU is CPU_Range range 1 .. CPU_Range'Last;
function Number_Of_CPUs return CPU;
end System.Multiprocessors;
|
package body agar.gui.widget.notebook is
package cbinds is
procedure set_padding
(notebook : notebook_access_t;
padding : c.int);
pragma import (c, set_padding, "AG_NotebookSetPadding");
procedure set_spacing
(notebook : notebook_access_t;
spacing : c.int);
pragma import (c, set_spacing, "AG_NotebookSetSpacing");
procedure set_tab_visibility
(notebook : notebook_access_t;
flag : c.int);
pragma import (c, set_tab_visibility, "AG_NotebookSetTabVisibility");
procedure add_tab
(notebook : notebook_access_t;
name : cs.chars_ptr;
box_type : agar.gui.widget.box.type_t);
pragma import (c, add_tab, "AG_NotebookAddTab");
end cbinds;
procedure set_padding
(notebook : notebook_access_t;
padding : natural) is
begin
cbinds.set_padding
(notebook => notebook,
padding => c.int (padding));
end set_padding;
procedure set_spacing
(notebook : notebook_access_t;
spacing : natural) is
begin
cbinds.set_spacing
(notebook => notebook,
spacing => c.int (spacing));
end set_spacing;
procedure set_tab_visibility
(notebook : notebook_access_t;
flag : boolean := false)
is
c_flag : c.int := 0;
begin
if flag then c_flag := 1; end if;
cbinds.set_tab_visibility
(notebook => notebook,
flag => c_flag);
end set_tab_visibility;
procedure add_tab
(notebook : notebook_access_t;
name : string;
box_type : agar.gui.widget.box.type_t)
is
c_name : aliased c.char_array := c.to_c (name);
begin
cbinds.add_tab
(notebook => notebook,
name => cs.to_chars_ptr (c_name'unchecked_access),
box_type => box_type);
end add_tab;
function widget (notebook : notebook_access_t) return widget_access_t is
begin
return notebook.widget'access;
end widget;
end agar.gui.widget.notebook;
|
with Screen_Interface; use Screen_Interface;
with Giza.Events; use Giza.Events;
with Giza.GUI; use Giza.GUI;
package body Utils is
task body Touch_Screen is
TS, Prev : Touch_State;
Evt : constant Click_Event_Ref := new Click_Event;
Released_Evt : constant Click_Released_Event_Ref :=
new Click_Released_Event;
begin
Prev.Touch_Detected := False;
loop
TS := Get_Touch_State;
if TS.Touch_Detected /= Prev.Touch_Detected then
if TS.Touch_Detected then
Evt.Pos.X := TS.X;
Evt.Pos.Y := TS.Y;
Emit (Event_Not_Null_Ref (Evt));
else
Emit (Event_Not_Null_Ref (Released_Evt));
end if;
end if;
Prev := TS;
end loop;
end Touch_Screen;
end Utils;
|
------------------------------------------------------------------------------
-- --
-- WAVEFILES --
-- --
-- Wavefile benchmarking --
-- --
-- The MIT License (MIT) --
-- --
-- Copyright (c) 2020 Gustavo A. Hoffmann --
-- --
-- Permission is hereby granted, free of charge, to any person obtaining --
-- a copy of this software and associated documentation files (the --
-- "Software"), to deal in the Software without restriction, including --
-- without limitation the rights to use, copy, modify, merge, publish, --
-- distribute, sublicense, and / or sell copies of the Software, and to --
-- permit persons to whom the Software is furnished to do so, subject to --
-- the following conditions: --
-- --
-- The above copyright notice and this permission notice shall be --
-- included in all copies or substantial portions of the Software. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, --
-- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF --
-- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. --
-- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY --
-- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, --
-- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE --
-- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --
------------------------------------------------------------------------------
with Ada.Text_IO; use Ada.Text_IO;
package body Time_Span_Conversions is
Display_Debug_Info : constant Boolean := False;
------------
-- To_MHz --
------------
function To_MHz (Elapsed_Time : Time_Span;
CPU_MHz : Float;
Factor : Long_Long_Float) return Float
is
Dur : constant Long_Long_Float :=
Long_Long_Float (To_Duration (Elapsed_Time));
-- Elapsed time in seconds
begin
if Display_Debug_Info then
Put_Line ("Dur: " & Long_Long_Float'Image (Dur));
Put_Line ("Factor: " & Long_Long_Float'Image (Factor));
end if;
return Float
(Long_Long_Float (CPU_MHz) * Dur / Factor);
end To_MHz;
------------
-- To_kHz --
------------
function To_kHz (Elapsed_Time : Time_Span;
CPU_MHz : Float;
Factor : Long_Long_Float) return Float is
(To_MHz (Elapsed_Time, CPU_MHz, Factor) * 10.0 ** 3);
--------------------
-- To_Miliseconds --
--------------------
function To_Miliseconds (Elapsed_Time : Time_Span) return Float is
T : constant Float := Float (To_Duration (Elapsed_Time));
begin
return T * 10.0 ** 3;
end To_Miliseconds;
--------------------
-- To_Nanoseconds --
--------------------
function To_Nanoseconds (Elapsed_Time : Time_Span) return Float is
T : constant Float := Float (To_Duration (Elapsed_Time));
begin
return T * 10.0 ** 9;
end To_Nanoseconds;
end Time_Span_Conversions;
|
-- { dg-do run }
with Ada.Streams.Stream_IO;
procedure In_Out_Parameter is
use Ada.Streams; use Stream_IO;
File : Stream_IO.File_Type;
type Bitmap is array (Natural range <>) of Boolean;
for Bitmap'Component_Size use 1;
type Message is record
B : Bitmap (0 .. 14);
end record;
for Message use record
B at 0 range 2 .. 16;
end record;
TX, RX : Message;
begin
TX.B := (others => False);
Stream_IO.Create (File => File, Mode => Out_File, Name => "data");
Message'Output (Stream (File), TX);
Stream_IO.Close (File);
--
Stream_IO.Open (File => File, Mode => In_File, Name => "data");
RX := Message'Input (Stream (File));
Stream_IO.Close (File);
if RX /= TX then
raise Program_Error;
end if;
end In_Out_Parameter;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015-2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of STMicroelectronics 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. --
-- --
-- --
-- This file is based on: --
-- --
-- @file stm32f429i_discovery.h --
-- @author MCD Application Team --
-- @version V1.1.0 --
-- @date 19-June-2014 --
-- @brief This file contains definitions for STM32F429I-Discovery Kit --
-- LEDs, push-buttons hardware resources. --
-- --
-- COPYRIGHT(c) 2014 STMicroelectronics --
------------------------------------------------------------------------------
-- This file provides declarations for devices on the STM32F429 Discovery kits
-- manufactured by ST Microelectronics.
with STM32.Device; use STM32.Device;
with STM32.GPIO; use STM32.GPIO;
with STM32.SPI; use STM32.SPI;
with STM32.FMC; use STM32.FMC;
with L3GD20;
with Framebuffer_ILI9341;
with Touch_Panel_STMPE811;
with Ada.Interrupts.Names; use Ada.Interrupts;
package STM32.Board is
pragma Elaborate_Body;
----------
-- LEDs --
----------
subtype User_LED is GPIO_Point;
Green_LED : User_LED renames PG13;
Red_LED : User_LED renames PG14;
LCH_LED : User_LED renames Red_LED;
All_LEDs : GPIO_Points := Green_LED & Red_LED;
procedure Initialize_LEDs;
-- MUST be called prior to any use of the LEDs unless initialization is
-- done by the app elsewhere.
procedure Turn_On (This : in out User_LED) renames STM32.GPIO.Set;
procedure Turn_Off (This : in out User_LED) renames STM32.GPIO.Clear;
procedure Toggle (This : in out User_LED) renames STM32.GPIO.Toggle;
procedure All_LEDs_Off with Inline;
procedure All_LEDs_On with Inline;
procedure Toggle_LEDs (These : in out GPIO_Points) renames STM32.GPIO.Toggle;
---------
-- FMC --
---------
FMC_D : constant GPIO_Points :=
(PD14, PD15, PD0, PD1, PE7, PE8, PE9, PE10,
PE11, PE12, PE13, PE14, PE15, PD8, PD9, PD10);
FMC_A : constant GPIO_Points :=
(PF0, PF1, PF2, PF3, PF4, PF5,
PF12, PF13, PF14, PF15, PG0, PG1);
FMC_SDNWE : GPIO_Point renames PC0;
FMC_SDNRAS : GPIO_Point renames PF11;
FMC_SDNCAS : GPIO_Point renames PG15;
FMC_SDCLK : GPIO_Point renames PG8;
FMC_BA0 : GPIO_Point renames PG4;
FMC_BA1 : GPIO_Point renames PG5;
FMC_NBL0 : GPIO_Point renames PE0;
FMC_NBL1 : GPIO_Point renames PE1;
FMC_SDNE1 : GPIO_Point renames PB6;
FMC_SDCKE1 : GPIO_Point renames PB5;
SDRAM_PINS : constant GPIO_Points :=
FMC_A & FMC_D &
FMC_SDNWE & FMC_SDNRAS & FMC_SDNCAS & FMC_SDCLK &
FMC_BA0 & FMC_BA1 & FMC_SDNE1 & FMC_SDCKE1 &
FMC_NBL0 & FMC_NBL1;
-- SDRAM CONFIGURATION Parameters
SDRAM_Base : constant := 16#D0000000#;
SDRAM_Size : constant := 16#800000#;
SDRAM_Bank : constant STM32.FMC.FMC_SDRAM_Cmd_Target_Bank :=
STM32.FMC.FMC_Bank2_SDRAM;
SDRAM_Row_Bits : constant STM32.FMC.FMC_SDRAM_Row_Address_Bits :=
STM32.FMC.FMC_RowBits_Number_12b;
SDRAM_Mem_Width : constant STM32.FMC.FMC_SDRAM_Memory_Bus_Width :=
STM32.FMC.FMC_SDMemory_Width_16b;
SDRAM_CAS_Latency : constant STM32.FMC.FMC_SDRAM_CAS_Latency :=
STM32.FMC.FMC_CAS_Latency_3;
SDRAM_CLOCK_Period : constant STM32.FMC.FMC_SDRAM_Clock_Configuration :=
STM32.FMC.FMC_SDClock_Period_2;
SDRAM_Read_Burst : constant STM32.FMC.FMC_SDRAM_Burst_Read :=
STM32.FMC.FMC_Read_Burst_Disable;
SDRAM_Read_Pipe : constant STM32.FMC.FMC_SDRAM_Read_Pipe_Delay :=
STM32.FMC.FMC_ReadPipe_Delay_1;
SDRAM_Refresh_Cnt : constant := 1386;
SDRAM_Min_Delay_In_ns : constant := 70;
---------------
-- SPI5 Pins --
---------------
-- Required for the gyro and LCD so defined here
SPI5_SCK : GPIO_Point renames PF7;
SPI5_MISO : GPIO_Point renames PF8;
SPI5_MOSI : GPIO_Point renames PF9;
NCS_MEMS_SPI : GPIO_Point renames PC1;
MEMS_INT1 : GPIO_Point renames PA1;
MEMS_INT2 : GPIO_Point renames PA2;
-------------------------
-- LCD and Touch Panel --
-------------------------
LCD_SPI : SPI_Port renames SPI_5;
-- See the STM32F429I-Discovery board schematics for the actual pin
-- assignments
-- RGB connection
LCD_VSYNC : GPIO_Point renames PA4;
LCD_HSYNC : GPIO_Point renames PC6;
LCD_ENABLE : GPIO_Point renames PF10;
LCD_CLK : GPIO_Point renames PG7;
-- See the STM32F427xx/STM32F429xx datasheet for the aleternate function
-- mapping.
LCD_RGB_AF9 : constant GPIO_Points :=
(PB0, PB1, PG10, PG12);
LCD_RGB_AF14 : constant GPIO_Points :=
(PC10, PA11, PA12, PG6,
PA6, PB10, PB11, PC7, PD3,
PD6, PG11, PA3, PB8, PB9);
LCD_PINS : constant GPIO_Points :=
LCD_RGB_AF14 & LCD_RGB_AF9 &
LCD_VSYNC & LCD_HSYNC & LCD_ENABLE & LCD_CLK;
LCD_Natural_Width : constant := 240;
LCD_Natural_Height : constant := 320;
Display : Framebuffer_ILI9341.Frame_Buffer;
Touch_Panel : Touch_Panel_STMPE811.Touch_Panel;
-----------------
-- User button --
-----------------
User_Button_Point : GPIO_Point renames PA0;
User_Button_Interrupt : constant Interrupt_ID := Names.EXTI0_Interrupt;
procedure Configure_User_Button_GPIO;
-- Configures the GPIO port/pin for the blue user button. Sufficient
-- for polling the button, and necessary for having the button generate
-- interrupts.
----------
-- Gyro --
----------
Gyro_SPI : SPI_Port renames LCD_SPI;
-- The gyro and LCD use the same port and pins. See the STM32F429 Discovery
-- kit User Manual (UM1670) pages 21 and 23.
Gyro_Interrupt_1_Pin : GPIO_Point renames MEMS_INT1;
Gyro_Interrupt_2_Pin : GPIO_Point renames MEMS_INT2;
-- Theese are the GPIO pins on which the gyro generates interrupts if so
-- commanded. The gyro package does not references these, only clients'
-- interrupt handlers do.
Gyro : L3GD20.Three_Axis_Gyroscope;
procedure Initialize_Gyro_IO;
-- This is a board-specific routine. It initializes and configures the
-- GPIO, SPI, etc. for the on-board L3GD20 gyro as required for the F429
-- Disco board. See the STM32F429 Discovery kit User Manual (UM1670) for
-- specifics.
end STM32.Board;
|
-----------------------------------------------------------------------
-- Atlas.Applications.Models -- Atlas.Applications.Models
-----------------------------------------------------------------------
-- File generated by ada-gen DO NOT MODIFY
-- Template used: templates/model/package-spec.xhtml
-- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 1095
-----------------------------------------------------------------------
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
pragma Warnings (Off, "unit * is not referenced");
with ADO.Sessions;
with ADO.Objects;
with ADO.Statements;
with ADO.SQL;
with ADO.Schemas;
with ADO.Queries;
with ADO.Queries.Loaders;
with Ada.Containers.Vectors;
with Ada.Strings.Unbounded;
with Util.Beans.Objects;
with Util.Beans.Basic.Lists;
pragma Warnings (On, "unit * is not referenced");
package Atlas.Applications.Models is
-- --------------------
-- Stats about what the user did.
-- --------------------
type User_Stat_Info is new Util.Beans.Basic.Readonly_Bean with record
-- the number of posts.
Post_Count : Integer;
-- the number of documents.
Document_Count : Integer;
-- the number of questions asked.
Question_Count : Integer;
-- the number of answers.
Answer_Count : Integer;
-- the number of reviews.
Review_Count : Integer;
end record;
-- Get the bean attribute identified by the given name.
overriding
function Get_Value (From : in User_Stat_Info;
Name : in String) return Util.Beans.Objects.Object;
package User_Stat_Info_Beans is
new Util.Beans.Basic.Lists (Element_Type => User_Stat_Info);
package User_Stat_Info_Vectors renames User_Stat_Info_Beans.Vectors;
subtype User_Stat_Info_List_Bean is User_Stat_Info_Beans.List_Bean;
type User_Stat_Info_List_Bean_Access is access all User_Stat_Info_List_Bean;
-- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>.
procedure List (Object : in out User_Stat_Info_List_Bean'Class;
Session : in out ADO.Sessions.Session'Class;
Context : in out ADO.Queries.Context'Class);
subtype User_Stat_Info_Vector is User_Stat_Info_Vectors.Vector;
-- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>.
procedure List (Object : in out User_Stat_Info_Vector;
Session : in out ADO.Sessions.Session'Class;
Context : in out ADO.Queries.Context'Class);
Query_User_Stat : constant ADO.Queries.Query_Definition_Access;
private
package File_1 is
new ADO.Queries.Loaders.File (Path => "user-stats.xml",
Sha1 => "57E3C61ACCA9CC94237EF0BB1167698EA1E0E648");
package Def_Userstatinfo_User_Stat is
new ADO.Queries.Loaders.Query (Name => "user-stat",
File => File_1.File'Access);
Query_User_Stat : constant ADO.Queries.Query_Definition_Access
:= Def_Userstatinfo_User_Stat.Query'Access;
end Atlas.Applications.Models;
|
-- { dg-do run }
with Generic_Disp_Pkg; use Generic_Disp_Pkg;
procedure Generic_Disp is
I : aliased Integer := 0;
D : Iface'Class := Dispatching_Constructor (DT'Tag, I'access);
begin
null;
end Generic_Disp;
|
with Ada.Real_Time;
with ACO.Drivers.Socket;
with ACO.CANopen;
with ACO.Nodes.Locals;
with ACO.Nodes.Remotes;
with ACO.OD.Example;
with ACO.Log;
with Ada.Text_IO.Text_Streams;
with Ada.Text_IO;
with Ada.Exceptions;
with ACO.OD_Types;
with ACO.OD_Types.Entries;
with ACO.SDO_Sessions;
package body App is
O : aliased ACO.OD.Example.Dictionary;
D : aliased ACO.Drivers.Socket.CAN_Driver;
H : aliased ACO.CANopen.Handler (Driver => D'Access);
W : ACO.CANopen.Periodic_Task (H'Access, Period_Ms => 10);
procedure Run
(Node : in out ACO.Nodes.Node_Base'Class)
is
use Ada.Text_IO;
use type Ada.Real_Time.Time;
Next_Release : Ada.Real_Time.Time;
begin
ACO.Log.Set_Stream (Text_Streams.Stream (Current_Output));
ACO.Log.Set_Level (ACO.Log.Debug);
D.Initialize;
Node.Start;
Next_Release := Ada.Real_Time.Clock;
loop
Next_Release := Next_Release + Ada.Real_Time.Milliseconds (10);
delay until Next_Release;
end loop;
exception
when E : others =>
Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Information (E));
end Run;
procedure Run_Local
is
Node : ACO.Nodes.Locals.Local
(Id => 1, Handler => H'Access, Od => O'Access);
begin
Run (Node);
end Run_Local;
procedure Run_Remote
is
Node : aliased ACO.Nodes.Remotes.Remote
(Id => 1, Handler => H'Access, Od => O'Access);
use Ada.Text_IO;
use type Ada.Real_Time.Time;
use ACO.OD_Types;
use ACO.OD_Types.Entries;
Next_Release : Ada.Real_Time.Time;
Value : U16 := 0;
begin
ACO.Log.Set_Stream (Text_Streams.Stream (Current_Output));
ACO.Log.Set_Level (ACO.Log.Debug);
D.Initialize;
Node.Start;
-- Poor man's "wait until heartbeat received"
delay until Ada.Real_Time.Clock + Ada.Real_Time.Milliseconds (3000);
Next_Release := Ada.Real_Time.Clock;
loop
Next_Release := Next_Release + Ada.Real_Time.Milliseconds (1000);
delay until Next_Release;
declare
function Read_U16 is new ACO.Nodes.Remotes.Generic_Read
(Entry_T => Entry_U16);
To_Entry : constant Entry_U16 :=
Read_U16 (Node, ACO.OD.Heartbeat_Producer_Index, 0);
begin
Ada.Text_IO.Put_Line
("Generic function read value = " & U16' (To_Entry.Read)'Img);
end;
-- Alternative way of reading...
declare
To_Entry : Entry_U16;
Result : ACO.Nodes.Remotes.SDO_Result;
begin
Node.Read
(Index => ACO.OD.Heartbeat_Producer_Index,
Subindex => 0,
Result => Result,
To_Entry => To_Entry);
Ada.Text_IO.Put_Line ("Remote node read result = " & Result'Img);
if ACO.SDO_Sessions.Is_Complete (Result) then
Ada.Text_IO.Put_Line ("Value =" & U16' (To_Entry.Read)'Img);
end if;
end;
declare
A_Value : constant U16 := 500 + Value;
An_Entry : constant Entry_U16 := Create (RW, A_Value);
begin
Node.Write
(Index => ACO.OD.Heartbeat_Producer_Index,
Subindex => 0,
An_Entry => An_Entry);
Ada.Text_IO.Put_Line ("Remote node write value =" & A_Value'Img);
end;
Value := (Value + 1) mod 500;
end loop;
exception
when E : others =>
Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Information (E));
end Run_Remote;
end App;
|
with Ada.Exception_Identification.From_Here;
with System.Zero_Terminated_WStrings;
with C.winnt;
package body System.Native_Directories.Temporary is
use Ada.Exception_Identification.From_Here;
use type C.size_t;
use type C.windef.UINT;
use type C.windef.WINBOOL;
TMP : aliased constant C.winnt.WCHAR_array (0 .. 3) := (
C.winnt.WCHAR'Val (Wide_Character'Pos ('T')),
C.winnt.WCHAR'Val (Wide_Character'Pos ('M')),
C.winnt.WCHAR'Val (Wide_Character'Pos ('P')),
C.winnt.WCHAR'Val (0));
Prefix : constant C.winnt.WCHAR_array (0 .. 3) := (
C.winnt.WCHAR'Val (Wide_Character'Pos ('A')),
C.winnt.WCHAR'Val (Wide_Character'Pos ('D')),
C.winnt.WCHAR'Val (Wide_Character'Pos ('A')),
C.winnt.WCHAR'Val (0));
-- implementation
function Temporary_Directory return String is
Result : C.winnt.WCHAR_array (0 .. C.windef.MAX_PATH - 1);
Length : C.windef.DWORD;
begin
Length := C.winbase.GetTempPath (Result'Length, Result (0)'Access);
return Zero_Terminated_WStrings.Value (
Result (0)'Access,
C.size_t (Length));
end Temporary_Directory;
procedure Set_Temporary_Directory (Name : String) is
W_Name : C.winnt.WCHAR_array (
0 ..
Name'Length * Zero_Terminated_WStrings.Expanding);
begin
Zero_Terminated_WStrings.To_C (Name, W_Name (0)'Access);
if C.winbase.SetEnvironmentVariable (TMP (0)'Access, W_Name (0)'Access) =
C.windef.FALSE
then
Raise_Exception (Use_Error'Identity);
end if;
end Set_Temporary_Directory;
function Create_Temporary_File (Directory : String) return String is
W_Directory : C.winnt.WCHAR_array (
0 ..
Directory'Length * Zero_Terminated_WStrings.Expanding);
Result : C.winnt.WCHAR_array (0 .. C.windef.MAX_PATH - 1);
begin
Zero_Terminated_WStrings.To_C (Directory, W_Directory (0)'Access);
if C.winbase.GetTempFileName (
W_Directory (0)'Access,
Prefix (0)'Access,
0,
Result (0)'Access) = 0
then
Raise_Exception (Named_IO_Exception_Id (C.winbase.GetLastError));
end if;
return Zero_Terminated_WStrings.Value (Result (0)'Access);
end Create_Temporary_File;
function Create_Temporary_Directory (Directory : String) return String is
begin
return Result : constant String := Create_Temporary_File (Directory) do
declare
W_Result : aliased
C.winnt.WCHAR_array (
0 .. Result'Length * Zero_Terminated_WStrings.Expanding);
begin
Zero_Terminated_WStrings.To_C (Result, W_Result (0)'Access);
if C.winbase.DeleteFile (W_Result (0)'Access) = C.windef.FALSE then
Raise_Exception (
Named_IO_Exception_Id (C.winbase.GetLastError));
end if;
if C.winbase.CreateDirectory (W_Result (0)'Access, null) =
C.windef.FALSE
then
Raise_Exception (
Named_IO_Exception_Id (C.winbase.GetLastError));
end if;
end;
end return;
end Create_Temporary_Directory;
end System.Native_Directories.Temporary;
|
with Ada.Text_IO;
package body Test_Annotation.Append is
File_Name : constant String := "tmp/test-append-annotation.sf";
procedure Initialize (T : in out Test) is
begin
Set_Name (T, "Test_Annotation.Append");
Ahven.Framework.Add_Test_Routine (T, Append_Test_1'Access, "append test 1");
Ahven.Framework.Add_Test_Routine (T, Append_Test_2'Access, "append test 2");
Ahven.Framework.Add_Test_Routine (T, Append_Test_3'Access, "append test 3");
end Initialize;
procedure Set_Up (T : in out Test) is
State : access Skill_State := new Skill_State;
begin
Skill.Read (State, "resources/annotationTest.sf");
Skill.Write (State, File_Name);
declare
A : Date_Type_Access := New_Date (State, 3);
B : Date_Type_Access := New_Date (State, 4);
begin
New_Test (State, Skill_Type_Access (A));
New_Test (State, Skill_Type_Access (B));
end;
Skill.Append (State);
end Set_Up;
procedure Tear_Down (T : in out Test) is
begin
Ada.Directories.Delete_File (File_Name);
end Tear_Down;
procedure Append_Test_1 (T : in out Ahven.Framework.Test_Case'Class) is
State : access Skill_State := new Skill_State;
begin
Skill.Read (State, File_Name);
declare
Test : Test_Type_Access := Skill.Get_Test (State, 1);
Date : Date_Type_Access := Skill.Get_Date (State, 1);
X : Date_Type_Access := Date_Type_Access (Test.Get_F);
Y : Date_Type_Access := Date;
begin
Ahven.Assert (X = Y, "objects are not equal");
end;
end Append_Test_1;
procedure Append_Test_2 (T : in out Ahven.Framework.Test_Case'Class) is
State : access Skill_State := new Skill_State;
begin
Skill.Read (State, File_Name);
declare
Test : Test_Type_Access := Skill.Get_Test (State, 2);
Date : Date_Type_Access := Skill.Get_Date (State, 3);
X : Date_Type_Access := Date_Type_Access (Test.Get_F);
Y : Date_Type_Access := Date;
begin
Ahven.Assert (X = Y, "objects are not equal");
end;
end Append_Test_2;
procedure Append_Test_3 (T : in out Ahven.Framework.Test_Case'Class) is
State : access Skill_State := new Skill_State;
begin
Skill.Read (State, File_Name);
declare
Test : Test_Type_Access := Skill.Get_Test (State, 3);
Date : Date_Type_Access := Skill.Get_Date (State, 4);
X : Date_Type_Access := Date_Type_Access (Test.Get_F);
Y : Date_Type_Access := Date;
begin
Ahven.Assert (X = Y, "objects are not equal");
end;
end Append_Test_3;
end Test_Annotation.Append;
|
with Lv.Style;
package Lv.Objx.Bar is
subtype Instance is Obj_T;
type Style_T is (Style_Bg, Style_Indic);
-- Create a bar objects
-- @param par pointer to an object, it will be the parent of the new bar
-- @param copy pointer to a bar object, if not NULL then the new object will be copied from it
-- @return pointer to the created bar
function Create (Parent : Instance; Copy : Obj_T) return Instance;
----------------------
-- Setter functions --
----------------------
-- Set a new value on the bar
-- @param self pointer to a bar object
-- @param value new value
procedure Set_Value (Self : Instance; Arg2 : Int16_T);
-- Set a new value with animation on the bar
-- @param self pointer to a bar object
-- @param value new value
-- @param anim_time animation time in milliseconds
procedure Set_Value_Anim (Self : Instance; Arg2 : Int16_T; Arg3 : Uint16_T);
-- Set minimum and the maximum values of a bar
-- @param self pointer to the bar object
-- @param min minimum value
-- @param max maximum value
procedure Set_Range (Self : Instance; Arg2 : Int16_T; Arg3 : Int16_T);
-- Set a style of a bar
-- @param self pointer to a bar object
-- @param type which style should be set
-- @param style pointer to a style
procedure Set_Style
(Self : Instance;
Arg2 : Style_T;
Arg3 : Lv.Style.Style);
----------------------
-- Getter functions --
----------------------
-- Get the value of a bar
-- @param self pointer to a bar object
-- @return the value of the bar
function Value (Self : Instance) return Int16_T;
-- Get the minimum value of a bar
-- @param self pointer to a bar object
-- @return the minimum value of the bar
function Min_Value (Self : Instance) return Int16_T;
-- Get the maximum value of a bar
-- @param self pointer to a bar object
-- @return the maximum value of the bar
function Max_Value (Self : Instance) return Int16_T;
-- Get a style of a bar
-- @param self pointer to a bar object
-- @param type which style should be get
-- @return style pointer to a style
function Style (Self : Instance; Arg2 : Style_T) return Lv.Style.Style;
-------------
-- Imports --
-------------
pragma Import (C, Create, "lv_bar_create");
pragma Import (C, Set_Value, "lv_bar_set_value");
pragma Import (C, Set_Value_Anim, "lv_bar_set_value_anim");
pragma Import (C, Set_Range, "lv_bar_set_range");
pragma Import (C, Set_Style, "lv_bar_set_style");
pragma Import (C, Value, "lv_bar_get_value");
pragma Import (C, Min_Value, "lv_bar_get_min_value");
pragma Import (C, Max_Value, "lv_bar_get_max_value");
pragma Import (C, Style, "lv_bar_get_style");
for Style_T'Size use 8;
for Style_T use (Style_Bg => 0,
Style_Indic => 1);
end Lv.Objx.Bar;
|
with agar.core.event;
with agar.core.limits;
with agar.core.tail_queue;
with agar.gui.widget.button;
with agar.gui.widget.combo;
with agar.gui.widget.label;
with agar.gui.widget.pane;
with agar.gui.widget.textbox;
with agar.gui.widget.tlist;
package agar.gui.widget.file_dialog is
use type c.unsigned;
type option_t is limited private;
type option_access_t is access all option_t;
pragma convention (c, option_access_t);
type filetype_t;
type filetype_access_t is access all filetype_t;
pragma convention (c, filetype_access_t);
type file_dialog_t is limited private;
type file_dialog_access_t is access all file_dialog_t;
pragma convention (c, file_dialog_access_t);
package option_tail_queue is new agar.core.tail_queue
(entry_type => option_access_t);
package filetype_tail_queue is new agar.core.tail_queue
(entry_type => filetype_access_t);
type option_type_t is (
FILE_DIALOG_BOOL,
FILE_DIALOG_INT,
FILE_DIALOG_FLOAT,
FILE_DIALOG_DOUBLE,
FILE_DIALOG_STRING
);
for option_type_t use (
FILE_DIALOG_BOOL => 0,
FILE_DIALOG_INT => 1,
FILE_DIALOG_FLOAT => 2,
FILE_DIALOG_DOUBLE => 3,
FILE_DIALOG_STRING => 4
);
for option_type_t'size use c.unsigned'size;
pragma convention (c, option_type_t);
-- union
type data_int_t is record
val : c.int;
min : c.int;
max : c.int;
end record;
pragma convention (c, data_int_t);
type data_flt_t is record
val : c.c_float;
min : c.c_float;
max : c.c_float;
end record;
pragma convention (c, data_flt_t);
type data_dbl_t is record
val : c.double;
min : c.double;
max : c.double;
end record;
pragma convention (c, data_dbl_t);
type data_str_t is array (1 .. 128) of aliased c.char;
pragma convention (c, data_str_t);
type data_selector_t is (select_int, select_float, select_double, select_string);
type option_data_t (member : data_selector_t := select_int) is record
case member is
when select_int => i : data_int_t;
when select_float => f : data_flt_t;
when select_double => d : data_dbl_t;
when select_string => s : data_str_t;
end case;
end record;
pragma convention (c, option_data_t);
pragma unchecked_union (option_data_t);
type filetype_t is record
fd : file_dialog_access_t;
descr : cs.chars_ptr;
exts : access cs.chars_ptr;
num_exts : c.unsigned;
action : access agar.core.event.event_t;
opts : option_tail_queue.head_t;
types : filetype_tail_queue.entry_t;
end record;
pragma convention (c, filetype_t);
type flags_t is new c.unsigned;
FILEDLG_MULTI : constant flags_t := 16#001#;
FILEDLG_CLOSEWIN : constant flags_t := 16#002#;
FILEDLG_LOAD : constant flags_t := 16#004#;
FILEDLG_SAVE : constant flags_t := 16#008#;
FILEDLG_ASYNC : constant flags_t := 16#010#;
FILEDLG_HFILL : constant flags_t := 16#100#;
FILEDLG_VFILL : constant flags_t := 16#200#;
FILEDLG_EXPAND : constant flags_t := FILEDLG_HFILL or FILEDLG_VFILL;
type path_t is array (1 .. agar.core.limits.pathname_max) of aliased c.char;
pragma convention (c, path_t);
-- API
function allocate
(parent : widget_access_t;
flags : flags_t) return file_dialog_access_t;
pragma import (c, allocate, "AG_FileDlgNew");
function allocate_mru
(parent : widget_access_t;
key : string;
flags : flags_t) return file_dialog_access_t;
pragma inline (allocate_mru);
function set_directory
(dialog : file_dialog_access_t;
path : string) return boolean;
pragma inline (set_directory);
procedure set_directory_mru
(dialog : file_dialog_access_t;
key : string;
path : string);
pragma inline (set_directory_mru);
procedure set_filename
(dialog : file_dialog_access_t;
file : string);
pragma inline (set_filename);
function add_filetype
(dialog : file_dialog_access_t;
description : string;
extensions : string) return filetype_access_t;
pragma inline (add_filetype);
function widget (dialog : file_dialog_access_t) return widget_access_t;
pragma inline (widget);
private
type option_t is record
desc : cs.chars_ptr;
key : cs.chars_ptr;
unit : cs.chars_ptr;
option_type : option_type_t;
data : option_data_t;
opts : option_tail_queue.entry_t;
end record;
pragma convention (c, option_t);
type file_dialog_t is record
widget : aliased widget_t;
flags : flags_t;
cwd : path_t;
cfile : path_t;
pane : agar.gui.widget.pane.pane_access_t;
dirs : agar.gui.widget.tlist.tlist_access_t;
files : agar.gui.widget.tlist.tlist_access_t;
label_cwd : agar.gui.widget.label.label_access_t;
file : agar.gui.widget.textbox.textbox_access_t;
combo_types : agar.gui.widget.combo.combo_access_t;
button_ok : agar.gui.widget.button.button_access_t;
button_cancel : agar.gui.widget.button.button_access_t;
ok_action : agar.core.event.event_access_t;
cancel_action : agar.core.event.event_access_t;
mru_dir : cs.chars_ptr;
opts_ctr : agar.core.types.void_ptr_t;
types : filetype_tail_queue.head_t;
end record;
pragma convention (c, file_dialog_t);
end agar.gui.widget.file_dialog;
|
------------------------------------------------------------------------------
-- --
-- Hardware Abstraction Layer for STM32 Targets --
-- --
-- Copyright (C) 2014, 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 file provides definitions for the STM32F4 (ARM Cortex M4F
-- from ST Microelectronics) Serial Peripheral Interface (SPI) facility.
package STM32F4.SPI is
type SPI_Port is limited private;
type SPI_Data_Direction is
(D2Lines_FullDuplex, D2Lines_RxOnly, D1Line_Rx, D1Line_Tx);
type SPI_Data_Size is (Data_16, Data_8);
type SPI_Mode is (Master, Slave);
type SPI_CLock_Polarity is (High, Low);
type SPI_CLock_Phase is (P1Edge, P2Edge);
type SPI_Slave_Management is (Soft, Hard);
type SPI_Baud_Rate_Prescaler is
(BRP_2, BRP_4, BRP_8, BRP_16, BRP_32, BRP_64, BRP_128, BRP_256);
type SPI_First_Bit is (MSB, LSB);
type SPI_Configuration is record
Direction : SPI_Data_Direction;
Mode : SPI_Mode;
Data_Size : SPI_Data_Size;
Clock_Polarity : SPI_Clock_Polarity;
Clock_Phase : SPI_Clock_Phase;
Slave_Management : SPI_Slave_Management;
Baud_Rate_Prescaler : SPI_Baud_Rate_Prescaler;
First_Bit : SPI_First_Bit;
CRC_Poly : Half_Word;
end record;
procedure Configure (Port : in out SPI_Port; Conf : SPI_Configuration);
procedure Enable (Port : in out SPI_Port);
procedure Disable (Port : in out SPI_Port);
function Enabled (Port : SPI_Port) return Boolean;
procedure Send (Port : in out SPI_Port; Data : Half_Word);
function Data (Port : SPI_Port) return Half_Word
with Inline;
procedure Send (Port : in out SPI_Port; Data : Byte);
function Data (Port : SPI_Port) return Byte
with Inline;
function Rx_Is_Empty (Port : SPI_Port) return Boolean
with Inline;
function Tx_Is_Empty (Port : SPI_Port) return Boolean
with Inline;
function Busy (Port : SPI_Port) return Boolean
with Inline;
function Channel_Side_Indicated (Port : SPI_Port) return Boolean
with Inline;
function Underrun_Indicated (Port : SPI_Port) return Boolean
with Inline;
function CRC_Error_Indicated (Port : SPI_Port) return Boolean
with Inline;
function Mode_Fault_Indicated (Port : SPI_Port) return Boolean
with Inline;
function Overrun_Indicated (Port : SPI_Port) return Boolean
with Inline;
function Frame_Fmt_Error_Indicated (Port : SPI_Port) return Boolean
with Inline;
private
type SPI_Control_Register is record
Clock_Phase : Bits_1;
Clock_Polarity : Bits_1;
Master_Select : Bits_1;
Baud_Rate_Ctrl : Bits_3;
SPI_Enable : Bits_1;
LSB_First : Bits_1; -- Frame Format
Slave_Select : Bits_1;
Soft_Slave_Mgt : Bits_1; -- Software Slave Management
RXOnly : Bits_1;
Data_Frame_Fmt : Bits_1; -- 1=16-bit 0=8-bit
CRC_Next : Bits_1; -- 1=CRC Phase 0=No CRC Phase
CRC_Enable : Bits_1;
Output_BiDir : Bits_1; -- Output enable in bidirectional mode
BiDir_Mode : Bits_1; -- Bidirectional data mode enable
end record with Pack, Volatile, Size => 16;
type SPI_Control_Register2 is record
RX_DMA_Enable : Bits_1;
TX_DMA_Enable : Bits_1;
SS_Out_Enable : Bits_1;
Reserved_1 : Bits_1;
Frame_Fmt : Bits_1; -- 0=Motorola Mode 1=TI Mode
Err_Int_Enable : Bits_1;
RX_Not_Empty_Int_Enable : Bits_1;
TX_Empty_Int_Enable : Bits_1;
Reserved_2 : Bits_8;
end record with Pack, Volatile, Size => 16;
type SPI_I2S_Config_Register is record
Channel_Length : Bits_1;
Data_Length : Bits_2;
Clock_Polarity : Bits_1;
I2S_Standard : Bits_2; -- 00==Philips 01=MSB (L) 10=LSB (R) 11=PCM
Reserved_1 : Bits_1;
PCM_Frame_Sync : Bits_1; -- 0=Short 1=Long
Config_Mode : Bits_2; -- 00=SlaveTX 01=SlaveRX 10=MasterTX11=MasterRX
Enable : Bits_1;
Mode_Select : Bits_1; -- 0=SPI Mode 1=I2S Mode
Reserved_2 : Bits_4;
end record with Pack, Volatile, Size => 16;
type SPI_I2S_Prescale_Register is record
Linear_Prescler : Bits_8;
Odd_Factor : Bits_1;
Master_CLK_Out_Enable : Bits_1;
Reserved : Bits_6;
end record with Pack, Volatile, Size => 16;
type SPI_Status_Register is record
RX_Buffer_Not_Empty : Boolean;
TX_Buffer_Empty : Boolean;
Channel_Side : Boolean;
Underrun_Flag : Boolean;
CRC_Error_Flag : Boolean;
Mode_Fault : Boolean;
Overrun_Flag : Boolean;
Busy_Flag : Boolean;
Frame_Fmt_Error : Boolean;
Reserved : Bits_7;
end record with Pack, Volatile, Size => 16;
type SPI_Port is record
CTRL1 : SPI_Control_Register;
Reserved_1 : Half_Word;
CTRL2 : SPI_Control_Register2;
Reserved_2 : Half_Word;
Status : SPI_Status_Register;
Reserved_3 : Half_Word;
Data : Half_Word;
Reserved_4 : Half_Word;
CRC_Poly : Half_Word; -- Default = 16#0007#
Reserved_5 : Half_Word;
RX_CRC : Half_Word;
Reserved_6 : Half_Word;
TX_CRC : Half_Word;
Reserved_7 : Half_Word;
I2S_Conf : SPI_I2S_Config_Register;
Reserved_8 : Half_Word;
I2S_PreScal : SPI_I2S_Prescale_Register;
Reserved_9 : Half_Word;
end record with Pack, Volatile, Size => 9 * 32;
end STM32F4.SPI;
|
package Radar_Internals is
procedure Time_Step (Radar_Angle : Float;
Time_To_Arrival : Float;
John_Connor_Status : String);
end Radar_Internals;
|
package body Moving_Thing is
procedure Faster (T : in out Thing;
D : in Direction;
M : in Float) is
begin
null; -- null statement
end Faster;
procedure Stop (T : in out Thing) is
begin
T.Spd.Vx := 0.0;
T.Spd.Vy := 0.0;
T.Spd.Vz := 0.0;
end;
end Moving_Thing;
|
------------------------------------------------------------------------------
-- Copyright (c) 2006-2013, Maxim Reznik
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * Neither the name of the Maxim Reznik, IE nor the names of its
-- contributors may be used to endorse or promote products derived from
-- this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
package Asis.Gela.Elements.Assoc is
--------------------------------------
-- Pragma_Argument_Association_Node --
--------------------------------------
type Pragma_Argument_Association_Node is
new Association_Node with private;
type Pragma_Argument_Association_Ptr is
access all Pragma_Argument_Association_Node;
for Pragma_Argument_Association_Ptr'Storage_Pool use Lists.Pool;
function New_Pragma_Argument_Association_Node
(The_Context : ASIS.Context)
return Pragma_Argument_Association_Ptr;
function Formal_Parameter
(Element : Pragma_Argument_Association_Node) return Asis.Identifier;
procedure Set_Formal_Parameter
(Element : in out Pragma_Argument_Association_Node;
Value : in Asis.Identifier);
function Actual_Parameter
(Element : Pragma_Argument_Association_Node) return Asis.Expression;
procedure Set_Actual_Parameter
(Element : in out Pragma_Argument_Association_Node;
Value : in Asis.Expression);
function Association_Kind (Element : Pragma_Argument_Association_Node)
return Asis.Association_Kinds;
function Children (Element : access Pragma_Argument_Association_Node)
return Traverse_List;
function Clone
(Element : Pragma_Argument_Association_Node;
Parent : Asis.Element)
return Asis.Element;
procedure Copy
(Source : in Asis.Element;
Target : access Pragma_Argument_Association_Node;
Cloner : in Cloner_Class;
Parent : in Asis.Element);
--------------------------------
-- Parameter_Association_Node --
--------------------------------
type Parameter_Association_Node is
new Pragma_Argument_Association_Node with private;
type Parameter_Association_Ptr is
access all Parameter_Association_Node;
for Parameter_Association_Ptr'Storage_Pool use Lists.Pool;
function New_Parameter_Association_Node
(The_Context : ASIS.Context)
return Parameter_Association_Ptr;
function Is_Normalized
(Element : Parameter_Association_Node) return Boolean;
procedure Set_Is_Normalized
(Element : in out Parameter_Association_Node;
Value : in Boolean);
function Is_Defaulted_Association
(Element : Parameter_Association_Node) return Boolean;
procedure Set_Is_Defaulted_Association
(Element : in out Parameter_Association_Node;
Value : in Boolean);
function Association_Kind (Element : Parameter_Association_Node)
return Asis.Association_Kinds;
function Clone
(Element : Parameter_Association_Node;
Parent : Asis.Element)
return Asis.Element;
procedure Copy
(Source : in Asis.Element;
Target : access Parameter_Association_Node;
Cloner : in Cloner_Class;
Parent : in Asis.Element);
------------------------------
-- Generic_Association_Node --
------------------------------
type Generic_Association_Node is
new Parameter_Association_Node with private;
type Generic_Association_Ptr is
access all Generic_Association_Node;
for Generic_Association_Ptr'Storage_Pool use Lists.Pool;
function New_Generic_Association_Node
(The_Context : ASIS.Context)
return Generic_Association_Ptr;
function Association_Kind (Element : Generic_Association_Node)
return Asis.Association_Kinds;
function Clone
(Element : Generic_Association_Node;
Parent : Asis.Element)
return Asis.Element;
procedure Copy
(Source : in Asis.Element;
Target : access Generic_Association_Node;
Cloner : in Cloner_Class;
Parent : in Asis.Element);
-----------------------------------
-- Discriminant_Association_Node --
-----------------------------------
type Discriminant_Association_Node is
new Association_Node with private;
type Discriminant_Association_Ptr is
access all Discriminant_Association_Node;
for Discriminant_Association_Ptr'Storage_Pool use Lists.Pool;
function New_Discriminant_Association_Node
(The_Context : ASIS.Context)
return Discriminant_Association_Ptr;
function Is_Normalized
(Element : Discriminant_Association_Node) return Boolean;
procedure Set_Is_Normalized
(Element : in out Discriminant_Association_Node;
Value : in Boolean);
function Discriminant_Expression
(Element : Discriminant_Association_Node) return Asis.Expression;
procedure Set_Discriminant_Expression
(Element : in out Discriminant_Association_Node;
Value : in Asis.Expression);
function Discriminant_Selector_Name
(Element : Discriminant_Association_Node) return Asis.Expression;
procedure Set_Discriminant_Selector_Name
(Element : in out Discriminant_Association_Node;
Value : in Asis.Expression);
function Discriminant_Selector_Names
(Element : Discriminant_Association_Node;
Include_Pragmas : in Boolean := False) return Asis.Element_List;
procedure Set_Discriminant_Selector_Names
(Element : in out Discriminant_Association_Node;
Value : in Asis.Element);
function Discriminant_Selector_Names_List
(Element : Discriminant_Association_Node) return Asis.Element;
function Association_Kind (Element : Discriminant_Association_Node)
return Asis.Association_Kinds;
function Children (Element : access Discriminant_Association_Node)
return Traverse_List;
function Clone
(Element : Discriminant_Association_Node;
Parent : Asis.Element)
return Asis.Element;
procedure Copy
(Source : in Asis.Element;
Target : access Discriminant_Association_Node;
Cloner : in Cloner_Class;
Parent : in Asis.Element);
---------------------------------------
-- Record_Component_Association_Node --
---------------------------------------
type Record_Component_Association_Node is
new Association_Node with private;
type Record_Component_Association_Ptr is
access all Record_Component_Association_Node;
for Record_Component_Association_Ptr'Storage_Pool use Lists.Pool;
function New_Record_Component_Association_Node
(The_Context : ASIS.Context)
return Record_Component_Association_Ptr;
function Is_Normalized
(Element : Record_Component_Association_Node) return Boolean;
procedure Set_Is_Normalized
(Element : in out Record_Component_Association_Node;
Value : in Boolean);
function Component_Expression
(Element : Record_Component_Association_Node) return Asis.Expression;
procedure Set_Component_Expression
(Element : in out Record_Component_Association_Node;
Value : in Asis.Expression);
function Record_Component_Choice
(Element : Record_Component_Association_Node) return Asis.Defining_Name;
procedure Set_Record_Component_Choice
(Element : in out Record_Component_Association_Node;
Value : in Asis.Defining_Name);
function Record_Component_Choices
(Element : Record_Component_Association_Node;
Include_Pragmas : in Boolean := False) return Asis.Element_List;
procedure Set_Record_Component_Choices
(Element : in out Record_Component_Association_Node;
Value : in Asis.Element);
function Record_Component_Choices_List
(Element : Record_Component_Association_Node) return Asis.Element;
function Association_Kind (Element : Record_Component_Association_Node)
return Asis.Association_Kinds;
function Children (Element : access Record_Component_Association_Node)
return Traverse_List;
function Clone
(Element : Record_Component_Association_Node;
Parent : Asis.Element)
return Asis.Element;
procedure Copy
(Source : in Asis.Element;
Target : access Record_Component_Association_Node;
Cloner : in Cloner_Class;
Parent : in Asis.Element);
--------------------------------------
-- Array_Component_Association_Node --
--------------------------------------
type Array_Component_Association_Node is
new Association_Node with private;
type Array_Component_Association_Ptr is
access all Array_Component_Association_Node;
for Array_Component_Association_Ptr'Storage_Pool use Lists.Pool;
function New_Array_Component_Association_Node
(The_Context : ASIS.Context)
return Array_Component_Association_Ptr;
function Array_Component_Choices
(Element : Array_Component_Association_Node;
Include_Pragmas : in Boolean := False) return Asis.Element_List;
procedure Set_Array_Component_Choices
(Element : in out Array_Component_Association_Node;
Value : in Asis.Element);
function Array_Component_Choices_List
(Element : Array_Component_Association_Node) return Asis.Element;
function Component_Expression
(Element : Array_Component_Association_Node) return Asis.Expression;
procedure Set_Component_Expression
(Element : in out Array_Component_Association_Node;
Value : in Asis.Expression);
function Association_Kind (Element : Array_Component_Association_Node)
return Asis.Association_Kinds;
function Children (Element : access Array_Component_Association_Node)
return Traverse_List;
function Clone
(Element : Array_Component_Association_Node;
Parent : Asis.Element)
return Asis.Element;
procedure Copy
(Source : in Asis.Element;
Target : access Array_Component_Association_Node;
Cloner : in Cloner_Class;
Parent : in Asis.Element);
private
type Pragma_Argument_Association_Node is
new Association_Node with
record
Formal_Parameter : aliased Asis.Identifier;
Actual_Parameter : aliased Asis.Expression;
end record;
type Parameter_Association_Node is
new Pragma_Argument_Association_Node with
record
Is_Normalized : aliased Boolean := False;
Is_Defaulted_Association : aliased Boolean := False;
end record;
type Generic_Association_Node is
new Parameter_Association_Node with
record
null;
end record;
type Discriminant_Association_Node is
new Association_Node with
record
Is_Normalized : aliased Boolean := False;
Discriminant_Expression : aliased Asis.Expression;
Discriminant_Selector_Name : aliased Asis.Expression;
Discriminant_Selector_Names : aliased Primary_Choise_Lists.List;
end record;
type Record_Component_Association_Node is
new Association_Node with
record
Is_Normalized : aliased Boolean := False;
Component_Expression : aliased Asis.Expression;
Record_Component_Choice : aliased Asis.Defining_Name;
Record_Component_Choices : aliased Primary_Choise_Lists.List;
end record;
type Array_Component_Association_Node is
new Association_Node with
record
Array_Component_Choices : aliased Primary_Choise_Lists.List;
Component_Expression : aliased Asis.Expression;
end record;
end Asis.Gela.Elements.Assoc;
|
-- { dg-do run }
-- { dg-options "-O2" }
with Ada.Text_Io; use Ada.Text_IO;
with Raise_From_Pure; use Raise_From_Pure;
procedure handle_raise_from_pure is
K : Integer;
begin
K := Raise_CE_If_0 (0);
exception
when others => Put_Line ("exception caught");
end;
|
-- StrongEd$WrapWidth=256
-- StrongEd$Mode=Ada
--
with Main;
procedure Ext2Dir is
begin
Main.Main;
end Ext2Dir;
|
-- see OpenUxAS\src\Includes\Constants\UxAS_String.h
package UxAS.Common.String_Constant.Content_Type is
Json : constant String := "json";
Lmcp : constant String := "lmcp";
Text : constant String := "text";
Xml : constant String := "xml";
end UxAS.Common.String_Constant.Content_Type;
|
package Pieces is
pragma Pure;
type Owner_Type is (Player_1, Player_2, None) with Size=>2;
type Moved_Signal is (No, Yes) with Size=>2;
type Piece_Name is (Pawn, Knight, Bishop, Rook, Queen, King, Empty) with Size=>4;
type Piece_Type is record
Name : Piece_Name;
Owner : Owner_Type;
Has_Moved : Moved_Signal;
end record
with Pack;
Player_1_Pawn : constant Piece_Type := (Name=>Pawn, Owner=>Player_1, Has_Moved=>No);
Player_1_Knight : constant Piece_Type := (Name=>Knight, Owner=>Player_1, Has_Moved=>No);
Player_1_Bishop : constant Piece_Type := (Name=>Bishop, Owner=>Player_1, Has_Moved=>No);
Player_1_Rook : constant Piece_Type := (Name=>Rook, Owner=>Player_1, Has_Moved=>No);
Player_1_King : constant Piece_Type := (Name=>King, Owner=>Player_1, Has_Moved=>No);
Player_1_Queen : constant Piece_Type := (Name=>Queen, Owner=>Player_1, Has_Moved=>No);
Player_2_Pawn : constant Piece_Type := (Name=>Pawn, Owner=>Player_2, Has_Moved=>No);
Player_2_Knight : constant Piece_Type := (Name=>Knight, Owner=>Player_2, Has_Moved=>No);
Player_2_Bishop : constant Piece_Type := (Name=>Bishop, Owner=>Player_2, Has_Moved=>No);
Player_2_Rook : constant Piece_Type := (Name=>Rook, Owner=>Player_2, Has_Moved=>No);
Player_2_King : constant Piece_Type := (Name=>King, Owner=>Player_2, Has_Moved=>No);
Player_2_Queen : constant Piece_Type := (Name=>Queen, Owner=>Player_2, Has_Moved=>No);
Empty_Piece : constant Piece_Type := (Name=>Empty, Owner=>None, Has_Moved=>Yes);
end Pieces; |
-----------------------------------------------------------------------
-- security-oauth -- OAuth Security
-- Copyright (C) 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Security.OAuth is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Get the application identifier.
-- ------------------------------
function Get_Application_Identifier (App : in Application) return String is
begin
return To_String (App.Client_Id);
end Get_Application_Identifier;
-- ------------------------------
-- Set the application identifier used by the OAuth authorization server
-- to identify the application (for example, the App ID in Facebook).
-- ------------------------------
procedure Set_Application_Identifier (App : in out Application;
Client : in String) is
begin
App.Client_Id := To_Unbounded_String (Client);
end Set_Application_Identifier;
-- ------------------------------
-- Set the application secret defined in the OAuth authorization server
-- for the application (for example, the App Secret in Facebook).
-- ------------------------------
procedure Set_Application_Secret (App : in out Application;
Secret : in String) is
begin
App.Secret := To_Unbounded_String (Secret);
end Set_Application_Secret;
-- ------------------------------
-- Set the redirection callback that will be used to redirect the user
-- back to the application after the OAuth authorization is finished.
-- ------------------------------
procedure Set_Application_Callback (App : in out Application;
URI : in String) is
begin
App.Callback := To_Unbounded_String (URI);
end Set_Application_Callback;
-- ------------------------------
-- Set the client authentication method used when doing OAuth calls for this application.
-- See RFC 6749, 2.3. Client Authentication
-- ------------------------------
procedure Set_Client_Authentication (App : in out Application;
Method : in Client_Authentication_Type) is
begin
App.Client_Auth := Method;
end Set_Client_Authentication;
end Security.OAuth;
|
with AAA.Strings;
with CLIC.Subcommand;
package CLIC_Ex.Commands.Subsub is
type Instance
is new CLIC.Subcommand.Command
with private;
overriding
function Name (Cmd : Instance) return CLIC.Subcommand.Identifier
is ("subsub");
overriding
function Switch_Parsing (This : Instance)
return CLIC.Subcommand.Switch_Parsing_Kind
is (CLIC.Subcommand.Parse_All);
overriding
procedure Execute (Cmd : in out Instance;
Args : AAA.Strings.Vector);
overriding
function Long_Description (Cmd : Instance) return AAA.Strings.Vector
is (AAA.Strings.Empty_Vector);
overriding
procedure Setup_Switches
(Cmd : in out Instance;
Config : in out CLIC.Subcommand.Switches_Configuration)
is null;
overriding
function Short_Description (Cmd : Instance) return String
is ("Subcommands in a subcommand");
overriding
function Usage_Custom_Parameters (Cmd : Instance) return String
is ("");
private
type Instance
is new CLIC.Subcommand.Command
with null record;
end CLIC_Ex.Commands.Subsub;
|
with Ada.Formatting;
procedure format is
begin
Integer : declare
type T is range -999 .. 999;
function Image is new Ada.Formatting.Integer_Image (T);
function Trimed_Image is new Ada.Formatting.Integer_Image (
T,
Signs => Ada.Formatting.Triming_Sign_Marks);
function Hex_Image is new Ada.Formatting.Integer_Image (
T,
Base => 16);
function Simple_Hex_Image is
new Ada.Formatting.Integer_Image (
T,
Form => Ada.Formatting.Simple,
Signs => Ada.Formatting.Triming_Sign_Marks,
Base => 16,
Digits_Width => 4);
begin
pragma Assert (Image (123) = " 123");
pragma Assert (Trimed_Image (123) = "123");
pragma Assert (Hex_Image (123) = " 16#7B#");
pragma Assert (Simple_Hex_Image (123) = "007B");
null;
end Integer;
Modular : declare
type T is mod 1024;
function Image is new Ada.Formatting.Modular_Image (T);
function Hex_Image is new Ada.Formatting.Modular_Image (
T,
Base => 16);
function Simple_Hex_Image is
new Ada.Formatting.Modular_Image (
T,
Form => Ada.Formatting.Simple,
Signs => Ada.Formatting.Triming_Unsign_Marks,
Base => 16,
Digits_Width => 4);
begin
pragma Assert (Image (123) = " 123");
pragma Assert (Hex_Image (123) = " 16#7B#");
pragma Assert (Simple_Hex_Image (123) = "007B");
null;
end Modular;
Float : declare
type T is digits 5;
function Image is new Ada.Formatting.Float_Image (T);
function Hex_Image is new Ada.Formatting.Float_Image (
T,
Base => 16,
Aft_Width => 2);
function Simple_Hex_Image is new Ada.Formatting.Float_Image (
T,
Form => Ada.Formatting.Simple,
Signs => Ada.Formatting.Triming_Sign_Marks,
Base => 16,
Aft_Width => 2);
begin
pragma Assert (Image (1.25) = " 1.2500E+00");
pragma Assert (Hex_Image (-1.25) = "-16#1.40#E+00");
pragma Assert (Simple_Hex_Image (1.25) = "1.40E+00");
null;
end Float;
Fixed : declare
type T is delta 0.001 range 0.000 .. 999.999;
function Bin_Image is new Ada.Formatting.Fixed_Image (
T,
Base => 2,
Aft_Width => 3);
function Image is new Ada.Formatting.Fixed_Image (T);
function Hex_Image is new Ada.Formatting.Fixed_Image (
T,
Base => 16,
Aft_Width => 2);
begin
pragma Assert (Bin_Image (1.25) = " 2#1.010#");
pragma Assert (Image (1.25) = " 1.250");
pragma Assert (Hex_Image (1.25) = " 16#1.40#");
null;
end Fixed;
Decimal : declare
type T is delta 0.001 digits 6;
function Image is new Ada.Formatting.Decimal_Image (T);
begin
pragma Assert (Image (1.25) = " 1.250");
pragma Assert (Image (-1.25) = "-1.250");
null;
end Decimal;
pragma Debug (Ada.Debug.Put ("OK"));
end format;
|
with Ada.Assertions; use Ada.Assertions;
with Ada.Containers.Ordered_Maps; use Ada.Containers;
with Ada.Text_IO; use Ada.Text_IO;
with Input; use Input;
procedure Day04 is
type Hour is array (Natural range 0 .. 59) of Natural;
package Time_Maps is new Ordered_Maps (Key_Type => Natural,
Element_Type => Hour);
Time_Table : Time_Maps.Map;
Most_Minutes_Guard : Natural := 0;
Most_Minutes_Max_Minute : Natural := 0;
Most_Minutes_Count : Natural := 0;
Most_In_Minute_Guard : Natural := 0;
Most_In_Minute_Count : Natural := 0;
Most_In_Minute : Natural := 0;
begin
-- Input Setup
declare
Current_Guard : Natural := 0;
Sleep_Start : Natural range 0 .. 59 := 0;
begin
for Repose_Record of Repose_Records loop
if Repose_Record.Action = Shift_Start then
Current_Guard := Repose_Record.Data;
elsif Repose_Record.Action = Fall_Asleep then
Sleep_Start := Repose_Record.Data;
elsif Repose_Record.Action = Wake_Up then
if not Time_Table.Contains (Current_Guard) then
Time_Table.Insert (Current_Guard, (others => 0));
end if;
declare
Current_Hour : Hour := Time_Table.Element (Current_Guard);
begin
for S in Sleep_Start .. (Repose_Record.Data - 1) loop
Current_Hour (S) := Current_Hour (S) + 1;
end loop;
Time_Table.Replace (Current_Guard, Current_Hour);
end;
else
Assert (False, "This should not happen!");
end if;
end loop;
end;
-- Part 1 & 2
for C in Time_Table.Iterate loop
declare
Max_Minute : Natural := 0;
Minute_Count : Natural := 0;
begin
for I in 0 .. 59 loop
Minute_Count := Minute_Count + Time_Maps.Element (C) (I);
if Time_Maps.Element (C) (I) > Time_Maps.Element (C) (Max_Minute) then
Max_Minute := I;
end if;
if Time_Maps.Element (C) (I) > Most_In_Minute_Count then
Most_In_Minute := I;
Most_In_Minute_Guard := Time_Maps.Key (C);
Most_In_Minute_Count := Time_Maps.Element (C) (I);
end if;
end loop;
if Minute_Count > Most_Minutes_Count then
Most_Minutes_Guard := Time_Maps.Key (C);
Most_Minutes_Count := Minute_Count;
Most_Minutes_Max_Minute := Max_Minute;
end if;
end;
end loop;
Put_Line ("Part 1 =" & Natural'Image (Most_Minutes_Guard * Most_Minutes_Max_Minute));
Put_Line ("Part 2 =" & Natural'Image (Most_In_Minute_Guard * Most_In_Minute));
end Day04;
|
with Ada.Text_IO; use Ada.Text_IO;
with System.Storage_Elements; use System.Storage_Elements;
with COBS.Stream.Encoder;
with Interfaces; use Interfaces;
package body Offmt is
type COBS_Encoder is new COBS.Stream.Encoder.Instance with null record;
overriding
procedure Flush (This : in out COBS_Encoder;
Data : Storage_Array);
Encoder : COBS_Encoder;
-----------
-- Flush --
-----------
overriding
procedure Flush (This : in out COBS_Encoder;
Data : Storage_Array)
is
begin
for Elt of Data loop
Ada.Text_IO.Put (Character'Val (Elt));
end loop;
end Flush;
-----------------
-- Start_Frame --
-----------------
procedure Start_Frame (Id : Log_Id) is
begin
Encoder.Push (Storage_Element (Id and 16#FF#));
Encoder.Push (Storage_Element (Shift_Right (Id, 8) and 16#FF#));
end Start_Frame;
---------------
-- End_Frame --
---------------
procedure End_Frame is
begin
Encoder.End_Frame;
end End_Frame;
-------------
-- Push_U8 --
-------------
procedure Push_U8 (V : U8) is
begin
Encoder.Push (Storage_Element (V));
end Push_U8;
--------------
-- Push_U16 --
--------------
procedure Push_U16 (V : U16) is
begin
Encoder.Push (Storage_Element (V and 16#FF#));
Encoder.Push (Storage_Element (Shift_Right (V, 8) and 16#FF#));
end Push_U16;
--------------
-- Push_U32 --
--------------
procedure Push_U32 (V : U32) is
begin
Encoder.Push (Storage_Element (V and 16#FF#));
Encoder.Push (Storage_Element (Shift_Right (V, 8) and 16#FF#));
Encoder.Push (Storage_Element (Shift_Right (V, 16) and 16#FF#));
Encoder.Push (Storage_Element (Shift_Right (V, 24) and 16#FF#));
end Push_U32;
end Offmt;
|
------------------------------------------------------------------------------
-- --
-- GNAT LIBRARY COMPONENTS --
-- --
-- A D A . C O N T A I N E R S . H A S H E D _ M A P S --
-- --
-- S p e c --
-- --
-- Copyright (C) 2004-2020, 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/>. --
-- --
-- This unit was originally developed by Matthew J Heaney. --
------------------------------------------------------------------------------
with Ada.Iterator_Interfaces;
private with Ada.Containers.Hash_Tables;
private with Ada.Finalization;
private with Ada.Streams;
private with Ada.Strings.Text_Output;
-- The language-defined generic package Containers.Hashed_Maps provides
-- private types Map and Cursor, and a set of operations for each type. A map
-- container allows an arbitrary type to be used as a key to find the element
-- associated with that key. A hashed map uses a hash function to organize the
-- keys.
--
-- A map contains pairs of keys and elements, called nodes. Map cursors
-- designate nodes, but also can be thought of as designating an element (the
-- element contained in the node) for consistency with the other containers.
-- There exists an equivalence relation on keys, whose definition is different
-- for hashed maps and ordered maps. A map never contains two or more nodes
-- with equivalent keys. The length of a map is the number of nodes it
-- contains.
--
-- Each nonempty map has two particular nodes called the first node and the
-- last node (which may be the same). Each node except for the last node has a
-- successor node. If there are no other intervening operations, starting with
-- the first node and repeatedly going to the successor node will visit each
-- node in the map exactly once until the last node is reached.
generic
type Key_Type is private;
type Element_Type is private;
with function Hash (Key : Key_Type) return Hash_Type;
-- The actual function for the generic formal function Hash is expected to
-- return the same value each time it is called with a particular key
-- value. For any two equivalent key values, the actual for Hash is
-- expected to return the same value. If the actual for Hash behaves in
-- some other manner, the behavior of this package is unspecified. Which
-- subprograms of this package call Hash, and how many times they call it,
-- is unspecified.
with function Equivalent_Keys (Left, Right : Key_Type) return Boolean;
-- The actual function for the generic formal function Equivalent_Keys on
-- Key_Type values is expected to return the same value each time it is
-- called with a particular pair of key values. It should define an
-- equivalence relationship, that is, be reflexive, symmetric, and
-- transitive. If the actual for Equivalent_Keys behaves in some other
-- manner, the behavior of this package is unspecified. Which subprograms
-- of this package call Equivalent_Keys, and how many times they call it,
-- is unspecified.
with function "=" (Left, Right : Element_Type) return Boolean is <>;
-- The actual function for the generic formal function "=" on Element_Type
-- values is expected to define a reflexive and symmetric relationship and
-- return the same result value each time it is called with a particular
-- pair of values. If it behaves in some other manner, the function "=" on
-- map values returns an unspecified value. The exact arguments and number
-- of calls of this generic formal function by the function "=" on map
-- values are unspecified.
package Ada.Containers.Hashed_Maps with
SPARK_Mode => Off
is
pragma Annotate (CodePeer, Skip_Analysis);
pragma Preelaborate;
pragma Remote_Types;
type Map is tagged private
with
Constant_Indexing => Constant_Reference,
Variable_Indexing => Reference,
Default_Iterator => Iterate,
Iterator_Element => Element_Type,
Aggregate => (Empty => Empty,
Add_Named => Insert);
pragma Preelaborable_Initialization (Map);
type Cursor is private;
pragma Preelaborable_Initialization (Cursor);
Empty_Map : constant Map;
-- Map objects declared without an initialization expression are
-- initialized to the value Empty_Map.
No_Element : constant Cursor;
-- Cursor objects declared without an initialization expression are
-- initialized to the value No_Element.
function Empty (Capacity : Count_Type := 1000) return Map;
function Has_Element (Position : Cursor) return Boolean;
-- Returns True if Position designates an element, and returns False
-- otherwise.
package Map_Iterator_Interfaces is new
Ada.Iterator_Interfaces (Cursor, Has_Element);
function "=" (Left, Right : Map) return Boolean;
-- If Left and Right denote the same map object, then the function returns
-- True. If Left and Right have different lengths, then the function
-- returns False. Otherwise, for each key K in Left, the function returns
-- False if:
--
-- * a key equivalent to K is not present in Right; or
--
-- * the element associated with K in Left is not equal to the
-- element associated with K in Right (using the generic formal
-- equality operator for elements).
--
-- If the function has not returned a result after checking all of the
-- keys, it returns True. Any exception raised during evaluation of key
-- equivalence or element equality is propagated.
function Capacity (Container : Map) return Count_Type;
-- Returns the current capacity of the map. Capacity is the maximum length
-- before which rehashing in guaranteed not to occur.
procedure Reserve_Capacity (Container : in out Map; Capacity : Count_Type);
-- Adjusts the current capacity, by allocating a new buckets array. If the
-- requested capacity is less than the current capacity, then the capacity
-- is contracted (to a value not less than the current length). If the
-- requested capacity is greater than the current capacity, then the
-- capacity is expanded (to a value not less than what is requested). In
-- either case, the nodes are rehashed from the old buckets array onto the
-- new buckets array (Hash is called once for each existing key in order to
-- compute the new index), and then the old buckets array is deallocated.
function Length (Container : Map) return Count_Type;
-- Returns the number of items in the map
function Is_Empty (Container : Map) return Boolean;
-- Equivalent to Length (Container) = 0
procedure Clear (Container : in out Map);
-- Removes all of the items from the map
function Key (Position : Cursor) return Key_Type;
-- Key returns the key component of the node designated by Position.
--
-- If Position equals No_Element, then Constraint_Error is propagated.
function Element (Position : Cursor) return Element_Type;
-- Element returns the element component of the node designated
-- by Position.
--
-- If Position equals No_Element, then Constraint_Error is propagated.
procedure Replace_Element
(Container : in out Map;
Position : Cursor;
New_Item : Element_Type);
-- Replace_Element assigns New_Item to the element of the node designated
-- by Position.
--
-- If Position equals No_Element, then Constraint_Error is propagated; if
-- Position does not designate an element in Container, then Program_Error
-- is propagated.
procedure Query_Element
(Position : Cursor;
Process : not null access
procedure (Key : Key_Type; Element : Element_Type));
-- Query_Element calls Process.all with the key and element from the node
-- designated by Position as the arguments.
--
-- If Position equals No_Element, then Constraint_Error is propagated.
--
-- Tampering with the elements of the map that contains the element
-- designated by Position is prohibited during the execution of the call on
-- Process.all. Any exception raised by Process.all is propagated.
procedure Update_Element
(Container : in out Map;
Position : Cursor;
Process : not null access
procedure (Key : Key_Type; Element : in out Element_Type));
-- Update_Element calls Process.all with the key and element from the node
-- designated by Position as the arguments.
--
-- If Position equals No_Element, then Constraint_Error is propagated; if
-- Position does not designate an element in Container, then Program_Error
-- is propagated.
--
-- Tampering with the elements of Container is prohibited during the
-- execution of the call on Process.all. Any exception raised by
-- Process.all is propagated.
type Constant_Reference_Type
(Element : not null access constant Element_Type) is private
with
Implicit_Dereference => Element;
type Reference_Type (Element : not null access Element_Type) is private
with
Implicit_Dereference => Element;
function Constant_Reference
(Container : aliased Map;
Position : Cursor) return Constant_Reference_Type;
pragma Inline (Constant_Reference);
-- This function (combined with the Constant_Indexing and
-- Implicit_Dereference aspects) provides a convenient way to gain read
-- access to an individual element of a map given a cursor.
-- Constant_Reference returns an object whose discriminant is an access
-- value that designates the element designated by Position.
--
-- If Position equals No_Element, then Constraint_Error is propagated; if
-- Position does not designate an element in Container, then Program_Error
-- is propagated.
--
-- Tampering with the elements of Container is prohibited
-- while the object returned by Constant_Reference exists and has not been
-- finalized.
function Reference
(Container : aliased in out Map;
Position : Cursor) return Reference_Type;
pragma Inline (Reference);
-- This function (combined with the Variable_Indexing and
-- Implicit_Dereference aspects) provides a convenient way to gain read and
-- write access to an individual element of a map given a cursor.
-- Reference returns an object whose discriminant is an access value that
-- designates the element designated by Position.
--
-- If Position equals No_Element, then Constraint_Error is propagated; if
-- Position does not designate an element in Container, then Program_Error
-- is propagated.
--
-- Tampering with the elements of Container is prohibited while the object
-- returned by Reference exists and has not been finalized.
function Constant_Reference
(Container : aliased Map;
Key : Key_Type) return Constant_Reference_Type;
pragma Inline (Constant_Reference);
-- Equivalent to Constant_Reference (Container, Find (Container, Key)).
function Reference
(Container : aliased in out Map;
Key : Key_Type) return Reference_Type;
pragma Inline (Reference);
-- Equivalent to Reference (Container, Find (Container, Key)).
procedure Assign (Target : in out Map; Source : Map);
-- If Target denotes the same object as Source, the operation has no
-- effect. Otherwise, the key/element pairs of Source are copied to Target
-- as for an assignment_statement assigning Source to Target.
function Copy (Source : Map; Capacity : Count_Type := 0) return Map;
procedure Move (Target : in out Map; Source : in out Map);
-- If Target denotes the same object as Source, then the operation has no
-- effect. Otherwise, the operation is equivalent to Assign (Target,
-- Source) followed by Clear (Source).
procedure Insert
(Container : in out Map;
Key : Key_Type;
New_Item : Element_Type;
Position : out Cursor;
Inserted : out Boolean);
-- Insert checks if a node with a key equivalent to Key is already present
-- in Container. If a match is found, Inserted is set to False and Position
-- designates the element with the matching key. Otherwise, Insert
-- allocates a new node, initializes it to Key and New_Item, and adds it to
-- Container; Inserted is set to True and Position designates the
-- newly-inserted node. Any exception raised during allocation is
-- propagated and Container is not modified.
procedure Insert
(Container : in out Map;
Key : Key_Type;
Position : out Cursor;
Inserted : out Boolean);
-- Insert inserts Key into Container as per the five-parameter Insert, with
-- the difference that an element initialized by default (see 3.3.1) is
-- inserted.
procedure Insert
(Container : in out Map;
Key : Key_Type;
New_Item : Element_Type);
-- Insert inserts Key and New_Item into Container as per the five-parameter
-- Insert, with the difference that if a node with a key equivalent to Key
-- is already in the map, then Constraint_Error is propagated.
procedure Include
(Container : in out Map;
Key : Key_Type;
New_Item : Element_Type);
-- Include inserts Key and New_Item into Container as per the
-- five-parameter Insert, with the difference that if a node with a key
-- equivalent to Key is already in the map, then this operation assigns Key
-- and New_Item to the matching node. Any exception raised during
-- assignment is propagated.
procedure Replace
(Container : in out Map;
Key : Key_Type;
New_Item : Element_Type);
-- Replace checks if a node with a key equivalent to Key is present in
-- Container. If a match is found, Replace assigns Key and New_Item to the
-- matching node; otherwise, Constraint_Error is propagated.
procedure Exclude (Container : in out Map; Key : Key_Type);
-- Exclude checks if a node with a key equivalent to Key is present in
-- Container. If a match is found, Exclude removes the node from the map.
procedure Delete (Container : in out Map; Key : Key_Type);
-- Delete checks if a node with a key equivalent to Key is present in
-- Container. If a match is found, Delete removes the node from the map;
-- otherwise, Constraint_Error is propagated.
procedure Delete (Container : in out Map; Position : in out Cursor);
-- Delete removes the node designated by Position from the map. Position is
-- set to No_Element on return.
--
-- If Position equals No_Element, then Constraint_Error is propagated. If
-- Position does not designate an element in Container, then Program_Error
-- is propagated.
function First (Container : Map) return Cursor;
-- If Length (Container) = 0, then First returns No_Element. Otherwise,
-- First returns a cursor that designates the first node in Container.
function Next (Position : Cursor) return Cursor;
-- Returns a cursor that designates the successor of the node designated by
-- Position. If Position designates the last node, then No_Element is
-- returned. If Position equals No_Element, then No_Element is returned.
procedure Next (Position : in out Cursor);
-- Equivalent to Position := Next (Position)
function Find (Container : Map; Key : Key_Type) return Cursor;
-- If Length (Container) equals 0, then Find returns No_Element.
-- Otherwise, Find checks if a node with a key equivalent to Key is present
-- in Container. If a match is found, a cursor designating the matching
-- node is returned; otherwise, No_Element is returned.
function Contains (Container : Map; Key : Key_Type) return Boolean;
-- Equivalent to Find (Container, Key) /= No_Element.
function Element (Container : Map; Key : Key_Type) return Element_Type;
-- Equivalent to Element (Find (Container, Key))
function Equivalent_Keys (Left, Right : Cursor) return Boolean;
-- Returns the result of calling Equivalent_Keys with the keys of the nodes
-- designated by cursors Left and Right.
function Equivalent_Keys (Left : Cursor; Right : Key_Type) return Boolean;
-- Returns the result of calling Equivalent_Keys with key of the node
-- designated by Left and key Right.
function Equivalent_Keys (Left : Key_Type; Right : Cursor) return Boolean;
-- Returns the result of calling Equivalent_Keys with key Left and the node
-- designated by Right.
procedure Iterate
(Container : Map;
Process : not null access procedure (Position : Cursor));
-- Iterate calls Process.all with a cursor that designates each node in
-- Container, starting with the first node and moving the cursor according
-- to the successor relation. Tampering with the cursors of Container is
-- prohibited during the execution of a call on Process.all. Any exception
-- raised by Process.all is propagated.
function Iterate
(Container : Map) return Map_Iterator_Interfaces.Forward_Iterator'Class;
private
pragma Inline ("=");
pragma Inline (Length);
pragma Inline (Is_Empty);
pragma Inline (Clear);
pragma Inline (Key);
pragma Inline (Element);
pragma Inline (Move);
pragma Inline (Contains);
pragma Inline (Capacity);
pragma Inline (Reserve_Capacity);
pragma Inline (Has_Element);
pragma Inline (Equivalent_Keys);
pragma Inline (Next);
type Node_Type;
type Node_Access is access Node_Type;
type Node_Type is limited record
Key : Key_Type;
Element : aliased Element_Type;
Next : Node_Access;
end record;
package HT_Types is
new Hash_Tables.Generic_Hash_Table_Types (Node_Type, Node_Access);
type Map is new Ada.Finalization.Controlled with record
HT : HT_Types.Hash_Table_Type;
end record with Put_Image => Put_Image;
procedure Put_Image
(S : in out Ada.Strings.Text_Output.Sink'Class; V : Map);
overriding procedure Adjust (Container : in out Map);
overriding procedure Finalize (Container : in out Map);
use HT_Types, HT_Types.Implementation;
use Ada.Finalization;
use Ada.Streams;
procedure Write
(Stream : not null access Root_Stream_Type'Class;
Container : Map);
for Map'Write use Write;
procedure Read
(Stream : not null access Root_Stream_Type'Class;
Container : out Map);
for Map'Read use Read;
type Map_Access is access all Map;
for Map_Access'Storage_Size use 0;
type Cursor is record
Container : Map_Access;
-- Access to this cursor's container
Node : Node_Access;
-- Access to the node pointed to by this cursor
Position : Hash_Type := Hash_Type'Last;
-- Position of the node in the buckets of the container. If this is
-- equal to Hash_Type'Last, then it will not be used.
end record;
procedure Read
(Stream : not null access Root_Stream_Type'Class;
Item : out Cursor);
for Cursor'Read use Read;
procedure Write
(Stream : not null access Root_Stream_Type'Class;
Item : Cursor);
for Cursor'Write use Write;
subtype Reference_Control_Type is Implementation.Reference_Control_Type;
-- It is necessary to rename this here, so that the compiler can find it
type Constant_Reference_Type
(Element : not null access constant Element_Type) is
record
Control : Reference_Control_Type :=
raise Program_Error with "uninitialized reference";
-- The RM says, "The default initialization of an object of
-- type Constant_Reference_Type or Reference_Type propagates
-- Program_Error."
end record;
procedure Write
(Stream : not null access Root_Stream_Type'Class;
Item : Constant_Reference_Type);
for Constant_Reference_Type'Write use Write;
procedure Read
(Stream : not null access Root_Stream_Type'Class;
Item : out Constant_Reference_Type);
for Constant_Reference_Type'Read use Read;
type Reference_Type
(Element : not null access Element_Type) is
record
Control : Reference_Control_Type :=
raise Program_Error with "uninitialized reference";
-- The RM says, "The default initialization of an object of
-- type Constant_Reference_Type or Reference_Type propagates
-- Program_Error."
end record;
procedure Write
(Stream : not null access Root_Stream_Type'Class;
Item : Reference_Type);
for Reference_Type'Write use Write;
procedure Read
(Stream : not null access Root_Stream_Type'Class;
Item : out Reference_Type);
for Reference_Type'Read use Read;
-- Three operations are used to optimize in the expansion of "for ... of"
-- loops: the Next(Cursor) procedure in the visible part, and the following
-- Pseudo_Reference and Get_Element_Access functions. See Sem_Ch5 for
-- details.
function Pseudo_Reference
(Container : aliased Map'Class) return Reference_Control_Type;
pragma Inline (Pseudo_Reference);
-- Creates an object of type Reference_Control_Type pointing to the
-- container, and increments the Lock. Finalization of this object will
-- decrement the Lock.
type Element_Access is access all Element_Type with
Storage_Size => 0;
function Get_Element_Access
(Position : Cursor) return not null Element_Access;
-- Returns a pointer to the element designated by Position.
Empty_Map : constant Map := (Controlled with others => <>);
No_Element : constant Cursor := (Container => null, Node => null,
Position => Hash_Type'Last);
type Iterator is new Limited_Controlled and
Map_Iterator_Interfaces.Forward_Iterator with
record
Container : Map_Access;
end record
with Disable_Controlled => not T_Check;
overriding procedure Finalize (Object : in out Iterator);
overriding function First (Object : Iterator) return Cursor;
overriding function Next
(Object : Iterator;
Position : Cursor) return Cursor;
end Ada.Containers.Hashed_Maps;
|
-- { dg-do compile }
package Attribute_Parsing is
I : constant Integer := 12345;
S : constant String := I'Img (1 .. 2);
end Attribute_Parsing;
|
-----------------------------------------------------------------------
-- city_mapping -- Example of serialization mapping for city CSV records
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body City_Mapping is
use Util.Beans.Objects;
-- ------------------------------
-- Set the name/value pair on the current object.
-- ------------------------------
procedure Set_Member (P : in out City;
Field : in City_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_COUNTRY =>
P.Country := To_Unbounded_String (Value);
when FIELD_CITY =>
P.City := To_Unbounded_String (Value);
when FIELD_NAME =>
P.Name := To_Unbounded_String (Value);
when FIELD_REGION =>
P.Region := To_Unbounded_String (Value);
when FIELD_LATITUDE =>
P.Latitude := To_Float (Value);
when FIELD_LONGITUDE =>
P.Longitude := To_Float (Value);
end case;
end Set_Member;
-- Mapping for the Person record.
City_Mapping : aliased City_Mapper.Mapper;
-- Mapping for a list of City records (stored as a Vector).
City_Vector_Mapping : aliased City_Vector_Mapper.Mapper;
-- ------------------------------
-- Get the address mapper which describes how to load an Address.
-- ------------------------------
function Get_City_Mapper return Util.Serialize.Mappers.Mapper_Access is
begin
return City_Mapping'Access;
end Get_City_Mapper;
-- ------------------------------
-- Get the person vector mapper which describes how to load a list of Person.
-- ------------------------------
function Get_City_Vector_Mapper return City_Vector_Mapper.Mapper_Access is
begin
return City_Vector_Mapping'Access;
end Get_City_Vector_Mapper;
begin
City_Mapping.Add_Mapping ("Country", FIELD_COUNTRY);
City_Mapping.Add_Mapping ("City", FIELD_CITY);
City_Mapping.Add_Mapping ("Accent City", FIELD_NAME);
City_Mapping.Add_Mapping ("Region", FIELD_REGION);
City_Mapping.Add_Mapping ("Latitude", FIELD_LATITUDE);
City_Mapping.Add_Mapping ("Longitude", FIELD_LONGITUDE);
City_Vector_Mapping.Set_Mapping (City_Mapping'Access);
end City_Mapping;
|
with Ada.Text_Io; use Ada.Text_Io;
with Numeric_Tests; use Numeric_Tests;
procedure Is_Numeric_Test is
S1 : String := "152";
S2 : String := "-3.1415926";
S3 : String := "Foo123";
begin
Put_Line(S1 & " results in " & Boolean'Image(Is_Numeric(S1)));
Put_Line(S2 & " results in " & Boolean'Image(Is_Numeric(S2)));
Put_Line(S3 & " results in " & Boolean'Image(Is_Numeric(S3)));
end Is_Numeric_Test;
|
-- { dg-do compile }
-- { dg-options "-gnatws" }
-- (bits of "Header" unused)
procedure Nested_Agg_Bitfield_Constructor is
type Uint64 is mod 2 ** 64;
type Uint16 is mod 2 ** 16;
type Time_Stamp is record
Sec : Uint64;
Year : Uint16;
end record;
type Msg_Header is record
Stamp : Time_Stamp;
end record;
for Msg_Header use record
Stamp at 0 range 0 .. 64+16-1;
end record;
for Msg_Header'Size use 80;
type Msg is record
Header : Msg_Header;
end record;
for Msg use record
Header at 0 range 0 .. 191;
end record;
M : Msg := (Header => (Stamp => (2, 4)));
begin
null;
end;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- E X P _ D I S P --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-2020, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. 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_Atag; use Exp_Atag;
with Exp_Ch6; use Exp_Ch6;
with Exp_CG; use Exp_CG;
with Exp_Dbug; use Exp_Dbug;
with Exp_Tss; use Exp_Tss;
with Exp_Util; use Exp_Util;
with Freeze; use Freeze;
with Ghost; use Ghost;
with Itypes; use Itypes;
with Layout; use Layout;
with Nlists; use Nlists;
with Nmake; use Nmake;
with Namet; use Namet;
with Opt; use Opt;
with Output; use Output;
with Restrict; use Restrict;
with Rident; use Rident;
with Rtsfind; use Rtsfind;
with Sem; use Sem;
with Sem_Aux; use Sem_Aux;
with Sem_Ch6; use Sem_Ch6;
with Sem_Ch7; use Sem_Ch7;
with Sem_Ch8; use Sem_Ch8;
with Sem_Disp; use Sem_Disp;
with Sem_Eval; use Sem_Eval;
with Sem_Res; use Sem_Res;
with Sem_Type; use Sem_Type;
with Sem_Util; use Sem_Util;
with Sinfo; use Sinfo;
with Sinput; use Sinput;
with Snames; use Snames;
with Stand; use Stand;
with Stringt; use Stringt;
with SCIL_LL; use SCIL_LL;
with Tbuild; use Tbuild;
package body Exp_Disp is
-----------------------
-- Local Subprograms --
-----------------------
function Default_Prim_Op_Position (E : Entity_Id) return Uint;
-- Ada 2005 (AI-251): Returns the fixed position in the dispatch table
-- of the default primitive operations.
function Has_DT (Typ : Entity_Id) return Boolean;
pragma Inline (Has_DT);
-- Returns true if we generate a dispatch table for tagged type Typ
function Is_Predefined_Dispatching_Alias (Prim : Entity_Id) return Boolean;
-- Returns true if Prim is not a predefined dispatching primitive but it is
-- an alias of a predefined dispatching primitive (i.e. through a renaming)
function New_Value (From : Node_Id) return Node_Id;
-- From is the original Expression. New_Value is equivalent to a call to
-- Duplicate_Subexpr with an explicit dereference when From is an access
-- parameter.
function Original_View_In_Visible_Part (Typ : Entity_Id) return Boolean;
-- Check if the type has a private view or if the public view appears in
-- the visible part of a package spec.
function Prim_Op_Kind
(Prim : Entity_Id;
Typ : Entity_Id) return Node_Id;
-- Ada 2005 (AI-345): Determine the primitive operation kind of Prim
-- according to its type Typ. Return a reference to an RE_Prim_Op_Kind
-- enumeration value.
function Tagged_Kind (T : Entity_Id) return Node_Id;
-- Ada 2005 (AI-345): Determine the tagged kind of T and return a reference
-- to an RE_Tagged_Kind enumeration value.
----------------------
-- Apply_Tag_Checks --
----------------------
procedure Apply_Tag_Checks (Call_Node : Node_Id) is
Loc : constant Source_Ptr := Sloc (Call_Node);
Ctrl_Arg : constant Node_Id := Controlling_Argument (Call_Node);
Ctrl_Typ : constant Entity_Id := Base_Type (Etype (Ctrl_Arg));
Param_List : constant List_Id := Parameter_Associations (Call_Node);
Subp : Entity_Id;
CW_Typ : Entity_Id;
Param : Node_Id;
Typ : Entity_Id;
Eq_Prim_Op : Entity_Id := Empty;
begin
if No_Run_Time_Mode then
Error_Msg_CRT ("tagged types", Call_Node);
return;
end if;
-- Apply_Tag_Checks is called directly from the semantics, so we
-- need a check to see whether expansion is active before proceeding.
-- In addition, there is no need to expand the call when compiling
-- under restriction No_Dispatching_Calls; the semantic analyzer has
-- previously notified the violation of this restriction.
if not Expander_Active
or else Restriction_Active (No_Dispatching_Calls)
then
return;
end if;
-- Set subprogram. If this is an inherited operation that was
-- overridden, the body that is being called is its alias.
Subp := Entity (Name (Call_Node));
if Present (Alias (Subp))
and then Is_Inherited_Operation (Subp)
and then No (DTC_Entity (Subp))
then
Subp := Alias (Subp);
end if;
-- Definition of the class-wide type and the tagged type
-- If the controlling argument is itself a tag rather than a tagged
-- object, then use the class-wide type associated with the subprogram's
-- controlling type. This case can occur when a call to an inherited
-- primitive has an actual that originated from a default parameter
-- given by a tag-indeterminate call and when there is no other
-- controlling argument providing the tag (AI-239 requires dispatching).
-- This capability of dispatching directly by tag is also needed by the
-- implementation of AI-260 (for the generic dispatching constructors).
if Ctrl_Typ = RTE (RE_Tag)
or else (RTE_Available (RE_Interface_Tag)
and then Ctrl_Typ = RTE (RE_Interface_Tag))
then
CW_Typ := Class_Wide_Type (Find_Dispatching_Type (Subp));
-- Class_Wide_Type is applied to the expressions used to initialize
-- CW_Typ, to ensure that CW_Typ always denotes a class-wide type, since
-- there are cases where the controlling type is resolved to a specific
-- type (such as for designated types of arguments such as CW'Access).
elsif Is_Access_Type (Ctrl_Typ) then
CW_Typ := Class_Wide_Type (Designated_Type (Ctrl_Typ));
else
CW_Typ := Class_Wide_Type (Ctrl_Typ);
end if;
Typ := Find_Specific_Type (CW_Typ);
if not Is_Limited_Type (Typ) then
Eq_Prim_Op := Find_Prim_Op (Typ, Name_Op_Eq);
end if;
-- Dispatching call to C++ primitive
if Is_CPP_Class (Typ) then
null;
-- Dispatching call to Ada primitive
elsif Present (Param_List) then
-- Generate the Tag checks when appropriate
Param := First_Actual (Call_Node);
while Present (Param) loop
-- No tag check with itself
if Param = Ctrl_Arg then
null;
-- No tag check for parameter whose type is neither tagged nor
-- access to tagged (for access parameters)
elsif No (Find_Controlling_Arg (Param)) then
null;
-- No tag check for function dispatching on result if the
-- Tag given by the context is this one
elsif Find_Controlling_Arg (Param) = Ctrl_Arg then
null;
-- "=" is the only dispatching operation allowed to get operands
-- with incompatible tags (it just returns false). We use
-- Duplicate_Subexpr_Move_Checks instead of calling Relocate_Node
-- because the value will be duplicated to check the tags.
elsif Subp = Eq_Prim_Op then
null;
-- No check in presence of suppress flags
elsif Tag_Checks_Suppressed (Etype (Param))
or else (Is_Access_Type (Etype (Param))
and then Tag_Checks_Suppressed
(Designated_Type (Etype (Param))))
then
null;
-- Optimization: no tag checks if the parameters are identical
elsif Is_Entity_Name (Param)
and then Is_Entity_Name (Ctrl_Arg)
and then Entity (Param) = Entity (Ctrl_Arg)
then
null;
-- Now we need to generate the Tag check
else
-- Generate code for tag equality check
-- Perhaps should have Checks.Apply_Tag_Equality_Check???
Insert_Action (Ctrl_Arg,
Make_Implicit_If_Statement (Call_Node,
Condition =>
Make_Op_Ne (Loc,
Left_Opnd =>
Make_Selected_Component (Loc,
Prefix => New_Value (Ctrl_Arg),
Selector_Name =>
New_Occurrence_Of
(First_Tag_Component (Typ), Loc)),
Right_Opnd =>
Make_Selected_Component (Loc,
Prefix =>
Unchecked_Convert_To (Typ, New_Value (Param)),
Selector_Name =>
New_Occurrence_Of
(First_Tag_Component (Typ), Loc))),
Then_Statements =>
New_List (New_Constraint_Error (Loc))));
end if;
Next_Actual (Param);
end loop;
end if;
end Apply_Tag_Checks;
------------------------
-- Building_Static_DT --
------------------------
function Building_Static_DT (Typ : Entity_Id) return Boolean is
Root_Typ : Entity_Id := Root_Type (Typ);
Static_DT : Boolean;
begin
-- Handle private types
if Present (Full_View (Root_Typ)) then
Root_Typ := Full_View (Root_Typ);
end if;
Static_DT :=
Building_Static_Dispatch_Tables
and then Is_Library_Level_Tagged_Type (Typ)
-- If the type is derived from a CPP class we cannot statically
-- build the dispatch tables because we must inherit primitives
-- from the CPP side.
and then not Is_CPP_Class (Root_Typ);
if not Static_DT then
Check_Restriction (Static_Dispatch_Tables, Typ);
end if;
return Static_DT;
end Building_Static_DT;
----------------------------------
-- Building_Static_Secondary_DT --
----------------------------------
function Building_Static_Secondary_DT (Typ : Entity_Id) return Boolean is
Full_Typ : Entity_Id := Typ;
Root_Typ : Entity_Id := Root_Type (Typ);
Static_DT : Boolean;
begin
-- Handle private types
if Present (Full_View (Typ)) then
Full_Typ := Full_View (Typ);
end if;
if Present (Full_View (Root_Typ)) then
Root_Typ := Full_View (Root_Typ);
end if;
Static_DT :=
Building_Static_DT (Full_Typ)
and then not Is_Interface (Full_Typ)
and then Has_Interfaces (Full_Typ)
and then (Full_Typ = Root_Typ
or else not Is_Variable_Size_Record (Etype (Full_Typ)));
if not Static_DT
and then not Is_Interface (Full_Typ)
and then Has_Interfaces (Full_Typ)
then
Check_Restriction (Static_Dispatch_Tables, Typ);
end if;
return Static_DT;
end Building_Static_Secondary_DT;
----------------------------------
-- Build_Static_Dispatch_Tables --
----------------------------------
procedure Build_Static_Dispatch_Tables (N : Entity_Id) is
Target_List : List_Id;
procedure Build_Dispatch_Tables (List : List_Id);
-- Build the static dispatch table of tagged types found in the list of
-- declarations. The generated nodes are added at the end of Target_List
procedure Build_Package_Dispatch_Tables (N : Node_Id);
-- Build static dispatch tables associated with package declaration N
---------------------------
-- Build_Dispatch_Tables --
---------------------------
procedure Build_Dispatch_Tables (List : List_Id) is
D : Node_Id;
begin
D := First (List);
while Present (D) loop
-- Handle nested packages and package bodies recursively. The
-- generated code is placed on the Target_List established for
-- the enclosing compilation unit.
if Nkind (D) = N_Package_Declaration then
Build_Package_Dispatch_Tables (D);
elsif Nkind (D) = N_Package_Body then
Build_Dispatch_Tables (Declarations (D));
elsif Nkind (D) = N_Package_Body_Stub
and then Present (Library_Unit (D))
then
Build_Dispatch_Tables
(Declarations (Proper_Body (Unit (Library_Unit (D)))));
-- Handle full type declarations and derivations of library level
-- tagged types
elsif Nkind (D) in
N_Full_Type_Declaration | N_Derived_Type_Definition
and then Is_Library_Level_Tagged_Type (Defining_Entity (D))
and then Ekind (Defining_Entity (D)) /= E_Record_Subtype
and then not Is_Private_Type (Defining_Entity (D))
then
-- We do not generate dispatch tables for the internal types
-- created for a type extension with unknown discriminants
-- The needed information is shared with the source type,
-- See Expand_N_Record_Extension.
if Is_Underlying_Record_View (Defining_Entity (D))
or else
(not Comes_From_Source (Defining_Entity (D))
and then
Has_Unknown_Discriminants (Etype (Defining_Entity (D)))
and then
not Comes_From_Source
(First_Subtype (Defining_Entity (D))))
then
null;
else
Insert_List_After_And_Analyze (Last (Target_List),
Make_DT (Defining_Entity (D)));
end if;
-- Handle private types of library level tagged types. We must
-- exchange the private and full-view to ensure the correct
-- expansion. If the full view is a synchronized type ignore
-- the type because the table will be built for the corresponding
-- record type, that has its own declaration.
elsif (Nkind (D) = N_Private_Type_Declaration
or else Nkind (D) = N_Private_Extension_Declaration)
and then Present (Full_View (Defining_Entity (D)))
then
declare
E1 : constant Entity_Id := Defining_Entity (D);
E2 : constant Entity_Id := Full_View (E1);
begin
if Is_Library_Level_Tagged_Type (E2)
and then Ekind (E2) /= E_Record_Subtype
and then not Is_Concurrent_Type (E2)
then
Exchange_Declarations (E1);
Insert_List_After_And_Analyze (Last (Target_List),
Make_DT (E1));
Exchange_Declarations (E2);
end if;
end;
end if;
Next (D);
end loop;
end Build_Dispatch_Tables;
-----------------------------------
-- Build_Package_Dispatch_Tables --
-----------------------------------
procedure Build_Package_Dispatch_Tables (N : Node_Id) is
Spec : constant Node_Id := Specification (N);
Id : constant Entity_Id := Defining_Entity (N);
Vis_Decls : constant List_Id := Visible_Declarations (Spec);
Priv_Decls : constant List_Id := Private_Declarations (Spec);
begin
Push_Scope (Id);
if Present (Priv_Decls) then
Build_Dispatch_Tables (Vis_Decls);
Build_Dispatch_Tables (Priv_Decls);
elsif Present (Vis_Decls) then
Build_Dispatch_Tables (Vis_Decls);
end if;
Pop_Scope;
end Build_Package_Dispatch_Tables;
-- Start of processing for Build_Static_Dispatch_Tables
begin
if not Expander_Active
or else not Tagged_Type_Expansion
then
return;
end if;
if Nkind (N) = N_Package_Declaration then
declare
Spec : constant Node_Id := Specification (N);
Vis_Decls : constant List_Id := Visible_Declarations (Spec);
Priv_Decls : constant List_Id := Private_Declarations (Spec);
begin
if Present (Priv_Decls)
and then Is_Non_Empty_List (Priv_Decls)
then
Target_List := Priv_Decls;
elsif not Present (Vis_Decls) then
Target_List := New_List;
Set_Private_Declarations (Spec, Target_List);
else
Target_List := Vis_Decls;
end if;
Build_Package_Dispatch_Tables (N);
end;
else pragma Assert (Nkind (N) = N_Package_Body);
Target_List := Declarations (N);
Build_Dispatch_Tables (Target_List);
end if;
end Build_Static_Dispatch_Tables;
------------------------------
-- Convert_Tag_To_Interface --
------------------------------
function Convert_Tag_To_Interface
(Typ : Entity_Id;
Expr : Node_Id) return Node_Id
is
Loc : constant Source_Ptr := Sloc (Expr);
Anon_Type : Entity_Id;
Result : Node_Id;
begin
pragma Assert (Is_Class_Wide_Type (Typ)
and then Is_Interface (Typ)
and then
((Nkind (Expr) = N_Selected_Component
and then Is_Tag (Entity (Selector_Name (Expr))))
or else
(Nkind (Expr) = N_Function_Call
and then RTE_Available (RE_Displace)
and then Entity (Name (Expr)) = RTE (RE_Displace))));
Anon_Type := Create_Itype (E_Anonymous_Access_Type, Expr);
Set_Directly_Designated_Type (Anon_Type, Typ);
Set_Etype (Anon_Type, Anon_Type);
Set_Can_Never_Be_Null (Anon_Type);
-- Decorate the size and alignment attributes of the anonymous access
-- type, as required by the back end.
Layout_Type (Anon_Type);
if Nkind (Expr) = N_Selected_Component
and then Is_Tag (Entity (Selector_Name (Expr)))
then
Result :=
Make_Explicit_Dereference (Loc,
Unchecked_Convert_To (Anon_Type,
Make_Attribute_Reference (Loc,
Prefix => Expr,
Attribute_Name => Name_Address)));
else
Result :=
Make_Explicit_Dereference (Loc,
Unchecked_Convert_To (Anon_Type, Expr));
end if;
return Result;
end Convert_Tag_To_Interface;
-------------------
-- CPP_Num_Prims --
-------------------
function CPP_Num_Prims (Typ : Entity_Id) return Nat is
CPP_Typ : Entity_Id;
Tag_Comp : Entity_Id;
begin
if not Is_Tagged_Type (Typ)
or else not Is_CPP_Class (Root_Type (Typ))
then
return 0;
else
CPP_Typ := Enclosing_CPP_Parent (Typ);
Tag_Comp := First_Tag_Component (CPP_Typ);
-- If number of primitives already set in the tag component, use it
if Present (Tag_Comp)
and then DT_Entry_Count (Tag_Comp) /= No_Uint
then
return UI_To_Int (DT_Entry_Count (Tag_Comp));
-- Otherwise, count the primitives of the enclosing CPP type
else
declare
Count : Nat := 0;
Elmt : Elmt_Id;
begin
Elmt := First_Elmt (Primitive_Operations (CPP_Typ));
while Present (Elmt) loop
Count := Count + 1;
Next_Elmt (Elmt);
end loop;
return Count;
end;
end if;
end if;
end CPP_Num_Prims;
------------------------------
-- Default_Prim_Op_Position --
------------------------------
function Default_Prim_Op_Position (E : Entity_Id) return Uint is
TSS_Name : TSS_Name_Type;
begin
Get_Name_String (Chars (E));
TSS_Name :=
TSS_Name_Type
(Name_Buffer (Name_Len - TSS_Name'Length + 1 .. Name_Len));
if Chars (E) = Name_uSize then
return Uint_1;
elsif TSS_Name = TSS_Stream_Read then
return Uint_2;
elsif TSS_Name = TSS_Stream_Write then
return Uint_3;
elsif TSS_Name = TSS_Stream_Input then
return Uint_4;
elsif TSS_Name = TSS_Stream_Output then
return Uint_5;
elsif Chars (E) = Name_Op_Eq then
return Uint_6;
elsif Chars (E) = Name_uAssign then
return Uint_7;
elsif TSS_Name = TSS_Deep_Adjust then
return Uint_8;
elsif TSS_Name = TSS_Deep_Finalize then
return Uint_9;
elsif TSS_Name = TSS_Put_Image then
return Uint_10;
-- In VM targets unconditionally allow obtaining the position associated
-- with predefined interface primitives since in these platforms any
-- tagged type has these primitives.
elsif Ada_Version >= Ada_2005 or else not Tagged_Type_Expansion then
if Chars (E) = Name_uDisp_Asynchronous_Select then
return Uint_11;
elsif Chars (E) = Name_uDisp_Conditional_Select then
return Uint_12;
elsif Chars (E) = Name_uDisp_Get_Prim_Op_Kind then
return Uint_13;
elsif Chars (E) = Name_uDisp_Get_Task_Id then
return Uint_14;
elsif Chars (E) = Name_uDisp_Requeue then
return Uint_15;
elsif Chars (E) = Name_uDisp_Timed_Select then
return Uint_16;
end if;
end if;
raise Program_Error;
end Default_Prim_Op_Position;
----------------------
-- Elab_Flag_Needed --
----------------------
function Elab_Flag_Needed (Typ : Entity_Id) return Boolean is
begin
return Ada_Version >= Ada_2005
and then not Is_Interface (Typ)
and then Has_Interfaces (Typ)
and then not Building_Static_DT (Typ);
end Elab_Flag_Needed;
-----------------------------
-- Expand_Dispatching_Call --
-----------------------------
procedure Expand_Dispatching_Call (Call_Node : Node_Id) is
Loc : constant Source_Ptr := Sloc (Call_Node);
Call_Typ : constant Entity_Id := Etype (Call_Node);
Ctrl_Arg : constant Node_Id := Controlling_Argument (Call_Node);
Ctrl_Typ : constant Entity_Id := Base_Type (Etype (Ctrl_Arg));
Param_List : constant List_Id := Parameter_Associations (Call_Node);
Subp : Entity_Id;
CW_Typ : Entity_Id;
New_Call : Node_Id;
New_Call_Name : Node_Id;
New_Params : List_Id := No_List;
Param : Node_Id;
Res_Typ : Entity_Id;
Subp_Ptr_Typ : Entity_Id;
Subp_Typ : Entity_Id;
Typ : Entity_Id;
Eq_Prim_Op : Entity_Id := Empty;
Controlling_Tag : Node_Id;
procedure Build_Class_Wide_Check;
-- If the denoted subprogram has a class-wide precondition, generate a
-- check using that precondition before the dispatching call, because
-- this is the only class-wide precondition that applies to the call.
function New_Value (From : Node_Id) return Node_Id;
-- From is the original Expression. New_Value is equivalent to a call
-- to Duplicate_Subexpr with an explicit dereference when From is an
-- access parameter.
----------------------------
-- Build_Class_Wide_Check --
----------------------------
procedure Build_Class_Wide_Check is
function Replace_Formals (N : Node_Id) return Traverse_Result;
-- Replace occurrences of the formals of the subprogram by the
-- corresponding actuals in the call, given that this check is
-- performed outside of the body of the subprogram.
-- If the dispatching call appears in the same scope as the
-- declaration of the dispatching subprogram (for example in
-- the expression of a local expression function), the spec
-- has not been analyzed yet, in which case we use the Chars
-- field to recognize intended occurrences of the formals.
---------------------
-- Replace_Formals --
---------------------
function Replace_Formals (N : Node_Id) return Traverse_Result is
A : Node_Id;
F : Entity_Id;
begin
if Is_Entity_Name (N) then
F := First_Formal (Subp);
A := First_Actual (Call_Node);
if Present (Entity (N)) and then Is_Formal (Entity (N)) then
while Present (F) loop
if F = Entity (N) then
Rewrite (N, New_Copy_Tree (A));
-- If the formal is class-wide, and thus not a
-- controlling argument, preserve its type because
-- it may appear in a nested call with a class-wide
-- parameter.
if Is_Class_Wide_Type (Etype (F)) then
Set_Etype (N, Etype (F));
-- Conversely, if this is a controlling argument
-- (in a dispatching call in the condition) that is a
-- dereference, the source is an access-to-class-wide
-- type, so preserve the dispatching nature of the
-- call in the rewritten condition.
elsif Nkind (Parent (N)) = N_Explicit_Dereference
and then Is_Controlling_Actual (Parent (N))
then
Set_Controlling_Argument (Parent (Parent (N)),
Parent (N));
end if;
exit;
end if;
Next_Formal (F);
Next_Actual (A);
end loop;
-- If the node is not analyzed, recognize occurrences of a
-- formal by name, as would be done when resolving the aspect
-- expression in the context of the subprogram.
elsif not Analyzed (N)
and then Nkind (N) = N_Identifier
and then No (Entity (N))
then
while Present (F) loop
if Chars (N) = Chars (F) then
Rewrite (N, New_Copy_Tree (A));
return Skip;
end if;
Next_Formal (F);
Next_Actual (A);
end loop;
end if;
end if;
return OK;
end Replace_Formals;
procedure Update is new Traverse_Proc (Replace_Formals);
-- Local variables
Str_Loc : constant String := Build_Location_String (Loc);
Cond : Node_Id;
Msg : Node_Id;
Prec : Node_Id;
-- Start of processing for Build_Class_Wide_Check
begin
-- Locate class-wide precondition, if any
if Present (Contract (Subp))
and then Present (Pre_Post_Conditions (Contract (Subp)))
then
Prec := Pre_Post_Conditions (Contract (Subp));
while Present (Prec) loop
exit when Pragma_Name (Prec) = Name_Precondition
and then Class_Present (Prec);
Prec := Next_Pragma (Prec);
end loop;
if No (Prec) or else Is_Ignored (Prec) then
return;
end if;
-- The expression for the precondition is analyzed within the
-- generated pragma. The message text is the last parameter of
-- the generated pragma, indicating source of precondition.
Cond :=
New_Copy_Tree
(Expression (First (Pragma_Argument_Associations (Prec))));
Update (Cond);
-- Build message indicating the failed precondition and the
-- dispatching call that caused it.
Msg := Expression (Last (Pragma_Argument_Associations (Prec)));
Name_Len := 0;
Append (Global_Name_Buffer, Strval (Msg));
Append (Global_Name_Buffer, " in dispatching call at ");
Append (Global_Name_Buffer, Str_Loc);
Msg := Make_String_Literal (Loc, Name_Buffer (1 .. Name_Len));
Insert_Action (Call_Node,
Make_If_Statement (Loc,
Condition => Make_Op_Not (Loc, Cond),
Then_Statements => New_List (
Make_Procedure_Call_Statement (Loc,
Name =>
New_Occurrence_Of (RTE (RE_Raise_Assert_Failure), Loc),
Parameter_Associations => New_List (Msg)))));
end if;
end Build_Class_Wide_Check;
---------------
-- New_Value --
---------------
function New_Value (From : Node_Id) return Node_Id is
Res : constant Node_Id := Duplicate_Subexpr (From);
begin
if Is_Access_Type (Etype (From)) then
return
Make_Explicit_Dereference (Sloc (From),
Prefix => Res);
else
return Res;
end if;
end New_Value;
-- Local variables
New_Node : Node_Id;
SCIL_Node : Node_Id := Empty;
SCIL_Related_Node : Node_Id := Call_Node;
-- Start of processing for Expand_Dispatching_Call
begin
if No_Run_Time_Mode then
Error_Msg_CRT ("tagged types", Call_Node);
return;
end if;
-- Expand_Dispatching_Call is called directly from the semantics, so we
-- only proceed if the expander is active.
if not Expander_Active
-- And there is no need to expand the call if we are compiling under
-- restriction No_Dispatching_Calls; the semantic analyzer has
-- previously notified the violation of this restriction.
or else Restriction_Active (No_Dispatching_Calls)
-- No action needed if the dispatching call has been already expanded
or else Is_Expanded_Dispatching_Call (Name (Call_Node))
then
return;
end if;
-- Set subprogram. If this is an inherited operation that was
-- overridden, the body that is being called is its alias.
Subp := Entity (Name (Call_Node));
if Present (Alias (Subp))
and then Is_Inherited_Operation (Subp)
and then No (DTC_Entity (Subp))
then
Subp := Alias (Subp);
end if;
Build_Class_Wide_Check;
-- Definition of the class-wide type and the tagged type
-- If the controlling argument is itself a tag rather than a tagged
-- object, then use the class-wide type associated with the subprogram's
-- controlling type. This case can occur when a call to an inherited
-- primitive has an actual that originated from a default parameter
-- given by a tag-indeterminate call and when there is no other
-- controlling argument providing the tag (AI-239 requires dispatching).
-- This capability of dispatching directly by tag is also needed by the
-- implementation of AI-260 (for the generic dispatching constructors).
if Ctrl_Typ = RTE (RE_Tag)
or else (RTE_Available (RE_Interface_Tag)
and then Ctrl_Typ = RTE (RE_Interface_Tag))
then
CW_Typ := Class_Wide_Type (Find_Dispatching_Type (Subp));
-- Class_Wide_Type is applied to the expressions used to initialize
-- CW_Typ, to ensure that CW_Typ always denotes a class-wide type, since
-- there are cases where the controlling type is resolved to a specific
-- type (such as for designated types of arguments such as CW'Access).
elsif Is_Access_Type (Ctrl_Typ) then
CW_Typ := Class_Wide_Type (Designated_Type (Ctrl_Typ));
else
CW_Typ := Class_Wide_Type (Ctrl_Typ);
end if;
Typ := Find_Specific_Type (CW_Typ);
if not Is_Limited_Type (Typ) then
Eq_Prim_Op := Find_Prim_Op (Typ, Name_Op_Eq);
end if;
-- Dispatching call to C++ primitive. Create a new parameter list
-- with no tag checks.
New_Params := New_List;
if Is_CPP_Class (Typ) then
Param := First_Actual (Call_Node);
while Present (Param) loop
Append_To (New_Params, Relocate_Node (Param));
Next_Actual (Param);
end loop;
-- Dispatching call to Ada primitive
elsif Present (Param_List) then
Apply_Tag_Checks (Call_Node);
Param := First_Actual (Call_Node);
while Present (Param) loop
-- Cases in which we may have generated run-time checks. Note that
-- we strip any qualification from Param before comparing with the
-- already-stripped controlling argument.
if Unqualify (Param) = Ctrl_Arg or else Subp = Eq_Prim_Op then
Append_To (New_Params,
Duplicate_Subexpr_Move_Checks (Param));
elsif Nkind (Parent (Param)) /= N_Parameter_Association
or else not Is_Accessibility_Actual (Parent (Param))
then
Append_To (New_Params, Relocate_Node (Param));
end if;
Next_Actual (Param);
end loop;
end if;
-- Generate the appropriate subprogram pointer type
if Etype (Subp) = Typ then
Res_Typ := CW_Typ;
else
Res_Typ := Etype (Subp);
end if;
Subp_Typ := Create_Itype (E_Subprogram_Type, Call_Node);
Subp_Ptr_Typ := Create_Itype (E_Access_Subprogram_Type, Call_Node);
Set_Etype (Subp_Typ, Res_Typ);
Set_Returns_By_Ref (Subp_Typ, Returns_By_Ref (Subp));
Set_Convention (Subp_Typ, Convention (Subp));
-- Notify gigi that the designated type is a dispatching primitive
Set_Is_Dispatch_Table_Entity (Subp_Typ);
-- Create a new list of parameters which is a copy of the old formal
-- list including the creation of a new set of matching entities.
declare
Old_Formal : Entity_Id := First_Formal (Subp);
New_Formal : Entity_Id;
Last_Formal : Entity_Id := Empty;
begin
if Present (Old_Formal) then
New_Formal := New_Copy (Old_Formal);
Set_First_Entity (Subp_Typ, New_Formal);
Param := First_Actual (Call_Node);
loop
Set_Scope (New_Formal, Subp_Typ);
-- Change all the controlling argument types to be class-wide
-- to avoid a recursion in dispatching.
if Is_Controlling_Formal (New_Formal) then
Set_Etype (New_Formal, Etype (Param));
end if;
-- If the type of the formal is an itype, there was code here
-- introduced in 1998 in revision 1.46, to create a new itype
-- by copy. This seems useless, and in fact leads to semantic
-- errors when the itype is the completion of a type derived
-- from a private type.
Last_Formal := New_Formal;
Next_Formal (Old_Formal);
exit when No (Old_Formal);
Link_Entities (New_Formal, New_Copy (Old_Formal));
Next_Entity (New_Formal);
Next_Actual (Param);
end loop;
Unlink_Next_Entity (New_Formal);
Set_Last_Entity (Subp_Typ, Last_Formal);
end if;
-- Now that the explicit formals have been duplicated, any extra
-- formals needed by the subprogram must be duplicated; we know
-- that extra formals are available because they were added when
-- the tagged type was frozen (see Expand_Freeze_Record_Type).
pragma Assert (Is_Frozen (Typ));
-- Warning: The addition of the extra formals cannot be performed
-- here invoking Create_Extra_Formals since we must ensure that all
-- the extra formals of the pointer type and the target subprogram
-- match (and for functions that return a tagged type the profile of
-- the built subprogram type always returns a class-wide type, which
-- may affect the addition of some extra formals).
if Present (Last_Formal)
and then Present (Extra_Formal (Last_Formal))
then
Old_Formal := Extra_Formal (Last_Formal);
New_Formal := New_Copy (Old_Formal);
Set_Scope (New_Formal, Subp_Typ);
Set_Extra_Formal (Last_Formal, New_Formal);
Set_Extra_Formals (Subp_Typ, New_Formal);
if Ekind (Subp) = E_Function
and then Present (Extra_Accessibility_Of_Result (Subp))
and then Extra_Accessibility_Of_Result (Subp) = Old_Formal
then
Set_Extra_Accessibility_Of_Result (Subp_Typ, New_Formal);
end if;
Old_Formal := Extra_Formal (Old_Formal);
while Present (Old_Formal) loop
Set_Extra_Formal (New_Formal, New_Copy (Old_Formal));
New_Formal := Extra_Formal (New_Formal);
Set_Scope (New_Formal, Subp_Typ);
if Ekind (Subp) = E_Function
and then Present (Extra_Accessibility_Of_Result (Subp))
and then Extra_Accessibility_Of_Result (Subp) = Old_Formal
then
Set_Extra_Accessibility_Of_Result (Subp_Typ, New_Formal);
end if;
Old_Formal := Extra_Formal (Old_Formal);
end loop;
end if;
end;
-- Complete description of pointer type, including size information, as
-- must be done with itypes to prevent order-of-elaboration anomalies
-- in gigi.
Set_Etype (Subp_Ptr_Typ, Subp_Ptr_Typ);
Set_Directly_Designated_Type (Subp_Ptr_Typ, Subp_Typ);
Set_Convention (Subp_Ptr_Typ, Convention (Subp_Typ));
Layout_Type (Subp_Ptr_Typ);
-- If the controlling argument is a value of type Ada.Tag or an abstract
-- interface class-wide type then use it directly. Otherwise, the tag
-- must be extracted from the controlling object.
if Ctrl_Typ = RTE (RE_Tag)
or else (RTE_Available (RE_Interface_Tag)
and then Ctrl_Typ = RTE (RE_Interface_Tag))
then
Controlling_Tag := Duplicate_Subexpr (Ctrl_Arg);
-- Extract the tag from an unchecked type conversion. Done to avoid
-- the expansion of additional code just to obtain the value of such
-- tag because the current management of interface type conversions
-- generates in some cases this unchecked type conversion with the
-- tag of the object (see Expand_Interface_Conversion).
elsif Nkind (Ctrl_Arg) = N_Unchecked_Type_Conversion
and then
(Etype (Expression (Ctrl_Arg)) = RTE (RE_Tag)
or else
(RTE_Available (RE_Interface_Tag)
and then
Etype (Expression (Ctrl_Arg)) = RTE (RE_Interface_Tag)))
then
Controlling_Tag := Duplicate_Subexpr (Expression (Ctrl_Arg));
-- Ada 2005 (AI-251): Abstract interface class-wide type
elsif Is_Interface (Ctrl_Typ)
and then Is_Class_Wide_Type (Ctrl_Typ)
then
Controlling_Tag := Duplicate_Subexpr (Ctrl_Arg);
elsif Is_Access_Type (Ctrl_Typ) then
Controlling_Tag :=
Make_Selected_Component (Loc,
Prefix =>
Make_Explicit_Dereference (Loc,
Duplicate_Subexpr_Move_Checks (Ctrl_Arg)),
Selector_Name => New_Occurrence_Of (DTC_Entity (Subp), Loc));
else
Controlling_Tag :=
Make_Selected_Component (Loc,
Prefix => Duplicate_Subexpr_Move_Checks (Ctrl_Arg),
Selector_Name => New_Occurrence_Of (DTC_Entity (Subp), Loc));
end if;
-- Handle dispatching calls to predefined primitives
if Is_Predefined_Dispatching_Operation (Subp)
or else Is_Predefined_Dispatching_Alias (Subp)
then
Build_Get_Predefined_Prim_Op_Address (Loc,
Tag_Node => Controlling_Tag,
Position => DT_Position (Subp),
New_Node => New_Node);
-- Handle dispatching calls to user-defined primitives
else
Build_Get_Prim_Op_Address (Loc,
Typ => Underlying_Type (Find_Dispatching_Type (Subp)),
Tag_Node => Controlling_Tag,
Position => DT_Position (Subp),
New_Node => New_Node);
end if;
New_Call_Name :=
Unchecked_Convert_To (Subp_Ptr_Typ, New_Node);
-- Generate the SCIL node for this dispatching call. Done now because
-- attribute SCIL_Controlling_Tag must be set after the new call name
-- is built to reference the nodes that will see the SCIL backend
-- (because Build_Get_Prim_Op_Address generates an unchecked type
-- conversion which relocates the controlling tag node).
if Generate_SCIL then
SCIL_Node := Make_SCIL_Dispatching_Call (Sloc (Call_Node));
Set_SCIL_Entity (SCIL_Node, Typ);
Set_SCIL_Target_Prim (SCIL_Node, Subp);
-- Common case: the controlling tag is the tag of an object
-- (for example, obj.tag)
if Nkind (Controlling_Tag) = N_Selected_Component then
Set_SCIL_Controlling_Tag (SCIL_Node, Controlling_Tag);
-- Handle renaming of selected component
elsif Nkind (Controlling_Tag) = N_Identifier
and then Nkind (Parent (Entity (Controlling_Tag))) =
N_Object_Renaming_Declaration
and then Nkind (Name (Parent (Entity (Controlling_Tag)))) =
N_Selected_Component
then
Set_SCIL_Controlling_Tag (SCIL_Node,
Name (Parent (Entity (Controlling_Tag))));
-- If the controlling tag is an identifier, the SCIL node references
-- the corresponding object or parameter declaration
elsif Nkind (Controlling_Tag) = N_Identifier
and then Nkind (Parent (Entity (Controlling_Tag))) in
N_Object_Declaration | N_Parameter_Specification
then
Set_SCIL_Controlling_Tag (SCIL_Node,
Parent (Entity (Controlling_Tag)));
-- If the controlling tag is a dereference, the SCIL node references
-- the corresponding object or parameter declaration
elsif Nkind (Controlling_Tag) = N_Explicit_Dereference
and then Nkind (Prefix (Controlling_Tag)) = N_Identifier
and then Nkind (Parent (Entity (Prefix (Controlling_Tag)))) in
N_Object_Declaration | N_Parameter_Specification
then
Set_SCIL_Controlling_Tag (SCIL_Node,
Parent (Entity (Prefix (Controlling_Tag))));
-- For a direct reference of the tag of the type the SCIL node
-- references the internal object declaration containing the tag
-- of the type.
elsif Nkind (Controlling_Tag) = N_Attribute_Reference
and then Attribute_Name (Controlling_Tag) = Name_Tag
then
Set_SCIL_Controlling_Tag (SCIL_Node,
Parent
(Node
(First_Elmt
(Access_Disp_Table (Entity (Prefix (Controlling_Tag)))))));
-- Interfaces are not supported. For now we leave the SCIL node
-- decorated with the Controlling_Tag. More work needed here???
elsif Is_Interface (Etype (Controlling_Tag)) then
Set_SCIL_Controlling_Tag (SCIL_Node, Controlling_Tag);
else
pragma Assert (False);
null;
end if;
end if;
if Nkind (Call_Node) = N_Function_Call then
New_Call :=
Make_Function_Call (Loc,
Name => New_Call_Name,
Parameter_Associations => New_Params);
-- If this is a dispatching "=", we must first compare the tags so
-- we generate: x.tag = y.tag and then x = y
if Subp = Eq_Prim_Op then
Param := First_Actual (Call_Node);
New_Call :=
Make_And_Then (Loc,
Left_Opnd =>
Make_Op_Eq (Loc,
Left_Opnd =>
Make_Selected_Component (Loc,
Prefix => New_Value (Param),
Selector_Name =>
New_Occurrence_Of (First_Tag_Component (Typ),
Loc)),
Right_Opnd =>
Make_Selected_Component (Loc,
Prefix =>
Unchecked_Convert_To (Typ,
New_Value (Next_Actual (Param))),
Selector_Name =>
New_Occurrence_Of
(First_Tag_Component (Typ), Loc))),
Right_Opnd => New_Call);
SCIL_Related_Node := Right_Opnd (New_Call);
end if;
else
New_Call :=
Make_Procedure_Call_Statement (Loc,
Name => New_Call_Name,
Parameter_Associations => New_Params);
end if;
-- Register the dispatching call in the call graph nodes table
Register_CG_Node (Call_Node);
Rewrite (Call_Node, New_Call);
-- Associate the SCIL node of this dispatching call
if Generate_SCIL then
Set_SCIL_Node (SCIL_Related_Node, SCIL_Node);
end if;
-- Suppress all checks during the analysis of the expanded code to avoid
-- the generation of spurious warnings under ZFP run-time.
Analyze_And_Resolve (Call_Node, Call_Typ, Suppress => All_Checks);
end Expand_Dispatching_Call;
---------------------------------
-- Expand_Interface_Conversion --
---------------------------------
procedure Expand_Interface_Conversion (N : Node_Id) is
function Underlying_Record_Type (Typ : Entity_Id) return Entity_Id;
-- Return the underlying record type of Typ
----------------------------
-- Underlying_Record_Type --
----------------------------
function Underlying_Record_Type (Typ : Entity_Id) return Entity_Id is
E : Entity_Id := Typ;
begin
-- Handle access types
if Is_Access_Type (E) then
E := Directly_Designated_Type (E);
end if;
-- Handle class-wide types. This conversion can appear explicitly in
-- the source code. Example: I'Class (Obj)
if Is_Class_Wide_Type (E) then
E := Root_Type (E);
end if;
-- If the target type is a tagged synchronized type, the dispatch
-- table info is in the corresponding record type.
if Is_Concurrent_Type (E) then
E := Corresponding_Record_Type (E);
end if;
-- Handle private types
E := Underlying_Type (E);
-- Handle subtypes
return Base_Type (E);
end Underlying_Record_Type;
-- Local variables
Loc : constant Source_Ptr := Sloc (N);
Etyp : constant Entity_Id := Etype (N);
Operand : constant Node_Id := Expression (N);
Operand_Typ : Entity_Id := Etype (Operand);
Func : Node_Id;
Iface_Typ : constant Entity_Id := Underlying_Record_Type (Etype (N));
Iface_Tag : Entity_Id;
Is_Static : Boolean;
-- Start of processing for Expand_Interface_Conversion
begin
-- Freeze the entity associated with the target interface to have
-- available the attribute Access_Disp_Table.
Freeze_Before (N, Iface_Typ);
-- Ada 2005 (AI-345): Handle synchronized interface type derivations
if Is_Concurrent_Type (Operand_Typ) then
Operand_Typ := Base_Type (Corresponding_Record_Type (Operand_Typ));
end if;
-- No displacement of the pointer to the object needed when the type of
-- the operand is not an interface type and the interface is one of
-- its parent types (since they share the primary dispatch table).
declare
Opnd : Entity_Id := Operand_Typ;
begin
if Is_Access_Type (Opnd) then
Opnd := Designated_Type (Opnd);
end if;
Opnd := Underlying_Record_Type (Opnd);
if not Is_Interface (Opnd)
and then Is_Ancestor (Iface_Typ, Opnd, Use_Full_View => True)
then
return;
end if;
-- When the type of the operand and the target interface type match,
-- it is generally safe to skip generating code to displace the
-- pointer to the object to reference the secondary dispatch table
-- associated with the target interface type. The exception to this
-- general rule is when the underlying object of the type conversion
-- is an object built by means of a dispatching constructor (since in
-- such case the expansion of the constructor call is a direct call
-- to an object primitive, i.e. without thunks, and the expansion of
-- the constructor call adds an explicit conversion to the target
-- interface type to force the displacement of the pointer to the
-- object to reference the corresponding secondary dispatch table
-- (cf. Make_DT and Expand_Dispatching_Constructor_Call)).
-- At this stage we cannot identify whether the underlying object is
-- a BIP object and hence we cannot skip generating the code to try
-- displacing the pointer to the object. However, under configurable
-- runtime it is safe to skip generating code to displace the pointer
-- to the object, because generic dispatching constructors are not
-- supported.
if Opnd = Iface_Typ and then not RTE_Available (RE_Displace) then
return;
end if;
end;
-- Evaluate if we can statically displace the pointer to the object
declare
Opnd_Typ : constant Node_Id := Underlying_Record_Type (Operand_Typ);
begin
Is_Static :=
not Is_Interface (Opnd_Typ)
and then Interface_Present_In_Ancestor
(Typ => Opnd_Typ,
Iface => Iface_Typ)
and then (Etype (Opnd_Typ) = Opnd_Typ
or else not
Is_Variable_Size_Record (Etype (Opnd_Typ)));
end;
if not Tagged_Type_Expansion then
return;
-- A static conversion to an interface type that is not class-wide is
-- curious but legal if the interface operation is a null procedure.
-- If the operation is abstract it will be rejected later.
elsif Is_Static
and then Is_Interface (Etype (N))
and then not Is_Class_Wide_Type (Etype (N))
and then Comes_From_Source (N)
then
Rewrite (N, Unchecked_Convert_To (Etype (N), N));
Analyze (N);
return;
end if;
if not Is_Static then
-- Give error if configurable run-time and Displace not available
if not RTE_Available (RE_Displace) then
Error_Msg_CRT ("dynamic interface conversion", N);
return;
end if;
-- Handle conversion of access-to-class-wide interface types. Target
-- can be an access to an object or an access to another class-wide
-- interface (see -1- and -2- in the following example):
-- type Iface1_Ref is access all Iface1'Class;
-- type Iface2_Ref is access all Iface1'Class;
-- Acc1 : Iface1_Ref := new ...
-- Obj : Obj_Ref := Obj_Ref (Acc); -- 1
-- Acc2 : Iface2_Ref := Iface2_Ref (Acc); -- 2
if Is_Access_Type (Operand_Typ) then
Rewrite (N,
Unchecked_Convert_To (Etype (N),
Make_Function_Call (Loc,
Name => New_Occurrence_Of (RTE (RE_Displace), Loc),
Parameter_Associations => New_List (
Unchecked_Convert_To (RTE (RE_Address),
Relocate_Node (Expression (N))),
New_Occurrence_Of
(Node (First_Elmt (Access_Disp_Table (Iface_Typ))),
Loc)))));
Analyze (N);
return;
end if;
Rewrite (N,
Make_Function_Call (Loc,
Name => New_Occurrence_Of (RTE (RE_Displace), Loc),
Parameter_Associations => New_List (
Make_Attribute_Reference (Loc,
Prefix => Relocate_Node (Expression (N)),
Attribute_Name => Name_Address),
New_Occurrence_Of
(Node (First_Elmt (Access_Disp_Table (Iface_Typ))),
Loc))));
Analyze (N);
-- If target is a class-wide interface, change the type of the data
-- returned by IW_Convert to indicate this is a dispatching call.
declare
New_Itype : Entity_Id;
begin
New_Itype := Create_Itype (E_Anonymous_Access_Type, N);
Set_Etype (New_Itype, New_Itype);
Set_Directly_Designated_Type (New_Itype, Etyp);
Rewrite (N,
Make_Explicit_Dereference (Loc,
Prefix =>
Unchecked_Convert_To (New_Itype, Relocate_Node (N))));
Analyze (N);
Freeze_Itype (New_Itype, N);
return;
end;
end if;
Iface_Tag := Find_Interface_Tag (Operand_Typ, Iface_Typ);
pragma Assert (Present (Iface_Tag));
-- Keep separate access types to interfaces because one internal
-- function is used to handle the null value (see following comments)
if not Is_Access_Type (Etype (N)) then
-- Statically displace the pointer to the object to reference the
-- component containing the secondary dispatch table.
Rewrite (N,
Convert_Tag_To_Interface (Class_Wide_Type (Iface_Typ),
Make_Selected_Component (Loc,
Prefix => Relocate_Node (Expression (N)),
Selector_Name => New_Occurrence_Of (Iface_Tag, Loc))));
else
-- Build internal function to handle the case in which the actual is
-- null. If the actual is null returns null because no displacement
-- is required; otherwise performs a type conversion that will be
-- expanded in the code that returns the value of the displaced
-- actual. That is:
-- function Func (O : Address) return Iface_Typ is
-- type Op_Typ is access all Operand_Typ;
-- Aux : Op_Typ := To_Op_Typ (O);
-- begin
-- if O = Null_Address then
-- return null;
-- else
-- return Iface_Typ!(Aux.Iface_Tag'Address);
-- end if;
-- end Func;
declare
Desig_Typ : Entity_Id;
Fent : Entity_Id;
New_Typ_Decl : Node_Id;
Stats : List_Id;
begin
Desig_Typ := Etype (Expression (N));
if Is_Access_Type (Desig_Typ) then
Desig_Typ :=
Available_View (Directly_Designated_Type (Desig_Typ));
end if;
if Is_Concurrent_Type (Desig_Typ) then
Desig_Typ := Base_Type (Corresponding_Record_Type (Desig_Typ));
end if;
New_Typ_Decl :=
Make_Full_Type_Declaration (Loc,
Defining_Identifier => Make_Temporary (Loc, 'T'),
Type_Definition =>
Make_Access_To_Object_Definition (Loc,
All_Present => True,
Null_Exclusion_Present => False,
Constant_Present => False,
Subtype_Indication =>
New_Occurrence_Of (Desig_Typ, Loc)));
Stats := New_List (
Make_Simple_Return_Statement (Loc,
Unchecked_Convert_To (Etype (N),
Make_Attribute_Reference (Loc,
Prefix =>
Make_Selected_Component (Loc,
Prefix =>
Unchecked_Convert_To
(Defining_Identifier (New_Typ_Decl),
Make_Identifier (Loc, Name_uO)),
Selector_Name =>
New_Occurrence_Of (Iface_Tag, Loc)),
Attribute_Name => Name_Address))));
-- If the type is null-excluding, no need for the null branch.
-- Otherwise we need to check for it and return null.
if not Can_Never_Be_Null (Etype (N)) then
Stats := New_List (
Make_If_Statement (Loc,
Condition =>
Make_Op_Eq (Loc,
Left_Opnd => Make_Identifier (Loc, Name_uO),
Right_Opnd => New_Occurrence_Of
(RTE (RE_Null_Address), Loc)),
Then_Statements => New_List (
Make_Simple_Return_Statement (Loc, Make_Null (Loc))),
Else_Statements => Stats));
end if;
Fent := Make_Temporary (Loc, 'F');
Func :=
Make_Subprogram_Body (Loc,
Specification =>
Make_Function_Specification (Loc,
Defining_Unit_Name => Fent,
Parameter_Specifications => New_List (
Make_Parameter_Specification (Loc,
Defining_Identifier =>
Make_Defining_Identifier (Loc, Name_uO),
Parameter_Type =>
New_Occurrence_Of (RTE (RE_Address), Loc))),
Result_Definition =>
New_Occurrence_Of (Etype (N), Loc)),
Declarations => New_List (New_Typ_Decl),
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc, Stats));
-- Place function body before the expression containing the
-- conversion. We suppress all checks because the body of the
-- internally generated function already takes care of the case
-- in which the actual is null; therefore there is no need to
-- double check that the pointer is not null when the program
-- executes the alternative that performs the type conversion).
Insert_Action (N, Func, Suppress => All_Checks);
if Is_Access_Type (Etype (Expression (N))) then
-- Generate: Func (Address!(Expression))
Rewrite (N,
Make_Function_Call (Loc,
Name => New_Occurrence_Of (Fent, Loc),
Parameter_Associations => New_List (
Unchecked_Convert_To (RTE (RE_Address),
Relocate_Node (Expression (N))))));
else
-- Generate: Func (Operand_Typ!(Expression)'Address)
Rewrite (N,
Make_Function_Call (Loc,
Name => New_Occurrence_Of (Fent, Loc),
Parameter_Associations => New_List (
Make_Attribute_Reference (Loc,
Prefix => Unchecked_Convert_To (Operand_Typ,
Relocate_Node (Expression (N))),
Attribute_Name => Name_Address))));
end if;
end;
end if;
Analyze (N);
end Expand_Interface_Conversion;
------------------------------
-- Expand_Interface_Actuals --
------------------------------
procedure Expand_Interface_Actuals (Call_Node : Node_Id) is
Actual : Node_Id;
Actual_Dup : Node_Id;
Actual_Typ : Entity_Id;
Anon : Entity_Id;
Conversion : Node_Id;
Formal : Entity_Id;
Formal_Typ : Entity_Id;
Subp : Entity_Id;
Formal_DDT : Entity_Id := Empty; -- initialize to prevent warning
Actual_DDT : Entity_Id := Empty; -- initialize to prevent warning
begin
-- This subprogram is called directly from the semantics, so we need a
-- check to see whether expansion is active before proceeding.
if not Expander_Active then
return;
end if;
-- Call using access to subprogram with explicit dereference
if Nkind (Name (Call_Node)) = N_Explicit_Dereference then
Subp := Etype (Name (Call_Node));
-- Call using selected component
elsif Nkind (Name (Call_Node)) = N_Selected_Component then
Subp := Entity (Selector_Name (Name (Call_Node)));
-- Call using direct name
else
Subp := Entity (Name (Call_Node));
end if;
-- Ada 2005 (AI-251): Look for interface type formals to force "this"
-- displacement
Formal := First_Formal (Subp);
Actual := First_Actual (Call_Node);
while Present (Formal) loop
Formal_Typ := Etype (Formal);
if Has_Non_Limited_View (Formal_Typ) then
Formal_Typ := Non_Limited_View (Formal_Typ);
end if;
if Ekind (Formal_Typ) = E_Record_Type_With_Private then
Formal_Typ := Full_View (Formal_Typ);
end if;
if Is_Access_Type (Formal_Typ) then
Formal_DDT := Directly_Designated_Type (Formal_Typ);
if Has_Non_Limited_View (Formal_DDT) then
Formal_DDT := Non_Limited_View (Formal_DDT);
end if;
end if;
Actual_Typ := Etype (Actual);
if Has_Non_Limited_View (Actual_Typ) then
Actual_Typ := Non_Limited_View (Actual_Typ);
end if;
if Is_Access_Type (Actual_Typ) then
Actual_DDT := Directly_Designated_Type (Actual_Typ);
if Has_Non_Limited_View (Actual_DDT) then
Actual_DDT := Non_Limited_View (Actual_DDT);
end if;
end if;
if Is_Interface (Formal_Typ)
and then Is_Class_Wide_Type (Formal_Typ)
then
-- No need to displace the pointer if the type of the actual
-- coincides with the type of the formal.
if Actual_Typ = Formal_Typ then
null;
-- No need to displace the pointer if the interface type is a
-- parent of the type of the actual because in this case the
-- interface primitives are located in the primary dispatch table.
elsif Is_Ancestor (Formal_Typ, Actual_Typ,
Use_Full_View => True)
then
null;
-- Implicit conversion to the class-wide formal type to force the
-- displacement of the pointer.
else
-- Normally, expansion of actuals for calls to build-in-place
-- functions happens as part of Expand_Actuals, but in this
-- case the call will be wrapped in a conversion and soon after
-- expanded further to handle the displacement for a class-wide
-- interface conversion, so if this is a BIP call then we need
-- to handle it now.
if Is_Build_In_Place_Function_Call (Actual) then
Make_Build_In_Place_Call_In_Anonymous_Context (Actual);
end if;
Conversion := Convert_To (Formal_Typ, Relocate_Node (Actual));
Rewrite (Actual, Conversion);
Analyze_And_Resolve (Actual, Formal_Typ);
end if;
-- Access to class-wide interface type
elsif Is_Access_Type (Formal_Typ)
and then Is_Interface (Formal_DDT)
and then Is_Class_Wide_Type (Formal_DDT)
and then Interface_Present_In_Ancestor
(Typ => Actual_DDT,
Iface => Etype (Formal_DDT))
then
-- Handle attributes 'Access and 'Unchecked_Access
if Nkind (Actual) = N_Attribute_Reference
and then
(Attribute_Name (Actual) = Name_Access
or else Attribute_Name (Actual) = Name_Unchecked_Access)
then
-- This case must have been handled by the analysis and
-- expansion of 'Access. The only exception is when types
-- match and no further expansion is required.
pragma Assert (Base_Type (Etype (Prefix (Actual)))
= Base_Type (Formal_DDT));
null;
-- No need to displace the pointer if the type of the actual
-- coincides with the type of the formal.
elsif Actual_DDT = Formal_DDT then
null;
-- No need to displace the pointer if the interface type is
-- a parent of the type of the actual because in this case the
-- interface primitives are located in the primary dispatch table.
elsif Is_Ancestor (Formal_DDT, Actual_DDT,
Use_Full_View => True)
then
null;
else
Actual_Dup := Relocate_Node (Actual);
if From_Limited_With (Actual_Typ) then
-- If the type of the actual parameter comes from a limited
-- with_clause and the nonlimited view is already available,
-- we replace the anonymous access type by a duplicate
-- declaration whose designated type is the nonlimited view.
if Has_Non_Limited_View (Actual_DDT) then
Anon := New_Copy (Actual_Typ);
if Is_Itype (Anon) then
Set_Scope (Anon, Current_Scope);
end if;
Set_Directly_Designated_Type
(Anon, Non_Limited_View (Actual_DDT));
Set_Etype (Actual_Dup, Anon);
end if;
end if;
Conversion := Convert_To (Formal_Typ, Actual_Dup);
Rewrite (Actual, Conversion);
Analyze_And_Resolve (Actual, Formal_Typ);
end if;
end if;
Next_Actual (Actual);
Next_Formal (Formal);
end loop;
end Expand_Interface_Actuals;
----------------------------
-- Expand_Interface_Thunk --
----------------------------
procedure Expand_Interface_Thunk
(Prim : Node_Id;
Thunk_Id : out Entity_Id;
Thunk_Code : out Node_Id;
Iface : Entity_Id)
is
Loc : constant Source_Ptr := Sloc (Prim);
Actuals : constant List_Id := New_List;
Decl : constant List_Id := New_List;
Formals : constant List_Id := New_List;
Target : constant Entity_Id := Ultimate_Alias (Prim);
Decl_1 : Node_Id;
Decl_2 : Node_Id;
Expr : Node_Id;
Formal : Node_Id;
Ftyp : Entity_Id;
Iface_Formal : Node_Id := Empty; -- initialize to prevent warning
Is_Predef_Op : constant Boolean :=
Is_Predefined_Dispatching_Operation (Prim)
or else Is_Predefined_Dispatching_Operation (Target);
New_Arg : Node_Id;
Offset_To_Top : Node_Id;
Target_Formal : Entity_Id;
begin
Thunk_Id := Empty;
Thunk_Code := Empty;
-- No thunk needed if the primitive has been eliminated
if Is_Eliminated (Target) then
return;
-- In case of primitives that are functions without formals and a
-- controlling result there is no need to build the thunk.
elsif not Present (First_Formal (Target)) then
pragma Assert (Ekind (Target) = E_Function
and then Has_Controlling_Result (Target));
return;
end if;
-- Duplicate the formals of the Target primitive. In the thunk, the type
-- of the controlling formal is the covered interface type (instead of
-- the target tagged type). Done to avoid problems with discriminated
-- tagged types because, if the controlling type has discriminants with
-- default values, then the type conversions done inside the body of
-- the thunk (after the displacement of the pointer to the base of the
-- actual object) generate code that modify its contents.
-- Note: This special management is not done for predefined primitives
-- because they don't have available the Interface_Alias attribute (see
-- Sem_Ch3.Add_Internal_Interface_Entities).
if not Is_Predef_Op then
Iface_Formal := First_Formal (Interface_Alias (Prim));
end if;
Formal := First_Formal (Target);
while Present (Formal) loop
Ftyp := Etype (Formal);
-- Use the interface type as the type of the controlling formal (see
-- comment above).
if not Is_Controlling_Formal (Formal) then
Ftyp := Etype (Formal);
Expr := New_Copy_Tree (Expression (Parent (Formal)));
-- For predefined primitives the controlling type of the thunk is
-- the interface type passed by the caller (since they don't have
-- available the Interface_Alias attribute; see comment above).
elsif Is_Predef_Op then
Ftyp := Iface;
Expr := Empty;
else
Ftyp := Etype (Iface_Formal);
Expr := Empty;
-- Sanity check performed to ensure the proper controlling type
-- when the thunk has exactly one controlling parameter and it
-- comes first. In such case the GCC backend reuses the C++
-- thunks machinery which perform a computation equivalent to
-- the code generated by the expander; for other cases the GCC
-- backend translates the expanded code unmodified. However, as
-- a generalization, the check is performed for all controlling
-- types.
if Is_Access_Type (Ftyp) then
pragma Assert (Base_Type (Designated_Type (Ftyp)) = Iface);
null;
else
Ftyp := Base_Type (Ftyp);
pragma Assert (Ftyp = Iface);
end if;
end if;
Append_To (Formals,
Make_Parameter_Specification (Loc,
Defining_Identifier =>
Make_Defining_Identifier (Sloc (Formal),
Chars => Chars (Formal)),
In_Present => In_Present (Parent (Formal)),
Out_Present => Out_Present (Parent (Formal)),
Parameter_Type => New_Occurrence_Of (Ftyp, Loc),
Expression => Expr));
if not Is_Predef_Op then
Next_Formal (Iface_Formal);
end if;
Next_Formal (Formal);
end loop;
Target_Formal := First_Formal (Target);
Formal := First (Formals);
while Present (Formal) loop
-- If the parent is a constrained discriminated type, then the
-- primitive operation will have been defined on a first subtype.
-- For proper matching with controlling type, use base type.
if Ekind (Target_Formal) = E_In_Parameter
and then Ekind (Etype (Target_Formal)) = E_Anonymous_Access_Type
then
Ftyp :=
Base_Type (Directly_Designated_Type (Etype (Target_Formal)));
else
Ftyp := Base_Type (Etype (Target_Formal));
end if;
-- For concurrent types, the relevant information is found in the
-- Corresponding_Record_Type, rather than the type entity itself.
if Is_Concurrent_Type (Ftyp) then
Ftyp := Corresponding_Record_Type (Ftyp);
end if;
if Ekind (Target_Formal) = E_In_Parameter
and then Ekind (Etype (Target_Formal)) = E_Anonymous_Access_Type
and then Is_Controlling_Formal (Target_Formal)
then
-- Generate:
-- type T is access all <<type of the target formal>>
-- S : Storage_Offset := Storage_Offset!(Formal)
-- + Offset_To_Top (address!(Formal))
Decl_2 :=
Make_Full_Type_Declaration (Loc,
Defining_Identifier => Make_Temporary (Loc, 'T'),
Type_Definition =>
Make_Access_To_Object_Definition (Loc,
All_Present => True,
Null_Exclusion_Present => False,
Constant_Present => False,
Subtype_Indication =>
New_Occurrence_Of (Ftyp, Loc)));
New_Arg :=
Unchecked_Convert_To (RTE (RE_Address),
New_Occurrence_Of (Defining_Identifier (Formal), Loc));
if not RTE_Available (RE_Offset_To_Top) then
Offset_To_Top :=
Build_Offset_To_Top (Loc, New_Arg);
else
Offset_To_Top :=
Make_Function_Call (Loc,
Name => New_Occurrence_Of (RTE (RE_Offset_To_Top), Loc),
Parameter_Associations => New_List (New_Arg));
end if;
Decl_1 :=
Make_Object_Declaration (Loc,
Defining_Identifier => Make_Temporary (Loc, 'S'),
Constant_Present => True,
Object_Definition =>
New_Occurrence_Of (RTE (RE_Storage_Offset), Loc),
Expression =>
Make_Op_Add (Loc,
Left_Opnd =>
Unchecked_Convert_To
(RTE (RE_Storage_Offset),
New_Occurrence_Of
(Defining_Identifier (Formal), Loc)),
Right_Opnd =>
Offset_To_Top));
Append_To (Decl, Decl_2);
Append_To (Decl, Decl_1);
-- Reference the new actual. Generate:
-- T!(S)
Append_To (Actuals,
Unchecked_Convert_To
(Defining_Identifier (Decl_2),
New_Occurrence_Of (Defining_Identifier (Decl_1), Loc)));
elsif Is_Controlling_Formal (Target_Formal) then
-- Generate:
-- S1 : Storage_Offset := Storage_Offset!(Formal'Address)
-- + Offset_To_Top (Formal'Address)
-- S2 : Addr_Ptr := Addr_Ptr!(S1)
New_Arg :=
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of (Defining_Identifier (Formal), Loc),
Attribute_Name =>
Name_Address);
if not RTE_Available (RE_Offset_To_Top) then
Offset_To_Top :=
Build_Offset_To_Top (Loc, New_Arg);
else
Offset_To_Top :=
Make_Function_Call (Loc,
Name => New_Occurrence_Of (RTE (RE_Offset_To_Top), Loc),
Parameter_Associations => New_List (New_Arg));
end if;
Decl_1 :=
Make_Object_Declaration (Loc,
Defining_Identifier => Make_Temporary (Loc, 'S'),
Constant_Present => True,
Object_Definition =>
New_Occurrence_Of (RTE (RE_Storage_Offset), Loc),
Expression =>
Make_Op_Add (Loc,
Left_Opnd =>
Unchecked_Convert_To
(RTE (RE_Storage_Offset),
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of
(Defining_Identifier (Formal), Loc),
Attribute_Name => Name_Address)),
Right_Opnd =>
Offset_To_Top));
Decl_2 :=
Make_Object_Declaration (Loc,
Defining_Identifier => Make_Temporary (Loc, 'S'),
Constant_Present => True,
Object_Definition =>
New_Occurrence_Of (RTE (RE_Addr_Ptr), Loc),
Expression =>
Unchecked_Convert_To
(RTE (RE_Addr_Ptr),
New_Occurrence_Of (Defining_Identifier (Decl_1), Loc)));
Append_To (Decl, Decl_1);
Append_To (Decl, Decl_2);
-- Reference the new actual, generate:
-- Target_Formal (S2.all)
Append_To (Actuals,
Unchecked_Convert_To (Ftyp,
Make_Explicit_Dereference (Loc,
New_Occurrence_Of (Defining_Identifier (Decl_2), Loc))));
-- Ensure proper matching of access types. Required to avoid
-- reporting spurious errors.
elsif Is_Access_Type (Etype (Target_Formal)) then
Append_To (Actuals,
Unchecked_Convert_To (Base_Type (Etype (Target_Formal)),
New_Occurrence_Of (Defining_Identifier (Formal), Loc)));
-- No special management required for this actual
else
Append_To (Actuals,
New_Occurrence_Of (Defining_Identifier (Formal), Loc));
end if;
Next_Formal (Target_Formal);
Next (Formal);
end loop;
Thunk_Id := Make_Temporary (Loc, 'T');
-- Note: any change to this symbol name needs to be coordinated
-- with GNATcoverage, as that tool relies on it to identify
-- thunks and exclude them from source coverage analysis.
Set_Ekind (Thunk_Id, Ekind (Prim));
Set_Is_Thunk (Thunk_Id);
Set_Convention (Thunk_Id, Convention (Prim));
Set_Needs_Debug_Info (Thunk_Id, Needs_Debug_Info (Target));
Set_Thunk_Entity (Thunk_Id, Target);
-- Procedure case
if Ekind (Target) = E_Procedure then
Thunk_Code :=
Make_Subprogram_Body (Loc,
Specification =>
Make_Procedure_Specification (Loc,
Defining_Unit_Name => Thunk_Id,
Parameter_Specifications => Formals),
Declarations => Decl,
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc,
Statements => New_List (
Make_Procedure_Call_Statement (Loc,
Name => New_Occurrence_Of (Target, Loc),
Parameter_Associations => Actuals))));
-- Function case
else pragma Assert (Ekind (Target) = E_Function);
declare
Result_Def : Node_Id;
Call_Node : Node_Id;
begin
Call_Node :=
Make_Function_Call (Loc,
Name => New_Occurrence_Of (Target, Loc),
Parameter_Associations => Actuals);
if not Is_Interface (Etype (Prim)) then
Result_Def := New_Copy (Result_Definition (Parent (Target)));
-- Thunk of function returning a class-wide interface object. No
-- extra displacement needed since the displacement is generated
-- in the return statement of Prim. Example:
-- type Iface is interface ...
-- function F (O : Iface) return Iface'Class;
-- type T is new ... and Iface with ...
-- function F (O : T) return Iface'Class;
elsif Is_Class_Wide_Type (Etype (Prim)) then
Result_Def := New_Occurrence_Of (Etype (Prim), Loc);
-- Thunk of function returning an interface object. Displacement
-- needed. Example:
-- type Iface is interface ...
-- function F (O : Iface) return Iface;
-- type T is new ... and Iface with ...
-- function F (O : T) return T;
else
Result_Def :=
New_Occurrence_Of (Class_Wide_Type (Etype (Prim)), Loc);
-- Adding implicit conversion to force the displacement of
-- the pointer to the object to reference the corresponding
-- secondary dispatch table.
Call_Node :=
Make_Type_Conversion (Loc,
Subtype_Mark =>
New_Occurrence_Of (Class_Wide_Type (Etype (Prim)), Loc),
Expression => Relocate_Node (Call_Node));
end if;
Thunk_Code :=
Make_Subprogram_Body (Loc,
Specification =>
Make_Function_Specification (Loc,
Defining_Unit_Name => Thunk_Id,
Parameter_Specifications => Formals,
Result_Definition => Result_Def),
Declarations => Decl,
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc,
Statements => New_List (
Make_Simple_Return_Statement (Loc, Call_Node))));
end;
end if;
end Expand_Interface_Thunk;
--------------------------
-- Has_CPP_Constructors --
--------------------------
function Has_CPP_Constructors (Typ : Entity_Id) return Boolean is
E : Entity_Id;
begin
-- Look for the constructor entities
E := Next_Entity (Typ);
while Present (E) loop
if Ekind (E) = E_Function and then Is_Constructor (E) then
return True;
end if;
Next_Entity (E);
end loop;
return False;
end Has_CPP_Constructors;
------------
-- Has_DT --
------------
function Has_DT (Typ : Entity_Id) return Boolean is
begin
return not Is_Interface (Typ)
and then not Restriction_Active (No_Dispatching_Calls);
end Has_DT;
----------------------------------
-- Is_Expanded_Dispatching_Call --
----------------------------------
function Is_Expanded_Dispatching_Call (N : Node_Id) return Boolean is
begin
return Nkind (N) in N_Subprogram_Call
and then Nkind (Name (N)) = N_Explicit_Dereference
and then Is_Dispatch_Table_Entity (Etype (Name (N)));
end Is_Expanded_Dispatching_Call;
-------------------------------------
-- Is_Predefined_Dispatching_Alias --
-------------------------------------
function Is_Predefined_Dispatching_Alias (Prim : Entity_Id) return Boolean
is
begin
return not Is_Predefined_Dispatching_Operation (Prim)
and then Present (Alias (Prim))
and then Is_Predefined_Dispatching_Operation (Ultimate_Alias (Prim));
end Is_Predefined_Dispatching_Alias;
----------------------------------------
-- Make_Disp_Asynchronous_Select_Body --
----------------------------------------
-- For interface types, generate:
-- procedure _Disp_Asynchronous_Select
-- (T : in out <Typ>;
-- S : Integer;
-- P : System.Address;
-- B : out System.Storage_Elements.Dummy_Communication_Block;
-- F : out Boolean)
-- is
-- begin
-- F := False;
-- C := Ada.Tags.POK_Function;
-- end _Disp_Asynchronous_Select;
-- For protected types, generate:
-- procedure _Disp_Asynchronous_Select
-- (T : in out <Typ>;
-- S : Integer;
-- P : System.Address;
-- B : out System.Storage_Elements.Dummy_Communication_Block;
-- F : out Boolean)
-- is
-- I : Integer :=
-- Ada.Tags.Get_Entry_Index (Ada.Tags.Tag (<Typ>VP, S));
-- Bnn : System.Tasking.Protected_Objects.Operations.
-- Communication_Block;
-- begin
-- System.Tasking.Protected_Objects.Operations.Protected_Entry_Call
-- (T._object'Access,
-- System.Tasking.Protected_Objects.Protected_Entry_Index (I),
-- P,
-- System.Tasking.Asynchronous_Call,
-- Bnn);
-- B := System.Storage_Elements.Dummy_Communication_Block (Bnn);
-- end _Disp_Asynchronous_Select;
-- For task types, generate:
-- procedure _Disp_Asynchronous_Select
-- (T : in out <Typ>;
-- S : Integer;
-- P : System.Address;
-- B : out System.Storage_Elements.Dummy_Communication_Block;
-- F : out Boolean)
-- is
-- I : Integer :=
-- Ada.Tags.Get_Entry_Index (Ada.Tags.Tag (<Typ>VP, S));
-- begin
-- System.Tasking.Rendezvous.Task_Entry_Call
-- (T._task_id,
-- System.Tasking.Task_Entry_Index (I),
-- P,
-- System.Tasking.Asynchronous_Call,
-- F);
-- end _Disp_Asynchronous_Select;
function Make_Disp_Asynchronous_Select_Body
(Typ : Entity_Id) return Node_Id
is
Com_Block : Entity_Id;
Conc_Typ : Entity_Id := Empty;
Decls : constant List_Id := New_List;
Loc : constant Source_Ptr := Sloc (Typ);
Obj_Ref : Node_Id;
Stmts : constant List_Id := New_List;
Tag_Node : Node_Id;
begin
pragma Assert (not Restriction_Active (No_Dispatching_Calls));
-- Null body is generated for interface types
if Is_Interface (Typ) then
return
Make_Subprogram_Body (Loc,
Specification =>
Make_Disp_Asynchronous_Select_Spec (Typ),
Declarations => New_List,
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc,
New_List (
Make_Assignment_Statement (Loc,
Name => Make_Identifier (Loc, Name_uF),
Expression => New_Occurrence_Of (Standard_False, Loc)))));
end if;
if Is_Concurrent_Record_Type (Typ) then
Conc_Typ := Corresponding_Concurrent_Type (Typ);
-- Generate:
-- I : Integer :=
-- Ada.Tags.Get_Entry_Index (Ada.Tags.Tag! (<type>VP), S);
-- where I will be used to capture the entry index of the primitive
-- wrapper at position S.
if Tagged_Type_Expansion then
Tag_Node :=
Unchecked_Convert_To (RTE (RE_Tag),
New_Occurrence_Of
(Node (First_Elmt (Access_Disp_Table (Typ))), Loc));
else
Tag_Node :=
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Typ, Loc),
Attribute_Name => Name_Tag);
end if;
Append_To (Decls,
Make_Object_Declaration (Loc,
Defining_Identifier =>
Make_Defining_Identifier (Loc, Name_uI),
Object_Definition =>
New_Occurrence_Of (Standard_Integer, Loc),
Expression =>
Make_Function_Call (Loc,
Name =>
New_Occurrence_Of (RTE (RE_Get_Entry_Index), Loc),
Parameter_Associations =>
New_List (Tag_Node, Make_Identifier (Loc, Name_uS)))));
if Ekind (Conc_Typ) = E_Protected_Type then
-- Generate:
-- Bnn : Communication_Block;
Com_Block := Make_Temporary (Loc, 'B');
Append_To (Decls,
Make_Object_Declaration (Loc,
Defining_Identifier => Com_Block,
Object_Definition =>
New_Occurrence_Of (RTE (RE_Communication_Block), Loc)));
-- Build T._object'Access for calls below
Obj_Ref :=
Make_Attribute_Reference (Loc,
Attribute_Name => Name_Unchecked_Access,
Prefix =>
Make_Selected_Component (Loc,
Prefix => Make_Identifier (Loc, Name_uT),
Selector_Name => Make_Identifier (Loc, Name_uObject)));
case Corresponding_Runtime_Package (Conc_Typ) is
when System_Tasking_Protected_Objects_Entries =>
-- Generate:
-- Protected_Entry_Call
-- (T._object'Access, -- Object
-- Protected_Entry_Index! (I), -- E
-- P, -- Uninterpreted_Data
-- Asynchronous_Call, -- Mode
-- Bnn); -- Communication_Block
-- where T is the protected object, I is the entry index, P
-- is the wrapped parameters and B is the name of the
-- communication block.
Append_To (Stmts,
Make_Procedure_Call_Statement (Loc,
Name =>
New_Occurrence_Of (RTE (RE_Protected_Entry_Call), Loc),
Parameter_Associations =>
New_List (
Obj_Ref,
Make_Unchecked_Type_Conversion (Loc, -- entry index
Subtype_Mark =>
New_Occurrence_Of
(RTE (RE_Protected_Entry_Index), Loc),
Expression => Make_Identifier (Loc, Name_uI)),
Make_Identifier (Loc, Name_uP), -- parameter block
New_Occurrence_Of -- Asynchronous_Call
(RTE (RE_Asynchronous_Call), Loc),
New_Occurrence_Of -- comm block
(Com_Block, Loc))));
when others =>
raise Program_Error;
end case;
-- Generate:
-- B := Dummy_Communication_Block (Bnn);
Append_To (Stmts,
Make_Assignment_Statement (Loc,
Name => Make_Identifier (Loc, Name_uB),
Expression =>
Make_Unchecked_Type_Conversion (Loc,
Subtype_Mark =>
New_Occurrence_Of
(RTE (RE_Dummy_Communication_Block), Loc),
Expression => New_Occurrence_Of (Com_Block, Loc))));
-- Generate:
-- F := False;
Append_To (Stmts,
Make_Assignment_Statement (Loc,
Name => Make_Identifier (Loc, Name_uF),
Expression => New_Occurrence_Of (Standard_False, Loc)));
else
pragma Assert (Ekind (Conc_Typ) = E_Task_Type);
-- Generate:
-- Task_Entry_Call
-- (T._task_id, -- Acceptor
-- Task_Entry_Index! (I), -- E
-- P, -- Uninterpreted_Data
-- Asynchronous_Call, -- Mode
-- F); -- Rendezvous_Successful
-- where T is the task object, I is the entry index, P is the
-- wrapped parameters and F is the status flag.
Append_To (Stmts,
Make_Procedure_Call_Statement (Loc,
Name =>
New_Occurrence_Of (RTE (RE_Task_Entry_Call), Loc),
Parameter_Associations =>
New_List (
Make_Selected_Component (Loc, -- T._task_id
Prefix => Make_Identifier (Loc, Name_uT),
Selector_Name => Make_Identifier (Loc, Name_uTask_Id)),
Make_Unchecked_Type_Conversion (Loc, -- entry index
Subtype_Mark =>
New_Occurrence_Of (RTE (RE_Task_Entry_Index), Loc),
Expression => Make_Identifier (Loc, Name_uI)),
Make_Identifier (Loc, Name_uP), -- parameter block
New_Occurrence_Of -- Asynchronous_Call
(RTE (RE_Asynchronous_Call), Loc),
Make_Identifier (Loc, Name_uF)))); -- status flag
end if;
else
-- Ensure that the statements list is non-empty
Append_To (Stmts,
Make_Assignment_Statement (Loc,
Name => Make_Identifier (Loc, Name_uF),
Expression => New_Occurrence_Of (Standard_False, Loc)));
end if;
return
Make_Subprogram_Body (Loc,
Specification =>
Make_Disp_Asynchronous_Select_Spec (Typ),
Declarations => Decls,
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc, Stmts));
end Make_Disp_Asynchronous_Select_Body;
----------------------------------------
-- Make_Disp_Asynchronous_Select_Spec --
----------------------------------------
function Make_Disp_Asynchronous_Select_Spec
(Typ : Entity_Id) return Node_Id
is
Loc : constant Source_Ptr := Sloc (Typ);
B_Id : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uB);
Def_Id : constant Entity_Id :=
Make_Defining_Identifier (Loc,
Name_uDisp_Asynchronous_Select);
Params : constant List_Id := New_List;
begin
pragma Assert (not Restriction_Active (No_Dispatching_Calls));
-- T : in out Typ; -- Object parameter
-- S : Integer; -- Primitive operation slot
-- P : Address; -- Wrapped parameters
-- B : out Dummy_Communication_Block; -- Communication block dummy
-- F : out Boolean; -- Status flag
-- The B parameter may be left uninitialized
Set_Warnings_Off (B_Id);
Append_List_To (Params, New_List (
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_uT),
Parameter_Type => New_Occurrence_Of (Typ, Loc),
In_Present => True,
Out_Present => True),
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_uS),
Parameter_Type => New_Occurrence_Of (Standard_Integer, Loc)),
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_uP),
Parameter_Type => New_Occurrence_Of (RTE (RE_Address), Loc)),
Make_Parameter_Specification (Loc,
Defining_Identifier => B_Id,
Parameter_Type =>
New_Occurrence_Of (RTE (RE_Dummy_Communication_Block), Loc),
Out_Present => True),
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_uF),
Parameter_Type => New_Occurrence_Of (Standard_Boolean, Loc),
Out_Present => True)));
return
Make_Procedure_Specification (Loc,
Defining_Unit_Name => Def_Id,
Parameter_Specifications => Params);
end Make_Disp_Asynchronous_Select_Spec;
---------------------------------------
-- Make_Disp_Conditional_Select_Body --
---------------------------------------
-- For interface types, generate:
-- procedure _Disp_Conditional_Select
-- (T : in out <Typ>;
-- S : Integer;
-- P : System.Address;
-- C : out Ada.Tags.Prim_Op_Kind;
-- F : out Boolean)
-- is
-- begin
-- F := False;
-- C := Ada.Tags.POK_Function;
-- end _Disp_Conditional_Select;
-- For protected types, generate:
-- procedure _Disp_Conditional_Select
-- (T : in out <Typ>;
-- S : Integer;
-- P : System.Address;
-- C : out Ada.Tags.Prim_Op_Kind;
-- F : out Boolean)
-- is
-- I : Integer;
-- Bnn : System.Tasking.Protected_Objects.Operations.
-- Communication_Block;
-- begin
-- C := Ada.Tags.Get_Prim_Op_Kind (Ada.Tags.Tag (<Typ>VP, S));
-- if C = Ada.Tags.POK_Procedure
-- or else C = Ada.Tags.POK_Protected_Procedure
-- or else C = Ada.Tags.POK_Task_Procedure
-- then
-- F := True;
-- return;
-- end if;
-- I := Ada.Tags.Get_Entry_Index (Ada.Tags.Tag (<Typ>VP, S));
-- System.Tasking.Protected_Objects.Operations.Protected_Entry_Call
-- (T.object'Access,
-- System.Tasking.Protected_Objects.Protected_Entry_Index (I),
-- P,
-- System.Tasking.Conditional_Call,
-- Bnn);
-- F := not Cancelled (Bnn);
-- end _Disp_Conditional_Select;
-- For task types, generate:
-- procedure _Disp_Conditional_Select
-- (T : in out <Typ>;
-- S : Integer;
-- P : System.Address;
-- C : out Ada.Tags.Prim_Op_Kind;
-- F : out Boolean)
-- is
-- I : Integer;
-- begin
-- I := Ada.Tags.Get_Entry_Index (Ada.Tags.Tag (<Typ>VP, S));
-- System.Tasking.Rendezvous.Task_Entry_Call
-- (T._task_id,
-- System.Tasking.Task_Entry_Index (I),
-- P,
-- System.Tasking.Conditional_Call,
-- F);
-- end _Disp_Conditional_Select;
function Make_Disp_Conditional_Select_Body
(Typ : Entity_Id) return Node_Id
is
Loc : constant Source_Ptr := Sloc (Typ);
Blk_Nam : Entity_Id;
Conc_Typ : Entity_Id := Empty;
Decls : constant List_Id := New_List;
Obj_Ref : Node_Id;
Stmts : constant List_Id := New_List;
Tag_Node : Node_Id;
begin
pragma Assert (not Restriction_Active (No_Dispatching_Calls));
-- Null body is generated for interface types
if Is_Interface (Typ) then
return
Make_Subprogram_Body (Loc,
Specification =>
Make_Disp_Conditional_Select_Spec (Typ),
Declarations => No_List,
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc,
New_List (Make_Assignment_Statement (Loc,
Name => Make_Identifier (Loc, Name_uF),
Expression => New_Occurrence_Of (Standard_False, Loc)))));
end if;
if Is_Concurrent_Record_Type (Typ) then
Conc_Typ := Corresponding_Concurrent_Type (Typ);
-- Generate:
-- I : Integer;
-- where I will be used to capture the entry index of the primitive
-- wrapper at position S.
Append_To (Decls,
Make_Object_Declaration (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_uI),
Object_Definition =>
New_Occurrence_Of (Standard_Integer, Loc)));
-- Generate:
-- C := Ada.Tags.Get_Prim_Op_Kind (Ada.Tags.Tag! (<type>VP), S);
-- if C = POK_Procedure
-- or else C = POK_Protected_Procedure
-- or else C = POK_Task_Procedure;
-- then
-- F := True;
-- return;
-- end if;
Build_Common_Dispatching_Select_Statements (Typ, Stmts);
-- Generate:
-- Bnn : Communication_Block;
-- where Bnn is the name of the communication block used in the
-- call to Protected_Entry_Call.
Blk_Nam := Make_Temporary (Loc, 'B');
Append_To (Decls,
Make_Object_Declaration (Loc,
Defining_Identifier => Blk_Nam,
Object_Definition =>
New_Occurrence_Of (RTE (RE_Communication_Block), Loc)));
-- Generate:
-- I := Ada.Tags.Get_Entry_Index (Ada.Tags.Tag! (<type>VP), S);
-- I is the entry index and S is the dispatch table slot
if Tagged_Type_Expansion then
Tag_Node :=
Unchecked_Convert_To (RTE (RE_Tag),
New_Occurrence_Of
(Node (First_Elmt (Access_Disp_Table (Typ))), Loc));
else
Tag_Node :=
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Typ, Loc),
Attribute_Name => Name_Tag);
end if;
Append_To (Stmts,
Make_Assignment_Statement (Loc,
Name => Make_Identifier (Loc, Name_uI),
Expression =>
Make_Function_Call (Loc,
Name =>
New_Occurrence_Of (RTE (RE_Get_Entry_Index), Loc),
Parameter_Associations => New_List (
Tag_Node,
Make_Identifier (Loc, Name_uS)))));
if Ekind (Conc_Typ) = E_Protected_Type then
Obj_Ref := -- T._object'Access
Make_Attribute_Reference (Loc,
Attribute_Name => Name_Unchecked_Access,
Prefix =>
Make_Selected_Component (Loc,
Prefix => Make_Identifier (Loc, Name_uT),
Selector_Name => Make_Identifier (Loc, Name_uObject)));
case Corresponding_Runtime_Package (Conc_Typ) is
when System_Tasking_Protected_Objects_Entries =>
-- Generate:
-- Protected_Entry_Call
-- (T._object'Access, -- Object
-- Protected_Entry_Index! (I), -- E
-- P, -- Uninterpreted_Data
-- Conditional_Call, -- Mode
-- Bnn); -- Block
-- where T is the protected object, I is the entry index, P
-- are the wrapped parameters and Bnn is the name of the
-- communication block.
Append_To (Stmts,
Make_Procedure_Call_Statement (Loc,
Name =>
New_Occurrence_Of (RTE (RE_Protected_Entry_Call), Loc),
Parameter_Associations => New_List (
Obj_Ref,
Make_Unchecked_Type_Conversion (Loc, -- entry index
Subtype_Mark =>
New_Occurrence_Of
(RTE (RE_Protected_Entry_Index), Loc),
Expression => Make_Identifier (Loc, Name_uI)),
Make_Identifier (Loc, Name_uP), -- parameter block
New_Occurrence_Of -- Conditional_Call
(RTE (RE_Conditional_Call), Loc),
New_Occurrence_Of -- Bnn
(Blk_Nam, Loc))));
when System_Tasking_Protected_Objects_Single_Entry =>
-- If we are compiling for a restricted run-time, the call
-- uses the simpler form.
Append_To (Stmts,
Make_Procedure_Call_Statement (Loc,
Name =>
New_Occurrence_Of
(RTE (RE_Protected_Single_Entry_Call), Loc),
Parameter_Associations => New_List (
Obj_Ref,
Make_Attribute_Reference (Loc,
Prefix => Make_Identifier (Loc, Name_uP),
Attribute_Name => Name_Address),
New_Occurrence_Of
(RTE (RE_Conditional_Call), Loc))));
when others =>
raise Program_Error;
end case;
-- Generate:
-- F := not Cancelled (Bnn);
-- where F is the success flag. The status of Cancelled is negated
-- in order to match the behavior of the version for task types.
Append_To (Stmts,
Make_Assignment_Statement (Loc,
Name => Make_Identifier (Loc, Name_uF),
Expression =>
Make_Op_Not (Loc,
Right_Opnd =>
Make_Function_Call (Loc,
Name =>
New_Occurrence_Of (RTE (RE_Cancelled), Loc),
Parameter_Associations => New_List (
New_Occurrence_Of (Blk_Nam, Loc))))));
else
pragma Assert (Ekind (Conc_Typ) = E_Task_Type);
-- Generate:
-- Task_Entry_Call
-- (T._task_id, -- Acceptor
-- Task_Entry_Index! (I), -- E
-- P, -- Uninterpreted_Data
-- Conditional_Call, -- Mode
-- F); -- Rendezvous_Successful
-- where T is the task object, I is the entry index, P are the
-- wrapped parameters and F is the status flag.
Append_To (Stmts,
Make_Procedure_Call_Statement (Loc,
Name =>
New_Occurrence_Of (RTE (RE_Task_Entry_Call), Loc),
Parameter_Associations => New_List (
Make_Selected_Component (Loc, -- T._task_id
Prefix => Make_Identifier (Loc, Name_uT),
Selector_Name => Make_Identifier (Loc, Name_uTask_Id)),
Make_Unchecked_Type_Conversion (Loc, -- entry index
Subtype_Mark =>
New_Occurrence_Of (RTE (RE_Task_Entry_Index), Loc),
Expression => Make_Identifier (Loc, Name_uI)),
Make_Identifier (Loc, Name_uP), -- parameter block
New_Occurrence_Of -- Conditional_Call
(RTE (RE_Conditional_Call), Loc),
Make_Identifier (Loc, Name_uF)))); -- status flag
end if;
else
-- Initialize out parameters
Append_To (Stmts,
Make_Assignment_Statement (Loc,
Name => Make_Identifier (Loc, Name_uF),
Expression => New_Occurrence_Of (Standard_False, Loc)));
Append_To (Stmts,
Make_Assignment_Statement (Loc,
Name => Make_Identifier (Loc, Name_uC),
Expression => New_Occurrence_Of (RTE (RE_POK_Function), Loc)));
end if;
return
Make_Subprogram_Body (Loc,
Specification =>
Make_Disp_Conditional_Select_Spec (Typ),
Declarations => Decls,
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc, Stmts));
end Make_Disp_Conditional_Select_Body;
---------------------------------------
-- Make_Disp_Conditional_Select_Spec --
---------------------------------------
function Make_Disp_Conditional_Select_Spec
(Typ : Entity_Id) return Node_Id
is
Loc : constant Source_Ptr := Sloc (Typ);
Def_Id : constant Node_Id :=
Make_Defining_Identifier (Loc,
Name_uDisp_Conditional_Select);
Params : constant List_Id := New_List;
begin
pragma Assert (not Restriction_Active (No_Dispatching_Calls));
-- T : in out Typ; -- Object parameter
-- S : Integer; -- Primitive operation slot
-- P : Address; -- Wrapped parameters
-- C : out Prim_Op_Kind; -- Call kind
-- F : out Boolean; -- Status flag
Append_List_To (Params, New_List (
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_uT),
Parameter_Type => New_Occurrence_Of (Typ, Loc),
In_Present => True,
Out_Present => True),
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_uS),
Parameter_Type => New_Occurrence_Of (Standard_Integer, Loc)),
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_uP),
Parameter_Type => New_Occurrence_Of (RTE (RE_Address), Loc)),
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_uC),
Parameter_Type =>
New_Occurrence_Of (RTE (RE_Prim_Op_Kind), Loc),
Out_Present => True),
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_uF),
Parameter_Type => New_Occurrence_Of (Standard_Boolean, Loc),
Out_Present => True)));
return
Make_Procedure_Specification (Loc,
Defining_Unit_Name => Def_Id,
Parameter_Specifications => Params);
end Make_Disp_Conditional_Select_Spec;
-------------------------------------
-- Make_Disp_Get_Prim_Op_Kind_Body --
-------------------------------------
function Make_Disp_Get_Prim_Op_Kind_Body (Typ : Entity_Id) return Node_Id is
Loc : constant Source_Ptr := Sloc (Typ);
Tag_Node : Node_Id;
begin
pragma Assert (not Restriction_Active (No_Dispatching_Calls));
if Is_Interface (Typ) then
return
Make_Subprogram_Body (Loc,
Specification =>
Make_Disp_Get_Prim_Op_Kind_Spec (Typ),
Declarations => New_List,
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc,
New_List (Make_Null_Statement (Loc))));
end if;
-- Generate:
-- C := get_prim_op_kind (tag! (<type>VP), S);
-- where C is the out parameter capturing the call kind and S is the
-- dispatch table slot number.
if Tagged_Type_Expansion then
Tag_Node :=
Unchecked_Convert_To (RTE (RE_Tag),
New_Occurrence_Of
(Node (First_Elmt (Access_Disp_Table (Typ))), Loc));
else
Tag_Node :=
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Typ, Loc),
Attribute_Name => Name_Tag);
end if;
return
Make_Subprogram_Body (Loc,
Specification =>
Make_Disp_Get_Prim_Op_Kind_Spec (Typ),
Declarations => New_List,
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc,
New_List (
Make_Assignment_Statement (Loc,
Name => Make_Identifier (Loc, Name_uC),
Expression =>
Make_Function_Call (Loc,
Name =>
New_Occurrence_Of (RTE (RE_Get_Prim_Op_Kind), Loc),
Parameter_Associations => New_List (
Tag_Node,
Make_Identifier (Loc, Name_uS)))))));
end Make_Disp_Get_Prim_Op_Kind_Body;
-------------------------------------
-- Make_Disp_Get_Prim_Op_Kind_Spec --
-------------------------------------
function Make_Disp_Get_Prim_Op_Kind_Spec
(Typ : Entity_Id) return Node_Id
is
Loc : constant Source_Ptr := Sloc (Typ);
Def_Id : constant Node_Id :=
Make_Defining_Identifier (Loc, Name_uDisp_Get_Prim_Op_Kind);
Params : constant List_Id := New_List;
begin
pragma Assert (not Restriction_Active (No_Dispatching_Calls));
-- T : in out Typ; -- Object parameter
-- S : Integer; -- Primitive operation slot
-- C : out Prim_Op_Kind; -- Call kind
Append_List_To (Params, New_List (
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_uT),
Parameter_Type => New_Occurrence_Of (Typ, Loc),
In_Present => True,
Out_Present => True),
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_uS),
Parameter_Type => New_Occurrence_Of (Standard_Integer, Loc)),
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_uC),
Parameter_Type =>
New_Occurrence_Of (RTE (RE_Prim_Op_Kind), Loc),
Out_Present => True)));
return
Make_Procedure_Specification (Loc,
Defining_Unit_Name => Def_Id,
Parameter_Specifications => Params);
end Make_Disp_Get_Prim_Op_Kind_Spec;
--------------------------------
-- Make_Disp_Get_Task_Id_Body --
--------------------------------
function Make_Disp_Get_Task_Id_Body
(Typ : Entity_Id) return Node_Id
is
Loc : constant Source_Ptr := Sloc (Typ);
Ret : Node_Id;
begin
pragma Assert (not Restriction_Active (No_Dispatching_Calls));
if Is_Concurrent_Record_Type (Typ)
and then Ekind (Corresponding_Concurrent_Type (Typ)) = E_Task_Type
then
-- Generate:
-- return To_Address (_T._task_id);
Ret :=
Make_Simple_Return_Statement (Loc,
Expression =>
Make_Unchecked_Type_Conversion (Loc,
Subtype_Mark => New_Occurrence_Of (RTE (RE_Address), Loc),
Expression =>
Make_Selected_Component (Loc,
Prefix => Make_Identifier (Loc, Name_uT),
Selector_Name => Make_Identifier (Loc, Name_uTask_Id))));
-- A null body is constructed for non-task types
else
-- Generate:
-- return Null_Address;
Ret :=
Make_Simple_Return_Statement (Loc,
Expression => New_Occurrence_Of (RTE (RE_Null_Address), Loc));
end if;
return
Make_Subprogram_Body (Loc,
Specification => Make_Disp_Get_Task_Id_Spec (Typ),
Declarations => New_List,
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc, New_List (Ret)));
end Make_Disp_Get_Task_Id_Body;
--------------------------------
-- Make_Disp_Get_Task_Id_Spec --
--------------------------------
function Make_Disp_Get_Task_Id_Spec
(Typ : Entity_Id) return Node_Id
is
Loc : constant Source_Ptr := Sloc (Typ);
begin
pragma Assert (not Restriction_Active (No_Dispatching_Calls));
return
Make_Function_Specification (Loc,
Defining_Unit_Name =>
Make_Defining_Identifier (Loc, Name_uDisp_Get_Task_Id),
Parameter_Specifications => New_List (
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_uT),
Parameter_Type => New_Occurrence_Of (Typ, Loc))),
Result_Definition =>
New_Occurrence_Of (RTE (RE_Address), Loc));
end Make_Disp_Get_Task_Id_Spec;
----------------------------
-- Make_Disp_Requeue_Body --
----------------------------
function Make_Disp_Requeue_Body
(Typ : Entity_Id) return Node_Id
is
Loc : constant Source_Ptr := Sloc (Typ);
Conc_Typ : Entity_Id := Empty;
Stmts : constant List_Id := New_List;
begin
pragma Assert (not Restriction_Active (No_Dispatching_Calls));
-- Null body is generated for interface types and non-concurrent
-- tagged types.
if Is_Interface (Typ)
or else not Is_Concurrent_Record_Type (Typ)
then
return
Make_Subprogram_Body (Loc,
Specification => Make_Disp_Requeue_Spec (Typ),
Declarations => No_List,
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc,
New_List (Make_Null_Statement (Loc))));
end if;
Conc_Typ := Corresponding_Concurrent_Type (Typ);
if Ekind (Conc_Typ) = E_Protected_Type then
-- Generate statements:
-- if F then
-- System.Tasking.Protected_Objects.Operations.
-- Requeue_Protected_Entry
-- (Protection_Entries_Access (P),
-- O._object'Unchecked_Access,
-- Protected_Entry_Index (I),
-- A);
-- else
-- System.Tasking.Protected_Objects.Operations.
-- Requeue_Task_To_Protected_Entry
-- (O._object'Unchecked_Access,
-- Protected_Entry_Index (I),
-- A);
-- end if;
if Restriction_Active (No_Entry_Queue) then
Append_To (Stmts, Make_Null_Statement (Loc));
else
Append_To (Stmts,
Make_If_Statement (Loc,
Condition => Make_Identifier (Loc, Name_uF),
Then_Statements =>
New_List (
-- Call to Requeue_Protected_Entry
Make_Procedure_Call_Statement (Loc,
Name =>
New_Occurrence_Of
(RTE (RE_Requeue_Protected_Entry), Loc),
Parameter_Associations =>
New_List (
Make_Unchecked_Type_Conversion (Loc, -- PEA (P)
Subtype_Mark =>
New_Occurrence_Of (
RTE (RE_Protection_Entries_Access), Loc),
Expression =>
Make_Identifier (Loc, Name_uP)),
Make_Attribute_Reference (Loc, -- O._object'Acc
Attribute_Name =>
Name_Unchecked_Access,
Prefix =>
Make_Selected_Component (Loc,
Prefix =>
Make_Identifier (Loc, Name_uO),
Selector_Name =>
Make_Identifier (Loc, Name_uObject))),
Make_Unchecked_Type_Conversion (Loc, -- entry index
Subtype_Mark =>
New_Occurrence_Of
(RTE (RE_Protected_Entry_Index), Loc),
Expression => Make_Identifier (Loc, Name_uI)),
Make_Identifier (Loc, Name_uA)))), -- abort status
Else_Statements =>
New_List (
-- Call to Requeue_Task_To_Protected_Entry
Make_Procedure_Call_Statement (Loc,
Name =>
New_Occurrence_Of
(RTE (RE_Requeue_Task_To_Protected_Entry), Loc),
Parameter_Associations =>
New_List (
Make_Attribute_Reference (Loc, -- O._object'Acc
Attribute_Name => Name_Unchecked_Access,
Prefix =>
Make_Selected_Component (Loc,
Prefix =>
Make_Identifier (Loc, Name_uO),
Selector_Name =>
Make_Identifier (Loc, Name_uObject))),
Make_Unchecked_Type_Conversion (Loc, -- entry index
Subtype_Mark =>
New_Occurrence_Of
(RTE (RE_Protected_Entry_Index), Loc),
Expression => Make_Identifier (Loc, Name_uI)),
Make_Identifier (Loc, Name_uA)))))); -- abort status
end if;
else
pragma Assert (Is_Task_Type (Conc_Typ));
-- Generate:
-- if F then
-- System.Tasking.Rendezvous.Requeue_Protected_To_Task_Entry
-- (Protection_Entries_Access (P),
-- O._task_id,
-- Task_Entry_Index (I),
-- A);
-- else
-- System.Tasking.Rendezvous.Requeue_Task_Entry
-- (O._task_id,
-- Task_Entry_Index (I),
-- A);
-- end if;
Append_To (Stmts,
Make_If_Statement (Loc,
Condition => Make_Identifier (Loc, Name_uF),
Then_Statements => New_List (
-- Call to Requeue_Protected_To_Task_Entry
Make_Procedure_Call_Statement (Loc,
Name =>
New_Occurrence_Of
(RTE (RE_Requeue_Protected_To_Task_Entry), Loc),
Parameter_Associations => New_List (
Make_Unchecked_Type_Conversion (Loc, -- PEA (P)
Subtype_Mark =>
New_Occurrence_Of
(RTE (RE_Protection_Entries_Access), Loc),
Expression => Make_Identifier (Loc, Name_uP)),
Make_Selected_Component (Loc, -- O._task_id
Prefix => Make_Identifier (Loc, Name_uO),
Selector_Name => Make_Identifier (Loc, Name_uTask_Id)),
Make_Unchecked_Type_Conversion (Loc, -- entry index
Subtype_Mark =>
New_Occurrence_Of (RTE (RE_Task_Entry_Index), Loc),
Expression => Make_Identifier (Loc, Name_uI)),
Make_Identifier (Loc, Name_uA)))), -- abort status
Else_Statements => New_List (
-- Call to Requeue_Task_Entry
Make_Procedure_Call_Statement (Loc,
Name =>
New_Occurrence_Of (RTE (RE_Requeue_Task_Entry), Loc),
Parameter_Associations => New_List (
Make_Selected_Component (Loc, -- O._task_id
Prefix => Make_Identifier (Loc, Name_uO),
Selector_Name => Make_Identifier (Loc, Name_uTask_Id)),
Make_Unchecked_Type_Conversion (Loc, -- entry index
Subtype_Mark =>
New_Occurrence_Of (RTE (RE_Task_Entry_Index), Loc),
Expression => Make_Identifier (Loc, Name_uI)),
Make_Identifier (Loc, Name_uA)))))); -- abort status
end if;
-- Even though no declarations are needed in both cases, we allocate
-- a list for entities added by Freeze.
return
Make_Subprogram_Body (Loc,
Specification => Make_Disp_Requeue_Spec (Typ),
Declarations => New_List,
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc, Stmts));
end Make_Disp_Requeue_Body;
----------------------------
-- Make_Disp_Requeue_Spec --
----------------------------
function Make_Disp_Requeue_Spec
(Typ : Entity_Id) return Node_Id
is
Loc : constant Source_Ptr := Sloc (Typ);
begin
pragma Assert (not Restriction_Active (No_Dispatching_Calls));
-- O : in out Typ; - Object parameter
-- F : Boolean; - Protected (True) / task (False) flag
-- P : Address; - Protection_Entries_Access value
-- I : Entry_Index - Index of entry call
-- A : Boolean - Abort flag
-- Note that the Protection_Entries_Access value is represented as a
-- System.Address in order to avoid dragging in the tasking runtime
-- when compiling sources without tasking constructs.
return
Make_Procedure_Specification (Loc,
Defining_Unit_Name =>
Make_Defining_Identifier (Loc, Name_uDisp_Requeue),
Parameter_Specifications => New_List (
Make_Parameter_Specification (Loc, -- O
Defining_Identifier =>
Make_Defining_Identifier (Loc, Name_uO),
Parameter_Type =>
New_Occurrence_Of (Typ, Loc),
In_Present => True,
Out_Present => True),
Make_Parameter_Specification (Loc, -- F
Defining_Identifier =>
Make_Defining_Identifier (Loc, Name_uF),
Parameter_Type =>
New_Occurrence_Of (Standard_Boolean, Loc)),
Make_Parameter_Specification (Loc, -- P
Defining_Identifier =>
Make_Defining_Identifier (Loc, Name_uP),
Parameter_Type =>
New_Occurrence_Of (RTE (RE_Address), Loc)),
Make_Parameter_Specification (Loc, -- I
Defining_Identifier =>
Make_Defining_Identifier (Loc, Name_uI),
Parameter_Type =>
New_Occurrence_Of (Standard_Integer, Loc)),
Make_Parameter_Specification (Loc, -- A
Defining_Identifier =>
Make_Defining_Identifier (Loc, Name_uA),
Parameter_Type =>
New_Occurrence_Of (Standard_Boolean, Loc))));
end Make_Disp_Requeue_Spec;
---------------------------------
-- Make_Disp_Timed_Select_Body --
---------------------------------
-- For interface types, generate:
-- procedure _Disp_Timed_Select
-- (T : in out <Typ>;
-- S : Integer;
-- P : System.Address;
-- D : Duration;
-- M : Integer;
-- C : out Ada.Tags.Prim_Op_Kind;
-- F : out Boolean)
-- is
-- begin
-- F := False;
-- C := Ada.Tags.POK_Function;
-- end _Disp_Timed_Select;
-- For protected types, generate:
-- procedure _Disp_Timed_Select
-- (T : in out <Typ>;
-- S : Integer;
-- P : System.Address;
-- D : Duration;
-- M : Integer;
-- C : out Ada.Tags.Prim_Op_Kind;
-- F : out Boolean)
-- is
-- I : Integer;
-- begin
-- C := Ada.Tags.Get_Prim_Op_Kind (Ada.Tags.Tag (<Typ>VP), S);
-- if C = Ada.Tags.POK_Procedure
-- or else C = Ada.Tags.POK_Protected_Procedure
-- or else C = Ada.Tags.POK_Task_Procedure
-- then
-- F := True;
-- return;
-- end if;
-- I := Ada.Tags.Get_Entry_Index (Ada.Tags.Tag (<Typ>VP), S);
-- System.Tasking.Protected_Objects.Operations.
-- Timed_Protected_Entry_Call
-- (T._object'Access,
-- System.Tasking.Protected_Objects.Protected_Entry_Index (I),
-- P,
-- D,
-- M,
-- F);
-- end _Disp_Timed_Select;
-- For task types, generate:
-- procedure _Disp_Timed_Select
-- (T : in out <Typ>;
-- S : Integer;
-- P : System.Address;
-- D : Duration;
-- M : Integer;
-- C : out Ada.Tags.Prim_Op_Kind;
-- F : out Boolean)
-- is
-- I : Integer;
-- begin
-- I := Ada.Tags.Get_Entry_Index (Ada.Tags.Tag (<Typ>VP), S);
-- System.Tasking.Rendezvous.Timed_Task_Entry_Call
-- (T._task_id,
-- System.Tasking.Task_Entry_Index (I),
-- P,
-- D,
-- M,
-- F);
-- end _Disp_Time_Select;
function Make_Disp_Timed_Select_Body
(Typ : Entity_Id) return Node_Id
is
Loc : constant Source_Ptr := Sloc (Typ);
Conc_Typ : Entity_Id := Empty;
Decls : constant List_Id := New_List;
Obj_Ref : Node_Id;
Stmts : constant List_Id := New_List;
Tag_Node : Node_Id;
begin
pragma Assert (not Restriction_Active (No_Dispatching_Calls));
-- Null body is generated for interface types
if Is_Interface (Typ) then
return
Make_Subprogram_Body (Loc,
Specification => Make_Disp_Timed_Select_Spec (Typ),
Declarations => New_List,
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc,
New_List (
Make_Assignment_Statement (Loc,
Name => Make_Identifier (Loc, Name_uF),
Expression => New_Occurrence_Of (Standard_False, Loc)))));
end if;
if Is_Concurrent_Record_Type (Typ) then
Conc_Typ := Corresponding_Concurrent_Type (Typ);
-- Generate:
-- I : Integer;
-- where I will be used to capture the entry index of the primitive
-- wrapper at position S.
Append_To (Decls,
Make_Object_Declaration (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_uI),
Object_Definition =>
New_Occurrence_Of (Standard_Integer, Loc)));
-- Generate:
-- C := Get_Prim_Op_Kind (tag! (<type>VP), S);
-- if C = POK_Procedure
-- or else C = POK_Protected_Procedure
-- or else C = POK_Task_Procedure;
-- then
-- F := True;
-- return;
-- end if;
Build_Common_Dispatching_Select_Statements (Typ, Stmts);
-- Generate:
-- I := Get_Entry_Index (tag! (<type>VP), S);
-- I is the entry index and S is the dispatch table slot
if Tagged_Type_Expansion then
Tag_Node :=
Unchecked_Convert_To (RTE (RE_Tag),
New_Occurrence_Of
(Node (First_Elmt (Access_Disp_Table (Typ))), Loc));
else
Tag_Node :=
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Typ, Loc),
Attribute_Name => Name_Tag);
end if;
Append_To (Stmts,
Make_Assignment_Statement (Loc,
Name => Make_Identifier (Loc, Name_uI),
Expression =>
Make_Function_Call (Loc,
Name => New_Occurrence_Of (RTE (RE_Get_Entry_Index), Loc),
Parameter_Associations => New_List (
Tag_Node,
Make_Identifier (Loc, Name_uS)))));
-- Protected case
if Ekind (Conc_Typ) = E_Protected_Type then
-- Build T._object'Access
Obj_Ref :=
Make_Attribute_Reference (Loc,
Attribute_Name => Name_Unchecked_Access,
Prefix =>
Make_Selected_Component (Loc,
Prefix => Make_Identifier (Loc, Name_uT),
Selector_Name => Make_Identifier (Loc, Name_uObject)));
-- Normal case, No_Entry_Queue restriction not active. In this
-- case we generate:
-- Timed_Protected_Entry_Call
-- (T._object'access,
-- Protected_Entry_Index! (I),
-- P, D, M, F);
-- where T is the protected object, I is the entry index, P are
-- the wrapped parameters, D is the delay amount, M is the delay
-- mode and F is the status flag.
-- Historically, there was also an implementation for single
-- entry protected types (in s-tposen). However, it was removed
-- by also testing for no No_Select_Statements restriction in
-- Exp_Utils.Corresponding_Runtime_Package. This simplified the
-- implementation of s-tposen.adb and provided consistency between
-- all versions of System.Tasking.Protected_Objects.Single_Entry
-- (s-tposen*.adb).
case Corresponding_Runtime_Package (Conc_Typ) is
when System_Tasking_Protected_Objects_Entries =>
Append_To (Stmts,
Make_Procedure_Call_Statement (Loc,
Name =>
New_Occurrence_Of
(RTE (RE_Timed_Protected_Entry_Call), Loc),
Parameter_Associations => New_List (
Obj_Ref,
Make_Unchecked_Type_Conversion (Loc, -- entry index
Subtype_Mark =>
New_Occurrence_Of
(RTE (RE_Protected_Entry_Index), Loc),
Expression => Make_Identifier (Loc, Name_uI)),
Make_Identifier (Loc, Name_uP), -- parameter block
Make_Identifier (Loc, Name_uD), -- delay
Make_Identifier (Loc, Name_uM), -- delay mode
Make_Identifier (Loc, Name_uF)))); -- status flag
when others =>
raise Program_Error;
end case;
-- Task case
else
pragma Assert (Ekind (Conc_Typ) = E_Task_Type);
-- Generate:
-- Timed_Task_Entry_Call (
-- T._task_id,
-- Task_Entry_Index! (I),
-- P,
-- D,
-- M,
-- F);
-- where T is the task object, I is the entry index, P are the
-- wrapped parameters, D is the delay amount, M is the delay
-- mode and F is the status flag.
Append_To (Stmts,
Make_Procedure_Call_Statement (Loc,
Name =>
New_Occurrence_Of (RTE (RE_Timed_Task_Entry_Call), Loc),
Parameter_Associations => New_List (
Make_Selected_Component (Loc, -- T._task_id
Prefix => Make_Identifier (Loc, Name_uT),
Selector_Name => Make_Identifier (Loc, Name_uTask_Id)),
Make_Unchecked_Type_Conversion (Loc, -- entry index
Subtype_Mark =>
New_Occurrence_Of (RTE (RE_Task_Entry_Index), Loc),
Expression => Make_Identifier (Loc, Name_uI)),
Make_Identifier (Loc, Name_uP), -- parameter block
Make_Identifier (Loc, Name_uD), -- delay
Make_Identifier (Loc, Name_uM), -- delay mode
Make_Identifier (Loc, Name_uF)))); -- status flag
end if;
else
-- Initialize out parameters
Append_To (Stmts,
Make_Assignment_Statement (Loc,
Name => Make_Identifier (Loc, Name_uF),
Expression => New_Occurrence_Of (Standard_False, Loc)));
Append_To (Stmts,
Make_Assignment_Statement (Loc,
Name => Make_Identifier (Loc, Name_uC),
Expression => New_Occurrence_Of (RTE (RE_POK_Function), Loc)));
end if;
return
Make_Subprogram_Body (Loc,
Specification => Make_Disp_Timed_Select_Spec (Typ),
Declarations => Decls,
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc, Stmts));
end Make_Disp_Timed_Select_Body;
---------------------------------
-- Make_Disp_Timed_Select_Spec --
---------------------------------
function Make_Disp_Timed_Select_Spec
(Typ : Entity_Id) return Node_Id
is
Loc : constant Source_Ptr := Sloc (Typ);
Def_Id : constant Node_Id :=
Make_Defining_Identifier (Loc,
Name_uDisp_Timed_Select);
Params : constant List_Id := New_List;
begin
pragma Assert (not Restriction_Active (No_Dispatching_Calls));
-- T : in out Typ; -- Object parameter
-- S : Integer; -- Primitive operation slot
-- P : Address; -- Wrapped parameters
-- D : Duration; -- Delay
-- M : Integer; -- Delay Mode
-- C : out Prim_Op_Kind; -- Call kind
-- F : out Boolean; -- Status flag
Append_List_To (Params, New_List (
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_uT),
Parameter_Type => New_Occurrence_Of (Typ, Loc),
In_Present => True,
Out_Present => True),
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_uS),
Parameter_Type => New_Occurrence_Of (Standard_Integer, Loc)),
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_uP),
Parameter_Type => New_Occurrence_Of (RTE (RE_Address), Loc)),
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_uD),
Parameter_Type => New_Occurrence_Of (Standard_Duration, Loc)),
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_uM),
Parameter_Type => New_Occurrence_Of (Standard_Integer, Loc)),
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_uC),
Parameter_Type =>
New_Occurrence_Of (RTE (RE_Prim_Op_Kind), Loc),
Out_Present => True)));
Append_To (Params,
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_uF),
Parameter_Type => New_Occurrence_Of (Standard_Boolean, Loc),
Out_Present => True));
return
Make_Procedure_Specification (Loc,
Defining_Unit_Name => Def_Id,
Parameter_Specifications => Params);
end Make_Disp_Timed_Select_Spec;
-------------
-- Make_DT --
-------------
-- The frontend supports two models for expanding dispatch tables
-- associated with library-level defined tagged types: statically and
-- non-statically allocated dispatch tables. In the former case the object
-- containing the dispatch table is constant and it is initialized by means
-- of a positional aggregate. In the latter case, the object containing
-- the dispatch table is a variable which is initialized by means of
-- assignments.
-- In case of locally defined tagged types, the object containing the
-- object containing the dispatch table is always a variable (instead of a
-- constant). This is currently required to give support to late overriding
-- of primitives. For example:
-- procedure Example is
-- package Pkg is
-- type T1 is tagged null record;
-- procedure Prim (O : T1);
-- end Pkg;
-- type T2 is new Pkg.T1 with null record;
-- procedure Prim (X : T2) is -- late overriding
-- begin
-- ...
-- ...
-- end;
-- WARNING: This routine manages Ghost regions. Return statements must be
-- replaced by gotos which jump to the end of the routine and restore the
-- Ghost mode.
function Make_DT (Typ : Entity_Id; N : Node_Id := Empty) return List_Id is
Loc : constant Source_Ptr := Sloc (Typ);
Max_Predef_Prims : constant Int :=
UI_To_Int
(Intval
(Expression
(Parent (RTE (RE_Max_Predef_Prims)))));
DT_Decl : constant Elist_Id := New_Elmt_List;
DT_Aggr : constant Elist_Id := New_Elmt_List;
-- Entities marked with attribute Is_Dispatch_Table_Entity
Dummy_Object : Entity_Id := Empty;
-- Extra nonexistent object of type Typ internally used to compute the
-- offset to the components that reference secondary dispatch tables.
-- Used to compute the offset of components located at fixed position.
procedure Check_Premature_Freezing
(Subp : Entity_Id;
Tagged_Type : Entity_Id;
Typ : Entity_Id);
-- Verify that all untagged types in the profile of a subprogram are
-- frozen at the point the subprogram is frozen. This enforces the rule
-- on RM 13.14 (14) as modified by AI05-019. At the point a subprogram
-- is frozen, enough must be known about it to build the activation
-- record for it, which requires at least that the size of all
-- parameters be known. Controlling arguments are by-reference,
-- and therefore the rule only applies to untagged types. Typical
-- violation of the rule involves an object declaration that freezes a
-- tagged type, when one of its primitive operations has a type in its
-- profile whose full view has not been analyzed yet. More complex cases
-- involve composite types that have one private unfrozen subcomponent.
-- Move this check to sem???
procedure Export_DT (Typ : Entity_Id; DT : Entity_Id; Index : Nat := 0);
-- Export the dispatch table DT of tagged type Typ. Required to generate
-- forward references and statically allocate the table. For primary
-- dispatch tables Index is 0; for secondary dispatch tables the value
-- of index must match the Suffix_Index value assigned to the table by
-- Make_Tags when generating its unique external name, and it is used to
-- retrieve from the Dispatch_Table_Wrappers list associated with Typ
-- the external name generated by Import_DT.
procedure Make_Secondary_DT
(Typ : Entity_Id;
Iface : Entity_Id;
Iface_Comp : Node_Id;
Suffix_Index : Int;
Num_Iface_Prims : Nat;
Iface_DT_Ptr : Entity_Id;
Predef_Prims_Ptr : Entity_Id;
Build_Thunks : Boolean;
Result : List_Id);
-- Ada 2005 (AI-251): Expand the declarations for a Secondary Dispatch
-- Table of Typ associated with Iface. Each abstract interface of Typ
-- has two secondary dispatch tables: one containing pointers to thunks
-- and another containing pointers to the primitives covering the
-- interface primitives. The former secondary table is generated when
-- Build_Thunks is True, and provides common support for dispatching
-- calls through interface types; the latter secondary table is
-- generated when Build_Thunks is False, and provides support for
-- Generic Dispatching Constructors that dispatch calls through
-- interface types. When constructing this latter table the value of
-- Suffix_Index is -1 to indicate that there is no need to export such
-- table when building statically allocated dispatch tables; a positive
-- value of Suffix_Index must match the Suffix_Index value assigned to
-- this secondary dispatch table by Make_Tags when its unique external
-- name was generated.
function Number_Of_Predefined_Prims (Typ : Entity_Id) return Nat;
-- Returns the number of predefined primitives of Typ
------------------------------
-- Check_Premature_Freezing --
------------------------------
procedure Check_Premature_Freezing
(Subp : Entity_Id;
Tagged_Type : Entity_Id;
Typ : Entity_Id)
is
Comp : Entity_Id;
function Is_Actual_For_Formal_Incomplete_Type
(T : Entity_Id) return Boolean;
-- In Ada 2012, if a nested generic has an incomplete formal type,
-- the actual may be (and usually is) a private type whose completion
-- appears later. It is safe to build the dispatch table in this
-- case, gigi will have full views available.
------------------------------------------
-- Is_Actual_For_Formal_Incomplete_Type --
------------------------------------------
function Is_Actual_For_Formal_Incomplete_Type
(T : Entity_Id) return Boolean
is
Gen_Par : Entity_Id;
F : Node_Id;
begin
if not Is_Generic_Instance (Current_Scope)
or else not Used_As_Generic_Actual (T)
then
return False;
else
Gen_Par := Generic_Parent (Parent (Current_Scope));
end if;
F :=
First
(Generic_Formal_Declarations
(Unit_Declaration_Node (Gen_Par)));
while Present (F) loop
if Ekind (Defining_Identifier (F)) = E_Incomplete_Type then
return True;
end if;
Next (F);
end loop;
return False;
end Is_Actual_For_Formal_Incomplete_Type;
-- Start of processing for Check_Premature_Freezing
begin
-- Note that if the type is a (subtype of) a generic actual, the
-- actual will have been frozen by the instantiation.
if Present (N)
and then Is_Private_Type (Typ)
and then No (Full_View (Typ))
and then not Is_Generic_Type (Typ)
and then not Is_Tagged_Type (Typ)
and then not Is_Frozen (Typ)
and then not Is_Generic_Actual_Type (Typ)
then
Error_Msg_Sloc := Sloc (Subp);
Error_Msg_NE
("declaration must appear after completion of type &", N, Typ);
Error_Msg_NE
("\which is an untagged type in the profile of "
& "primitive operation & declared#", N, Subp);
else
Comp := Private_Component (Typ);
if not Is_Tagged_Type (Typ)
and then Present (Comp)
and then not Is_Frozen (Comp)
and then not Is_Actual_For_Formal_Incomplete_Type (Comp)
then
Error_Msg_Sloc := Sloc (Subp);
Error_Msg_Node_2 := Subp;
Error_Msg_Name_1 := Chars (Tagged_Type);
Error_Msg_NE
("declaration must appear after completion of type &",
N, Comp);
Error_Msg_NE
("\which is a component of untagged type& in the profile "
& "of primitive & of type % that is frozen by the "
& "declaration ", N, Typ);
end if;
end if;
end Check_Premature_Freezing;
---------------
-- Export_DT --
---------------
procedure Export_DT (Typ : Entity_Id; DT : Entity_Id; Index : Nat := 0)
is
Count : Nat;
Elmt : Elmt_Id;
begin
Set_Is_Statically_Allocated (DT);
Set_Is_True_Constant (DT);
Set_Is_Exported (DT);
Count := 0;
Elmt := First_Elmt (Dispatch_Table_Wrappers (Typ));
while Count /= Index loop
Next_Elmt (Elmt);
Count := Count + 1;
end loop;
pragma Assert (Related_Type (Node (Elmt)) = Typ);
Get_External_Name (Node (Elmt));
Set_Interface_Name (DT,
Make_String_Literal (Loc,
Strval => String_From_Name_Buffer));
-- Ensure proper Sprint output of this implicit importation
Set_Is_Internal (DT);
Set_Is_Public (DT);
end Export_DT;
-----------------------
-- Make_Secondary_DT --
-----------------------
procedure Make_Secondary_DT
(Typ : Entity_Id;
Iface : Entity_Id;
Iface_Comp : Node_Id;
Suffix_Index : Int;
Num_Iface_Prims : Nat;
Iface_DT_Ptr : Entity_Id;
Predef_Prims_Ptr : Entity_Id;
Build_Thunks : Boolean;
Result : List_Id)
is
Loc : constant Source_Ptr := Sloc (Typ);
Exporting_Table : constant Boolean :=
Building_Static_DT (Typ)
and then Suffix_Index > 0;
Iface_DT : constant Entity_Id := Make_Temporary (Loc, 'T');
Predef_Prims : constant Entity_Id := Make_Temporary (Loc, 'R');
DT_Constr_List : List_Id;
DT_Aggr_List : List_Id;
Empty_DT : Boolean := False;
Nb_Prim : Nat;
New_Node : Node_Id;
OSD : Entity_Id;
OSD_Aggr_List : List_Id;
Prim : Entity_Id;
Prim_Elmt : Elmt_Id;
Prim_Ops_Aggr_List : List_Id;
begin
-- Handle cases in which we do not generate statically allocated
-- dispatch tables.
if not Building_Static_DT (Typ) then
Set_Ekind (Predef_Prims, E_Variable);
Set_Ekind (Iface_DT, E_Variable);
-- Statically allocated dispatch tables and related entities are
-- constants.
else
Set_Ekind (Predef_Prims, E_Constant);
Set_Is_Statically_Allocated (Predef_Prims);
Set_Is_True_Constant (Predef_Prims);
Set_Ekind (Iface_DT, E_Constant);
Set_Is_Statically_Allocated (Iface_DT);
Set_Is_True_Constant (Iface_DT);
end if;
-- Calculate the number of slots of the dispatch table. If the number
-- of primitives of Typ is 0 we reserve a dummy single entry for its
-- DT because at run time the pointer to this dummy entry will be
-- used as the tag.
if Num_Iface_Prims = 0 then
Empty_DT := True;
Nb_Prim := 1;
else
Nb_Prim := Num_Iface_Prims;
end if;
-- Generate:
-- Predef_Prims : Address_Array (1 .. Default_Prim_Ops_Count) :=
-- (predef-prim-op-thunk-1'address,
-- predef-prim-op-thunk-2'address,
-- ...
-- predef-prim-op-thunk-n'address);
-- Create the thunks associated with the predefined primitives and
-- save their entity to fill the aggregate.
declare
Nb_P_Prims : constant Nat := Number_Of_Predefined_Prims (Typ);
Prim_Table : array (Nat range 1 .. Nb_P_Prims) of Entity_Id;
Decl : Node_Id;
Thunk_Id : Entity_Id;
Thunk_Code : Node_Id;
begin
Prim_Ops_Aggr_List := New_List;
Prim_Table := (others => Empty);
if Building_Static_DT (Typ) then
Prim_Elmt := First_Elmt (Primitive_Operations (Typ));
while Present (Prim_Elmt) loop
Prim := Node (Prim_Elmt);
if Is_Predefined_Dispatching_Operation (Prim)
and then not Is_Abstract_Subprogram (Prim)
and then not Is_Eliminated (Prim)
and then not Generate_SCIL
and then not Present (Prim_Table
(UI_To_Int (DT_Position (Prim))))
then
if not Build_Thunks then
Prim_Table (UI_To_Int (DT_Position (Prim))) :=
Alias (Prim);
else
Expand_Interface_Thunk
(Prim, Thunk_Id, Thunk_Code, Iface);
if Present (Thunk_Id) then
Append_To (Result, Thunk_Code);
Prim_Table (UI_To_Int (DT_Position (Prim))) :=
Thunk_Id;
end if;
end if;
end if;
Next_Elmt (Prim_Elmt);
end loop;
end if;
for J in Prim_Table'Range loop
if Present (Prim_Table (J)) then
New_Node :=
Unchecked_Convert_To (RTE (RE_Prim_Ptr),
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Prim_Table (J), Loc),
Attribute_Name => Name_Unrestricted_Access));
else
New_Node := Make_Null (Loc);
end if;
Append_To (Prim_Ops_Aggr_List, New_Node);
end loop;
New_Node :=
Make_Aggregate (Loc, Expressions => Prim_Ops_Aggr_List);
-- Remember aggregates initializing dispatch tables
Append_Elmt (New_Node, DT_Aggr);
Decl :=
Make_Subtype_Declaration (Loc,
Defining_Identifier => Make_Temporary (Loc, 'S'),
Subtype_Indication =>
New_Occurrence_Of (RTE (RE_Address_Array), Loc));
Append_To (Result, Decl);
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => Predef_Prims,
Constant_Present => Building_Static_DT (Typ),
Aliased_Present => True,
Object_Definition => New_Occurrence_Of
(Defining_Identifier (Decl), Loc),
Expression => New_Node));
end;
-- Generate
-- OSD : Ada.Tags.Object_Specific_Data (Nb_Prims) :=
-- (OSD_Table => (1 => <value>,
-- ...
-- N => <value>));
-- for OSD'Alignment use Address'Alignment;
-- Iface_DT : Dispatch_Table (Nb_Prims) :=
-- ([ Signature => <sig-value> ],
-- Tag_Kind => <tag_kind-value>,
-- Predef_Prims => Predef_Prims'Address,
-- Offset_To_Top => 0,
-- OSD => OSD'Address,
-- Prims_Ptr => (prim-op-1'address,
-- prim-op-2'address,
-- ...
-- prim-op-n'address));
-- Stage 3: Initialize the discriminant and the record components
DT_Constr_List := New_List;
DT_Aggr_List := New_List;
-- Nb_Prim
Append_To (DT_Constr_List, Make_Integer_Literal (Loc, Nb_Prim));
Append_To (DT_Aggr_List, Make_Integer_Literal (Loc, Nb_Prim));
-- Signature
if RTE_Record_Component_Available (RE_Signature) then
Append_To (DT_Aggr_List,
New_Occurrence_Of (RTE (RE_Secondary_DT), Loc));
end if;
-- Tag_Kind
if RTE_Record_Component_Available (RE_Tag_Kind) then
Append_To (DT_Aggr_List, Tagged_Kind (Typ));
end if;
-- Predef_Prims
Append_To (DT_Aggr_List,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Predef_Prims, Loc),
Attribute_Name => Name_Address));
-- Interface component located at variable offset; the value of
-- Offset_To_Top will be set by the init subprogram.
if No (Dummy_Object)
or else Is_Variable_Size_Record (Etype (Scope (Iface_Comp)))
then
Append_To (DT_Aggr_List, Make_Integer_Literal (Loc, 0));
-- Interface component located at fixed offset
else
Append_To (DT_Aggr_List,
Make_Op_Minus (Loc,
Make_Attribute_Reference (Loc,
Prefix =>
Make_Selected_Component (Loc,
Prefix =>
New_Occurrence_Of (Dummy_Object, Loc),
Selector_Name =>
New_Occurrence_Of (Iface_Comp, Loc)),
Attribute_Name => Name_Position)));
end if;
-- Generate the Object Specific Data table required to dispatch calls
-- through synchronized interfaces.
if Empty_DT
or else Is_Abstract_Type (Typ)
or else Is_Controlled (Typ)
or else Restriction_Active (No_Dispatching_Calls)
or else not Is_Limited_Type (Typ)
or else not Has_Interfaces (Typ)
or else not Build_Thunks
or else not RTE_Record_Component_Available (RE_OSD_Table)
then
-- No OSD table required
Append_To (DT_Aggr_List,
New_Occurrence_Of (RTE (RE_Null_Address), Loc));
else
OSD_Aggr_List := New_List;
declare
Prim_Table : array (Nat range 1 .. Nb_Prim) of Entity_Id;
Prim : Entity_Id;
Prim_Alias : Entity_Id;
Prim_Elmt : Elmt_Id;
E : Entity_Id;
Count : Nat := 0;
Pos : Nat;
begin
Prim_Table := (others => Empty);
Prim_Alias := Empty;
Prim_Elmt := First_Elmt (Primitive_Operations (Typ));
while Present (Prim_Elmt) loop
Prim := Node (Prim_Elmt);
if Present (Interface_Alias (Prim))
and then Find_Dispatching_Type
(Interface_Alias (Prim)) = Iface
then
Prim_Alias := Interface_Alias (Prim);
E := Ultimate_Alias (Prim);
Pos := UI_To_Int (DT_Position (Prim_Alias));
if Present (Prim_Table (Pos)) then
pragma Assert (Prim_Table (Pos) = E);
null;
else
Prim_Table (Pos) := E;
Append_To (OSD_Aggr_List,
Make_Component_Association (Loc,
Choices => New_List (
Make_Integer_Literal (Loc,
DT_Position (Prim_Alias))),
Expression =>
Make_Integer_Literal (Loc,
DT_Position (Alias (Prim)))));
Count := Count + 1;
end if;
end if;
Next_Elmt (Prim_Elmt);
end loop;
pragma Assert (Count = Nb_Prim);
end;
OSD := Make_Temporary (Loc, 'I');
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => OSD,
Constant_Present => True,
Object_Definition =>
Make_Subtype_Indication (Loc,
Subtype_Mark =>
New_Occurrence_Of (RTE (RE_Object_Specific_Data), Loc),
Constraint =>
Make_Index_Or_Discriminant_Constraint (Loc,
Constraints => New_List (
Make_Integer_Literal (Loc, Nb_Prim)))),
Expression =>
Make_Aggregate (Loc,
Component_Associations => New_List (
Make_Component_Association (Loc,
Choices => New_List (
New_Occurrence_Of
(RTE_Record_Component (RE_OSD_Num_Prims), Loc)),
Expression =>
Make_Integer_Literal (Loc, Nb_Prim)),
Make_Component_Association (Loc,
Choices => New_List (
New_Occurrence_Of
(RTE_Record_Component (RE_OSD_Table), Loc)),
Expression => Make_Aggregate (Loc,
Component_Associations => OSD_Aggr_List))))));
Append_To (Result,
Make_Attribute_Definition_Clause (Loc,
Name => New_Occurrence_Of (OSD, Loc),
Chars => Name_Alignment,
Expression =>
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of (RTE (RE_Integer_Address), Loc),
Attribute_Name => Name_Alignment)));
-- In secondary dispatch tables the Typeinfo component contains
-- the address of the Object Specific Data (see a-tags.ads).
Append_To (DT_Aggr_List,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (OSD, Loc),
Attribute_Name => Name_Address));
end if;
-- Initialize the table of primitive operations
Prim_Ops_Aggr_List := New_List;
if Empty_DT then
Append_To (Prim_Ops_Aggr_List, Make_Null (Loc));
elsif Is_Abstract_Type (Typ)
or else not Building_Static_DT (Typ)
then
for J in 1 .. Nb_Prim loop
Append_To (Prim_Ops_Aggr_List, Make_Null (Loc));
end loop;
else
declare
CPP_Nb_Prims : constant Nat := CPP_Num_Prims (Typ);
E : Entity_Id;
Prim_Pos : Nat;
Prim_Table : array (Nat range 1 .. Nb_Prim) of Entity_Id;
Thunk_Code : Node_Id;
Thunk_Id : Entity_Id;
begin
Prim_Table := (others => Empty);
Prim_Elmt := First_Elmt (Primitive_Operations (Typ));
while Present (Prim_Elmt) loop
Prim := Node (Prim_Elmt);
E := Ultimate_Alias (Prim);
Prim_Pos := UI_To_Int (DT_Position (E));
-- Do not reference predefined primitives because they are
-- located in a separate dispatch table; skip abstract and
-- eliminated primitives; skip primitives located in the C++
-- part of the dispatch table because their slot is set by
-- the IC routine.
if not Is_Predefined_Dispatching_Operation (Prim)
and then Present (Interface_Alias (Prim))
and then not Is_Abstract_Subprogram (Alias (Prim))
and then not Is_Eliminated (Alias (Prim))
and then (not Is_CPP_Class (Root_Type (Typ))
or else Prim_Pos > CPP_Nb_Prims)
and then Find_Dispatching_Type
(Interface_Alias (Prim)) = Iface
-- Generate the code of the thunk only if the abstract
-- interface type is not an immediate ancestor of
-- Tagged_Type. Otherwise the DT associated with the
-- interface is the primary DT.
and then not Is_Ancestor (Iface, Typ,
Use_Full_View => True)
then
if not Build_Thunks then
Prim_Pos :=
UI_To_Int (DT_Position (Interface_Alias (Prim)));
Prim_Table (Prim_Pos) := Alias (Prim);
else
Expand_Interface_Thunk
(Prim, Thunk_Id, Thunk_Code, Iface);
if Present (Thunk_Id) then
Prim_Pos :=
UI_To_Int (DT_Position (Interface_Alias (Prim)));
Prim_Table (Prim_Pos) := Thunk_Id;
Append_To (Result, Thunk_Code);
end if;
end if;
end if;
Next_Elmt (Prim_Elmt);
end loop;
for J in Prim_Table'Range loop
if Present (Prim_Table (J)) then
New_Node :=
Unchecked_Convert_To (RTE (RE_Prim_Ptr),
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Prim_Table (J), Loc),
Attribute_Name => Name_Unrestricted_Access));
else
New_Node := Make_Null (Loc);
end if;
Append_To (Prim_Ops_Aggr_List, New_Node);
end loop;
end;
end if;
New_Node :=
Make_Aggregate (Loc,
Expressions => Prim_Ops_Aggr_List);
Append_To (DT_Aggr_List, New_Node);
-- Remember aggregates initializing dispatch tables
Append_Elmt (New_Node, DT_Aggr);
-- Note: Secondary dispatch tables are declared constant only if
-- we can compute their offset field by means of the extra dummy
-- object; otherwise they cannot be declared constant and the
-- Offset_To_Top component is initialized by the IP routine.
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => Iface_DT,
Aliased_Present => True,
Constant_Present => Building_Static_Secondary_DT (Typ),
Object_Definition =>
Make_Subtype_Indication (Loc,
Subtype_Mark => New_Occurrence_Of
(RTE (RE_Dispatch_Table_Wrapper), Loc),
Constraint => Make_Index_Or_Discriminant_Constraint (Loc,
Constraints => DT_Constr_List)),
Expression =>
Make_Aggregate (Loc,
Expressions => DT_Aggr_List)));
if Exporting_Table then
Export_DT (Typ, Iface_DT, Suffix_Index);
-- Generate code to create the pointer to the dispatch table
-- Iface_DT_Ptr : Tag := Tag!(DT.Prims_Ptr'Address);
-- Note: This declaration is not added here if the table is exported
-- because in such case Make_Tags has already added this declaration.
else
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => Iface_DT_Ptr,
Constant_Present => True,
Object_Definition =>
New_Occurrence_Of (RTE (RE_Interface_Tag), Loc),
Expression =>
Unchecked_Convert_To (RTE (RE_Interface_Tag),
Make_Attribute_Reference (Loc,
Prefix =>
Make_Selected_Component (Loc,
Prefix => New_Occurrence_Of (Iface_DT, Loc),
Selector_Name =>
New_Occurrence_Of
(RTE_Record_Component (RE_Prims_Ptr), Loc)),
Attribute_Name => Name_Address))));
end if;
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => Predef_Prims_Ptr,
Constant_Present => True,
Object_Definition =>
New_Occurrence_Of (RTE (RE_Address), Loc),
Expression =>
Make_Attribute_Reference (Loc,
Prefix =>
Make_Selected_Component (Loc,
Prefix => New_Occurrence_Of (Iface_DT, Loc),
Selector_Name =>
New_Occurrence_Of
(RTE_Record_Component (RE_Predef_Prims), Loc)),
Attribute_Name => Name_Address)));
-- Remember entities containing dispatch tables
Append_Elmt (Predef_Prims, DT_Decl);
Append_Elmt (Iface_DT, DT_Decl);
end Make_Secondary_DT;
--------------------------------
-- Number_Of_Predefined_Prims --
--------------------------------
function Number_Of_Predefined_Prims (Typ : Entity_Id) return Nat is
Nb_Predef_Prims : Nat := 0;
begin
if not Generate_SCIL then
declare
Prim : Entity_Id;
Prim_Elmt : Elmt_Id;
Pos : Nat;
begin
Prim_Elmt := First_Elmt (Primitive_Operations (Typ));
while Present (Prim_Elmt) loop
Prim := Node (Prim_Elmt);
if Is_Predefined_Dispatching_Operation (Prim)
and then not Is_Abstract_Subprogram (Prim)
then
Pos := UI_To_Int (DT_Position (Prim));
if Pos > Nb_Predef_Prims then
Nb_Predef_Prims := Pos;
end if;
end if;
Next_Elmt (Prim_Elmt);
end loop;
end;
end if;
pragma Assert (Nb_Predef_Prims <= Max_Predef_Prims);
return Nb_Predef_Prims;
end Number_Of_Predefined_Prims;
-- Local variables
Elab_Code : constant List_Id := New_List;
Result : constant List_Id := New_List;
Tname : constant Name_Id := Chars (Typ);
-- When pragmas Discard_Names and No_Tagged_Streams simultaneously apply
-- we initialize the Expanded_Name and the External_Tag of this tagged
-- type with an empty string. This is useful to avoid exposing entity
-- names at binary level. It can be done when both pragmas apply because
-- (1) Discard_Names allows initializing Expanded_Name with an
-- implementation defined value (Ada RM Section C.5 (7/2)).
-- (2) External_Tag (combined with Internal_Tag) is used for object
-- streaming and No_Tagged_Streams inhibits the generation of
-- streams.
Discard_Names : constant Boolean :=
Present (No_Tagged_Streams_Pragma (Typ))
and then (Global_Discard_Names
or else Einfo.Discard_Names (Typ));
-- The following name entries are used by Make_DT to generate a number
-- of entities related to a tagged type. These entities may be generated
-- in a scope other than that of the tagged type declaration, and if
-- the entities for two tagged types with the same name happen to be
-- generated in the same scope, we have to take care to use different
-- names. This is achieved by means of a unique serial number appended
-- to each generated entity name.
Name_DT : constant Name_Id :=
New_External_Name (Tname, 'T', Suffix_Index => -1);
Name_Exname : constant Name_Id :=
New_External_Name (Tname, 'E', Suffix_Index => -1);
Name_HT_Link : constant Name_Id :=
New_External_Name (Tname, 'H', Suffix_Index => -1);
Name_Predef_Prims : constant Name_Id :=
New_External_Name (Tname, 'R', Suffix_Index => -1);
Name_SSD : constant Name_Id :=
New_External_Name (Tname, 'S', Suffix_Index => -1);
Name_TSD : constant Name_Id :=
New_External_Name (Tname, 'B', Suffix_Index => -1);
Saved_GM : constant Ghost_Mode_Type := Ghost_Mode;
Saved_IGR : constant Node_Id := Ignored_Ghost_Region;
-- Save the Ghost-related attributes to restore on exit
AI : Elmt_Id;
AI_Tag_Elmt : Elmt_Id;
AI_Tag_Comp : Elmt_Id;
DT : Entity_Id;
DT_Aggr_List : List_Id;
DT_Constr_List : List_Id;
DT_Ptr : Entity_Id;
Exname : Entity_Id;
HT_Link : Entity_Id;
ITable : Node_Id;
I_Depth : Nat := 0;
Iface_Table_Node : Node_Id;
Name_ITable : Name_Id;
Nb_Prim : Nat := 0;
New_Node : Node_Id;
Num_Ifaces : Nat := 0;
Parent_Typ : Entity_Id;
Predef_Prims : Entity_Id;
Prim : Entity_Id;
Prim_Elmt : Elmt_Id;
Prim_Ops_Aggr_List : List_Id;
SSD : Entity_Id;
Suffix_Index : Int;
Typ_Comps : Elist_Id;
Typ_Ifaces : Elist_Id;
TSD : Entity_Id;
TSD_Aggr_List : List_Id;
TSD_Tags_List : List_Id;
-- Start of processing for Make_DT
begin
pragma Assert (Is_Frozen (Typ));
-- The tagged type being processed may be subject to pragma Ghost. Set
-- the mode now to ensure that any nodes generated during dispatch table
-- creation are properly marked as Ghost.
Set_Ghost_Mode (Typ);
-- Handle cases in which there is no need to build the dispatch table
if Has_Dispatch_Table (Typ)
or else No (Access_Disp_Table (Typ))
or else Is_CPP_Class (Typ)
then
goto Leave;
elsif No_Run_Time_Mode then
Error_Msg_CRT ("tagged types", Typ);
goto Leave;
elsif not RTE_Available (RE_Tag) then
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier =>
Node (First_Elmt (Access_Disp_Table (Typ))),
Object_Definition => New_Occurrence_Of (RTE (RE_Tag), Loc),
Constant_Present => True,
Expression =>
Unchecked_Convert_To (RTE (RE_Tag),
New_Occurrence_Of (RTE (RE_Null_Address), Loc))));
Analyze_List (Result, Suppress => All_Checks);
Error_Msg_CRT ("tagged types", Typ);
goto Leave;
end if;
-- Ensure that the value of Max_Predef_Prims defined in a-tags is
-- correct. Valid values are 10 under configurable runtime or 16
-- with full runtime.
if RTE_Available (RE_Interface_Data) then
if Max_Predef_Prims /= 16 then
Error_Msg_N ("run-time library configuration error", Typ);
goto Leave;
end if;
else
if Max_Predef_Prims /= 10 then
Error_Msg_N ("run-time library configuration error", Typ);
Error_Msg_CRT ("tagged types", Typ);
goto Leave;
end if;
end if;
DT := Make_Defining_Identifier (Loc, Name_DT);
Exname := Make_Defining_Identifier (Loc, Name_Exname);
HT_Link := Make_Defining_Identifier (Loc, Name_HT_Link);
Predef_Prims := Make_Defining_Identifier (Loc, Name_Predef_Prims);
SSD := Make_Defining_Identifier (Loc, Name_SSD);
TSD := Make_Defining_Identifier (Loc, Name_TSD);
-- Initialize Parent_Typ handling private types
Parent_Typ := Etype (Typ);
if Present (Full_View (Parent_Typ)) then
Parent_Typ := Full_View (Parent_Typ);
end if;
-- Ensure that all the primitives are frozen. This is only required when
-- building static dispatch tables --- the primitives must be frozen to
-- be referenced (otherwise we have problems with the backend). It is
-- not a requirement with nonstatic dispatch tables because in this case
-- we generate now an empty dispatch table; the extra code required to
-- register the primitives in the slots will be generated later --- when
-- each primitive is frozen (see Freeze_Subprogram).
if Building_Static_DT (Typ) then
declare
Saved_FLLTT : constant Boolean :=
Freezing_Library_Level_Tagged_Type;
Formal : Entity_Id;
Frnodes : List_Id;
Prim : Entity_Id;
Prim_Elmt : Elmt_Id;
begin
Freezing_Library_Level_Tagged_Type := True;
Prim_Elmt := First_Elmt (Primitive_Operations (Typ));
while Present (Prim_Elmt) loop
Prim := Node (Prim_Elmt);
Frnodes := Freeze_Entity (Prim, Typ);
-- We disable this check for abstract subprograms, given that
-- they cannot be called directly and thus the state of their
-- untagged formals is of no concern. The RM is unclear in any
-- case concerning the need for this check, and this topic may
-- go back to the ARG.
if not Is_Abstract_Subprogram (Prim) then
Formal := First_Formal (Prim);
while Present (Formal) loop
Check_Premature_Freezing (Prim, Typ, Etype (Formal));
Next_Formal (Formal);
end loop;
Check_Premature_Freezing (Prim, Typ, Etype (Prim));
end if;
if Present (Frnodes) then
Append_List_To (Result, Frnodes);
end if;
Next_Elmt (Prim_Elmt);
end loop;
Freezing_Library_Level_Tagged_Type := Saved_FLLTT;
end;
end if;
if not Is_Interface (Typ) and then Has_Interfaces (Typ) then
declare
Cannot_Have_Null_Disc : Boolean := False;
Dummy_Object_Typ : constant Entity_Id := Typ;
Name_Dummy_Object : constant Name_Id :=
New_External_Name (Tname,
'P', Suffix_Index => -1);
begin
Dummy_Object := Make_Defining_Identifier (Loc, Name_Dummy_Object);
-- Define the extra object imported and constant to avoid linker
-- errors (since this object is never declared). Required because
-- we implement RM 13.3(19) for exported and imported (variable)
-- objects by making them volatile.
Set_Is_Imported (Dummy_Object);
Set_Ekind (Dummy_Object, E_Constant);
Set_Is_True_Constant (Dummy_Object);
Set_Related_Type (Dummy_Object, Typ);
-- The scope must be set now to call Get_External_Name
Set_Scope (Dummy_Object, Current_Scope);
Get_External_Name (Dummy_Object);
Set_Interface_Name (Dummy_Object,
Make_String_Literal (Loc, Strval => String_From_Name_Buffer));
-- Ensure proper Sprint output of this implicit importation
Set_Is_Internal (Dummy_Object);
if not Has_Discriminants (Dummy_Object_Typ) then
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => Dummy_Object,
Constant_Present => True,
Object_Definition => New_Occurrence_Of
(Dummy_Object_Typ, Loc)));
else
declare
Constr_List : constant List_Id := New_List;
Discrim : Node_Id;
begin
Discrim := First_Discriminant (Dummy_Object_Typ);
while Present (Discrim) loop
if Is_Discrete_Type (Etype (Discrim)) then
Append_To (Constr_List,
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of (Etype (Discrim), Loc),
Attribute_Name => Name_First));
else
pragma Assert (Is_Access_Type (Etype (Discrim)));
Cannot_Have_Null_Disc :=
Cannot_Have_Null_Disc
or else Can_Never_Be_Null (Etype (Discrim));
Append_To (Constr_List, Make_Null (Loc));
end if;
Next_Discriminant (Discrim);
end loop;
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => Dummy_Object,
Constant_Present => True,
Object_Definition =>
Make_Subtype_Indication (Loc,
Subtype_Mark =>
New_Occurrence_Of (Dummy_Object_Typ, Loc),
Constraint =>
Make_Index_Or_Discriminant_Constraint (Loc,
Constraints => Constr_List))));
end;
end if;
-- Given that the dummy object will not be declared at run time,
-- analyze its declaration with expansion disabled and warnings
-- and error messages ignored.
Expander_Mode_Save_And_Set (False);
Ignore_Errors_Enable := Ignore_Errors_Enable + 1;
Analyze (Last (Result), Suppress => All_Checks);
Ignore_Errors_Enable := Ignore_Errors_Enable - 1;
Expander_Mode_Restore;
end;
end if;
-- Ada 2005 (AI-251): Build the secondary dispatch tables
if Has_Interfaces (Typ) then
Collect_Interface_Components (Typ, Typ_Comps);
-- Each secondary dispatch table is assigned an unique positive
-- suffix index; such value also corresponds with the location of
-- its entity in the Dispatch_Table_Wrappers list (see Make_Tags).
-- Note: This value must be kept sync with the Suffix_Index values
-- generated by Make_Tags
Suffix_Index := 1;
AI_Tag_Elmt :=
Next_Elmt (Next_Elmt (First_Elmt (Access_Disp_Table (Typ))));
AI_Tag_Comp := First_Elmt (Typ_Comps);
while Present (AI_Tag_Comp) loop
pragma Assert (Has_Suffix (Node (AI_Tag_Elmt), 'P'));
-- Build the secondary table containing pointers to thunks
Make_Secondary_DT
(Typ => Typ,
Iface =>
Base_Type (Related_Type (Node (AI_Tag_Comp))),
Iface_Comp => Node (AI_Tag_Comp),
Suffix_Index => Suffix_Index,
Num_Iface_Prims =>
UI_To_Int (DT_Entry_Count (Node (AI_Tag_Comp))),
Iface_DT_Ptr => Node (AI_Tag_Elmt),
Predef_Prims_Ptr => Node (Next_Elmt (AI_Tag_Elmt)),
Build_Thunks => True,
Result => Result);
-- Skip secondary dispatch table referencing thunks to predefined
-- primitives.
Next_Elmt (AI_Tag_Elmt);
pragma Assert (Has_Suffix (Node (AI_Tag_Elmt), 'Y'));
-- Secondary dispatch table referencing user-defined primitives
-- covered by this interface.
Next_Elmt (AI_Tag_Elmt);
pragma Assert (Has_Suffix (Node (AI_Tag_Elmt), 'D'));
-- Build the secondary table containing pointers to primitives
-- (used to give support to Generic Dispatching Constructors).
Make_Secondary_DT
(Typ => Typ,
Iface => Base_Type
(Related_Type (Node (AI_Tag_Comp))),
Iface_Comp => Node (AI_Tag_Comp),
Suffix_Index => -1,
Num_Iface_Prims => UI_To_Int
(DT_Entry_Count (Node (AI_Tag_Comp))),
Iface_DT_Ptr => Node (AI_Tag_Elmt),
Predef_Prims_Ptr => Node (Next_Elmt (AI_Tag_Elmt)),
Build_Thunks => False,
Result => Result);
-- Skip secondary dispatch table referencing predefined primitives
Next_Elmt (AI_Tag_Elmt);
pragma Assert (Has_Suffix (Node (AI_Tag_Elmt), 'Z'));
Suffix_Index := Suffix_Index + 1;
Next_Elmt (AI_Tag_Elmt);
Next_Elmt (AI_Tag_Comp);
end loop;
end if;
-- Get the _tag entity and number of primitives of its dispatch table
DT_Ptr := Node (First_Elmt (Access_Disp_Table (Typ)));
Nb_Prim := UI_To_Int (DT_Entry_Count (First_Tag_Component (Typ)));
if Generate_SCIL then
Nb_Prim := 0;
end if;
Set_Is_Statically_Allocated (DT, Is_Library_Level_Tagged_Type (Typ));
Set_Is_Statically_Allocated (SSD, Is_Library_Level_Tagged_Type (Typ));
Set_Is_Statically_Allocated (TSD, Is_Library_Level_Tagged_Type (Typ));
Set_Is_Statically_Allocated (Predef_Prims,
Is_Library_Level_Tagged_Type (Typ));
-- In case of locally defined tagged type we declare the object
-- containing the dispatch table by means of a variable. Its
-- initialization is done later by means of an assignment. This is
-- required to generate its External_Tag.
if not Building_Static_DT (Typ) then
-- Generate:
-- DT : No_Dispatch_Table_Wrapper;
-- DT_Ptr : Tag := !Tag (DT.NDT_Prims_Ptr'Address);
if not Has_DT (Typ) then
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => DT,
Aliased_Present => True,
Constant_Present => False,
Object_Definition =>
New_Occurrence_Of
(RTE (RE_No_Dispatch_Table_Wrapper), Loc)));
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => DT_Ptr,
Object_Definition => New_Occurrence_Of (RTE (RE_Tag), Loc),
Constant_Present => True,
Expression =>
Unchecked_Convert_To (RTE (RE_Tag),
Make_Attribute_Reference (Loc,
Prefix =>
Make_Selected_Component (Loc,
Prefix => New_Occurrence_Of (DT, Loc),
Selector_Name =>
New_Occurrence_Of
(RTE_Record_Component (RE_NDT_Prims_Ptr), Loc)),
Attribute_Name => Name_Address))));
Set_Is_Statically_Allocated (DT_Ptr,
Is_Library_Level_Tagged_Type (Typ));
-- Generate the SCIL node for the previous object declaration
-- because it has a tag initialization.
if Generate_SCIL then
New_Node :=
Make_SCIL_Dispatch_Table_Tag_Init (Sloc (Last (Result)));
Set_SCIL_Entity (New_Node, Typ);
Set_SCIL_Node (Last (Result), New_Node);
goto Leave_SCIL;
-- Gnat2scil has its own implementation of dispatch tables,
-- different than what is being implemented here. Generating
-- further dispatch table initialization code would just
-- cause gnat2scil to generate useless Scil which CodePeer
-- would waste time and space analyzing, so we skip it.
end if;
-- Generate:
-- DT : Dispatch_Table_Wrapper (Nb_Prim);
-- DT_Ptr : Tag := !Tag (DT.Prims_Ptr'Address);
else
-- If the tagged type has no primitives we add a dummy slot
-- whose address will be the tag of this type.
if Nb_Prim = 0 then
DT_Constr_List :=
New_List (Make_Integer_Literal (Loc, 1));
else
DT_Constr_List :=
New_List (Make_Integer_Literal (Loc, Nb_Prim));
end if;
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => DT,
Aliased_Present => True,
Constant_Present => False,
Object_Definition =>
Make_Subtype_Indication (Loc,
Subtype_Mark =>
New_Occurrence_Of (RTE (RE_Dispatch_Table_Wrapper), Loc),
Constraint =>
Make_Index_Or_Discriminant_Constraint (Loc,
Constraints => DT_Constr_List))));
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => DT_Ptr,
Object_Definition => New_Occurrence_Of (RTE (RE_Tag), Loc),
Constant_Present => True,
Expression =>
Unchecked_Convert_To (RTE (RE_Tag),
Make_Attribute_Reference (Loc,
Prefix =>
Make_Selected_Component (Loc,
Prefix => New_Occurrence_Of (DT, Loc),
Selector_Name =>
New_Occurrence_Of
(RTE_Record_Component (RE_Prims_Ptr), Loc)),
Attribute_Name => Name_Address))));
Set_Is_Statically_Allocated (DT_Ptr,
Is_Library_Level_Tagged_Type (Typ));
-- Generate the SCIL node for the previous object declaration
-- because it has a tag initialization.
if Generate_SCIL then
New_Node :=
Make_SCIL_Dispatch_Table_Tag_Init (Sloc (Last (Result)));
Set_SCIL_Entity (New_Node, Typ);
Set_SCIL_Node (Last (Result), New_Node);
goto Leave_SCIL;
-- Gnat2scil has its own implementation of dispatch tables,
-- different than what is being implemented here. Generating
-- further dispatch table initialization code would just
-- cause gnat2scil to generate useless Scil which CodePeer
-- would waste time and space analyzing, so we skip it.
end if;
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier =>
Node (Next_Elmt (First_Elmt (Access_Disp_Table (Typ)))),
Constant_Present => True,
Object_Definition =>
New_Occurrence_Of (RTE (RE_Address), Loc),
Expression =>
Make_Attribute_Reference (Loc,
Prefix =>
Make_Selected_Component (Loc,
Prefix => New_Occurrence_Of (DT, Loc),
Selector_Name =>
New_Occurrence_Of
(RTE_Record_Component (RE_Predef_Prims), Loc)),
Attribute_Name => Name_Address)));
end if;
end if;
-- Generate: Expanded_Name : constant String := "";
if Discard_Names then
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => Exname,
Constant_Present => True,
Object_Definition => New_Occurrence_Of (Standard_String, Loc),
Expression =>
Make_String_Literal (Loc, "")));
-- Generate: Exname : constant String := full_qualified_name (typ);
-- The type itself may be an anonymous parent type, so use the first
-- subtype to have a user-recognizable name.
else
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => Exname,
Constant_Present => True,
Object_Definition => New_Occurrence_Of (Standard_String, Loc),
Expression =>
Make_String_Literal (Loc,
Fully_Qualified_Name_String (First_Subtype (Typ)))));
end if;
Set_Is_Statically_Allocated (Exname);
Set_Is_True_Constant (Exname);
-- Declare the object used by Ada.Tags.Register_Tag
if RTE_Available (RE_Register_Tag) then
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => HT_Link,
Object_Definition => New_Occurrence_Of (RTE (RE_Tag), Loc),
Expression => New_Occurrence_Of (RTE (RE_No_Tag), Loc)));
end if;
-- Generate code to create the storage for the type specific data object
-- with enough space to store the tags of the ancestors plus the tags
-- of all the implemented interfaces (as described in a-tags.adb).
-- TSD : Type_Specific_Data (I_Depth) :=
-- (Idepth => I_Depth,
-- Access_Level => Type_Access_Level (Typ),
-- Alignment => Typ'Alignment,
-- Expanded_Name => Cstring_Ptr!(Exname'Address))
-- External_Tag => Cstring_Ptr!(Exname'Address))
-- HT_Link => HT_Link'Address,
-- Transportable => <<boolean-value>>,
-- Is_Abstract => <<boolean-value>>,
-- Needs_Finalization => <<boolean-value>>,
-- [ Size_Func => Size_Prim'Access, ]
-- [ Interfaces_Table => <<access-value>>, ]
-- [ SSD => SSD_Table'Address ]
-- Tags_Table => (0 => null,
-- 1 => Parent'Tag
-- ...);
TSD_Aggr_List := New_List;
-- Idepth: Count ancestors to compute the inheritance depth. For private
-- extensions, always go to the full view in order to compute the real
-- inheritance depth.
declare
Current_Typ : Entity_Id;
Parent_Typ : Entity_Id;
begin
I_Depth := 0;
Current_Typ := Typ;
loop
Parent_Typ := Etype (Current_Typ);
if Is_Private_Type (Parent_Typ) then
Parent_Typ := Full_View (Base_Type (Parent_Typ));
end if;
exit when Parent_Typ = Current_Typ;
I_Depth := I_Depth + 1;
Current_Typ := Parent_Typ;
end loop;
end;
Append_To (TSD_Aggr_List,
Make_Integer_Literal (Loc, I_Depth));
-- Access_Level
Append_To (TSD_Aggr_List,
Make_Integer_Literal (Loc, Type_Access_Level (Typ)));
-- Alignment
-- For CPP types we cannot rely on the value of 'Alignment provided
-- by the backend to initialize this TSD field.
if Convention (Typ) = Convention_CPP
or else Is_CPP_Class (Root_Type (Typ))
then
Append_To (TSD_Aggr_List,
Make_Integer_Literal (Loc, 0));
else
Append_To (TSD_Aggr_List,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Typ, Loc),
Attribute_Name => Name_Alignment));
end if;
-- Expanded_Name
Append_To (TSD_Aggr_List,
Unchecked_Convert_To (RTE (RE_Cstring_Ptr),
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Exname, Loc),
Attribute_Name => Name_Address)));
-- External_Tag of a local tagged type
-- <typ>A : constant String :=
-- "Internal tag at 16#tag-addr#: <full-name-of-typ>";
-- The reason we generate this strange name is that we do not want to
-- enter local tagged types in the global hash table used to compute
-- the Internal_Tag attribute for two reasons:
-- 1. It is hard to avoid a tasking race condition for entering the
-- entry into the hash table.
-- 2. It would cause a storage leak, unless we rig up considerable
-- mechanism to remove the entry from the hash table on exit.
-- So what we do is to generate the above external tag name, where the
-- hex address is the address of the local dispatch table (i.e. exactly
-- the value we want if Internal_Tag is computed from this string).
-- Of course this value will only be valid if the tagged type is still
-- in scope, but it clearly must be erroneous to compute the internal
-- tag of a tagged type that is out of scope.
-- We don't do this processing if an explicit external tag has been
-- specified. That's an odd case for which we have already issued a
-- warning, where we will not be able to compute the internal tag.
if not Discard_Names
and then not Is_Library_Level_Entity (Typ)
and then not Has_External_Tag_Rep_Clause (Typ)
then
declare
Exname : constant Entity_Id :=
Make_Defining_Identifier (Loc,
Chars => New_External_Name (Tname, 'A'));
Full_Name : constant String_Id :=
Fully_Qualified_Name_String (First_Subtype (Typ));
Str1_Id : String_Id;
Str2_Id : String_Id;
begin
-- Generate:
-- Str1 = "Internal tag at 16#";
Start_String;
Store_String_Chars ("Internal tag at 16#");
Str1_Id := End_String;
-- Generate:
-- Str2 = "#: <type-full-name>";
Start_String;
Store_String_Chars ("#: ");
Store_String_Chars (Full_Name);
Str2_Id := End_String;
-- Generate:
-- Exname : constant String :=
-- Str1 & Address_Image (Tag) & Str2;
if RTE_Available (RE_Address_Image) then
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => Exname,
Constant_Present => True,
Object_Definition => New_Occurrence_Of
(Standard_String, Loc),
Expression =>
Make_Op_Concat (Loc,
Left_Opnd => Make_String_Literal (Loc, Str1_Id),
Right_Opnd =>
Make_Op_Concat (Loc,
Left_Opnd =>
Make_Function_Call (Loc,
Name =>
New_Occurrence_Of
(RTE (RE_Address_Image), Loc),
Parameter_Associations => New_List (
Unchecked_Convert_To (RTE (RE_Address),
New_Occurrence_Of (DT_Ptr, Loc)))),
Right_Opnd =>
Make_String_Literal (Loc, Str2_Id)))));
-- Generate:
-- Exname : constant String := Str1 & Str2;
else
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => Exname,
Constant_Present => True,
Object_Definition =>
New_Occurrence_Of (Standard_String, Loc),
Expression =>
Make_Op_Concat (Loc,
Left_Opnd => Make_String_Literal (Loc, Str1_Id),
Right_Opnd => Make_String_Literal (Loc, Str2_Id))));
end if;
New_Node :=
Unchecked_Convert_To (RTE (RE_Cstring_Ptr),
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Exname, Loc),
Attribute_Name => Name_Address));
end;
-- External tag of a library-level tagged type: Check for a definition
-- of External_Tag. The clause is considered only if it applies to this
-- specific tagged type, as opposed to one of its ancestors.
-- If the type is an unconstrained type extension, we are building the
-- dispatch table of its anonymous base type, so the external tag, if
-- any was specified, must be retrieved from the first subtype. Go to
-- the full view in case the clause is in the private part.
else
declare
Def : constant Node_Id := Get_Attribute_Definition_Clause
(Underlying_Type (First_Subtype (Typ)),
Attribute_External_Tag);
Old_Val : String_Id;
New_Val : String_Id;
E : Entity_Id;
begin
if not Present (Def)
or else Entity (Name (Def)) /= First_Subtype (Typ)
then
New_Node :=
Unchecked_Convert_To (RTE (RE_Cstring_Ptr),
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Exname, Loc),
Attribute_Name => Name_Address));
else
Old_Val := Strval (Expr_Value_S (Expression (Def)));
-- For the rep clause "for <typ>'external_tag use y" generate:
-- <typ>A : constant string := y;
--
-- <typ>A'Address is used to set the External_Tag component
-- of the TSD
-- Create a new nul terminated string if it is not already
if String_Length (Old_Val) > 0
and then
Get_String_Char (Old_Val, String_Length (Old_Val)) = 0
then
New_Val := Old_Val;
else
Start_String (Old_Val);
Store_String_Char (Get_Char_Code (ASCII.NUL));
New_Val := End_String;
end if;
E := Make_Defining_Identifier (Loc,
New_External_Name (Chars (Typ), 'A'));
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => E,
Constant_Present => True,
Object_Definition =>
New_Occurrence_Of (Standard_String, Loc),
Expression =>
Make_String_Literal (Loc, New_Val)));
New_Node :=
Unchecked_Convert_To (RTE (RE_Cstring_Ptr),
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (E, Loc),
Attribute_Name => Name_Address));
end if;
end;
end if;
Append_To (TSD_Aggr_List, New_Node);
-- HT_Link
if RTE_Available (RE_Register_Tag) then
Append_To (TSD_Aggr_List,
Unchecked_Convert_To (RTE (RE_Tag_Ptr),
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (HT_Link, Loc),
Attribute_Name => Name_Address)));
elsif RTE_Record_Component_Available (RE_HT_Link) then
Append_To (TSD_Aggr_List,
Unchecked_Convert_To (RTE (RE_Tag_Ptr),
New_Occurrence_Of (RTE (RE_Null_Address), Loc)));
end if;
-- Transportable: Set for types that can be used in remote calls
-- with respect to E.4(18) legality rules.
declare
Transportable : Entity_Id;
begin
Transportable :=
Boolean_Literals
(Is_Pure (Typ)
or else Is_Shared_Passive (Typ)
or else
((Is_Remote_Types (Typ)
or else Is_Remote_Call_Interface (Typ))
and then Original_View_In_Visible_Part (Typ))
or else not Comes_From_Source (Typ));
Append_To (TSD_Aggr_List,
New_Occurrence_Of (Transportable, Loc));
end;
-- Is_Abstract (Ada 2012: AI05-0173). This functionality is not
-- available in the HIE runtime.
if RTE_Record_Component_Available (RE_Is_Abstract) then
declare
Is_Abstract : Entity_Id;
begin
Is_Abstract := Boolean_Literals (Is_Abstract_Type (Typ));
Append_To (TSD_Aggr_List,
New_Occurrence_Of (Is_Abstract, Loc));
end;
end if;
-- Needs_Finalization: Set if the type is controlled or has controlled
-- components.
declare
Needs_Fin : Entity_Id;
begin
Needs_Fin := Boolean_Literals (Needs_Finalization (Typ));
Append_To (TSD_Aggr_List, New_Occurrence_Of (Needs_Fin, Loc));
end;
-- Size_Func
if RTE_Record_Component_Available (RE_Size_Func) then
-- Initialize this field to Null_Address if we are not building
-- static dispatch tables static or if the size function is not
-- available. In the former case we cannot initialize this field
-- until the function is frozen and registered in the dispatch
-- table (see Register_Primitive).
if not Building_Static_DT (Typ) or else not Has_DT (Typ) then
Append_To (TSD_Aggr_List,
Unchecked_Convert_To (RTE (RE_Size_Ptr),
New_Occurrence_Of (RTE (RE_Null_Address), Loc)));
else
declare
Prim_Elmt : Elmt_Id;
Prim : Entity_Id;
Size_Comp : Node_Id := Empty;
begin
Prim_Elmt := First_Elmt (Primitive_Operations (Typ));
while Present (Prim_Elmt) loop
Prim := Node (Prim_Elmt);
if Chars (Prim) = Name_uSize then
Prim := Ultimate_Alias (Prim);
if Is_Abstract_Subprogram (Prim) then
Size_Comp :=
Unchecked_Convert_To (RTE (RE_Size_Ptr),
New_Occurrence_Of (RTE (RE_Null_Address), Loc));
else
Size_Comp :=
Unchecked_Convert_To (RTE (RE_Size_Ptr),
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Prim, Loc),
Attribute_Name => Name_Unrestricted_Access));
end if;
exit;
end if;
Next_Elmt (Prim_Elmt);
end loop;
pragma Assert (Present (Size_Comp));
Append_To (TSD_Aggr_List, Size_Comp);
end;
end if;
end if;
-- Interfaces_Table (required for AI-405)
if RTE_Record_Component_Available (RE_Interfaces_Table) then
-- Count the number of interface types implemented by Typ
Collect_Interfaces (Typ, Typ_Ifaces);
AI := First_Elmt (Typ_Ifaces);
while Present (AI) loop
Num_Ifaces := Num_Ifaces + 1;
Next_Elmt (AI);
end loop;
if Num_Ifaces = 0 then
Iface_Table_Node := Make_Null (Loc);
-- Generate the Interface_Table object
else
declare
TSD_Ifaces_List : constant List_Id := New_List;
Elmt : Elmt_Id;
Offset_To_Top : Node_Id;
Sec_DT_Tag : Node_Id;
Dummy_Object_Ifaces_List : Elist_Id := No_Elist;
Dummy_Object_Ifaces_Comp_List : Elist_Id := No_Elist;
Dummy_Object_Ifaces_Tag_List : Elist_Id := No_Elist;
-- Interfaces information of the dummy object
begin
-- Collect interfaces information if we need to compute the
-- offset to the top using the dummy object.
if Present (Dummy_Object) then
Collect_Interfaces_Info (Typ,
Ifaces_List => Dummy_Object_Ifaces_List,
Components_List => Dummy_Object_Ifaces_Comp_List,
Tags_List => Dummy_Object_Ifaces_Tag_List);
end if;
AI := First_Elmt (Typ_Ifaces);
while Present (AI) loop
if Is_Ancestor (Node (AI), Typ, Use_Full_View => True) then
Sec_DT_Tag := New_Occurrence_Of (DT_Ptr, Loc);
else
Elmt :=
Next_Elmt
(Next_Elmt (First_Elmt (Access_Disp_Table (Typ))));
pragma Assert (Has_Thunks (Node (Elmt)));
while Is_Tag (Node (Elmt))
and then not
Is_Ancestor (Node (AI), Related_Type (Node (Elmt)),
Use_Full_View => True)
loop
pragma Assert (Has_Thunks (Node (Elmt)));
Next_Elmt (Elmt);
pragma Assert (Has_Thunks (Node (Elmt)));
Next_Elmt (Elmt);
pragma Assert (not Has_Thunks (Node (Elmt)));
Next_Elmt (Elmt);
pragma Assert (not Has_Thunks (Node (Elmt)));
Next_Elmt (Elmt);
end loop;
pragma Assert (Ekind (Node (Elmt)) = E_Constant
and then not
Has_Thunks (Node (Next_Elmt (Next_Elmt (Elmt)))));
Sec_DT_Tag :=
New_Occurrence_Of
(Node (Next_Elmt (Next_Elmt (Elmt))), Loc);
end if;
-- Use the dummy object to compute Offset_To_Top of
-- components located at fixed position.
if Present (Dummy_Object) then
declare
Iface : constant Node_Id := Node (AI);
Iface_Comp : Node_Id := Empty;
Iface_Comp_Elmt : Elmt_Id;
Iface_Elmt : Elmt_Id;
begin
Iface_Elmt :=
First_Elmt (Dummy_Object_Ifaces_List);
Iface_Comp_Elmt :=
First_Elmt (Dummy_Object_Ifaces_Comp_List);
while Present (Iface_Elmt) loop
if Node (Iface_Elmt) = Iface then
Iface_Comp := Node (Iface_Comp_Elmt);
exit;
end if;
Next_Elmt (Iface_Elmt);
Next_Elmt (Iface_Comp_Elmt);
end loop;
pragma Assert (Present (Iface_Comp));
if not
Is_Variable_Size_Record (Etype (Scope (Iface_Comp)))
then
Offset_To_Top :=
Make_Op_Minus (Loc,
Make_Attribute_Reference (Loc,
Prefix =>
Make_Selected_Component (Loc,
Prefix =>
New_Occurrence_Of (Dummy_Object, Loc),
Selector_Name =>
New_Occurrence_Of (Iface_Comp, Loc)),
Attribute_Name => Name_Position));
else
Offset_To_Top := Make_Integer_Literal (Loc, 0);
end if;
end;
else
Offset_To_Top := Make_Integer_Literal (Loc, 0);
end if;
Append_To (TSD_Ifaces_List,
Make_Aggregate (Loc,
Expressions => New_List (
-- Iface_Tag
Unchecked_Convert_To (RTE (RE_Tag),
New_Occurrence_Of
(Node (First_Elmt (Access_Disp_Table (Node (AI)))),
Loc)),
-- Static_Offset_To_Top
New_Occurrence_Of (Standard_True, Loc),
-- Offset_To_Top_Value
Offset_To_Top,
-- Offset_To_Top_Func
Make_Null (Loc),
-- Secondary_DT
Unchecked_Convert_To (RTE (RE_Tag), Sec_DT_Tag))));
Next_Elmt (AI);
end loop;
Name_ITable := New_External_Name (Tname, 'I');
ITable := Make_Defining_Identifier (Loc, Name_ITable);
Set_Is_Statically_Allocated (ITable,
Is_Library_Level_Tagged_Type (Typ));
-- The table of interfaces is constant if we are building a
-- static dispatch table; otherwise is not constant because
-- its slots are filled at run time by the IP routine.
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => ITable,
Aliased_Present => True,
Constant_Present => Building_Static_Secondary_DT (Typ),
Object_Definition =>
Make_Subtype_Indication (Loc,
Subtype_Mark =>
New_Occurrence_Of (RTE (RE_Interface_Data), Loc),
Constraint =>
Make_Index_Or_Discriminant_Constraint (Loc,
Constraints => New_List (
Make_Integer_Literal (Loc, Num_Ifaces)))),
Expression =>
Make_Aggregate (Loc,
Expressions => New_List (
Make_Integer_Literal (Loc, Num_Ifaces),
Make_Aggregate (Loc, TSD_Ifaces_List)))));
Iface_Table_Node :=
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (ITable, Loc),
Attribute_Name => Name_Unchecked_Access);
end;
end if;
Append_To (TSD_Aggr_List, Iface_Table_Node);
end if;
-- Generate the Select Specific Data table for synchronized types that
-- implement synchronized interfaces. The size of the table is
-- constrained by the number of non-predefined primitive operations.
if RTE_Record_Component_Available (RE_SSD) then
if Ada_Version >= Ada_2005
and then Has_DT (Typ)
and then Is_Concurrent_Record_Type (Typ)
and then Has_Interfaces (Typ)
and then Nb_Prim > 0
and then not Is_Abstract_Type (Typ)
and then not Is_Controlled (Typ)
and then not Restriction_Active (No_Dispatching_Calls)
and then not Restriction_Active (No_Select_Statements)
then
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => SSD,
Aliased_Present => True,
Object_Definition =>
Make_Subtype_Indication (Loc,
Subtype_Mark => New_Occurrence_Of (
RTE (RE_Select_Specific_Data), Loc),
Constraint =>
Make_Index_Or_Discriminant_Constraint (Loc,
Constraints => New_List (
Make_Integer_Literal (Loc, Nb_Prim))))));
Append_To (Result,
Make_Attribute_Definition_Clause (Loc,
Name => New_Occurrence_Of (SSD, Loc),
Chars => Name_Alignment,
Expression =>
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of (RTE (RE_Integer_Address), Loc),
Attribute_Name => Name_Alignment)));
-- This table is initialized by Make_Select_Specific_Data_Table,
-- which calls Set_Entry_Index and Set_Prim_Op_Kind.
Append_To (TSD_Aggr_List,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (SSD, Loc),
Attribute_Name => Name_Unchecked_Access));
else
Append_To (TSD_Aggr_List, Make_Null (Loc));
end if;
end if;
-- Initialize the table of ancestor tags. In case of interface types
-- this table is not needed.
TSD_Tags_List := New_List;
-- If we are not statically allocating the dispatch table then we must
-- fill position 0 with null because we still have not generated the
-- tag of Typ.
if not Building_Static_DT (Typ)
or else Is_Interface (Typ)
then
Append_To (TSD_Tags_List,
Unchecked_Convert_To (RTE (RE_Tag),
New_Occurrence_Of (RTE (RE_Null_Address), Loc)));
-- Otherwise we can safely reference the tag
else
Append_To (TSD_Tags_List,
New_Occurrence_Of (DT_Ptr, Loc));
end if;
-- Fill the rest of the table with the tags of the ancestors
declare
Current_Typ : Entity_Id;
Parent_Typ : Entity_Id;
Pos : Nat;
begin
Pos := 1;
Current_Typ := Typ;
loop
Parent_Typ := Etype (Current_Typ);
if Is_Private_Type (Parent_Typ) then
Parent_Typ := Full_View (Base_Type (Parent_Typ));
end if;
exit when Parent_Typ = Current_Typ;
if Is_CPP_Class (Parent_Typ) then
-- The tags defined in the C++ side will be inherited when
-- the object is constructed (Exp_Ch3.Build_Init_Procedure)
Append_To (TSD_Tags_List,
Unchecked_Convert_To (RTE (RE_Tag),
New_Occurrence_Of (RTE (RE_Null_Address), Loc)));
else
Append_To (TSD_Tags_List,
New_Occurrence_Of
(Node (First_Elmt (Access_Disp_Table (Parent_Typ))),
Loc));
end if;
Pos := Pos + 1;
Current_Typ := Parent_Typ;
end loop;
pragma Assert (Pos = I_Depth + 1);
end;
Append_To (TSD_Aggr_List,
Make_Aggregate (Loc,
Expressions => TSD_Tags_List));
-- Build the TSD object
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => TSD,
Aliased_Present => True,
Constant_Present => Building_Static_DT (Typ),
Object_Definition =>
Make_Subtype_Indication (Loc,
Subtype_Mark => New_Occurrence_Of (
RTE (RE_Type_Specific_Data), Loc),
Constraint =>
Make_Index_Or_Discriminant_Constraint (Loc,
Constraints => New_List (
Make_Integer_Literal (Loc, I_Depth)))),
Expression => Make_Aggregate (Loc,
Expressions => TSD_Aggr_List)));
Set_Is_True_Constant (TSD, Building_Static_DT (Typ));
-- Initialize or declare the dispatch table object
if not Has_DT (Typ) then
DT_Constr_List := New_List;
DT_Aggr_List := New_List;
-- Typeinfo
New_Node :=
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (TSD, Loc),
Attribute_Name => Name_Address);
Append_To (DT_Constr_List, New_Node);
Append_To (DT_Aggr_List, New_Copy (New_Node));
Append_To (DT_Aggr_List, Make_Integer_Literal (Loc, 0));
-- In case of locally defined tagged types we have already declared
-- and uninitialized object for the dispatch table, which is now
-- initialized by means of the following assignment:
-- DT := (TSD'Address, 0);
if not Building_Static_DT (Typ) then
Append_To (Result,
Make_Assignment_Statement (Loc,
Name => New_Occurrence_Of (DT, Loc),
Expression => Make_Aggregate (Loc, DT_Aggr_List)));
-- In case of library level tagged types we declare and export now
-- the constant object containing the dummy dispatch table. There
-- is no need to declare the tag here because it has been previously
-- declared by Make_Tags
-- DT : aliased constant No_Dispatch_Table :=
-- (NDT_TSD => TSD'Address;
-- NDT_Prims_Ptr => 0);
else
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => DT,
Aliased_Present => True,
Constant_Present => True,
Object_Definition =>
New_Occurrence_Of (RTE (RE_No_Dispatch_Table_Wrapper), Loc),
Expression => Make_Aggregate (Loc, DT_Aggr_List)));
Export_DT (Typ, DT);
end if;
-- Common case: Typ has a dispatch table
-- Generate:
-- Predef_Prims : Address_Array (1 .. Default_Prim_Ops_Count) :=
-- (predef-prim-op-1'address,
-- predef-prim-op-2'address,
-- ...
-- predef-prim-op-n'address);
-- DT : Dispatch_Table (Nb_Prims) :=
-- (Signature => <sig-value>,
-- Tag_Kind => <tag_kind-value>,
-- Predef_Prims => Predef_Prims'First'Address,
-- Offset_To_Top => 0,
-- TSD => TSD'Address;
-- Prims_Ptr => (prim-op-1'address,
-- prim-op-2'address,
-- ...
-- prim-op-n'address));
-- for DT'Alignment use Address'Alignment
else
declare
Nb_P_Prims : constant Nat := Number_Of_Predefined_Prims (Typ);
Prim_Table : array (Nat range 1 .. Nb_P_Prims) of Entity_Id;
Decl : Node_Id;
E : Entity_Id;
begin
Prim_Ops_Aggr_List := New_List;
Prim_Table := (others => Empty);
if Building_Static_DT (Typ) then
Prim_Elmt := First_Elmt (Primitive_Operations (Typ));
while Present (Prim_Elmt) loop
Prim := Node (Prim_Elmt);
if Is_Predefined_Dispatching_Operation (Prim)
and then not Is_Abstract_Subprogram (Prim)
and then not Is_Eliminated (Prim)
and then not Generate_SCIL
and then not Present (Prim_Table
(UI_To_Int (DT_Position (Prim))))
then
E := Ultimate_Alias (Prim);
pragma Assert (not Is_Abstract_Subprogram (E));
Prim_Table (UI_To_Int (DT_Position (Prim))) := E;
end if;
Next_Elmt (Prim_Elmt);
end loop;
end if;
for J in Prim_Table'Range loop
if Present (Prim_Table (J)) then
New_Node :=
Unchecked_Convert_To (RTE (RE_Prim_Ptr),
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of (Prim_Table (J), Loc),
Attribute_Name => Name_Unrestricted_Access));
else
New_Node := Make_Null (Loc);
end if;
Append_To (Prim_Ops_Aggr_List, New_Node);
end loop;
New_Node :=
Make_Aggregate (Loc,
Expressions => Prim_Ops_Aggr_List);
Decl :=
Make_Subtype_Declaration (Loc,
Defining_Identifier => Make_Temporary (Loc, 'S'),
Subtype_Indication =>
New_Occurrence_Of (RTE (RE_Address_Array), Loc));
Append_To (Result, Decl);
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => Predef_Prims,
Aliased_Present => True,
Constant_Present => Building_Static_DT (Typ),
Object_Definition =>
New_Occurrence_Of (Defining_Identifier (Decl), Loc),
Expression => New_Node));
-- Remember aggregates initializing dispatch tables
Append_Elmt (New_Node, DT_Aggr);
end;
-- Stage 1: Initialize the discriminant and the record components
DT_Constr_List := New_List;
DT_Aggr_List := New_List;
-- Num_Prims. If the tagged type has no primitives we add a dummy
-- slot whose address will be the tag of this type.
if Nb_Prim = 0 then
New_Node := Make_Integer_Literal (Loc, 1);
else
New_Node := Make_Integer_Literal (Loc, Nb_Prim);
end if;
Append_To (DT_Constr_List, New_Node);
Append_To (DT_Aggr_List, New_Copy (New_Node));
-- Signature
if RTE_Record_Component_Available (RE_Signature) then
Append_To (DT_Aggr_List,
New_Occurrence_Of (RTE (RE_Primary_DT), Loc));
end if;
-- Tag_Kind
if RTE_Record_Component_Available (RE_Tag_Kind) then
Append_To (DT_Aggr_List, Tagged_Kind (Typ));
end if;
-- Predef_Prims
Append_To (DT_Aggr_List,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Predef_Prims, Loc),
Attribute_Name => Name_Address));
-- Offset_To_Top
Append_To (DT_Aggr_List, Make_Integer_Literal (Loc, 0));
-- Typeinfo
Append_To (DT_Aggr_List,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (TSD, Loc),
Attribute_Name => Name_Address));
-- Stage 2: Initialize the table of user-defined primitive operations
Prim_Ops_Aggr_List := New_List;
if Nb_Prim = 0 then
Append_To (Prim_Ops_Aggr_List, Make_Null (Loc));
elsif not Building_Static_DT (Typ) then
for J in 1 .. Nb_Prim loop
Append_To (Prim_Ops_Aggr_List, Make_Null (Loc));
end loop;
else
declare
CPP_Nb_Prims : constant Nat := CPP_Num_Prims (Typ);
E : Entity_Id;
Prim : Entity_Id;
Prim_Elmt : Elmt_Id;
Prim_Pos : Nat;
Prim_Table : array (Nat range 1 .. Nb_Prim) of Entity_Id;
begin
Prim_Table := (others => Empty);
Prim_Elmt := First_Elmt (Primitive_Operations (Typ));
while Present (Prim_Elmt) loop
Prim := Node (Prim_Elmt);
-- Retrieve the ultimate alias of the primitive for proper
-- handling of renamings and eliminated primitives.
E := Ultimate_Alias (Prim);
-- If the alias is not a primitive operation then Prim does
-- not rename another primitive, but rather an operation
-- declared elsewhere (e.g. in another scope) and therefore
-- Prim is a new primitive.
if No (Find_Dispatching_Type (E)) then
E := Prim;
end if;
Prim_Pos := UI_To_Int (DT_Position (E));
-- Skip predefined primitives because they are located in a
-- separate dispatch table.
if not Is_Predefined_Dispatching_Operation (Prim)
and then not Is_Predefined_Dispatching_Operation (E)
-- Skip entities with attribute Interface_Alias because
-- those are only required to build secondary dispatch
-- tables.
and then not Present (Interface_Alias (Prim))
-- Skip abstract and eliminated primitives
and then not Is_Abstract_Subprogram (E)
and then not Is_Eliminated (E)
-- For derivations of CPP types skip primitives located in
-- the C++ part of the dispatch table because their slots
-- are initialized by the IC routine.
and then (not Is_CPP_Class (Root_Type (Typ))
or else Prim_Pos > CPP_Nb_Prims)
-- Skip ignored Ghost subprograms as those will be removed
-- from the executable.
and then not Is_Ignored_Ghost_Entity (E)
then
pragma Assert
(UI_To_Int (DT_Position (Prim)) <= Nb_Prim);
Prim_Table (UI_To_Int (DT_Position (Prim))) := E;
end if;
Next_Elmt (Prim_Elmt);
end loop;
for J in Prim_Table'Range loop
if Present (Prim_Table (J)) then
New_Node :=
Unchecked_Convert_To (RTE (RE_Prim_Ptr),
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of (Prim_Table (J), Loc),
Attribute_Name => Name_Unrestricted_Access));
else
New_Node := Make_Null (Loc);
end if;
Append_To (Prim_Ops_Aggr_List, New_Node);
end loop;
end;
end if;
New_Node :=
Make_Aggregate (Loc,
Expressions => Prim_Ops_Aggr_List);
Append_To (DT_Aggr_List, New_Node);
-- Remember aggregates initializing dispatch tables
Append_Elmt (New_Node, DT_Aggr);
-- In case of locally defined tagged types we have already declared
-- and uninitialized object for the dispatch table, which is now
-- initialized by means of an assignment.
if not Building_Static_DT (Typ) then
Append_To (Result,
Make_Assignment_Statement (Loc,
Name => New_Occurrence_Of (DT, Loc),
Expression => Make_Aggregate (Loc, DT_Aggr_List)));
-- In case of library level tagged types we declare now and export
-- the constant object containing the dispatch table.
else
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => DT,
Aliased_Present => True,
Constant_Present => True,
Object_Definition =>
Make_Subtype_Indication (Loc,
Subtype_Mark => New_Occurrence_Of
(RTE (RE_Dispatch_Table_Wrapper), Loc),
Constraint => Make_Index_Or_Discriminant_Constraint (Loc,
Constraints => DT_Constr_List)),
Expression => Make_Aggregate (Loc, DT_Aggr_List)));
Export_DT (Typ, DT);
end if;
end if;
-- Initialize the table of ancestor tags if not building static
-- dispatch table
if not Building_Static_DT (Typ)
and then not Is_Interface (Typ)
and then not Is_CPP_Class (Typ)
then
Append_To (Result,
Make_Assignment_Statement (Loc,
Name =>
Make_Indexed_Component (Loc,
Prefix =>
Make_Selected_Component (Loc,
Prefix => New_Occurrence_Of (TSD, Loc),
Selector_Name =>
New_Occurrence_Of
(RTE_Record_Component (RE_Tags_Table), Loc)),
Expressions =>
New_List (Make_Integer_Literal (Loc, 0))),
Expression =>
New_Occurrence_Of
(Node (First_Elmt (Access_Disp_Table (Typ))), Loc)));
end if;
-- Inherit the dispatch tables of the parent. There is no need to
-- inherit anything from the parent when building static dispatch tables
-- because the whole dispatch table (including inherited primitives) has
-- been already built.
if Building_Static_DT (Typ) then
null;
-- If the ancestor is a CPP_Class type we inherit the dispatch tables
-- in the init proc, and we don't need to fill them in here.
elsif Is_CPP_Class (Parent_Typ) then
null;
-- Otherwise we fill in the dispatch tables here
else
if Typ /= Parent_Typ
and then not Is_Interface (Typ)
and then not Restriction_Active (No_Dispatching_Calls)
then
-- Inherit the dispatch table
if not Is_Interface (Typ)
and then not Is_Interface (Parent_Typ)
and then not Is_CPP_Class (Parent_Typ)
then
declare
Nb_Prims : constant Int :=
UI_To_Int (DT_Entry_Count
(First_Tag_Component (Parent_Typ)));
begin
Append_To (Elab_Code,
Build_Inherit_Predefined_Prims (Loc,
Old_Tag_Node =>
New_Occurrence_Of
(Node
(Next_Elmt
(First_Elmt
(Access_Disp_Table (Parent_Typ)))), Loc),
New_Tag_Node =>
New_Occurrence_Of
(Node
(Next_Elmt
(First_Elmt
(Access_Disp_Table (Typ)))), Loc),
Num_Predef_Prims =>
Number_Of_Predefined_Prims (Parent_Typ)));
if Nb_Prims /= 0 then
Append_To (Elab_Code,
Build_Inherit_Prims (Loc,
Typ => Typ,
Old_Tag_Node =>
New_Occurrence_Of
(Node
(First_Elmt
(Access_Disp_Table (Parent_Typ))), Loc),
New_Tag_Node => New_Occurrence_Of (DT_Ptr, Loc),
Num_Prims => Nb_Prims));
end if;
end;
end if;
-- Inherit the secondary dispatch tables of the ancestor
if not Is_CPP_Class (Parent_Typ) then
declare
Sec_DT_Ancestor : Elmt_Id :=
Next_Elmt
(Next_Elmt
(First_Elmt
(Access_Disp_Table
(Parent_Typ))));
Sec_DT_Typ : Elmt_Id :=
Next_Elmt
(Next_Elmt
(First_Elmt
(Access_Disp_Table (Typ))));
procedure Copy_Secondary_DTs (Typ : Entity_Id);
-- Local procedure required to climb through the ancestors
-- and copy the contents of all their secondary dispatch
-- tables.
------------------------
-- Copy_Secondary_DTs --
------------------------
procedure Copy_Secondary_DTs (Typ : Entity_Id) is
E : Entity_Id;
Iface : Elmt_Id;
begin
-- Climb to the ancestor (if any) handling private types
if Present (Full_View (Etype (Typ))) then
if Full_View (Etype (Typ)) /= Typ then
Copy_Secondary_DTs (Full_View (Etype (Typ)));
end if;
elsif Etype (Typ) /= Typ then
Copy_Secondary_DTs (Etype (Typ));
end if;
if Present (Interfaces (Typ))
and then not Is_Empty_Elmt_List (Interfaces (Typ))
then
Iface := First_Elmt (Interfaces (Typ));
E := First_Entity (Typ);
while Present (E)
and then Present (Node (Sec_DT_Ancestor))
and then Ekind (Node (Sec_DT_Ancestor)) = E_Constant
loop
if Is_Tag (E) and then Chars (E) /= Name_uTag then
declare
Num_Prims : constant Int :=
UI_To_Int (DT_Entry_Count (E));
begin
if not Is_Interface (Etype (Typ)) then
-- Inherit first secondary dispatch table
Append_To (Elab_Code,
Build_Inherit_Predefined_Prims (Loc,
Old_Tag_Node =>
Unchecked_Convert_To (RTE (RE_Tag),
New_Occurrence_Of
(Node
(Next_Elmt (Sec_DT_Ancestor)),
Loc)),
New_Tag_Node =>
Unchecked_Convert_To (RTE (RE_Tag),
New_Occurrence_Of
(Node (Next_Elmt (Sec_DT_Typ)),
Loc)),
Num_Predef_Prims =>
Number_Of_Predefined_Prims
(Parent_Typ)));
if Num_Prims /= 0 then
Append_To (Elab_Code,
Build_Inherit_Prims (Loc,
Typ => Node (Iface),
Old_Tag_Node =>
Unchecked_Convert_To
(RTE (RE_Tag),
New_Occurrence_Of
(Node (Sec_DT_Ancestor),
Loc)),
New_Tag_Node =>
Unchecked_Convert_To
(RTE (RE_Tag),
New_Occurrence_Of
(Node (Sec_DT_Typ), Loc)),
Num_Prims => Num_Prims));
end if;
end if;
Next_Elmt (Sec_DT_Ancestor);
Next_Elmt (Sec_DT_Typ);
-- Skip the secondary dispatch table of
-- predefined primitives
Next_Elmt (Sec_DT_Ancestor);
Next_Elmt (Sec_DT_Typ);
if not Is_Interface (Etype (Typ)) then
-- Inherit second secondary dispatch table
Append_To (Elab_Code,
Build_Inherit_Predefined_Prims (Loc,
Old_Tag_Node =>
Unchecked_Convert_To (RTE (RE_Tag),
New_Occurrence_Of
(Node
(Next_Elmt (Sec_DT_Ancestor)),
Loc)),
New_Tag_Node =>
Unchecked_Convert_To (RTE (RE_Tag),
New_Occurrence_Of
(Node (Next_Elmt (Sec_DT_Typ)),
Loc)),
Num_Predef_Prims =>
Number_Of_Predefined_Prims
(Parent_Typ)));
if Num_Prims /= 0 then
Append_To (Elab_Code,
Build_Inherit_Prims (Loc,
Typ => Node (Iface),
Old_Tag_Node =>
Unchecked_Convert_To
(RTE (RE_Tag),
New_Occurrence_Of
(Node (Sec_DT_Ancestor),
Loc)),
New_Tag_Node =>
Unchecked_Convert_To
(RTE (RE_Tag),
New_Occurrence_Of
(Node (Sec_DT_Typ), Loc)),
Num_Prims => Num_Prims));
end if;
end if;
end;
Next_Elmt (Sec_DT_Ancestor);
Next_Elmt (Sec_DT_Typ);
-- Skip the secondary dispatch table of
-- predefined primitives
Next_Elmt (Sec_DT_Ancestor);
Next_Elmt (Sec_DT_Typ);
Next_Elmt (Iface);
end if;
Next_Entity (E);
end loop;
end if;
end Copy_Secondary_DTs;
begin
if Present (Node (Sec_DT_Ancestor))
and then Ekind (Node (Sec_DT_Ancestor)) = E_Constant
then
-- Handle private types
if Present (Full_View (Typ)) then
Copy_Secondary_DTs (Full_View (Typ));
else
Copy_Secondary_DTs (Typ);
end if;
end if;
end;
end if;
end if;
end if;
-- Generate code to check if the external tag of this type is the same
-- as the external tag of some other declaration.
-- Check_TSD (TSD'Unrestricted_Access);
-- This check is a consequence of AI05-0113-1/06, so it officially
-- applies to Ada 2005 (and Ada 2012). It might be argued that it is
-- a desirable check to add in Ada 95 mode, but we hesitate to make
-- this change, as it would be incompatible, and could conceivably
-- cause a problem in existing Ada 95 code.
-- We check for No_Run_Time_Mode here, because we do not want to pick
-- up the RE_Check_TSD entity and call it in No_Run_Time mode.
-- We cannot perform this check if the generation of its expanded name
-- was discarded.
if not No_Run_Time_Mode
and then not Discard_Names
and then Ada_Version >= Ada_2005
and then RTE_Available (RE_Check_TSD)
and then not Duplicated_Tag_Checks_Suppressed (Typ)
then
Append_To (Elab_Code,
Make_Procedure_Call_Statement (Loc,
Name =>
New_Occurrence_Of (RTE (RE_Check_TSD), Loc),
Parameter_Associations => New_List (
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (TSD, Loc),
Attribute_Name => Name_Unchecked_Access))));
end if;
-- Generate code to register the Tag in the External_Tag hash table for
-- the pure Ada type only.
-- Register_Tag (Dt_Ptr);
-- Skip this action in the following cases:
-- 1) if Register_Tag is not available.
-- 2) in No_Run_Time mode.
-- 3) if Typ is not defined at the library level (this is required
-- to avoid adding concurrency control to the hash table used
-- by the run-time to register the tags).
if not No_Run_Time_Mode
and then Is_Library_Level_Entity (Typ)
and then RTE_Available (RE_Register_Tag)
then
Append_To (Elab_Code,
Make_Procedure_Call_Statement (Loc,
Name =>
New_Occurrence_Of (RTE (RE_Register_Tag), Loc),
Parameter_Associations =>
New_List (New_Occurrence_Of (DT_Ptr, Loc))));
end if;
if not Is_Empty_List (Elab_Code) then
Append_List_To (Result, Elab_Code);
end if;
-- Populate the two auxiliary tables used for dispatching asynchronous,
-- conditional and timed selects for synchronized types that implement
-- a limited interface. Skip this step in Ravenscar profile or when
-- general dispatching is forbidden.
if Ada_Version >= Ada_2005
and then Is_Concurrent_Record_Type (Typ)
and then Has_Interfaces (Typ)
and then not Restriction_Active (No_Dispatching_Calls)
and then not Restriction_Active (No_Select_Statements)
then
Append_List_To (Result,
Make_Select_Specific_Data_Table (Typ));
end if;
-- Remember entities containing dispatch tables
Append_Elmt (Predef_Prims, DT_Decl);
Append_Elmt (DT, DT_Decl);
Analyze_List (Result, Suppress => All_Checks);
Set_Has_Dispatch_Table (Typ);
-- Mark entities containing dispatch tables. Required by the backend to
-- handle them properly.
if Has_DT (Typ) then
declare
Elmt : Elmt_Id;
begin
-- Object declarations
Elmt := First_Elmt (DT_Decl);
while Present (Elmt) loop
Set_Is_Dispatch_Table_Entity (Node (Elmt));
pragma Assert (Ekind (Etype (Node (Elmt))) = E_Array_Subtype
or else Ekind (Etype (Node (Elmt))) = E_Record_Subtype);
Set_Is_Dispatch_Table_Entity (Etype (Node (Elmt)));
Next_Elmt (Elmt);
end loop;
-- Aggregates initializing dispatch tables
Elmt := First_Elmt (DT_Aggr);
while Present (Elmt) loop
Set_Is_Dispatch_Table_Entity (Etype (Node (Elmt)));
Next_Elmt (Elmt);
end loop;
end;
end if;
<<Leave_SCIL>>
-- Register the tagged type in the call graph nodes table
Register_CG_Node (Typ);
<<Leave>>
Restore_Ghost_Region (Saved_GM, Saved_IGR);
return Result;
end Make_DT;
-------------------------------------
-- Make_Select_Specific_Data_Table --
-------------------------------------
function Make_Select_Specific_Data_Table
(Typ : Entity_Id) return List_Id
is
Assignments : constant List_Id := New_List;
Loc : constant Source_Ptr := Sloc (Typ);
Conc_Typ : Entity_Id;
Decls : List_Id := No_List;
Prim : Entity_Id;
Prim_Als : Entity_Id;
Prim_Elmt : Elmt_Id;
Prim_Pos : Uint;
Nb_Prim : Nat := 0;
type Examined_Array is array (Int range <>) of Boolean;
function Find_Entry_Index (E : Entity_Id) return Uint;
-- Given an entry, find its index in the visible declarations of the
-- corresponding concurrent type of Typ.
----------------------
-- Find_Entry_Index --
----------------------
function Find_Entry_Index (E : Entity_Id) return Uint is
Index : Uint := Uint_1;
Subp_Decl : Entity_Id;
begin
if Present (Decls)
and then not Is_Empty_List (Decls)
then
Subp_Decl := First (Decls);
while Present (Subp_Decl) loop
if Nkind (Subp_Decl) = N_Entry_Declaration then
if Defining_Identifier (Subp_Decl) = E then
return Index;
end if;
Index := Index + 1;
end if;
Next (Subp_Decl);
end loop;
end if;
return Uint_0;
end Find_Entry_Index;
-- Local variables
Tag_Node : Node_Id;
-- Start of processing for Make_Select_Specific_Data_Table
begin
pragma Assert (not Restriction_Active (No_Dispatching_Calls));
if Present (Corresponding_Concurrent_Type (Typ)) then
Conc_Typ := Corresponding_Concurrent_Type (Typ);
if Present (Full_View (Conc_Typ)) then
Conc_Typ := Full_View (Conc_Typ);
end if;
if Ekind (Conc_Typ) = E_Protected_Type then
Decls := Visible_Declarations (Protected_Definition (
Parent (Conc_Typ)));
else
pragma Assert (Ekind (Conc_Typ) = E_Task_Type);
Decls := Visible_Declarations (Task_Definition (
Parent (Conc_Typ)));
end if;
end if;
-- Count the non-predefined primitive operations
Prim_Elmt := First_Elmt (Primitive_Operations (Typ));
while Present (Prim_Elmt) loop
Prim := Node (Prim_Elmt);
if not (Is_Predefined_Dispatching_Operation (Prim)
or else Is_Predefined_Dispatching_Alias (Prim))
then
Nb_Prim := Nb_Prim + 1;
end if;
Next_Elmt (Prim_Elmt);
end loop;
declare
Examined : Examined_Array (1 .. Nb_Prim) := (others => False);
begin
Prim_Elmt := First_Elmt (Primitive_Operations (Typ));
while Present (Prim_Elmt) loop
Prim := Node (Prim_Elmt);
-- Look for primitive overriding an abstract interface subprogram
if Present (Interface_Alias (Prim))
and then not
Is_Ancestor
(Find_Dispatching_Type (Interface_Alias (Prim)), Typ,
Use_Full_View => True)
and then not Examined (UI_To_Int (DT_Position (Alias (Prim))))
then
Prim_Pos := DT_Position (Alias (Prim));
pragma Assert (UI_To_Int (Prim_Pos) <= Nb_Prim);
Examined (UI_To_Int (Prim_Pos)) := True;
-- Set the primitive operation kind regardless of subprogram
-- type. Generate:
-- Ada.Tags.Set_Prim_Op_Kind (DT_Ptr, <position>, <kind>);
if Tagged_Type_Expansion then
Tag_Node :=
New_Occurrence_Of
(Node (First_Elmt (Access_Disp_Table (Typ))), Loc);
else
Tag_Node :=
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Typ, Loc),
Attribute_Name => Name_Tag);
end if;
Append_To (Assignments,
Make_Procedure_Call_Statement (Loc,
Name => New_Occurrence_Of (RTE (RE_Set_Prim_Op_Kind), Loc),
Parameter_Associations => New_List (
Tag_Node,
Make_Integer_Literal (Loc, Prim_Pos),
Prim_Op_Kind (Alias (Prim), Typ))));
-- Retrieve the root of the alias chain
Prim_Als := Ultimate_Alias (Prim);
-- In the case of an entry wrapper, set the entry index
if Ekind (Prim) = E_Procedure
and then Is_Primitive_Wrapper (Prim_Als)
and then Ekind (Wrapped_Entity (Prim_Als)) = E_Entry
then
-- Generate:
-- Ada.Tags.Set_Entry_Index
-- (DT_Ptr, <position>, <index>);
if Tagged_Type_Expansion then
Tag_Node :=
New_Occurrence_Of
(Node (First_Elmt (Access_Disp_Table (Typ))), Loc);
else
Tag_Node :=
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Typ, Loc),
Attribute_Name => Name_Tag);
end if;
Append_To (Assignments,
Make_Procedure_Call_Statement (Loc,
Name =>
New_Occurrence_Of (RTE (RE_Set_Entry_Index), Loc),
Parameter_Associations => New_List (
Tag_Node,
Make_Integer_Literal (Loc, Prim_Pos),
Make_Integer_Literal (Loc,
Find_Entry_Index (Wrapped_Entity (Prim_Als))))));
end if;
end if;
Next_Elmt (Prim_Elmt);
end loop;
end;
return Assignments;
end Make_Select_Specific_Data_Table;
---------------
-- Make_Tags --
---------------
function Make_Tags (Typ : Entity_Id) return List_Id is
Loc : constant Source_Ptr := Sloc (Typ);
Result : constant List_Id := New_List;
procedure Import_DT
(Tag_Typ : Entity_Id;
DT : Entity_Id;
Is_Secondary_DT : Boolean);
-- Import the dispatch table DT of tagged type Tag_Typ. Required to
-- generate forward references and statically allocate the table. For
-- primary dispatch tables that require no dispatch table generate:
-- DT : static aliased constant Non_Dispatch_Table_Wrapper;
-- pragma Import (Ada, DT);
-- Otherwise generate:
-- DT : static aliased constant Dispatch_Table_Wrapper (Nb_Prim);
-- pragma Import (Ada, DT);
---------------
-- Import_DT --
---------------
procedure Import_DT
(Tag_Typ : Entity_Id;
DT : Entity_Id;
Is_Secondary_DT : Boolean)
is
DT_Constr_List : List_Id;
Nb_Prim : Nat;
begin
Set_Is_Imported (DT);
Set_Ekind (DT, E_Constant);
Set_Related_Type (DT, Typ);
-- The scope must be set now to call Get_External_Name
Set_Scope (DT, Current_Scope);
Get_External_Name (DT);
Set_Interface_Name (DT,
Make_String_Literal (Loc, Strval => String_From_Name_Buffer));
-- Ensure proper Sprint output of this implicit importation
Set_Is_Internal (DT);
-- Save this entity to allow Make_DT to generate its exportation
Append_Elmt (DT, Dispatch_Table_Wrappers (Typ));
-- No dispatch table required
if not Is_Secondary_DT and then not Has_DT (Tag_Typ) then
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => DT,
Aliased_Present => True,
Constant_Present => True,
Object_Definition =>
New_Occurrence_Of
(RTE (RE_No_Dispatch_Table_Wrapper), Loc)));
else
-- Calculate the number of primitives of the dispatch table and
-- the size of the Type_Specific_Data record.
Nb_Prim :=
UI_To_Int (DT_Entry_Count (First_Tag_Component (Tag_Typ)));
-- If the tagged type has no primitives we add a dummy slot whose
-- address will be the tag of this type.
if Nb_Prim = 0 then
DT_Constr_List :=
New_List (Make_Integer_Literal (Loc, 1));
else
DT_Constr_List :=
New_List (Make_Integer_Literal (Loc, Nb_Prim));
end if;
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => DT,
Aliased_Present => True,
Constant_Present => True,
Object_Definition =>
Make_Subtype_Indication (Loc,
Subtype_Mark =>
New_Occurrence_Of (RTE (RE_Dispatch_Table_Wrapper), Loc),
Constraint => Make_Index_Or_Discriminant_Constraint (Loc,
Constraints => DT_Constr_List))));
end if;
end Import_DT;
-- Local variables
Tname : constant Name_Id := Chars (Typ);
AI_Tag_Comp : Elmt_Id;
DT : Node_Id := Empty;
DT_Ptr : Node_Id;
Predef_Prims_Ptr : Node_Id;
Iface_DT : Node_Id := Empty;
Iface_DT_Ptr : Node_Id;
New_Node : Node_Id;
Suffix_Index : Int;
Typ_Name : Name_Id;
Typ_Comps : Elist_Id;
-- Start of processing for Make_Tags
begin
pragma Assert (No (Access_Disp_Table (Typ)));
Set_Access_Disp_Table (Typ, New_Elmt_List);
-- If the elaboration of this tagged type needs a boolean flag then
-- define now its entity. It is initialized to True to indicate that
-- elaboration is still pending; set to False by the IP routine.
-- TypFxx : boolean := True;
if Elab_Flag_Needed (Typ) then
Set_Access_Disp_Table_Elab_Flag (Typ,
Make_Defining_Identifier (Loc,
Chars => New_External_Name (Tname, 'F')));
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => Access_Disp_Table_Elab_Flag (Typ),
Object_Definition => New_Occurrence_Of (Standard_Boolean, Loc),
Expression => New_Occurrence_Of (Standard_True, Loc)));
end if;
-- 1) Generate the primary tag entities
-- Primary dispatch table containing user-defined primitives
DT_Ptr := Make_Defining_Identifier (Loc, New_External_Name (Tname, 'P'));
Set_Etype (DT_Ptr, RTE (RE_Tag));
Append_Elmt (DT_Ptr, Access_Disp_Table (Typ));
-- Minimum decoration
Set_Ekind (DT_Ptr, E_Variable);
Set_Related_Type (DT_Ptr, Typ);
-- Notify back end that the types are associated with a dispatch table
Set_Is_Dispatch_Table_Entity (RTE (RE_Prim_Ptr));
Set_Is_Dispatch_Table_Entity (RTE (RE_Predef_Prims_Table_Ptr));
-- For CPP types there is no need to build the dispatch tables since
-- they are imported from the C++ side. If the CPP type has an IP then
-- we declare now the variable that will store the copy of the C++ tag.
-- If the CPP type is an interface, we need the variable as well because
-- it becomes the pointer to the corresponding secondary table.
if Is_CPP_Class (Typ) then
if Has_CPP_Constructors (Typ) or else Is_Interface (Typ) then
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => DT_Ptr,
Object_Definition => New_Occurrence_Of (RTE (RE_Tag), Loc),
Expression =>
Unchecked_Convert_To (RTE (RE_Tag),
New_Occurrence_Of (RTE (RE_Null_Address), Loc))));
Set_Is_Statically_Allocated (DT_Ptr,
Is_Library_Level_Tagged_Type (Typ));
end if;
-- Ada types
else
-- Primary dispatch table containing predefined primitives
Predef_Prims_Ptr :=
Make_Defining_Identifier (Loc,
Chars => New_External_Name (Tname, 'Y'));
Set_Etype (Predef_Prims_Ptr, RTE (RE_Address));
Append_Elmt (Predef_Prims_Ptr, Access_Disp_Table (Typ));
-- Import the forward declaration of the Dispatch Table wrapper
-- record (Make_DT will take care of exporting it).
if Building_Static_DT (Typ) then
Set_Dispatch_Table_Wrappers (Typ, New_Elmt_List);
DT :=
Make_Defining_Identifier (Loc,
Chars => New_External_Name (Tname, 'T'));
Import_DT (Typ, DT, Is_Secondary_DT => False);
if Has_DT (Typ) then
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => DT_Ptr,
Constant_Present => True,
Object_Definition =>
New_Occurrence_Of (RTE (RE_Tag), Loc),
Expression =>
Unchecked_Convert_To (RTE (RE_Tag),
Make_Attribute_Reference (Loc,
Prefix =>
Make_Selected_Component (Loc,
Prefix => New_Occurrence_Of (DT, Loc),
Selector_Name =>
New_Occurrence_Of
(RTE_Record_Component (RE_Prims_Ptr), Loc)),
Attribute_Name => Name_Address))));
-- Generate the SCIL node for the previous object declaration
-- because it has a tag initialization.
if Generate_SCIL then
New_Node :=
Make_SCIL_Dispatch_Table_Tag_Init (Sloc (Last (Result)));
Set_SCIL_Entity (New_Node, Typ);
Set_SCIL_Node (Last (Result), New_Node);
end if;
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => Predef_Prims_Ptr,
Constant_Present => True,
Object_Definition =>
New_Occurrence_Of (RTE (RE_Address), Loc),
Expression =>
Make_Attribute_Reference (Loc,
Prefix =>
Make_Selected_Component (Loc,
Prefix => New_Occurrence_Of (DT, Loc),
Selector_Name =>
New_Occurrence_Of
(RTE_Record_Component (RE_Predef_Prims), Loc)),
Attribute_Name => Name_Address)));
-- No dispatch table required
else
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => DT_Ptr,
Constant_Present => True,
Object_Definition =>
New_Occurrence_Of (RTE (RE_Tag), Loc),
Expression =>
Unchecked_Convert_To (RTE (RE_Tag),
Make_Attribute_Reference (Loc,
Prefix =>
Make_Selected_Component (Loc,
Prefix => New_Occurrence_Of (DT, Loc),
Selector_Name =>
New_Occurrence_Of
(RTE_Record_Component (RE_NDT_Prims_Ptr),
Loc)),
Attribute_Name => Name_Address))));
end if;
Set_Is_True_Constant (DT_Ptr);
Set_Is_Statically_Allocated (DT_Ptr);
end if;
end if;
-- 2) Generate the secondary tag entities
-- Collect the components associated with secondary dispatch tables
if Has_Interfaces (Typ) then
Collect_Interface_Components (Typ, Typ_Comps);
-- For each interface type we build a unique external name associated
-- with its secondary dispatch table. This name is used to declare an
-- object that references this secondary dispatch table, whose value
-- will be used for the elaboration of Typ objects, and also for the
-- elaboration of objects of types derived from Typ that do not
-- override the primitives of this interface type.
Suffix_Index := 1;
-- Note: The value of Suffix_Index must be in sync with the values of
-- Suffix_Index in secondary dispatch tables generated by Make_DT.
if Is_CPP_Class (Typ) then
AI_Tag_Comp := First_Elmt (Typ_Comps);
while Present (AI_Tag_Comp) loop
Get_Secondary_DT_External_Name
(Typ, Related_Type (Node (AI_Tag_Comp)), Suffix_Index);
Typ_Name := Name_Find;
-- Declare variables to store copy of the C++ secondary tags
Iface_DT_Ptr :=
Make_Defining_Identifier (Loc,
Chars => New_External_Name (Typ_Name, 'P'));
Set_Etype (Iface_DT_Ptr, RTE (RE_Interface_Tag));
Set_Ekind (Iface_DT_Ptr, E_Variable);
Set_Is_Tag (Iface_DT_Ptr);
Set_Has_Thunks (Iface_DT_Ptr);
Set_Related_Type
(Iface_DT_Ptr, Related_Type (Node (AI_Tag_Comp)));
Append_Elmt (Iface_DT_Ptr, Access_Disp_Table (Typ));
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => Iface_DT_Ptr,
Object_Definition => New_Occurrence_Of
(RTE (RE_Interface_Tag), Loc),
Expression =>
Unchecked_Convert_To (RTE (RE_Interface_Tag),
New_Occurrence_Of (RTE (RE_Null_Address), Loc))));
Set_Is_Statically_Allocated (Iface_DT_Ptr,
Is_Library_Level_Tagged_Type (Typ));
Next_Elmt (AI_Tag_Comp);
end loop;
-- This is not a CPP_Class type
else
AI_Tag_Comp := First_Elmt (Typ_Comps);
while Present (AI_Tag_Comp) loop
Get_Secondary_DT_External_Name
(Typ, Related_Type (Node (AI_Tag_Comp)), Suffix_Index);
Typ_Name := Name_Find;
if Building_Static_DT (Typ) then
Iface_DT :=
Make_Defining_Identifier (Loc,
Chars => New_External_Name (Typ_Name, 'T'));
Import_DT
(Tag_Typ => Related_Type (Node (AI_Tag_Comp)),
DT => Iface_DT,
Is_Secondary_DT => True);
end if;
-- Secondary dispatch table referencing thunks to user-defined
-- primitives covered by this interface.
Iface_DT_Ptr :=
Make_Defining_Identifier (Loc,
Chars => New_External_Name (Typ_Name, 'P'));
Set_Etype (Iface_DT_Ptr, RTE (RE_Interface_Tag));
Set_Ekind (Iface_DT_Ptr, E_Constant);
Set_Is_Tag (Iface_DT_Ptr);
Set_Has_Thunks (Iface_DT_Ptr);
Set_Is_Statically_Allocated (Iface_DT_Ptr,
Is_Library_Level_Tagged_Type (Typ));
Set_Is_True_Constant (Iface_DT_Ptr);
Set_Related_Type
(Iface_DT_Ptr, Related_Type (Node (AI_Tag_Comp)));
Append_Elmt (Iface_DT_Ptr, Access_Disp_Table (Typ));
if Building_Static_DT (Typ) then
Append_To (Result,
Make_Object_Declaration (Loc,
Defining_Identifier => Iface_DT_Ptr,
Constant_Present => True,
Object_Definition => New_Occurrence_Of
(RTE (RE_Interface_Tag), Loc),
Expression =>
Unchecked_Convert_To (RTE (RE_Interface_Tag),
Make_Attribute_Reference (Loc,
Prefix =>
Make_Selected_Component (Loc,
Prefix =>
New_Occurrence_Of (Iface_DT, Loc),
Selector_Name =>
New_Occurrence_Of
(RTE_Record_Component (RE_Prims_Ptr),
Loc)),
Attribute_Name => Name_Address))));
end if;
-- Secondary dispatch table referencing thunks to predefined
-- primitives.
Iface_DT_Ptr :=
Make_Defining_Identifier (Loc,
Chars => New_External_Name (Typ_Name, 'Y'));
Set_Etype (Iface_DT_Ptr, RTE (RE_Address));
Set_Ekind (Iface_DT_Ptr, E_Constant);
Set_Is_Tag (Iface_DT_Ptr);
Set_Has_Thunks (Iface_DT_Ptr);
Set_Is_Statically_Allocated (Iface_DT_Ptr,
Is_Library_Level_Tagged_Type (Typ));
Set_Is_True_Constant (Iface_DT_Ptr);
Set_Related_Type
(Iface_DT_Ptr, Related_Type (Node (AI_Tag_Comp)));
Append_Elmt (Iface_DT_Ptr, Access_Disp_Table (Typ));
-- Secondary dispatch table referencing user-defined primitives
-- covered by this interface.
Iface_DT_Ptr :=
Make_Defining_Identifier (Loc,
Chars => New_External_Name (Typ_Name, 'D'));
Set_Etype (Iface_DT_Ptr, RTE (RE_Interface_Tag));
Set_Ekind (Iface_DT_Ptr, E_Constant);
Set_Is_Tag (Iface_DT_Ptr);
Set_Is_Statically_Allocated (Iface_DT_Ptr,
Is_Library_Level_Tagged_Type (Typ));
Set_Is_True_Constant (Iface_DT_Ptr);
Set_Related_Type
(Iface_DT_Ptr, Related_Type (Node (AI_Tag_Comp)));
Append_Elmt (Iface_DT_Ptr, Access_Disp_Table (Typ));
-- Secondary dispatch table referencing predefined primitives
Iface_DT_Ptr :=
Make_Defining_Identifier (Loc,
Chars => New_External_Name (Typ_Name, 'Z'));
Set_Etype (Iface_DT_Ptr, RTE (RE_Address));
Set_Ekind (Iface_DT_Ptr, E_Constant);
Set_Is_Tag (Iface_DT_Ptr);
Set_Is_Statically_Allocated (Iface_DT_Ptr,
Is_Library_Level_Tagged_Type (Typ));
Set_Is_True_Constant (Iface_DT_Ptr);
Set_Related_Type
(Iface_DT_Ptr, Related_Type (Node (AI_Tag_Comp)));
Append_Elmt (Iface_DT_Ptr, Access_Disp_Table (Typ));
Next_Elmt (AI_Tag_Comp);
end loop;
end if;
end if;
-- 3) At the end of Access_Disp_Table, if the type has user-defined
-- primitives, we add the entity of an access type declaration that
-- is used by Build_Get_Prim_Op_Address to expand dispatching calls
-- through the primary dispatch table.
if UI_To_Int (DT_Entry_Count (First_Tag_Component (Typ))) = 0 then
Analyze_List (Result);
-- Generate:
-- subtype Typ_DT is Address_Array (1 .. Nb_Prims);
-- type Typ_DT_Acc is access Typ_DT;
else
declare
Name_DT_Prims : constant Name_Id :=
New_External_Name (Tname, 'G');
Name_DT_Prims_Acc : constant Name_Id :=
New_External_Name (Tname, 'H');
DT_Prims : constant Entity_Id :=
Make_Defining_Identifier (Loc,
Name_DT_Prims);
DT_Prims_Acc : constant Entity_Id :=
Make_Defining_Identifier (Loc,
Name_DT_Prims_Acc);
begin
Append_To (Result,
Make_Subtype_Declaration (Loc,
Defining_Identifier => DT_Prims,
Subtype_Indication =>
Make_Subtype_Indication (Loc,
Subtype_Mark =>
New_Occurrence_Of (RTE (RE_Address_Array), Loc),
Constraint =>
Make_Index_Or_Discriminant_Constraint (Loc, New_List (
Make_Range (Loc,
Low_Bound => Make_Integer_Literal (Loc, 1),
High_Bound =>
Make_Integer_Literal (Loc,
DT_Entry_Count
(First_Tag_Component (Typ)))))))));
Append_To (Result,
Make_Full_Type_Declaration (Loc,
Defining_Identifier => DT_Prims_Acc,
Type_Definition =>
Make_Access_To_Object_Definition (Loc,
Subtype_Indication =>
New_Occurrence_Of (DT_Prims, Loc))));
Append_Elmt (DT_Prims_Acc, Access_Disp_Table (Typ));
-- Analyze the resulting list and suppress the generation of the
-- Init_Proc associated with the above array declaration because
-- this type is never used in object declarations. It is only used
-- to simplify the expansion associated with dispatching calls.
Analyze_List (Result);
Set_Suppress_Initialization (Base_Type (DT_Prims));
-- Disable backend optimizations based on assumptions about the
-- aliasing status of objects designated by the access to the
-- dispatch table. Required to handle dispatch tables imported
-- from C++.
Set_No_Strict_Aliasing (Base_Type (DT_Prims_Acc));
-- Add the freezing nodes of these declarations; required to avoid
-- generating these freezing nodes in wrong scopes (for example in
-- the IC routine of a derivation of Typ).
-- What is an "IC routine"? Is "init_proc" meant here???
Append_List_To (Result, Freeze_Entity (DT_Prims, Typ));
Append_List_To (Result, Freeze_Entity (DT_Prims_Acc, Typ));
-- Mark entity of dispatch table. Required by the back end to
-- handle them properly.
Set_Is_Dispatch_Table_Entity (DT_Prims);
end;
end if;
-- Mark entities of dispatch table. Required by the back end to handle
-- them properly.
if Present (DT) then
Set_Is_Dispatch_Table_Entity (DT);
Set_Is_Dispatch_Table_Entity (Etype (DT));
end if;
if Present (Iface_DT) then
Set_Is_Dispatch_Table_Entity (Iface_DT);
Set_Is_Dispatch_Table_Entity (Etype (Iface_DT));
end if;
if Is_CPP_Class (Root_Type (Typ)) then
Set_Ekind (DT_Ptr, E_Variable);
else
Set_Ekind (DT_Ptr, E_Constant);
end if;
Set_Is_Tag (DT_Ptr);
Set_Related_Type (DT_Ptr, Typ);
return Result;
end Make_Tags;
---------------
-- New_Value --
---------------
function New_Value (From : Node_Id) return Node_Id is
Res : constant Node_Id := Duplicate_Subexpr (From);
begin
if Is_Access_Type (Etype (From)) then
return Make_Explicit_Dereference (Sloc (From), Prefix => Res);
else
return Res;
end if;
end New_Value;
-----------------------------------
-- Original_View_In_Visible_Part --
-----------------------------------
function Original_View_In_Visible_Part (Typ : Entity_Id) return Boolean is
Scop : constant Entity_Id := Scope (Typ);
begin
-- The scope must be a package
if not Is_Package_Or_Generic_Package (Scop) then
return False;
end if;
-- A type with a private declaration has a private view declared in
-- the visible part.
if Has_Private_Declaration (Typ) then
return True;
end if;
return List_Containing (Parent (Typ)) =
Visible_Declarations (Package_Specification (Scop));
end Original_View_In_Visible_Part;
------------------
-- Prim_Op_Kind --
------------------
function Prim_Op_Kind
(Prim : Entity_Id;
Typ : Entity_Id) return Node_Id
is
Full_Typ : Entity_Id := Typ;
Loc : constant Source_Ptr := Sloc (Prim);
Prim_Op : Entity_Id;
begin
-- Retrieve the original primitive operation
Prim_Op := Ultimate_Alias (Prim);
if Ekind (Typ) = E_Record_Type
and then Present (Corresponding_Concurrent_Type (Typ))
then
Full_Typ := Corresponding_Concurrent_Type (Typ);
end if;
-- When a private tagged type is completed by a concurrent type,
-- retrieve the full view.
if Is_Private_Type (Full_Typ) then
Full_Typ := Full_View (Full_Typ);
end if;
if Ekind (Prim_Op) = E_Function then
-- Protected function
if Ekind (Full_Typ) = E_Protected_Type then
return New_Occurrence_Of (RTE (RE_POK_Protected_Function), Loc);
-- Task function
elsif Ekind (Full_Typ) = E_Task_Type then
return New_Occurrence_Of (RTE (RE_POK_Task_Function), Loc);
-- Regular function
else
return New_Occurrence_Of (RTE (RE_POK_Function), Loc);
end if;
else
pragma Assert (Ekind (Prim_Op) = E_Procedure);
if Ekind (Full_Typ) = E_Protected_Type then
-- Protected entry
if Is_Primitive_Wrapper (Prim_Op)
and then Ekind (Wrapped_Entity (Prim_Op)) = E_Entry
then
return New_Occurrence_Of (RTE (RE_POK_Protected_Entry), Loc);
-- Protected procedure
else
return
New_Occurrence_Of (RTE (RE_POK_Protected_Procedure), Loc);
end if;
elsif Ekind (Full_Typ) = E_Task_Type then
-- Task entry
if Is_Primitive_Wrapper (Prim_Op)
and then Ekind (Wrapped_Entity (Prim_Op)) = E_Entry
then
return New_Occurrence_Of (RTE (RE_POK_Task_Entry), Loc);
-- Task "procedure". These are the internally Expander-generated
-- procedures (task body for instance).
else
return New_Occurrence_Of (RTE (RE_POK_Task_Procedure), Loc);
end if;
-- Regular procedure
else
return New_Occurrence_Of (RTE (RE_POK_Procedure), Loc);
end if;
end if;
end Prim_Op_Kind;
------------------------
-- Register_Primitive --
------------------------
function Register_Primitive
(Loc : Source_Ptr;
Prim : Entity_Id) return List_Id
is
DT_Ptr : Entity_Id;
Iface_Prim : Entity_Id;
Iface_Typ : Entity_Id;
Iface_DT_Ptr : Entity_Id;
Iface_DT_Elmt : Elmt_Id;
L : constant List_Id := New_List;
Pos : Uint;
Tag : Entity_Id;
Tag_Typ : Entity_Id;
Thunk_Id : Entity_Id;
Thunk_Code : Node_Id;
begin
pragma Assert (not Restriction_Active (No_Dispatching_Calls));
-- Do not register in the dispatch table eliminated primitives
if not RTE_Available (RE_Tag)
or else Is_Eliminated (Ultimate_Alias (Prim))
or else Generate_SCIL
then
return L;
end if;
if not Present (Interface_Alias (Prim)) then
Tag_Typ := Scope (DTC_Entity (Prim));
Pos := DT_Position (Prim);
Tag := First_Tag_Component (Tag_Typ);
if Is_Predefined_Dispatching_Operation (Prim)
or else Is_Predefined_Dispatching_Alias (Prim)
then
DT_Ptr :=
Node (Next_Elmt (First_Elmt (Access_Disp_Table (Tag_Typ))));
Append_To (L,
Build_Set_Predefined_Prim_Op_Address (Loc,
Tag_Node => New_Occurrence_Of (DT_Ptr, Loc),
Position => Pos,
Address_Node =>
Unchecked_Convert_To (RTE (RE_Prim_Ptr),
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Prim, Loc),
Attribute_Name => Name_Unrestricted_Access))));
-- Register copy of the pointer to the 'size primitive in the TSD
if Chars (Prim) = Name_uSize
and then RTE_Record_Component_Available (RE_Size_Func)
then
DT_Ptr := Node (First_Elmt (Access_Disp_Table (Tag_Typ)));
Append_To (L,
Build_Set_Size_Function (Loc,
Tag_Node => New_Occurrence_Of (DT_Ptr, Loc),
Size_Func => Prim));
end if;
else
pragma Assert (Pos /= Uint_0 and then Pos <= DT_Entry_Count (Tag));
-- Skip registration of primitives located in the C++ part of the
-- dispatch table. Their slot is set by the IC routine.
if not Is_CPP_Class (Root_Type (Tag_Typ))
or else Pos > CPP_Num_Prims (Tag_Typ)
then
DT_Ptr := Node (First_Elmt (Access_Disp_Table (Tag_Typ)));
Append_To (L,
Build_Set_Prim_Op_Address (Loc,
Typ => Tag_Typ,
Tag_Node => New_Occurrence_Of (DT_Ptr, Loc),
Position => Pos,
Address_Node =>
Unchecked_Convert_To (RTE (RE_Prim_Ptr),
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Prim, Loc),
Attribute_Name => Name_Unrestricted_Access))));
end if;
end if;
-- Ada 2005 (AI-251): Primitive associated with an interface type
-- Generate the code of the thunk only if the interface type is not an
-- immediate ancestor of Typ; otherwise the dispatch table associated
-- with the interface is the primary dispatch table and we have nothing
-- else to do here.
else
Tag_Typ := Find_Dispatching_Type (Alias (Prim));
Iface_Typ := Find_Dispatching_Type (Interface_Alias (Prim));
pragma Assert (Is_Interface (Iface_Typ));
-- No action needed for interfaces that are ancestors of Typ because
-- their primitives are located in the primary dispatch table.
if Is_Ancestor (Iface_Typ, Tag_Typ, Use_Full_View => True) then
return L;
-- No action needed for primitives located in the C++ part of the
-- dispatch table. Their slot is set by the IC routine.
elsif Is_CPP_Class (Root_Type (Tag_Typ))
and then DT_Position (Alias (Prim)) <= CPP_Num_Prims (Tag_Typ)
and then not Is_Predefined_Dispatching_Operation (Prim)
and then not Is_Predefined_Dispatching_Alias (Prim)
then
return L;
end if;
Expand_Interface_Thunk (Prim, Thunk_Id, Thunk_Code, Iface_Typ);
if not Is_Ancestor (Iface_Typ, Tag_Typ, Use_Full_View => True)
and then Present (Thunk_Code)
then
-- Generate the code necessary to fill the appropriate entry of
-- the secondary dispatch table of Prim's controlling type with
-- Thunk_Id's address.
Iface_DT_Elmt := Find_Interface_ADT (Tag_Typ, Iface_Typ);
Iface_DT_Ptr := Node (Iface_DT_Elmt);
pragma Assert (Has_Thunks (Iface_DT_Ptr));
Iface_Prim := Interface_Alias (Prim);
Pos := DT_Position (Iface_Prim);
Tag := First_Tag_Component (Iface_Typ);
Prepend_To (L, Thunk_Code);
if Is_Predefined_Dispatching_Operation (Prim)
or else Is_Predefined_Dispatching_Alias (Prim)
then
Append_To (L,
Build_Set_Predefined_Prim_Op_Address (Loc,
Tag_Node =>
New_Occurrence_Of (Node (Next_Elmt (Iface_DT_Elmt)), Loc),
Position => Pos,
Address_Node =>
Unchecked_Convert_To (RTE (RE_Prim_Ptr),
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Thunk_Id, Loc),
Attribute_Name => Name_Unrestricted_Access))));
Next_Elmt (Iface_DT_Elmt);
Next_Elmt (Iface_DT_Elmt);
Iface_DT_Ptr := Node (Iface_DT_Elmt);
pragma Assert (not Has_Thunks (Iface_DT_Ptr));
Append_To (L,
Build_Set_Predefined_Prim_Op_Address (Loc,
Tag_Node =>
New_Occurrence_Of (Node (Next_Elmt (Iface_DT_Elmt)), Loc),
Position => Pos,
Address_Node =>
Unchecked_Convert_To (RTE (RE_Prim_Ptr),
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of (Alias (Prim), Loc),
Attribute_Name => Name_Unrestricted_Access))));
else
pragma Assert (Pos /= Uint_0
and then Pos <= DT_Entry_Count (Tag));
Append_To (L,
Build_Set_Prim_Op_Address (Loc,
Typ => Iface_Typ,
Tag_Node => New_Occurrence_Of (Iface_DT_Ptr, Loc),
Position => Pos,
Address_Node =>
Unchecked_Convert_To (RTE (RE_Prim_Ptr),
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Thunk_Id, Loc),
Attribute_Name => Name_Unrestricted_Access))));
Next_Elmt (Iface_DT_Elmt);
Next_Elmt (Iface_DT_Elmt);
Iface_DT_Ptr := Node (Iface_DT_Elmt);
pragma Assert (not Has_Thunks (Iface_DT_Ptr));
Append_To (L,
Build_Set_Prim_Op_Address (Loc,
Typ => Iface_Typ,
Tag_Node => New_Occurrence_Of (Iface_DT_Ptr, Loc),
Position => Pos,
Address_Node =>
Unchecked_Convert_To (RTE (RE_Prim_Ptr),
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of (Ultimate_Alias (Prim), Loc),
Attribute_Name => Name_Unrestricted_Access))));
end if;
end if;
end if;
return L;
end Register_Primitive;
-------------------------
-- Set_All_DT_Position --
-------------------------
procedure Set_All_DT_Position (Typ : Entity_Id) is
function In_Predef_Prims_DT (Prim : Entity_Id) return Boolean;
-- Returns True if Prim is located in the dispatch table of
-- predefined primitives
procedure Validate_Position (Prim : Entity_Id);
-- Check that position assigned to Prim is completely safe (it has not
-- been assigned to a previously defined primitive operation of Typ).
------------------------
-- In_Predef_Prims_DT --
------------------------
function In_Predef_Prims_DT (Prim : Entity_Id) return Boolean is
begin
-- Predefined primitives
if Is_Predefined_Dispatching_Operation (Prim) then
return True;
-- Renamings of predefined primitives
elsif Present (Alias (Prim))
and then Is_Predefined_Dispatching_Operation (Ultimate_Alias (Prim))
then
if Chars (Ultimate_Alias (Prim)) /= Name_Op_Eq then
return True;
-- An overriding operation that is a user-defined renaming of
-- predefined equality inherits its slot from the overridden
-- operation. Otherwise it is treated as a predefined op and
-- occupies the same predefined slot as equality. A call to it is
-- transformed into a call to its alias, which is the predefined
-- equality op. A dispatching call thus uses the proper slot if
-- operation is further inherited and called with class-wide
-- arguments.
else
return
not Comes_From_Source (Prim)
or else No (Overridden_Operation (Prim));
end if;
-- User-defined primitives
else
return False;
end if;
end In_Predef_Prims_DT;
-----------------------
-- Validate_Position --
-----------------------
procedure Validate_Position (Prim : Entity_Id) is
Op_Elmt : Elmt_Id;
Op : Entity_Id;
begin
-- Aliased primitives are safe
if Present (Alias (Prim)) then
return;
end if;
Op_Elmt := First_Elmt (Primitive_Operations (Typ));
while Present (Op_Elmt) loop
Op := Node (Op_Elmt);
-- No need to check against itself
if Op = Prim then
null;
-- Primitive operations covering abstract interfaces are
-- allocated later
elsif Present (Interface_Alias (Op)) then
null;
-- Predefined dispatching operations are completely safe. They
-- are allocated at fixed positions in a separate table.
elsif Is_Predefined_Dispatching_Operation (Op)
or else Is_Predefined_Dispatching_Alias (Op)
then
null;
-- Aliased subprograms are safe
elsif Present (Alias (Op)) then
null;
elsif DT_Position (Op) = DT_Position (Prim)
and then not Is_Predefined_Dispatching_Operation (Op)
and then not Is_Predefined_Dispatching_Operation (Prim)
and then not Is_Predefined_Dispatching_Alias (Op)
and then not Is_Predefined_Dispatching_Alias (Prim)
then
-- Handle aliased subprograms
declare
Op_1 : Entity_Id;
Op_2 : Entity_Id;
begin
Op_1 := Op;
loop
if Present (Overridden_Operation (Op_1)) then
Op_1 := Overridden_Operation (Op_1);
elsif Present (Alias (Op_1)) then
Op_1 := Alias (Op_1);
else
exit;
end if;
end loop;
Op_2 := Prim;
loop
if Present (Overridden_Operation (Op_2)) then
Op_2 := Overridden_Operation (Op_2);
elsif Present (Alias (Op_2)) then
Op_2 := Alias (Op_2);
else
exit;
end if;
end loop;
if Op_1 /= Op_2 then
raise Program_Error;
end if;
end;
end if;
Next_Elmt (Op_Elmt);
end loop;
end Validate_Position;
-- Local variables
Parent_Typ : constant Entity_Id := Etype (Typ);
First_Prim : constant Elmt_Id := First_Elmt (Primitive_Operations (Typ));
The_Tag : constant Entity_Id := First_Tag_Component (Typ);
Adjusted : Boolean := False;
Finalized : Boolean := False;
Count_Prim : Nat;
DT_Length : Nat;
Nb_Prim : Nat;
Prim : Entity_Id;
Prim_Elmt : Elmt_Id;
-- Start of processing for Set_All_DT_Position
begin
pragma Assert (Present (First_Tag_Component (Typ)));
-- Set the DT_Position for each primitive operation. Perform some sanity
-- checks to avoid building inconsistent dispatch tables.
-- First stage: Set DTC entity of all the primitive operations. This is
-- required to properly read the DT_Position attribute in latter stages.
Prim_Elmt := First_Prim;
Count_Prim := 0;
while Present (Prim_Elmt) loop
Prim := Node (Prim_Elmt);
-- Predefined primitives have a separate dispatch table
if not In_Predef_Prims_DT (Prim) then
Count_Prim := Count_Prim + 1;
end if;
Set_DTC_Entity_Value (Typ, Prim);
-- Clear any previous value of the DT_Position attribute. In this
-- way we ensure that the final position of all the primitives is
-- established by the following stages of this algorithm.
Set_DT_Position_Value (Prim, No_Uint);
Next_Elmt (Prim_Elmt);
end loop;
declare
Fixed_Prim : array (Int range 0 .. Count_Prim) of Boolean :=
(others => False);
E : Entity_Id;
procedure Handle_Inherited_Private_Subprograms (Typ : Entity_Id);
-- Called if Typ is declared in a nested package or a public child
-- package to handle inherited primitives that were inherited by Typ
-- in the visible part, but whose declaration was deferred because
-- the parent operation was private and not visible at that point.
procedure Set_Fixed_Prim (Pos : Nat);
-- Sets to true an element of the Fixed_Prim table to indicate
-- that this entry of the dispatch table of Typ is occupied.
------------------------------------------
-- Handle_Inherited_Private_Subprograms --
------------------------------------------
procedure Handle_Inherited_Private_Subprograms (Typ : Entity_Id) is
Op_List : Elist_Id;
Op_Elmt : Elmt_Id;
Op_Elmt_2 : Elmt_Id;
Prim_Op : Entity_Id;
Parent_Subp : Entity_Id;
begin
Op_List := Primitive_Operations (Typ);
Op_Elmt := First_Elmt (Op_List);
while Present (Op_Elmt) loop
Prim_Op := Node (Op_Elmt);
-- Search primitives that are implicit operations with an
-- internal name whose parent operation has a normal name.
if Present (Alias (Prim_Op))
and then Find_Dispatching_Type (Alias (Prim_Op)) /= Typ
and then not Comes_From_Source (Prim_Op)
and then Is_Internal_Name (Chars (Prim_Op))
and then not Is_Internal_Name (Chars (Alias (Prim_Op)))
then
Parent_Subp := Alias (Prim_Op);
-- Check if the type has an explicit overriding for this
-- primitive.
Op_Elmt_2 := Next_Elmt (Op_Elmt);
while Present (Op_Elmt_2) loop
if Chars (Node (Op_Elmt_2)) = Chars (Parent_Subp)
and then Type_Conformant (Prim_Op, Node (Op_Elmt_2))
then
Set_DT_Position_Value (Prim_Op,
DT_Position (Parent_Subp));
Set_DT_Position_Value (Node (Op_Elmt_2),
DT_Position (Parent_Subp));
Set_Fixed_Prim (UI_To_Int (DT_Position (Prim_Op)));
goto Next_Primitive;
end if;
Next_Elmt (Op_Elmt_2);
end loop;
end if;
<<Next_Primitive>>
Next_Elmt (Op_Elmt);
end loop;
end Handle_Inherited_Private_Subprograms;
--------------------
-- Set_Fixed_Prim --
--------------------
procedure Set_Fixed_Prim (Pos : Nat) is
begin
pragma Assert (Pos <= Count_Prim);
Fixed_Prim (Pos) := True;
exception
when Constraint_Error =>
raise Program_Error;
end Set_Fixed_Prim;
begin
-- In case of nested packages and public child package it may be
-- necessary a special management on inherited subprograms so that
-- the dispatch table is properly filled.
if Ekind (Scope (Scope (Typ))) = E_Package
and then Scope (Scope (Typ)) /= Standard_Standard
and then ((Is_Derived_Type (Typ) and then not Is_Private_Type (Typ))
or else
(Nkind (Parent (Typ)) = N_Private_Extension_Declaration
and then Is_Generic_Type (Typ)))
and then In_Open_Scopes (Scope (Etype (Typ)))
and then Is_Base_Type (Typ)
then
Handle_Inherited_Private_Subprograms (Typ);
end if;
-- Second stage: Register fixed entries
Nb_Prim := 0;
Prim_Elmt := First_Prim;
while Present (Prim_Elmt) loop
Prim := Node (Prim_Elmt);
-- Predefined primitives have a separate table and all its
-- entries are at predefined fixed positions.
if In_Predef_Prims_DT (Prim) then
if Is_Predefined_Dispatching_Operation (Prim) then
Set_DT_Position_Value (Prim,
Default_Prim_Op_Position (Prim));
else pragma Assert (Present (Alias (Prim)));
Set_DT_Position_Value (Prim,
Default_Prim_Op_Position (Ultimate_Alias (Prim)));
end if;
-- Overriding primitives of ancestor abstract interfaces
elsif Present (Interface_Alias (Prim))
and then Is_Ancestor
(Find_Dispatching_Type (Interface_Alias (Prim)), Typ,
Use_Full_View => True)
then
pragma Assert (DT_Position (Prim) = No_Uint
and then Present (DTC_Entity (Interface_Alias (Prim))));
E := Interface_Alias (Prim);
Set_DT_Position_Value (Prim, DT_Position (E));
pragma Assert
(DT_Position (Alias (Prim)) = No_Uint
or else DT_Position (Alias (Prim)) = DT_Position (E));
Set_DT_Position_Value (Alias (Prim), DT_Position (E));
Set_Fixed_Prim (UI_To_Int (DT_Position (Prim)));
-- Overriding primitives must use the same entry as the overridden
-- primitive. Note that the Alias of the operation is set when the
-- operation is declared by a renaming, in which case it is not
-- overriding. If it renames another primitive it will use the
-- same dispatch table slot, but if it renames an operation in a
-- nested package it's a new primitive and will have its own slot.
elsif not Present (Interface_Alias (Prim))
and then Present (Alias (Prim))
and then Chars (Prim) = Chars (Alias (Prim))
and then Nkind (Unit_Declaration_Node (Prim)) /=
N_Subprogram_Renaming_Declaration
then
declare
Par_Type : constant Entity_Id :=
Find_Dispatching_Type (Alias (Prim));
begin
if Present (Par_Type)
and then Par_Type /= Typ
and then Is_Ancestor (Par_Type, Typ, Use_Full_View => True)
and then Present (DTC_Entity (Alias (Prim)))
then
E := Alias (Prim);
Set_DT_Position_Value (Prim, DT_Position (E));
if not Is_Predefined_Dispatching_Alias (E) then
Set_Fixed_Prim (UI_To_Int (DT_Position (E)));
end if;
end if;
end;
end if;
Next_Elmt (Prim_Elmt);
end loop;
-- Third stage: Fix the position of all the new primitives. Entries
-- associated with primitives covering interfaces are handled in a
-- latter round.
Prim_Elmt := First_Prim;
while Present (Prim_Elmt) loop
Prim := Node (Prim_Elmt);
-- Skip primitives previously set entries
if DT_Position (Prim) /= No_Uint then
null;
-- Primitives covering interface primitives are handled later
elsif Present (Interface_Alias (Prim)) then
null;
else
-- Take the next available position in the DT
loop
Nb_Prim := Nb_Prim + 1;
pragma Assert (Nb_Prim <= Count_Prim);
exit when not Fixed_Prim (Nb_Prim);
end loop;
Set_DT_Position_Value (Prim, UI_From_Int (Nb_Prim));
Set_Fixed_Prim (Nb_Prim);
end if;
Next_Elmt (Prim_Elmt);
end loop;
end;
-- Fourth stage: Complete the decoration of primitives covering
-- interfaces (that is, propagate the DT_Position attribute from
-- the aliased primitive)
Prim_Elmt := First_Prim;
while Present (Prim_Elmt) loop
Prim := Node (Prim_Elmt);
if DT_Position (Prim) = No_Uint
and then Present (Interface_Alias (Prim))
then
pragma Assert (Present (Alias (Prim))
and then Find_Dispatching_Type (Alias (Prim)) = Typ);
-- Check if this entry will be placed in the primary DT
if Is_Ancestor
(Find_Dispatching_Type (Interface_Alias (Prim)), Typ,
Use_Full_View => True)
then
pragma Assert (DT_Position (Alias (Prim)) /= No_Uint);
Set_DT_Position_Value (Prim, DT_Position (Alias (Prim)));
-- Otherwise it will be placed in the secondary DT
else
pragma Assert
(DT_Position (Interface_Alias (Prim)) /= No_Uint);
Set_DT_Position_Value (Prim,
DT_Position (Interface_Alias (Prim)));
end if;
end if;
Next_Elmt (Prim_Elmt);
end loop;
-- Generate listing showing the contents of the dispatch tables. This
-- action is done before some further static checks because in case of
-- critical errors caused by a wrong dispatch table we need to see the
-- contents of such table.
if Debug_Flag_ZZ then
Write_DT (Typ);
end if;
-- Final stage: Ensure that the table is correct plus some further
-- verifications concerning the primitives.
Prim_Elmt := First_Prim;
DT_Length := 0;
while Present (Prim_Elmt) loop
Prim := Node (Prim_Elmt);
-- At this point all the primitives MUST have a position in the
-- dispatch table.
if DT_Position (Prim) = No_Uint then
raise Program_Error;
end if;
-- Calculate real size of the dispatch table
if not In_Predef_Prims_DT (Prim)
and then UI_To_Int (DT_Position (Prim)) > DT_Length
then
DT_Length := UI_To_Int (DT_Position (Prim));
end if;
-- Ensure that the assigned position to non-predefined dispatching
-- operations in the dispatch table is correct.
if not Is_Predefined_Dispatching_Operation (Prim)
and then not Is_Predefined_Dispatching_Alias (Prim)
then
Validate_Position (Prim);
end if;
if Chars (Prim) = Name_Finalize then
Finalized := True;
end if;
if Chars (Prim) = Name_Adjust then
Adjusted := True;
end if;
-- An abstract operation cannot be declared in the private part for a
-- visible abstract type, because it can't be overridden outside this
-- package hierarchy. For explicit declarations this is checked at
-- the point of declaration, but for inherited operations it must be
-- done when building the dispatch table.
-- Ada 2005 (AI-251): Primitives associated with interfaces are
-- excluded from this check because interfaces must be visible in
-- the public and private part (RM 7.3 (7.3/2))
-- We disable this check in Relaxed_RM_Semantics mode, to accommodate
-- legacy Ada code.
if not Relaxed_RM_Semantics
and then Is_Abstract_Type (Typ)
and then Is_Abstract_Subprogram (Prim)
and then Present (Alias (Prim))
and then not Is_Interface
(Find_Dispatching_Type (Ultimate_Alias (Prim)))
and then not Present (Interface_Alias (Prim))
and then Is_Derived_Type (Typ)
and then In_Private_Part (Current_Scope)
and then
List_Containing (Parent (Prim)) =
Private_Declarations (Package_Specification (Current_Scope))
and then Original_View_In_Visible_Part (Typ)
then
-- We exclude Input and Output stream operations because
-- Limited_Controlled inherits useless Input and Output stream
-- operations from Root_Controlled, which can never be overridden.
-- Move this check to sem???
if not Is_TSS (Prim, TSS_Stream_Input)
and then
not Is_TSS (Prim, TSS_Stream_Output)
then
Error_Msg_NE
("abstract inherited private operation&" &
" must be overridden (RM 3.9.3(10))",
Parent (Typ), Prim);
end if;
end if;
Next_Elmt (Prim_Elmt);
end loop;
-- Additional check
if Is_Controlled (Typ) then
if not Finalized then
Error_Msg_N
("controlled type has no explicit Finalize method??", Typ);
elsif not Adjusted then
Error_Msg_N
("controlled type has no explicit Adjust method??", Typ);
end if;
end if;
-- Set the final size of the Dispatch Table
Set_DT_Entry_Count (The_Tag, UI_From_Int (DT_Length));
-- The derived type must have at least as many components as its parent
-- (for root types Etype points to itself and the test cannot fail).
if DT_Entry_Count (The_Tag) <
DT_Entry_Count (First_Tag_Component (Parent_Typ))
then
raise Program_Error;
end if;
end Set_All_DT_Position;
--------------------------
-- Set_CPP_Constructors --
--------------------------
procedure Set_CPP_Constructors (Typ : Entity_Id) is
function Gen_Parameters_Profile (E : Entity_Id) return List_Id;
-- Duplicate the parameters profile of the imported C++ constructor
-- adding the "this" pointer to the object as the additional first
-- parameter under the usual form _Init : in out Typ.
----------------------------
-- Gen_Parameters_Profile --
----------------------------
function Gen_Parameters_Profile (E : Entity_Id) return List_Id is
Loc : constant Source_Ptr := Sloc (E);
Parms : List_Id;
P : Node_Id;
begin
Parms :=
New_List (
Make_Parameter_Specification (Loc,
Defining_Identifier =>
Make_Defining_Identifier (Loc, Name_uInit),
In_Present => True,
Out_Present => True,
Parameter_Type => New_Occurrence_Of (Typ, Loc)));
if Present (Parameter_Specifications (Parent (E))) then
P := First (Parameter_Specifications (Parent (E)));
while Present (P) loop
Append_To (Parms,
Make_Parameter_Specification (Loc,
Defining_Identifier =>
Make_Defining_Identifier (Loc,
Chars => Chars (Defining_Identifier (P))),
Parameter_Type => New_Copy_Tree (Parameter_Type (P)),
Expression => New_Copy_Tree (Expression (P))));
Next (P);
end loop;
end if;
return Parms;
end Gen_Parameters_Profile;
-- Local variables
Loc : Source_Ptr;
E : Entity_Id;
Found : Boolean := False;
IP : Entity_Id;
IP_Body : Node_Id;
P : Node_Id;
Parms : List_Id;
Covers_Default_Constructor : Entity_Id := Empty;
-- Start of processing for Set_CPP_Constructor
begin
pragma Assert (Is_CPP_Class (Typ));
-- Look for the constructor entities
E := Next_Entity (Typ);
while Present (E) loop
if Ekind (E) = E_Function
and then Is_Constructor (E)
then
Found := True;
Loc := Sloc (E);
Parms := Gen_Parameters_Profile (E);
IP := Make_Defining_Identifier (Loc, Make_Init_Proc_Name (Typ));
-- Case 1: Constructor of untagged type
-- If the C++ class has no virtual methods then the matching Ada
-- type is an untagged record type. In such case there is no need
-- to generate a wrapper of the C++ constructor because the _tag
-- component is not available.
if not Is_Tagged_Type (Typ) then
Discard_Node
(Make_Subprogram_Declaration (Loc,
Specification =>
Make_Procedure_Specification (Loc,
Defining_Unit_Name => IP,
Parameter_Specifications => Parms)));
Set_Init_Proc (Typ, IP);
Set_Is_Imported (IP);
Set_Is_Constructor (IP);
Set_Interface_Name (IP, Interface_Name (E));
Set_Convention (IP, Convention_CPP);
Set_Is_Public (IP);
Set_Has_Completion (IP);
-- Case 2: Constructor of a tagged type
-- In this case we generate the IP routine as a wrapper of the
-- C++ constructor because IP must also save a copy of the _tag
-- generated in the C++ side. The copy of the _tag is used by
-- Build_CPP_Init_Procedure to elaborate derivations of C++ types.
-- Generate:
-- procedure IP (_init : in out Typ; ...) is
-- procedure ConstructorP (_init : in out Typ; ...);
-- pragma Import (ConstructorP);
-- begin
-- ConstructorP (_init, ...);
-- if Typ._tag = null then
-- Typ._tag := _init._tag;
-- end if;
-- end IP;
else
declare
Body_Stmts : constant List_Id := New_List;
Constructor_Id : Entity_Id;
Constructor_Decl_Node : Node_Id;
Init_Tags_List : List_Id;
begin
Constructor_Id := Make_Temporary (Loc, 'P');
Constructor_Decl_Node :=
Make_Subprogram_Declaration (Loc,
Make_Procedure_Specification (Loc,
Defining_Unit_Name => Constructor_Id,
Parameter_Specifications => Parms));
Set_Is_Imported (Constructor_Id);
Set_Is_Constructor (Constructor_Id);
Set_Interface_Name (Constructor_Id, Interface_Name (E));
Set_Convention (Constructor_Id, Convention_CPP);
Set_Is_Public (Constructor_Id);
Set_Has_Completion (Constructor_Id);
-- Build the init procedure as a wrapper of this constructor
Parms := Gen_Parameters_Profile (E);
-- Invoke the C++ constructor
declare
Actuals : constant List_Id := New_List;
begin
P := First (Parms);
while Present (P) loop
Append_To (Actuals,
New_Occurrence_Of (Defining_Identifier (P), Loc));
Next (P);
end loop;
Append_To (Body_Stmts,
Make_Procedure_Call_Statement (Loc,
Name => New_Occurrence_Of (Constructor_Id, Loc),
Parameter_Associations => Actuals));
end;
-- Initialize copies of C++ primary and secondary tags
Init_Tags_List := New_List;
declare
Tag_Elmt : Elmt_Id;
Tag_Comp : Node_Id;
begin
Tag_Elmt := First_Elmt (Access_Disp_Table (Typ));
Tag_Comp := First_Tag_Component (Typ);
while Present (Tag_Elmt)
and then Is_Tag (Node (Tag_Elmt))
loop
-- Skip the following assertion with primary tags
-- because Related_Type is not set on primary tag
-- components.
pragma Assert
(Tag_Comp = First_Tag_Component (Typ)
or else Related_Type (Node (Tag_Elmt))
= Related_Type (Tag_Comp));
Append_To (Init_Tags_List,
Make_Assignment_Statement (Loc,
Name =>
New_Occurrence_Of (Node (Tag_Elmt), Loc),
Expression =>
Make_Selected_Component (Loc,
Prefix =>
Make_Identifier (Loc, Name_uInit),
Selector_Name =>
New_Occurrence_Of (Tag_Comp, Loc))));
Tag_Comp := Next_Tag_Component (Tag_Comp);
Next_Elmt (Tag_Elmt);
end loop;
end;
Append_To (Body_Stmts,
Make_If_Statement (Loc,
Condition =>
Make_Op_Eq (Loc,
Left_Opnd =>
New_Occurrence_Of
(Node (First_Elmt (Access_Disp_Table (Typ))),
Loc),
Right_Opnd =>
Unchecked_Convert_To (RTE (RE_Tag),
New_Occurrence_Of (RTE (RE_Null_Address), Loc))),
Then_Statements => Init_Tags_List));
IP_Body :=
Make_Subprogram_Body (Loc,
Specification =>
Make_Procedure_Specification (Loc,
Defining_Unit_Name => IP,
Parameter_Specifications => Parms),
Declarations => New_List (Constructor_Decl_Node),
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc,
Statements => Body_Stmts,
Exception_Handlers => No_List));
Discard_Node (IP_Body);
Set_Init_Proc (Typ, IP);
end;
end if;
-- If this constructor has parameters and all its parameters have
-- defaults then it covers the default constructor. The semantic
-- analyzer ensures that only one constructor with defaults covers
-- the default constructor.
if Present (Parameter_Specifications (Parent (E)))
and then Needs_No_Actuals (E)
then
Covers_Default_Constructor := IP;
end if;
end if;
Next_Entity (E);
end loop;
-- If there are no constructors, mark the type as abstract since we
-- won't be able to declare objects of that type.
if not Found then
Set_Is_Abstract_Type (Typ);
end if;
-- Handle constructor that has all its parameters with defaults and
-- hence it covers the default constructor. We generate a wrapper IP
-- which calls the covering constructor.
if Present (Covers_Default_Constructor) then
declare
Body_Stmts : List_Id;
begin
Loc := Sloc (Covers_Default_Constructor);
Body_Stmts := New_List (
Make_Procedure_Call_Statement (Loc,
Name =>
New_Occurrence_Of (Covers_Default_Constructor, Loc),
Parameter_Associations => New_List (
Make_Identifier (Loc, Name_uInit))));
IP := Make_Defining_Identifier (Loc, Make_Init_Proc_Name (Typ));
IP_Body :=
Make_Subprogram_Body (Loc,
Specification =>
Make_Procedure_Specification (Loc,
Defining_Unit_Name => IP,
Parameter_Specifications => New_List (
Make_Parameter_Specification (Loc,
Defining_Identifier =>
Make_Defining_Identifier (Loc, Name_uInit),
Parameter_Type => New_Occurrence_Of (Typ, Loc)))),
Declarations => No_List,
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc,
Statements => Body_Stmts,
Exception_Handlers => No_List));
Discard_Node (IP_Body);
Set_Init_Proc (Typ, IP);
end;
end if;
-- If the CPP type has constructors then it must import also the default
-- C++ constructor. It is required for default initialization of objects
-- of the type. It is also required to elaborate objects of Ada types
-- that are defined as derivations of this CPP type.
if Has_CPP_Constructors (Typ)
and then No (Init_Proc (Typ))
then
Error_Msg_N ("??default constructor must be imported from C++", Typ);
end if;
end Set_CPP_Constructors;
---------------------------
-- Set_DT_Position_Value --
---------------------------
procedure Set_DT_Position_Value (Prim : Entity_Id; Value : Uint) is
begin
Set_DT_Position (Prim, Value);
-- Propagate the value to the wrapped subprogram (if one is present)
if Ekind (Prim) in E_Function | E_Procedure
and then Is_Primitive_Wrapper (Prim)
and then Present (Wrapped_Entity (Prim))
and then Is_Dispatching_Operation (Wrapped_Entity (Prim))
then
Set_DT_Position (Wrapped_Entity (Prim), Value);
end if;
end Set_DT_Position_Value;
--------------------------
-- Set_DTC_Entity_Value --
--------------------------
procedure Set_DTC_Entity_Value
(Tagged_Type : Entity_Id;
Prim : Entity_Id)
is
begin
if Present (Interface_Alias (Prim))
and then Is_Interface
(Find_Dispatching_Type (Interface_Alias (Prim)))
then
Set_DTC_Entity (Prim,
Find_Interface_Tag
(T => Tagged_Type,
Iface => Find_Dispatching_Type (Interface_Alias (Prim))));
else
Set_DTC_Entity (Prim,
First_Tag_Component (Tagged_Type));
end if;
-- Propagate the value to the wrapped subprogram (if one is present)
if Ekind (Prim) in E_Function | E_Procedure
and then Is_Primitive_Wrapper (Prim)
and then Present (Wrapped_Entity (Prim))
and then Is_Dispatching_Operation (Wrapped_Entity (Prim))
then
Set_DTC_Entity (Wrapped_Entity (Prim), DTC_Entity (Prim));
end if;
end Set_DTC_Entity_Value;
-----------------
-- Tagged_Kind --
-----------------
function Tagged_Kind (T : Entity_Id) return Node_Id is
Conc_Typ : Entity_Id;
Loc : constant Source_Ptr := Sloc (T);
begin
pragma Assert
(Is_Tagged_Type (T) and then RTE_Available (RE_Tagged_Kind));
-- Abstract kinds
if Is_Abstract_Type (T) then
if Is_Limited_Record (T) then
return New_Occurrence_Of
(RTE (RE_TK_Abstract_Limited_Tagged), Loc);
else
return New_Occurrence_Of
(RTE (RE_TK_Abstract_Tagged), Loc);
end if;
-- Concurrent kinds
elsif Is_Concurrent_Record_Type (T) then
Conc_Typ := Corresponding_Concurrent_Type (T);
if Present (Full_View (Conc_Typ)) then
Conc_Typ := Full_View (Conc_Typ);
end if;
if Ekind (Conc_Typ) = E_Protected_Type then
return New_Occurrence_Of (RTE (RE_TK_Protected), Loc);
else
pragma Assert (Ekind (Conc_Typ) = E_Task_Type);
return New_Occurrence_Of (RTE (RE_TK_Task), Loc);
end if;
-- Regular tagged kinds
else
if Is_Limited_Record (T) then
return New_Occurrence_Of (RTE (RE_TK_Limited_Tagged), Loc);
else
return New_Occurrence_Of (RTE (RE_TK_Tagged), Loc);
end if;
end if;
end Tagged_Kind;
--------------
-- Write_DT --
--------------
procedure Write_DT (Typ : Entity_Id) is
Elmt : Elmt_Id;
Prim : Node_Id;
begin
-- Protect this procedure against wrong usage. Required because it will
-- be used directly from GDB
if not (Typ <= Last_Node_Id)
or else not Is_Tagged_Type (Typ)
then
Write_Str ("wrong usage: Write_DT must be used with tagged types");
Write_Eol;
return;
end if;
Write_Int (Int (Typ));
Write_Str (": ");
Write_Name (Chars (Typ));
if Is_Interface (Typ) then
Write_Str (" is interface");
end if;
Write_Eol;
Elmt := First_Elmt (Primitive_Operations (Typ));
while Present (Elmt) loop
Prim := Node (Elmt);
Write_Str (" - ");
-- Indicate if this primitive will be allocated in the primary
-- dispatch table or in a secondary dispatch table associated
-- with an abstract interface type
if Present (DTC_Entity (Prim)) then
if Etype (DTC_Entity (Prim)) = RTE (RE_Tag) then
Write_Str ("[P] ");
else
Write_Str ("[s] ");
end if;
end if;
-- Output the node of this primitive operation and its name
Write_Int (Int (Prim));
Write_Str (": ");
if Is_Predefined_Dispatching_Operation (Prim) then
Write_Str ("(predefined) ");
end if;
-- Prefix the name of the primitive with its corresponding tagged
-- type to facilitate seeing inherited primitives.
if Present (Alias (Prim)) then
Write_Name
(Chars (Find_Dispatching_Type (Ultimate_Alias (Prim))));
else
Write_Name (Chars (Typ));
end if;
Write_Str (".");
Write_Name (Chars (Prim));
-- Indicate if this primitive has an aliased primitive
if Present (Alias (Prim)) then
Write_Str (" (alias = ");
Write_Int (Int (Alias (Prim)));
-- If the DTC_Entity attribute is already set we can also output
-- the name of the interface covered by this primitive (if any).
if Ekind (Alias (Prim)) in E_Function | E_Procedure
and then Present (DTC_Entity (Alias (Prim)))
and then Is_Interface (Scope (DTC_Entity (Alias (Prim))))
then
Write_Str (" from interface ");
Write_Name (Chars (Scope (DTC_Entity (Alias (Prim)))));
end if;
if Present (Interface_Alias (Prim)) then
Write_Str (", AI_Alias of ");
if Is_Null_Interface_Primitive (Interface_Alias (Prim)) then
Write_Str ("null primitive ");
end if;
Write_Name
(Chars (Find_Dispatching_Type (Interface_Alias (Prim))));
Write_Char (':');
Write_Int (Int (Interface_Alias (Prim)));
end if;
Write_Str (")");
end if;
-- Display the final position of this primitive in its associated
-- (primary or secondary) dispatch table.
if Present (DTC_Entity (Prim))
and then DT_Position (Prim) /= No_Uint
then
Write_Str (" at #");
Write_Int (UI_To_Int (DT_Position (Prim)));
end if;
if Is_Abstract_Subprogram (Prim) then
Write_Str (" is abstract;");
-- Check if this is a null primitive
elsif Comes_From_Source (Prim)
and then Ekind (Prim) = E_Procedure
and then Null_Present (Parent (Prim))
then
Write_Str (" is null;");
end if;
if Is_Eliminated (Ultimate_Alias (Prim)) then
Write_Str (" (eliminated)");
end if;
if Is_Imported (Prim)
and then Convention (Prim) = Convention_CPP
then
Write_Str (" (C++)");
end if;
Write_Eol;
Next_Elmt (Elmt);
end loop;
end Write_DT;
end Exp_Disp;
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_Io;
procedure Compare_Ints is
A, B : Integer;
begin
Get(Item => A);
Get(Item => B);
-- Test for equality
if A = B then
Put_Line("A equals B");
end if;
-- Test For Less Than
if A < B then
Put_Line("A is less than B");
end if;
-- Test For Greater Than
if A > B then
Put_Line("A is greater than B");
end if;
end Compare_Ints;
|
pragma License (Unrestricted);
-- extended unit
with Ada.Streams;
private with Ada.Containers.Weak_Access_Holders;
private with Ada.Finalization;
private with System.Reference_Counting;
generic
type Name is private; -- it must have default value
with procedure Free (X : in out Name) is <>;
package Ada.Containers.Access_Holders is
-- Reference counted access types.
pragma Preelaborate;
type Holder is tagged private;
pragma Preelaborable_Initialization (Holder);
function Null_Holder return Holder;
overriding function "=" (Left, Right : Holder) return Boolean;
function To_Holder (Source : Name) return Holder;
-- for shorthand
function "+" (Right : Name) return Holder
renames To_Holder;
function Is_Null (Container : Holder) return Boolean;
procedure Clear (Container : in out Holder);
function Element (Container : Holder'Class) return Name;
procedure Replace_Element (Target : in out Holder; Source : Name);
-- procedure Query_Element (
-- Container : Holder;
-- Process : not null access procedure (Element : Element_Type));
-- procedure Update_Element (
-- Container : in out Holder;
-- Process : not null access procedure (Element : in out Element_Type));
function Constant_Reference (Container : Holder) return Name;
-- function Reference (
-- Container : aliased in out Holder)
-- return Reference_Type;
procedure Assign (Target : in out Holder; Source : Holder);
-- function Copy (Source : Holder) return Holder;
procedure Move (Target : in out Holder; Source : in out Holder);
procedure Swap (I, J : in out Holder);
package Weak is
type Weak_Holder is tagged private;
overriding function "=" (Left, Right : Weak_Holder) return Boolean;
function To_Weak_Holder (Source : Holder) return Weak_Holder;
function "+" (Right : Holder) return Weak_Holder
renames To_Weak_Holder;
function Null_Weak_Holder return Weak_Holder;
function To_Holder (Source : Weak_Holder) return Holder;
function "+" (Right : Weak_Holder) return Holder
renames To_Holder;
function Is_Null (Container : Weak_Holder) return Boolean;
procedure Clear (Container : in out Weak_Holder);
procedure Assign (Target : in out Weak_Holder; Source : Holder);
procedure Assign (Target : in out Holder; Source : Weak_Holder);
private
type Weak_Holder is new Finalization.Controlled with record
Super : aliased Weak_Access_Holders.Weak_Holder;
end record;
overriding procedure Initialize (Object : in out Weak_Holder);
overriding procedure Adjust (Object : in out Weak_Holder);
overriding procedure Finalize (Object : in out Weak_Holder);
package Streaming is
procedure Missing_Read (
Stream : not null access Streams.Root_Stream_Type'Class;
Item : out Weak_Holder)
with Import,
Convention => Ada, External_Name => "__drake_program_error";
procedure Missing_Write (
Stream : not null access Streams.Root_Stream_Type'Class;
Item : Weak_Holder)
with Import,
Convention => Ada, External_Name => "__drake_program_error";
function Missing_Input (
Stream : not null access Streams.Root_Stream_Type'Class)
return Weak_Holder
with Import,
Convention => Ada, External_Name => "__drake_program_error";
pragma No_Return (Missing_Read);
pragma No_Return (Missing_Write);
pragma Machine_Attribute (Missing_Input, "noreturn");
end Streaming;
for Weak_Holder'Read use Streaming.Missing_Read;
for Weak_Holder'Write use Streaming.Missing_Write;
for Weak_Holder'Input use Streaming.Missing_Input;
end Weak;
private
type Data is limited record
Super : aliased Weak_Access_Holders.Data;
Item : aliased Name;
end record;
pragma Suppress_Initialization (Data);
for Data use record
Super at 0 range 0 .. Weak_Access_Holders.Data_Size - 1;
end record;
pragma Warnings (Off, "uninitialized"); -- [gcc-5] default value of Name
Null_Data : aliased constant Data :=
(Super => (System.Reference_Counting.Static, null), Item => <>);
pragma Warnings (On, "uninitialized");
type Data_Access is access all Data;
type Holder is new Finalization.Controlled with record
Data : aliased not null Data_Access := Null_Data'Unrestricted_Access;
end record;
overriding procedure Adjust (Object : in out Holder);
overriding procedure Finalize (Object : in out Holder);
package Streaming is
procedure Missing_Read (
Stream : not null access Streams.Root_Stream_Type'Class;
Item : out Holder)
with Import,
Convention => Ada, External_Name => "__drake_program_error";
procedure Missing_Write (
Stream : not null access Streams.Root_Stream_Type'Class;
Item : Holder)
with Import,
Convention => Ada, External_Name => "__drake_program_error";
function Missing_Input (
Stream : not null access Streams.Root_Stream_Type'Class)
return Holder
with Import,
Convention => Ada, External_Name => "__drake_program_error";
pragma No_Return (Missing_Read);
pragma No_Return (Missing_Write);
pragma Machine_Attribute (Missing_Input, "noreturn");
end Streaming;
for Holder'Read use Streaming.Missing_Read;
for Holder'Write use Streaming.Missing_Write;
for Holder'Input use Streaming.Missing_Input;
end Ada.Containers.Access_Holders;
|
with Big_Integers; use Big_Integers;
with Types ; use Types;
package Construct_Conversion_Array with
SPARK_Mode,
Ghost
is
function Property
(Conversion_Array : Conversion_Array_Type;
J, K : Index_Type)
return Boolean
is
(if J mod 2 = 1 and then K mod 2 = 1
then Conversion_Array (J + K) * (+2)
= Conversion_Array (J) * Conversion_Array (K)
else Conversion_Array (J + K)
= Conversion_Array (J) * Conversion_Array (K));
-- The conversion array has a property that helps to prove
-- the product function. This function verifies the property
-- at index J + K.
--------------------------
-- Functions and lemmas --
--------------------------
function Two_Power (Expon : Natural) return Big_Integer is
((+2) ** Expon);
-- Returns a big integer equal to 2 to the power Expon.
procedure Two_Power_Lemma (A, B : Natural) with
Pre => A <= Natural'Last - B,
Post => Two_Power (A + B) = Two_Power (A) * Two_Power (B);
procedure Two_Power_Lemma (A, B : Natural) is null;
-- Basic property of exponentiation used in proof.
function Exposant (J : Product_Index_Type) return Natural is
(Natural (J) / 2 * 51 + (if J mod 2 = 1 then 26 else 0))
with
Post => Exposant'Result <= Natural (J) * 51;
-- Returns the exposant of 2 at J index of conversion array.
-- (i.e Conversion_Array (J) = Two_Power (Exposant (J)))
procedure Exposant_Lemma (J, K : Index_Type) with
Contract_Cases =>
(J mod 2 = 1 and then K mod 2 = 1 => Exposant (J + K) + 1 = Exposant (J) + Exposant (K),
others => Exposant (J + K) = Exposant (J) + Exposant (K));
procedure Exposant_Lemma (J, K : Index_Type) is null;
-- Specificity of Exposant function, that helps to prove
-- the property.
----------------------------------------------------------------
-- Computation and proof of Conversion array and its property --
----------------------------------------------------------------
function Conversion_Array return Conversion_Array_Type with
Post => (for all J in Index_Type =>
(for all K in Index_Type =>
Property (Conversion_Array'Result, J, K)));
-- Computes the conversion array
procedure Prove_Property (Conversion_Array : Conversion_Array_Type) with
Pre => (for all J in Product_Index_Type => Conversion_Array (J) = Two_Power (Exposant (J))),
Post => (for all L in Index_Type =>
(for all M in Index_Type =>
Property (Conversion_Array, L, M)));
-- Helps to prove the property for all indexes of
-- Conversion_Array. Preconditions states that
-- the input array has the right content.
end Construct_Conversion_Array;
|
with Pack13_Pkg;
package Pack13 is
package Four_Bits is new Pack13_Pkg (4);
package Thirty_Two_Bits is new Pack13_Pkg (32);
type Object is private;
type Object_Ptr is access all Object;
procedure Set (Myself : Object_Ptr; The_Data : Thirty_Two_Bits.Object);
private
type Some_Record is record
Data_1 : Thirty_Two_Bits.Object;
Data_2 : Thirty_Two_Bits.Object;
Small_Data : Four_Bits.Object;
end record;
for Some_Record use record
Data_1 at 0 range 0 .. 31;
Data_2 at 4 range 0 .. 31;
Small_Data at 8 range 0 .. 3;
end record;
type Object is record
Something : Some_Record;
end record;
for Object use record
Something at 0 range 0 .. 67;
end record;
end Pack13;
|
-- part of AdaYaml, (c) 2017 Felix Krause
-- released under the terms of the MIT license, see the file "copying.txt"
with Ada.Text_IO;
with Ada.Command_Line;
with Yaml.Source.Text_IO;
with Yaml.Source.File;
with Yaml.Stream_Concept;
with Yaml.Parser.Stream;
with Yaml.Presenter;
with Yaml.Destination.Text_IO;
with Yaml.Source;
with Yaml.Transformator.Annotation_Processor;
with Yaml.Transformator.Canonical;
with Yaml.Transformation;
procedure Yaml.Transform is
package Parser_Transformation is new Transformation (Parser.Stream);
package Transformation_Stream is new Stream_Concept
(Parser_Transformation.Instance, Parser_Transformation.Reference,
Parser_Transformation.Accessor, Parser_Transformation.Value,
Parser_Transformation.Next);
Input : Source.Pointer;
P : constant Parser.Reference := Parser.New_Parser;
Trans : Parser_Transformation.Instance := Parser_Transformation.Transform (P);
Pres : Presenter.Instance;
procedure Consume_Canonical is new
Presenter.Consume (Transformation_Stream);
begin
if Ada.Command_Line.Argument_Count = 0 then
Input := Source.Text_IO.As_Source (Ada.Text_IO.Standard_Input);
else
Input := Source.File.As_Source (Ada.Command_Line.Argument (1));
end if;
P.Value.Set_Input (Input);
Trans.Append (Transformator.Annotation_Processor.New_Processor (P.Value.Pool));
Trans.Append (new Transformator.Canonical.Instance);
Pres.Configure (Presenter.Default_Line_Length, Presenter.Canonical);
Pres.Set_Output (Destination.Text_IO.As_Destination (Ada.Text_IO.Standard_Output));
Consume_Canonical (Pres, Trans);
end Yaml.Transform;
|
-- Generated by utildgen.c from system includes
with Interfaces.C;
package Util.Systems.Constants is
pragma Pure;
-- Flags used when opening a file with open/creat.
O_RDONLY : constant Interfaces.C.int := 8#000000#;
O_WRONLY : constant Interfaces.C.int := 8#000001#;
O_RDWR : constant Interfaces.C.int := 8#000002#;
O_CREAT : constant Interfaces.C.int := 8#001000#;
O_EXCL : constant Interfaces.C.int := 8#004000#;
O_TRUNC : constant Interfaces.C.int := 8#002000#;
O_APPEND : constant Interfaces.C.int := 8#000010#;
O_CLOEXEC : constant Interfaces.C.int := 8#100000000#;
O_SYNC : constant Interfaces.C.int := 8#000200#;
O_DIRECT : constant Interfaces.C.int := 0;
O_NONBLOCK : constant Interfaces.C.int := 8#000004#;
-- Flags used by fcntl
F_SETFL : constant Interfaces.C.int := 4;
F_GETFL : constant Interfaces.C.int := 3;
FD_CLOEXEC : constant Interfaces.C.int := 1;
-- Flags used by dlopen
RTLD_LAZY : constant Interfaces.C.int := 8#000001#;
RTLD_NOW : constant Interfaces.C.int := 8#000002#;
RTLD_NOLOAD : constant Interfaces.C.int := 8#000020#;
RTLD_DEEPBIND : constant Interfaces.C.int := 8#000000#;
RTLD_GLOBAL : constant Interfaces.C.int := 8#000010#;
RTLD_LOCAL : constant Interfaces.C.int := 8#000004#;
RTLD_NODELETE : constant Interfaces.C.int := 8#000200#;
DLL_OPTIONS : constant String := "-ldl";
SYMBOL_PREFIX : constant String := "_";
end Util.Systems.Constants;
|
with Ada.Text_Io; use Ada.Text_Io;
package body Example1 is
procedure Sense is
begin
Dummy := 0;
Count := Count + 1;
Put_Line ("Sense Start");
Put_Line (Integer'Image(Count mod 2));
if Count mod 2 = 0 then
for I in Integer range 1 .. 10000000 loop
Dummy := Dummy + 1;
end loop;
for I in Integer range 1 .. 10000000 loop
Dummy := Dummy + 1;
end loop;
else
for I in Integer range 1 .. 10 loop
Dummy := Dummy + 1;
end if;
Put_Line ("Sense End");
end Sense;
function Handle_Deadline (N : Positive) return Positive is
begin
if Count mod 2 = 0 then
for I in Integer range 1 .. 10000000 loop
Dummy := Dummy + 1;
end loop;
for I in Integer range 1 .. 10000000 loop
Dummy := Dummy + 1;
end loop;
else
for I in Integer range 1 .. 10 loop
Dummy := Dummy + 1;
end loop;
end if;
return Dummy;
end Handle_Deadline;
end Example1;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- E X P _ P A K D --
-- --
-- S p e c --
-- --
-- $Revision$
-- --
-- Copyright (C) 1992-2001 Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
-- MA 02111-1307, USA. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- Expand routines for manipulation of packed arrays
with Types; use Types;
package Exp_Pakd is
-------------------------------------
-- Implementation of Packed Arrays --
-------------------------------------
-- When a packed array (sub)type is frozen, we create a corresponding
-- type that will be used to hold the bits of the packed value, and
-- store the entity for this type in the Packed_Array_Type field of the
-- E_Array_Type or E_Array_Subtype entity for the packed array.
-- This packed array type has the name xxxPn, where xxx is the name
-- of the packed type, and n is the component size. The expanded
-- declaration declares a type that is one of the following:
-- For an unconstrained array with component size 1,2,4 or any other
-- odd component size. These are the cases in which we do not need
-- to align the underlying array.
-- type xxxPn is new Packed_Bytes1;
-- For an unconstrained array with component size that is divisible
-- by 2, but not divisible by 4 (other than 2 itself). These are the
-- cases in which we can generate better code if the underlying array
-- is 2-byte aligned (see System.Pack_14 in file s-pack14 for example).
-- type xxxPn is new Packed_Bytes2;
-- For an unconstrained array with component size that is divisible
-- by 4, other than powers of 2 (which either come under the 1,2,4
-- exception above, or are not packed at all). These are cases where
-- we can generate better code if the underlying array is 4-byte
-- aligned (see System.Pack_20 in file s-pack20 for example).
-- type xxxPn is new Packed_Bytes4;
-- For a constrained array with a static index type where the number
-- of bits does not exceed the size of Unsigned:
-- type xxxPn is new Unsigned range 0 .. 2 ** nbits - 1;
-- For a constrained array with a static index type where the number
-- of bits is greater than the size of Unsigned, but does not exceed
-- the size of Long_Long_Unsigned:
-- type xxxPn is new Long_Long_Unsigned range 0 .. 2 ** nbits - 1;
-- For all other constrained arrays, we use one of
-- type xxxPn is new Packed_Bytes1 (0 .. m);
-- type xxxPn is new Packed_Bytes2 (0 .. m);
-- type xxxPn is new Packed_Bytes4 (0 .. m);
-- where m is calculated (from the length of the original packed array)
-- to hold the required number of bits, and the choice of the particular
-- Packed_Bytes{1,2,4} type is made on the basis of alignment needs as
-- described above for the unconstrained case.
-- When a variable of packed array type is allocated, gigi will allocate
-- the amount of space indicated by the corresponding packed array type.
-- However, we do NOT attempt to rewrite the types of any references or
-- to retype the variable itself, since this would cause all kinds of
-- semantic problems in the front end (remember that expansion proceeds
-- at the same time as analysis).
-- For an indexed reference to a packed array, we simply convert the
-- reference to the appropriate equivalent reference to the object
-- of the packed array type (using unchecked conversion).
-- In some cases (for internally generated types, and for the subtypes
-- for record fields that depend on a discriminant), the corresponding
-- packed type cannot be easily generated in advance. In these cases,
-- we generate the required subtype on the fly at the reference point.
-- For the modular case, any unused bits are initialized to zero, and
-- all operations maintain these bits as zero (where necessary all
-- unchecked conversions from corresponding array values require
-- these bits to be clear, which is done automatically by gigi).
-- For the array cases, there can be unused bits in the last byte, and
-- these are neither initialized, nor treated specially in operations
-- (i.e. it is allowable for these bits to be clobbered, e.g. by not).
---------------------------
-- Endian Considerations --
---------------------------
-- The standard does not specify the way in which bits are numbered in
-- a packed array. There are two reasonable rules for deciding this:
-- Store the first bit at right end (low order) word. This means
-- that the scaled subscript can be used directly as a right shift
-- count (if we put bit 0 at the left end, then we need an extra
-- subtract to compute the shift count.
-- Layout the bits so that if the packed boolean array is overlaid on
-- a record, using unchecked conversion, then bit 0 of the array is
-- the same as the bit numbered bit 0 in a record representation
-- clause applying to the record. For example:
-- type Rec is record
-- C : Bits4;
-- D : Bits7;
-- E : Bits5;
-- end record;
-- for Rec use record
-- C at 0 range 0 .. 3;
-- D at 0 range 4 .. 10;
-- E at 0 range 11 .. 15;
-- end record;
-- type P16 is array (0 .. 15) of Boolean;
-- pragma Pack (P16);
-- Now if we use unchecked conversion to convert a value of the record
-- type to the packed array type, according to this second criterion,
-- we would expect field D to occupy bits 4..10 of the Boolean array.
-- Although not required, this correspondence seems a highly desirable
-- property, and is one that GNAT decides to guarantee. For a little
-- endian machine, we can also meet the first requirement, but for a
-- big endian machine, it will be necessary to store the first bit of
-- a Boolean array in the left end (most significant) bit of the word.
-- This may cost an extra instruction on some machines, but we consider
-- that a worthwhile price to pay for the consistency.
-- One more important point arises in the case where we have a constrained
-- subtype of an unconstrained array. Take the case of 20-bits. For the
-- unconstrained representation, we would use an array of bytes:
-- Little-endian case
-- 8-7-6-5-4-3-2-1 16-15-14-13-12-11-10-9 x-x-x-x-20-19-18-17
-- Big-endian case
-- 1-2-3-4-5-6-7-8 9-10-11-12-13-14-15-16 17-18-19-20-x-x-x-x
-- For the constrained case, we use a 20-bit modular value, but in
-- general this value may well be stored in 32 bits. Let's look at
-- what it looks like:
-- Little-endian case
-- x-x-x-x-x-x-x-x-x-x-x-x-20-19-18-17-...-10-9-8-7-6-5-4-3-2-1
-- which stored in memory looks like
-- 8-7-...-2-1 16-15-...-10-9 x-x-x-x-20-19-18-17 x-x-x-x-x-x-x
-- An important rule is that the constrained and unconstrained cases
-- must have the same bit representation in memory, since we will often
-- convert from one to the other (e.g. when calling a procedure whose
-- formal is unconstrained). As we see, that criterion is met for the
-- little-endian case above. Now let's look at the big-endian case:
-- Big-endian case
-- x-x-x-x-x-x-x-x-x-x-x-x-1-2-3-4-5-6-7-8-9-10-...-17-18-19-20
-- which stored in memory looks like
-- x-x-x-x-x-x-x-x x-x-x-x-1-2-3-4 5-6-...11-12 13-14-...-19-20
-- That won't do, the representation value in memory is NOT the same in
-- the constrained and unconstrained case. The solution is to store the
-- modular value left-justified:
-- 1-2-3-4-5-6-7-8-9-10-...-17-18-19-20-x-x-x-x-x-x-x-x-x-x-x
-- which stored in memory looks like
-- 1-2-...-7-8 9-10-...15-16 17-18-19-20-x-x-x-x x-x-x-x-x-x-x-x
-- and now, we do indeed have the same representation. The special flag
-- Is_Left_Justified_Modular is set in the modular type used as the
-- packed array type in the big-endian case to ensure that this required
-- left justification occurs.
-----------------
-- Subprograms --
-----------------
procedure Create_Packed_Array_Type (Typ : Entity_Id);
-- Typ is a array type or subtype to which pragma Pack applies. If the
-- Packed_Array_Type field of Typ is already set, then the call has no
-- effect, otherwise a suitable type or subtype is created and stored
-- in the Packed_Array_Type field of Typ. This created type is an Itype
-- so that Gigi will simply elaborate and freeze the type on first use
-- (which is typically the definition of the corresponding array type).
--
-- Note: although this routine is included in the expander package for
-- packed types, it is actually called unconditionally from Freeze,
-- whether or not expansion (and code generation) is enabled. We do this
-- since we want gigi to be able to properly compute type charactersitics
-- (for the Data Decomposition Annex of ASIS, and possible other future
-- uses) even if code generation is not active. Strictly this means that
-- this procedure is not part of the expander, but it seems appropriate
-- to keep it together with the other expansion routines that have to do
-- with packed array types.
procedure Expand_Packed_Boolean_Operator (N : Node_Id);
-- N is an N_Op_And, N_Op_Or or N_Op_Xor node whose operand type is a
-- packed boolean array. This routine expands the appropriate operations
-- to carry out the logical operation on the packed arrays. It handles
-- both the modular and array representation cases.
procedure Expand_Packed_Element_Reference (N : Node_Id);
-- N is an N_Indexed_Component node whose prefix is a packed array. In
-- the bit packed case, this routine can only be used for the expression
-- evaluation case not the assignment case, since the result is not a
-- variable. See Expand_Bit_Packed_Element_Set for how he assignment case
-- is handled in the bit packed case. For the enumeration case, the result
-- of this call is always a variable, so the call can be used for both the
-- expression evaluation and assignment cases.
procedure Expand_Bit_Packed_Element_Set (N : Node_Id);
-- N is an N_Assignment_Statement node whose name is an indexed
-- component of a bit-packed array. This procedure rewrites the entire
-- assignment statement with appropriate code to set the referenced
-- bits of the packed array type object. Note that this procedure is
-- used only for the bit-packed case, not for the enumeration case.
procedure Expand_Packed_Eq (N : Node_Id);
-- N is an N_Op_Eq node where the operands are packed arrays whose
-- representation is an array-of-bytes type (the case where a modular
-- type is used for the representation does not require any special
-- handling, because in the modular case, unused bits are zeroes.
procedure Expand_Packed_Not (N : Node_Id);
-- N is an N_Op_Not node where the operand is packed array of Boolean
-- in standard representation (i.e. component size is one bit). This
-- procedure expands the corresponding not operation. Note that the
-- non-standard representation case is handled by using a loop through
-- elements generated by the normal non-packed circuitry.
function Involves_Packed_Array_Reference (N : Node_Id) return Boolean;
-- N is the node for a name. This function returns true if the name
-- involves a packed array reference. A node involves a packed array
-- reference if it is itself an indexed compoment referring to a bit-
-- packed array, or it is a selected component whose prefix involves
-- a packed array reference.
procedure Expand_Packed_Address_Reference (N : Node_Id);
-- The node N is an attribute reference for the 'Address reference, where
-- the prefix involves a packed array reference. This routine expands the
-- necessary code for performing the address reference in this case.
end Exp_Pakd;
|
package body Bit_Streams is
procedure Finalize (Stream : in out Bit_Stream) is
begin
if Stream.Write_Count > 0 then
Stream.Output (1) := Stream.Output (1) * 2**(Stream_Element'Size - Stream.Write_Count);
Stream.Channel.Write (Stream.Output);
end if;
end Finalize;
procedure Read (Stream : in out Bit_Stream; Data : out Bit_Array) is
Last : Stream_Element_Offset;
begin
for Index in Data'Range loop
if Stream.Read_Count = 0 then
Stream.Channel.Read (Stream.Input, Last);
Stream.Read_Count := Stream_Element'Size;
end if;
Data (Index) := Bit (Stream.Input (1) / 2**(Stream_Element'Size - 1));
Stream.Input (1) := Stream.Input (1) * 2;
Stream.Read_Count := Stream.Read_Count - 1;
end loop;
end Read;
procedure Write (Stream : in out Bit_Stream; Data : Bit_Array) is
begin
for Index in Data'Range loop
if Stream.Write_Count = Stream_Element'Size then
Stream.Channel.Write (Stream.Output);
Stream.Write_Count := 0;
end if;
Stream.Output (1) := Stream.Output (1) * 2 or Stream_Element (Data (Index));
Stream.Write_Count := Stream.Write_Count + 1;
end loop;
end Write;
end Bit_Streams;
|
-----------------------------------------------------------------------
-- druss-gateways -- Gateway management
-- Copyright (C) 2017, 2021 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Properties.Basic;
with Util.Strings;
with Util.Log.Loggers;
with Util.Http.Clients;
package body Druss.Gateways is
use Ada.Strings.Unbounded;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Gateways");
protected body Gateway_State is
function Get_State return State_Type is
begin
return State;
end Get_State;
end Gateway_State;
function "=" (Left, Right : in Gateway_Ref) return Boolean is
begin
if Left.Is_Null then
return Right.Is_Null;
elsif Right.Is_Null then
return False;
else
declare
Left_Rule : constant Gateway_Refs.Element_Accessor := Left.Value;
Right_Rule : constant Gateway_Refs.Element_Accessor := Right.Value;
begin
return Left_Rule.Element = Right_Rule.Element;
end;
end if;
end "=";
package Int_Property renames Util.Properties.Basic.Integer_Property;
package Bool_Property renames Util.Properties.Basic.Boolean_Property;
-- ------------------------------
-- Initalize the list of gateways from the property list.
-- ------------------------------
procedure Initialize (Config : in Util.Properties.Manager;
List : in out Gateway_Vector) is
Count : constant Natural := Int_Property.Get (Config, "druss.bbox.count", 0);
begin
for I in 1 .. Count loop
declare
Gw : constant Gateway_Ref := Gateway_Refs.Create;
Base : constant String := "druss.bbox." & Util.Strings.Image (I);
begin
Gw.Value.Ip := Config.Get (Base & ".ip");
if Config.Exists (Base & ".images") then
Gw.Value.Images := Config.Get (Base & ".images");
end if;
Gw.Value.Passwd := Config.Get (Base & ".password");
Gw.Value.Serial := Config.Get (Base & ".serial");
Gw.Value.Enable := Bool_Property.Get (Config, Base & ".enable", True);
List.Append (Gw);
exception
when Util.Properties.NO_PROPERTY =>
Log.Debug ("Ignoring gatway {0}", Base);
end;
end loop;
end Initialize;
-- ------------------------------
-- Save the list of gateways.
-- ------------------------------
procedure Save_Gateways (Config : in out Util.Properties.Manager;
List : in Druss.Gateways.Gateway_Vector) is
Pos : Natural := 0;
begin
for Gw of List loop
Pos := Pos + 1;
declare
Base : constant String := "druss.bbox." & Util.Strings.Image (Pos);
begin
Config.Set (Base & ".ip", Gw.Value.Ip);
Config.Set (Base & ".password", Gw.Value.Passwd);
Config.Set (Base & ".serial", Gw.Value.Serial);
Bool_Property.Set (Config, Base & ".enable", Gw.Value.Enable);
exception
when Util.Properties.NO_PROPERTY =>
null;
end;
end loop;
Util.Properties.Basic.Integer_Property.Set (Config, "druss.bbox.count", Pos);
end Save_Gateways;
-- ------------------------------
-- Refresh the information by using the Bbox API.
-- ------------------------------
procedure Refresh (Gateway : in out Gateway_Type) is
Box : Bbox.API.Client_Type;
begin
if Gateway.State.Get_State = BUSY then
return;
end if;
Box.Set_Server (To_String (Gateway.Ip));
if Ada.Strings.Unbounded.Length (Gateway.Passwd) > 0 then
Box.Login (To_String (Gateway.Passwd));
end if;
Box.Get ("wan/ip", Gateway.Wan);
Box.Get ("lan/ip", Gateway.Lan);
Box.Get ("device", Gateway.Device);
Box.Get ("wireless", Gateway.Wifi);
Box.Get ("voip", Gateway.Voip);
Box.Get ("iptv", Gateway.IPtv);
Box.Get ("hosts", Gateway.Hosts);
if Gateway.Device.Exists ("device.serialnumber") then
Gateway.Serial := Gateway.Device.Get ("device.serialnumber");
end if;
exception
when Util.Http.Clients.Connection_Error =>
Log.Error ("Cannot connect to {0}", To_String (Gateway.Ip));
end Refresh;
-- ------------------------------
-- Refresh the information by using the Bbox API.
-- ------------------------------
procedure Refresh (Gateway : in Gateway_Ref) is
begin
Gateway.Value.Refresh;
end Refresh;
-- ------------------------------
-- Iterate over the list of gateways and execute the <tt>Process</tt> procedure.
-- ------------------------------
procedure Iterate (List : in Gateway_Vector;
Mode : in Iterate_Type := ITER_ALL;
Process : not null access procedure (G : in out Gateway_Type)) is
Expect : constant Boolean := Mode = ITER_ENABLE;
begin
for G of List loop
if Mode = ITER_ALL or else G.Value.Enable = Expect then
Process (G.Value);
end if;
end loop;
end Iterate;
Null_Gateway : Gateway_Ref;
-- ------------------------------
-- Find the gateway with the given IP address.
-- ------------------------------
function Find_IP (List : in Gateway_Vector;
IP : in String) return Gateway_Ref is
begin
for G of List loop
if G.Value.Ip = IP then
return G;
end if;
end loop;
Log.Debug ("No gateway with IP {0}", IP);
return Null_Gateway;
end Find_IP;
end Druss.Gateways;
|
with Ada.Text_IO,
POSIX.IO,
POSIX.Memory_Mapping,
System.Storage_Elements;
procedure Read_Entire_File is
use POSIX, POSIX.IO, POSIX.Memory_Mapping;
use System.Storage_Elements;
Text_File : File_Descriptor;
Text_Size : System.Storage_Elements.Storage_Offset;
Text_Address : System.Address;
begin
Text_File := Open (Name => "read_entire_file.adb",
Mode => Read_Only);
Text_Size := Storage_Offset (File_Size (Text_File));
Text_Address := Map_Memory (Length => Text_Size,
Protection => Allow_Read,
Mapping => Map_Shared,
File => Text_File,
Offset => 0);
declare
Text : String (1 .. Natural (Text_Size));
for Text'Address use Text_Address;
begin
Ada.Text_IO.Put (Text);
end;
Unmap_Memory (First => Text_Address,
Length => Text_Size);
Close (File => Text_File);
end Read_Entire_File;
|
-- part of OpenGLAda, (c) 2017 Felix Krause
-- released under the terms of the MIT license, see the file "COPYING"
with GL.API;
package body GL.Toggles is
procedure Enable (Subject : Toggle) is
begin
API.Enable (Subject);
Raise_Exception_On_OpenGL_Error;
end Enable;
procedure Disable (Subject : Toggle) is
begin
API.Disable (Subject);
Raise_Exception_On_OpenGL_Error;
end Disable;
procedure Set (Subject : Toggle; Value : Toggle_State) is
begin
if Value = Disabled then
API.Disable (Subject);
else
API.Enable (Subject);
end if;
Raise_Exception_On_OpenGL_Error;
end Set;
function State (Subject : Toggle) return Toggle_State is
Value : constant Low_Level.Bool := API.Is_Enabled (Subject);
begin
Raise_Exception_On_OpenGL_Error;
if Value then
return Enabled;
else
return Disabled;
end if;
end State;
end GL.Toggles; |
with agar.core.error;
package body agar.gui is
use type c.int;
package cbinds is
function init (flags : agar.core.init_flags_t := 0) return c.int;
pragma import (c, init, "AG_InitGUI");
function init_video
(width : c.int;
height : c.int;
bpp : c.int;
flags : video_flags_t := 0) return c.int;
pragma import (c, init_video, "AG_InitVideo");
end cbinds;
protected state is
procedure init_gui;
procedure init_video;
function inited_gui return boolean;
function inited_video return boolean;
private
gui : boolean := false;
video : boolean := false;
end state;
protected body state is
procedure init_gui is begin gui := true; end;
procedure init_video is begin video := true; end;
function inited_gui return boolean is begin return gui; end;
function inited_video return boolean is begin return video; end;
end state;
function init_video
(width : positive;
height : positive;
bpp : natural;
flags : video_flags_t := 0) return boolean is
begin
if cbinds.init_video
(width => c.int (width),
height => c.int (height),
bpp => c.int (bpp),
flags => flags) = 0 then
state.init_video;
end if;
return state.inited_video;
end init_video;
function init (flags : agar.core.init_flags_t := 0) return boolean is
begin
if state.inited_video then
if cbinds.init (flags) = 0 then
state.init_gui;
end if;
else
agar.core.error.set ("video must be initialised before GUI");
end if;
return state.inited_gui;
end init;
end agar.gui;
|
-----------------------------------------------------------------------
-- util-nullables -- Basic types that can hold a null value
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
-- === Nullable types ===
-- Sometimes it is necessary to represent a simple data type with an optional boolean information
-- that indicates whether the value is valid or just null. The concept of nullable type is often
-- used in databases but also in JSON data representation. The <tt>Util.Nullables</tt> package
-- provides several standard type to express the null capability of a value.
--
-- By default a nullable instance is created with the null flag set.
package Util.Nullables is
use type Ada.Strings.Unbounded.Unbounded_String;
use type Ada.Calendar.Time;
DEFAULT_TIME : constant Ada.Calendar.Time;
-- ------------------------------
-- A boolean which can be null.
-- ------------------------------
type Nullable_Boolean is record
Value : Boolean := False;
Is_Null : Boolean := True;
end record;
Null_Boolean : constant Nullable_Boolean;
-- Return True if the two nullable times are identical (both null or both same value).
function "=" (Left, Right : in Nullable_Boolean) return Boolean is
(Left.Is_Null = Right.Is_Null and (Left.Is_Null or else Left.Value = Right.Value));
-- ------------------------------
-- An integer which can be null.
-- ------------------------------
type Nullable_Integer is record
Value : Integer := 0;
Is_Null : Boolean := True;
end record;
Null_Integer : constant Nullable_Integer;
-- Return True if the two nullable times are identical (both null or both same value).
function "=" (Left, Right : in Nullable_Integer) return Boolean is
(Left.Is_Null = Right.Is_Null and (Left.Is_Null or else Left.Value = Right.Value));
-- ------------------------------
-- A long which can be null.
-- ------------------------------
type Nullable_Long is record
Value : Long_Long_Integer := 0;
Is_Null : Boolean := True;
end record;
Null_Long : constant Nullable_Long;
-- Return True if the two nullable times are identical (both null or both same value).
function "=" (Left, Right : in Nullable_Long) return Boolean is
(Left.Is_Null = Right.Is_Null and (Left.Is_Null or else Left.Value = Right.Value));
-- ------------------------------
-- A string which can be null.
-- ------------------------------
type Nullable_String is record
Value : Ada.Strings.Unbounded.Unbounded_String;
Is_Null : Boolean := True;
end record;
Null_String : constant Nullable_String;
-- Return True if the two nullable times are identical (both null or both same value).
function "=" (Left, Right : in Nullable_String) return Boolean is
(Left.Is_Null = Right.Is_Null and (Left.Is_Null or else Left.Value = Right.Value));
-- ------------------------------
-- A date which can be null.
-- ------------------------------
type Nullable_Time is record
Value : Ada.Calendar.Time := DEFAULT_TIME;
Is_Null : Boolean := True;
end record;
Null_Time : constant Nullable_Time;
-- Return True if the two nullable times are identical (both null or both same time).
function "=" (Left, Right : in Nullable_Time) return Boolean is
(Left.Is_Null = Right.Is_Null and (Left.Is_Null or else Left.Value = Right.Value));
private
DEFAULT_TIME : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1901,
Month => 1,
Day => 2,
Seconds => 0.0);
Null_Boolean : constant Nullable_Boolean
:= Nullable_Boolean '(Is_Null => True,
Value => False);
Null_Integer : constant Nullable_Integer
:= Nullable_Integer '(Is_Null => True,
Value => 0);
Null_Long : constant Nullable_Long
:= Nullable_Long '(Is_Null => True,
Value => 0);
Null_String : constant Nullable_String
:= Nullable_String '(Is_Null => True,
Value => Ada.Strings.Unbounded.Null_Unbounded_String);
Null_Time : constant Nullable_Time
:= Nullable_Time '(Is_Null => True,
Value => DEFAULT_TIME);
end Util.Nullables;
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Natools.S_Expressions.Test_Tools;
package body Natools.S_Expressions.Atom_Buffers.Tests is
----------------------
-- Whole Test Suite --
----------------------
procedure All_Tests (Report : in out NT.Reporter'Class) is
begin
Test_Block_Append (Report);
Test_Octet_Append (Report);
Test_Preallocate (Report);
Test_Query (Report);
Test_Query_Null (Report);
Test_Reset (Report);
Test_Reverse_Append (Report);
Test_Invert (Report);
Test_Empty_Append (Report);
Test_Stream_Interface (Report);
end All_Tests;
----------------------
-- Individual Tests --
----------------------
procedure Test_Block_Append (Report : in out NT.Reporter'Class) is
Name : constant String := "Append in blocks";
Data : Atom (0 .. 255);
begin
for O in Octet loop
Data (Count (O)) := O;
end loop;
declare
Buffer : Atom_Buffer;
begin
Buffer.Append (Data (0 .. 10));
Buffer.Append (Data (11 .. 11));
Buffer.Append (Data (12 .. 101));
Buffer.Append (Data (102 .. 101));
Buffer.Append (Data (102 .. 255));
Test_Tools.Test_Atom (Report, Name, Data, Buffer.Data);
end;
exception
when Error : others => Report.Report_Exception (Name, Error);
end Test_Block_Append;
procedure Test_Invert (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Invert procedure");
Source : Atom (1 .. 10);
Inverse : Atom (1 .. 10);
begin
for I in Source'Range loop
Source (I) := 10 + Octet (I);
Inverse (11 - I) := Source (I);
end loop;
declare
Buffer : Atom_Buffer;
begin
Buffer.Invert;
Test_Tools.Test_Atom (Test, Null_Atom, Buffer.Data);
Buffer.Append (Source (1 .. 1));
Buffer.Invert;
Test_Tools.Test_Atom (Test, Source (1 .. 1), Buffer.Data);
Buffer.Append (Source (2 .. 7));
Buffer.Invert;
Test_Tools.Test_Atom (Test, Inverse (4 .. 10), Buffer.Data);
Buffer.Invert;
Buffer.Append (Source (8 .. 10));
Buffer.Invert;
Test_Tools.Test_Atom (Test, Inverse, Buffer.Data);
end;
exception
when Error : others => Test.Report_Exception (Error);
end Test_Invert;
procedure Test_Octet_Append (Report : in out NT.Reporter'Class) is
Name : constant String := "Append octet by octet";
Data : Atom (0 .. 255);
begin
for O in Octet loop
Data (Count (O)) := O;
end loop;
declare
Buffer : Atom_Buffer;
begin
for O in Octet loop
Buffer.Append (O);
end loop;
Test_Tools.Test_Atom (Report, Name, Data, Buffer.Data);
end;
exception
when Error : others => Report.Report_Exception (Name, Error);
end Test_Octet_Append;
procedure Test_Preallocate (Report : in out NT.Reporter'Class) is
Name : constant String := "Preallocation of memory";
begin
declare
Buffer : Atom_Buffer;
begin
Buffer.Preallocate (256);
declare
Old_Accessor : Atom_Refs.Accessor := Buffer.Raw_Query;
begin
for O in Octet loop
Buffer.Append (O);
end loop;
Report.Item (Name,
NT.To_Result (Old_Accessor.Data = Buffer.Raw_Query.Data));
end;
end;
exception
when Error : others => Report.Report_Exception (Name, Error);
end Test_Preallocate;
procedure Test_Query (Report : in out NT.Reporter'Class) is
Name : constant String := "Accessors";
Data : Atom (0 .. 255);
begin
for O in Octet loop
Data (Count (O)) := O;
end loop;
declare
Buffer : Atom_Buffer;
begin
Buffer.Append (Data);
if Buffer.Length /= Data'Length then
Report.Item (Name, NT.Fail);
Report.Info ("Buffer.Length returned" & Count'Image (Buffer.Length)
& ", expected" & Count'Image (Data'Length));
return;
end if;
if Buffer.Data /= Data then
Report.Item (Name, NT.Fail);
Report.Info ("Data, returning an Atom");
Test_Tools.Dump_Atom (Report, Buffer.Data, "Found");
Test_Tools.Dump_Atom (Report, Data, "Expected");
return;
end if;
if Buffer.Raw_Query.Data.all /= Data then
Report.Item (Name, NT.Fail);
Report.Info ("Raw_Query, returning an accessor");
Test_Tools.Dump_Atom (Report, Buffer.Raw_Query.Data.all, "Found");
Test_Tools.Dump_Atom (Report, Data, "Expected");
return;
end if;
if Buffer.Element (25) /= Data (24) then
Report.Item (Name, NT.Fail);
Report.Info ("Element, returning an octet");
return;
end if;
declare
O, P : Octet;
begin
Buffer.Pop (O);
Buffer.Pop (P);
if O /= Data (Data'Last)
or P /= Data (Data'Last - 1)
or Buffer.Data /= Data (Data'First .. Data'Last - 2)
then
Report.Item (Name, NT.Fail);
Report.Info ("Pop of an octet: "
& Octet'Image (P) & " " & Octet'Image (O));
Test_Tools.Dump_Atom (Report, Buffer.Data, "Remaining");
Test_Tools.Dump_Atom (Report, Data, "Expected");
return;
end if;
Buffer.Append ((P, O));
if Buffer.Data /= Data then
Report.Item (Name, NT.Fail);
Report.Info ("Append back after Pop");
Test_Tools.Dump_Atom (Report, Buffer.Data, "Found");
Test_Tools.Dump_Atom (Report, Data, "Expected");
return;
end if;
end;
declare
Retrieved : Atom (10 .. 310);
Length : Count;
begin
Buffer.Peek (Retrieved, Length);
if Length /= Data'Length
or else Retrieved (10 .. Length + 9) /= Data
then
Report.Item (Name, NT.Fail);
Report.Info ("Peek into an existing buffer");
Report.Info ("Length returned" & Count'Image (Length)
& ", expected" & Count'Image (Data'Length));
Test_Tools.Dump_Atom
(Report, Retrieved (10 .. Length + 9), "Found");
Test_Tools.Dump_Atom (Report, Data, "Expected");
return;
end if;
end;
declare
Retrieved : Atom (20 .. 50);
Length : Count;
begin
Buffer.Peek (Retrieved, Length);
if Length /= Data'Length or else Retrieved /= Data (0 .. 30) then
Report.Item (Name, NT.Fail);
Report.Info ("Peek into a buffer too small");
Report.Info ("Length returned" & Count'Image (Length)
& ", expected" & Count'Image (Data'Length));
Test_Tools.Dump_Atom (Report, Retrieved, "Found");
Test_Tools.Dump_Atom (Report, Data (0 .. 30), "Expected");
return;
end if;
end;
declare
procedure Check (Found : in Atom);
Result : Boolean := False;
procedure Check (Found : in Atom) is
begin
Result := Found = Data;
end Check;
begin
Buffer.Query (Check'Access);
if not Result then
Report.Item (Name, NT.Fail);
Report.Info ("Query with callback");
return;
end if;
end;
end;
Report.Item (Name, NT.Success);
exception
when Error : others => Report.Report_Exception (Name, Error);
end Test_Query;
procedure Test_Query_Null (Report : in out NT.Reporter'Class) is
Name : constant String := "Accessor variants against a null buffer";
begin
declare
Buffer : Atom_Buffer;
begin
if Buffer.Data /= Null_Atom then
Report.Item (Name, NT.Fail);
Report.Info ("Data, returning an Atom");
Test_Tools.Dump_Atom (Report, Buffer.Data, "Found");
return;
end if;
if Buffer.Raw_Query.Data.all /= Null_Atom then
Report.Item (Name, NT.Fail);
Report.Info ("Raw_Query, returning an accessor");
Test_Tools.Dump_Atom (Report, Buffer.Raw_Query.Data.all, "Found");
return;
end if;
declare
Retrieved : Atom (1 .. 10);
Length : Count;
begin
Buffer.Peek (Retrieved, Length);
if Length /= 0 then
Report.Item (Name, NT.Fail);
Report.Info ("Peek into an existing buffer");
Report.Info ("Length returned" & Count'Image (Length)
& ", expected 0");
return;
end if;
end;
declare
procedure Check (Found : in Atom);
Result : Boolean := False;
procedure Check (Found : in Atom) is
begin
Result := Found = Null_Atom;
end Check;
begin
Buffer.Query (Check'Access);
if not Result then
Report.Item (Name, NT.Fail);
Report.Info ("Query with callback");
return;
end if;
end;
end;
Report.Item (Name, NT.Success);
exception
when Error : others => Report.Report_Exception (Name, Error);
end Test_Query_Null;
procedure Test_Reset (Report : in out NT.Reporter'Class) is
Name : constant String := "Reset procedures";
begin
declare
Buffer : Atom_Buffer;
begin
for O in Octet loop
Buffer.Append (O);
end loop;
declare
Accessor : Atom_Refs.Accessor := Buffer.Raw_Query;
begin
Buffer.Soft_Reset;
if Buffer.Length /= 0 then
Report.Item (Name, NT.Fail);
Report.Info ("Soft reset left length"
& Count'Image (Buffer.Length));
return;
end if;
if Buffer.Raw_Query.Data /= Accessor.Data then
Report.Item (Name, NT.Fail);
Report.Info ("Soft reset changed storage area");
return;
end if;
if Buffer.Raw_Query.Data.all'Length /= Buffer.Capacity then
Report.Item (Name, NT.Fail);
Report.Info ("Available length inconsistency, recorded"
& Count'Image (Buffer.Capacity) & ", actual"
& Count'Image (Buffer.Raw_Query.Data.all'Length));
return;
end if;
if Buffer.Data'Length /= Buffer.Used then
Report.Item (Name, NT.Fail);
Report.Info ("Used length inconsistency, recorded"
& Count'Image (Buffer.Used) & ", actual"
& Count'Image (Buffer.Data'Length));
return;
end if;
end;
for O in Octet'(10) .. Octet'(50) loop
Buffer.Append (O);
end loop;
Buffer.Hard_Reset;
if Buffer.Length /= 0
or else Buffer.Capacity /= 0
or else not Buffer.Ref.Is_Empty
then
Report.Item (Name, NT.Fail);
Report.Info ("Hard reset did not completely clean structure");
end if;
end;
Report.Item (Name, NT.Success);
exception
when Error : others => Report.Report_Exception (Name, Error);
end Test_Reset;
procedure Test_Reverse_Append (Report : in out NT.Reporter'Class) is
Name : constant String := "procedure Append_Reverse";
Source_1 : Atom (1 .. 10);
Source_2 : Atom (1 .. 1);
Source_3 : Atom (51 .. 65);
Source_4 : Atom (1 .. 0);
Source_5 : Atom (101 .. 114);
Expected : Atom (1 .. 40);
begin
for I in Source_1'Range loop
Source_1 (I) := 10 + Octet (I);
Expected (Expected'First + Source_1'Last - I) := Source_1 (I);
end loop;
for I in Source_2'Range loop
Source_2 (I) := 42;
Expected (Expected'First + Source_1'Length + Source_2'Last - I)
:= Source_2 (I);
end loop;
for I in Source_3'Range loop
Source_3 (I) := Octet (I);
Expected (Expected'First + Source_1'Length + Source_2'Length
+ I - Source_3'First)
:= Source_3 (I);
end loop;
for I in Source_5'Range loop
Source_5 (I) := Octet (I);
Expected (Expected'First + Source_1'Length + Source_2'Length
+ Source_3'Length + Source_5'Last - I)
:= Source_5 (I);
end loop;
declare
Buffer : Atom_Buffer;
begin
Buffer.Append_Reverse (Source_1);
Buffer.Append_Reverse (Source_2);
Buffer.Append (Source_3);
Buffer.Append_Reverse (Source_4);
Buffer.Append_Reverse (Source_5);
Test_Tools.Test_Atom (Report, Name, Expected, Buffer.Data);
end;
exception
when Error : others => Report.Report_Exception (Name, Error);
end Test_Reverse_Append;
procedure Test_Empty_Append (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Empty append on empty buffer");
begin
declare
Buffer : Atom_Buffer;
begin
Buffer.Append (Null_Atom);
Test_Tools.Test_Atom (Test, Null_Atom, Buffer.Data);
end;
exception
when Error : others => Test.Report_Exception (Error);
end Test_Empty_Append;
procedure Test_Stream_Interface (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Stream interface");
begin
declare
Buffer : Atom_Buffer;
Part_1 : constant Atom := To_Atom ("0123456789");
Part_2 : constant Atom := To_Atom ("ABCDEF");
Data : Atom (1 .. 10);
Last : Offset;
begin
Buffer.Write (Part_1 & Part_2);
Buffer.Read (Data, Last);
Test_Tools.Test_Atom (Test, Part_1, Data);
Test_Tools.Test_Atom (Test, Part_2, Buffer.Data);
Buffer.Read (Data, Last);
Test_Tools.Test_Atom (Test, Part_2, Data (Data'First .. Last));
Test_Tools.Test_Atom (Test, Null_Atom, Buffer.Data);
end;
exception
when Error : others => Test.Report_Exception (Error);
end Test_Stream_Interface;
end Natools.S_Expressions.Atom_Buffers.Tests;
|
with Ada.Text_IO; use Ada.Text_IO;
package body EU_Projects.Node_Tables is
procedure Dump (T : Node_Table) is
use Node_Maps;
begin
for Pos in T.Table.Iterate loop
Put_Line (EU_Projects.Nodes.To_String(Key (Pos)) & ":");
end loop;
end Dump;
------------
-- Insert --
------------
procedure Insert
(T : in out Node_Table;
ID : Nodes.Node_Label;
Item : Nodes.Node_Access)
is
begin
T.Table.Insert (Key => ID,
New_Item => Item);
exception
when Constraint_Error =>
raise Duplicated_Label;
end Insert;
---------------
-- Labels_Of --
---------------
function Labels_Of (T : Node_Table;
Class : Nodes.Node_Class)
return Nodes.Node_Label_Lists.Vector
is
use Node_Maps;
use type Nodes.Node_Class;
Result : Nodes.Node_Label_Lists.Vector;
begin
for Pos in T.Table.Iterate loop
if Nodes.Class (Element (Pos).all) = Class then
Result.Append (Key (Pos));
end if;
end loop;
return Result;
end Labels_Of;
end EU_Projects.Node_Tables;
|
pragma License (Unrestricted);
with Ada.Numerics.Generic_Complex_Types;
with Ada.Text_IO.Complex_IO;
generic
with package Complex_Types is new Numerics.Generic_Complex_Types (<>);
package Ada.Wide_Wide_Text_IO.Complex_IO is
-- use Complex_Types;
-- for renaming
package Strings is new Text_IO.Complex_IO (Complex_Types);
Default_Fore : Field
renames Strings.Default_Fore; -- 2
Default_Aft : Field
renames Strings.Default_Aft; -- Complex_Types.Real'Digits - 1
Default_Exp : Field
renames Strings.Default_Exp; -- 3
procedure Get (
File : File_Type; -- Input_File_Type
Item : out Complex_Types.Complex;
Width : Field := 0)
renames Strings.Get;
procedure Get (
Item : out Complex_Types.Complex;
Width : Field := 0)
renames Strings.Get;
procedure Put (
File : File_Type; -- Output_File_Type
Item : Complex_Types.Complex;
Fore : Field := Default_Fore;
Aft : Field := Default_Aft;
Exp : Field := Default_Exp)
renames Strings.Put;
procedure Put (
Item : Complex_Types.Complex;
Fore : Field := Default_Fore;
Aft : Field := Default_Aft;
Exp : Field := Default_Exp)
renames Strings.Put;
procedure Get (
From : Wide_Wide_String;
Item : out Complex_Types.Complex;
Last : out Positive)
renames Strings.Overloaded_Get;
procedure Put (
To : out Wide_Wide_String;
Item : Complex_Types.Complex;
Aft : Field := Default_Aft;
Exp : Field := Default_Exp)
renames Strings.Overloaded_Put;
end Ada.Wide_Wide_Text_IO.Complex_IO;
|
With Gnat.IO; use Gnat.IO;
procedure ej2 is
type Peras is new Integer;
type Naranjas is new Integer;
P : Peras;
N : Naranjas;
S : Integer;
begin
Put ("Ingrese primer operando entero: ");
Get (Integer(N));
New_Line;
Put ("Ingrese segundo operando entero: ");
Get (Integer(P));
New_Line;
S:= Integer(P)+Integer(N);
Put ("La suma es: ");
Put (S);
end ej2;
|
------------------------------------------------------------------------------
-- --
-- Ada binding for OpenGL/WebGL --
-- --
-- Examples Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2018, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with League.Characters.Latin;
with League.Strings;
package body Pyramid.Programs is
use type League.Strings.Universal_String;
Text_V : League.Strings.Universal_String :=
League.Strings.To_Universal_String
("#version 130") & League.Characters.Latin.Line_Feed &
"in vec3 vp;" &
"in vec2 tc;" &
"out vec2 TexCoord0;" &
"void main() {" &
" gl_Position = vec4(vp, 1.0);" &
" TexCoord0 = tc;" &
"}";
Text_F : League.Strings.Universal_String :=
League.Strings.To_Universal_String
("#version 130") & League.Characters.Latin.Line_Feed &
"in vec2 TexCoord0;" &
"out vec4 frag_colour;" &
"uniform sampler2D gSampler;" &
"void main() {" &
" frag_colour = texture2D(gSampler, TexCoord0.xy) +vec4(0.0, 0.0, 0.2, 0.2);" &
"}";
GS : constant League.Strings.Universal_String :=
League.Strings.To_Universal_String ("gSampler");
VP : constant League.Strings.Universal_String :=
League.Strings.To_Universal_String ("vp");
TC : constant League.Strings.Universal_String :=
League.Strings.To_Universal_String ("tc");
----------------
-- Initialize --
----------------
procedure Initialize (Self : in out Pyramid_Program'Class) is
begin
Self.Add_Shader_From_Source_Code (OpenGL.Vertex, Text_V);
Self.Add_Shader_From_Source_Code (OpenGL.Fragment, Text_F);
end Initialize;
----------
-- Link --
----------
overriding function Link (Self : in out Pyramid_Program) return Boolean is
begin
if not OpenGL.Programs.OpenGL_Program (Self).Link then
return False;
end if;
Self.GS := Self.Uniform_Location (GS);
Self.VP := Self.Attribute_Location (VP);
Self.TC := Self.Attribute_Location (TC);
return True;
end Link;
----------------------
-- Set_Texture_Unit --
----------------------
procedure Set_Texture_Unit
(Self : in out Pyramid_Program'Class;
Unit : OpenGL.Texture_Unit) is
begin
Self.Set_Uniform_Value (Self.GS, Unit);
end Set_Texture_Unit;
----------------------------
-- Set_Vertex_Data_Buffer --
----------------------------
procedure Set_Vertex_Data_Buffer
(Self : in out Pyramid_Program'Class;
Buffer : Vertex_Data_Buffers.OpenGL_Buffer'Class)
is
Dummy : Vertex_Data;
begin
Self.Enable_Attribute_Array (Self.VP);
Self.Enable_Attribute_Array (Self.TC);
Self.Set_Attribute_Buffer
(Location => Self.VP,
Data_Type => OpenGL.GL_FLOAT,
Tuple_Size => Dummy.VP'Length,
Offset => Dummy.VP'Position,
Stride => Vertex_Data_Buffers.Stride);
Self.Set_Attribute_Buffer
(Location => Self.TC,
Data_Type => OpenGL.GL_FLOAT,
Tuple_Size => Dummy.TC'Length,
Offset => Dummy.TC'Position,
Stride => Vertex_Data_Buffers.Stride);
end Set_Vertex_Data_Buffer;
end Pyramid.Programs;
|
with -<full_parent_datatype_package>-; use -<full_parent_datatype_package>-;
with -<full_series_name_dots>-.enumerations; use -<full_series_name_dots>-.enumerations;
with avtas.lmcp.byteBuffers; use avtas.lmcp.byteBuffers;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Streams;
with Ada.Containers.Indefinite_Vectors;
-<with_all_field_types>-
package -<full_series_name_dots>-.-<datatype_name>- is
type -<datatype_name>- is new -<full_parent_datatype>- with private;
type -<datatype_name>-_Acc is access all -<datatype_name>-;
type -<datatype_name>-_Any is access all -<datatype_name>-'Class;
Subscription : constant String := "-<full_datatype_name_dots>-";
TypeName : constant String := "-<datatype_name>-";
SeriesName : constant String := "-<series_name>-";
TypeId : constant := -<series_name>-Enum'Pos(-<datatype_name_caps>-_ENUM) + 1;
-- The other languages start their enums at 1, whereas Ada starts at 0,
-- so add 1. This is critical in the case statement (switch) in the
-- factories so that an object of the right subclass is created.
-<vector_package_import>-
overriding
function getFullLmcpTypeName(this : -<datatype_name>-) return String is (Subscription);
overriding
function getLmcpTypeName(this : -<datatype_name>-) return String is (TypeName);
overriding
function getLmcpType(this : -<datatype_name>-) return UInt32 is (TypeId);
-<get_and_set_methods_spec>-
overriding
function calculatePackedSize(this: -<datatype_name>-) return UInt32;
overriding
procedure Pack (This : -<datatype_name>-; Buffer : in out ByteBuffer);
overriding
procedure Unpack (This : out -<datatype_name>-; Buffer : in out ByteBuffer);
--function toString(this : -<datatype_name>-; depth : Integer) return String;
package String_Vectors is new Ada.Containers.Indefinite_Vectors
(Index_Type => Positive, Element_Type => String);
-- TODO: move to a single, shared instantiation
function -<datatype_name>-_Descendants return String_Vectors.Vector;
private
type -<datatype_name>- is new -<full_parent_datatype>- with record
-<record_fields>-
end record;
overriding
procedure XML_Write (this : -<datatype_name>-;
S : access Ada.Streams.Root_Stream_Type'Class;
Level : Natural);
end -<full_series_name_dots>-.-<datatype_name>-;
|
package gel.human_Types
--
-- Provides core types for defining a Human.
--
is
pragma Pure;
type controller_joint_Id is (MasterFloor,
Root,
Hips,
UpLeg_L, LoLeg_L, Foot_L, Toe_L,
UpLeg_R, LoLeg_R, Foot_R, Toe_R,
Spine1, Spine2, Spine3,
Neck, Head, Jaw,
TongueBase, TongueMid, TongueTip,
Eye_R, Eye_L,
UpLid_R, LoLid_R,
UpLid_L, LoLid_L,
Clavicle_L, UpArm_L, LoArm_L, Hand_L,
Wrist_1_L,
Palm_2_L, Finger_2_1_L, Finger_2_2_L, Finger_2_3_L,
Palm_3_L, Finger_3_1_L, Finger_3_2_L, Finger_3_3_L,
Wrist_2_L,
Palm_4_L, Finger_4_1_L, Finger_4_2_L, Finger_4_3_L,
Palm_5_L, Finger_5_1_L, Finger_5_2_L, Finger_5_3_L,
Palm_1_L, Finger_1_1_L, Finger_1_2_L, Finger_1_3_L,
Clavicle_R, UpArm_R, LoArm_R, Hand_R,
Wrist_1_R,
Palm_2_R, Finger_2_1_R, Finger_2_2_R, Finger_2_3_R,
Palm_3_R, Finger_3_1_R, Finger_3_2_R, Finger_3_3_R,
Wrist_2_R,
Palm_4_R, Finger_4_1_R, Finger_4_2_R, Finger_4_3_R,
Palm_5_R, Finger_5_1_R, Finger_5_2_R, Finger_5_3_R,
Palm_1_R, Finger_1_1_R, Finger_1_2_R, Finger_1_3_R,
Wrist_L, Wrist_R,
Ankle_L, Ankle_R);
type bone_Id is new controller_joint_Id range Hips .. controller_joint_Id'Last;
type controller_Joint is
record
inverse_bind_Matrix : math.Matrix_4x4;
joint_to_bone_site_Offet : math.Vector_3; -- The 'bind time' offset from a joint to its bone.
end record;
type controller_Joints is array (controller_joint_Id) of controller_Joint;
end gel.human_Types;
|
with ObjectPack, AbstractStrategyCombinatorPackage, IntrospectorPackage, StrategyPackage;
use ObjectPack, AbstractStrategyCombinatorPackage, IntrospectorPackage, StrategyPackage;
package ChoiceIdStrategy is
FIRST : constant Integer := 0;
SECOND : constant Integer := 1;
type ChoiceId is new AbstractStrategyCombinator and Object with null record;
----------------------------------------------------------------------------
-- Object implementation
----------------------------------------------------------------------------
function toString(c: ChoiceId) return String;
----------------------------------------------------------------------------
-- Strategy implementation
----------------------------------------------------------------------------
function visitLight(str:access ChoiceId; any: ObjectPtr; i: access Introspector'Class) return ObjectPtr;
function visit(str: access ChoiceId; i: access Introspector'Class) return Integer;
----------------------------------------------------------------------------
function make(first, second : StrategyPtr) return StrategyPtr;
function newChoiceId(first, second: StrategyPtr) return StrategyPtr;
end ChoiceIdStrategy;
|
with Ada.Strings.Unbounded;
with Ada.Tags.Delegating;
procedure delegate is
package I is
type Intf is limited interface;
procedure Method (Object : Intf) is abstract;
end I;
package A is
type Aggregated_Object (Message : access String) is new I.Intf with null record;
procedure Dummy (Object : Aggregated_Object);
overriding procedure Method (Object : Aggregated_Object);
end A;
package body A is
procedure Dummy (Object : Aggregated_Object) is
begin
null;
end Dummy;
overriding procedure Method (Object : Aggregated_Object) is
begin
Ada.Debug.Put (Object.Message.all);
end Method;
end A;
package C is
type String_Access is access String;
type Container (Message : String_Access) is tagged limited record
Field : aliased A.Aggregated_Object (Message);
end record;
function Get (Object : not null access Container'Class) return access I.Intf'Class;
end C;
package body C is
function Get (Object : not null access Container'Class) return access I.Intf'Class is
begin
return I.Intf'Class (Object.Field)'Access;
end Get;
procedure Impl is new Ada.Tags.Delegating.Implements (Container, I.Intf, Get);
begin
Impl;
end C;
package D is
type Container (Additional : C.String_Access) is
new C.Container (Additional) with
record
Controlled_Field : Ada.Strings.Unbounded.Unbounded_String;
end record;
end D;
begin
declare
Obj : aliased C.Container (new String'("Hello."));
X : Boolean := C.Container'Class (Obj) in I.Intf'Class;
Intf : access I.Intf'Class := I.Intf'Class (C.Container'Class (Obj))'Access;
begin
if X then
Ada.Debug.Put ("membership test is ok.");
end if;
Ada.Debug.Put (Ada.Tags.Expanded_Name (Intf'Tag));
I.Method (Intf.all);
end;
declare
Obj : aliased D.Container (new String'("Hello, derived."));
X : Boolean := D.Container'Class (Obj) in I.Intf'Class;
Intf : access I.Intf'Class := I.Intf'Class (D.Container'Class (Obj))'Access;
begin
if X then
Ada.Debug.Put ("membership test for derived type is ok.");
end if;
Ada.Debug.Put (Ada.Tags.Expanded_Name (Intf'Tag));
I.Method (Intf.all);
end;
end delegate;
|
with Ada.Text_IO; use Ada.Text_IO;
with Libadalang.Analysis; use Libadalang.Analysis;
with Libadalang.Common; use Libadalang.Common;
with Rejuvenation.Simple_Factory; use Rejuvenation.Simple_Factory;
package body Examples.Visitor is
procedure Demo_Visitor (Unit : Analysis_Unit);
procedure Demo (File_Name : String) is
Unit : constant Analysis_Unit := Analyze_File (File_Name);
begin
Put_Line ("=== Examples of Visitor =======");
New_Line;
Demo_Visitor (Unit);
New_Line;
end Demo;
procedure Demo_Visitor (Unit : Analysis_Unit) is
function Visit_Function (Node : Ada_Node'Class) return Visit_Status;
function Visit_Function (Node : Ada_Node'Class) return Visit_Status is
begin
if Node.Kind = Ada_Call_Expr then
Put_Line (Node.Image);
end if;
return Into; -- Always continue the traversal.
end Visit_Function;
begin
Unit.Root.Traverse (Visit_Function'Access);
end Demo_Visitor;
end Examples.Visitor;
|
-- Copyright (c) 2020 Maxim Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with Ada.Calendar;
with Ada.Containers.Hashed_Sets;
with Ada.Containers.Ordered_Sets;
with Ada.Containers.Vectors;
with Ada.Exceptions;
with Ada.Text_IO;
with Ada.Unchecked_Deallocation;
with System.Address_To_Access_Conversions;
with System.Storage_Elements;
with Torrent.Contexts;
with Torrent.Handshakes;
with Torrent.Logs;
package body Torrent.Initiators is
procedure Free is new Ada.Unchecked_Deallocation
(Torrent.Connections.Connection'Class,
Torrent.Connections.Connection_Access);
---------------
-- Initiator --
---------------
task body Initiator is
use type Ada.Streams.Stream_Element_Offset;
type Socket_Connection is record
Socket : GNAT.Sockets.Socket_Type;
Addr : GNAT.Sockets.Sock_Addr_Type;
Job : Torrent.Downloaders.Downloader_Access;
end record;
package Socket_Connection_Vectors is new Ada.Containers.Vectors
(Positive, Socket_Connection);
type Planned_Connection is record
Time : Ada.Calendar.Time;
Addr : GNAT.Sockets.Sock_Addr_Type;
Job : Torrent.Downloaders.Downloader_Access;
end record;
function Less (Left, Right : Planned_Connection) return Boolean;
package Planned_Connection_Sets is new Ada.Containers.Ordered_Sets
(Element_Type => Planned_Connection,
"<" => Less);
type Accepted_Connection is record
Socket : GNAT.Sockets.Socket_Type;
Address : GNAT.Sockets.Sock_Addr_Type;
Data : Torrent.Handshakes.Handshake_Image;
Last : Ada.Streams.Stream_Element_Count;
Done : Boolean;
Session : Torrent.Connections.Connection_Access;
end record;
package Accepted_Connection_Vectors is new Ada.Containers.Vectors
(Positive, Accepted_Connection);
procedure Accept_Connection
(Server : GNAT.Sockets.Socket_Type;
Accepted : in out Accepted_Connection_Vectors.Vector);
procedure Read_Handshake (Item : in out Accepted_Connection);
function Hash (Item : Torrent.Connections.Connection_Access)
return Ada.Containers.Hash_Type;
package Connection_Sets is new Ada.Containers.Hashed_Sets
(Element_Type => Torrent.Connections.Connection_Access,
Hash => Hash,
Equivalent_Elements => Torrent.Connections."=",
"=" => Torrent.Connections."=");
function "+"
(Value : Torrent.Connections.Connection_Access)
return System.Storage_Elements.Integer_Address;
---------
-- "+" --
---------
function "+"
(Value : Torrent.Connections.Connection_Access)
return System.Storage_Elements.Integer_Address
is
package Conv is new System.Address_To_Access_Conversions
(Object => Torrent.Connections.Connection'Class);
begin
return System.Storage_Elements.To_Integer
(Conv.To_Address (Conv.Object_Pointer (Value)));
end "+";
-----------------------
-- Accept_Connection --
-----------------------
procedure Accept_Connection
(Server : GNAT.Sockets.Socket_Type;
Accepted : in out Accepted_Connection_Vectors.Vector)
is
Address : GNAT.Sockets.Sock_Addr_Type;
Socket : GNAT.Sockets.Socket_Type;
begin
GNAT.Sockets.Accept_Socket (Server, Socket, Address);
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print ("Accepted: " & GNAT.Sockets.Image (Address)));
GNAT.Sockets.Set_Socket_Option
(Socket => Socket,
Level => GNAT.Sockets.Socket_Level,
Option => (GNAT.Sockets.Receive_Timeout, 0.0));
Accepted.Append
((Socket,
Last => 0,
Done => False,
Address => Address,
others => <>));
end Accept_Connection;
----------
-- Hash --
----------
function Hash (Item : Torrent.Connections.Connection_Access)
return Ada.Containers.Hash_Type is
begin
return Ada.Containers.Hash_Type'Mod (+Item);
end Hash;
----------
-- Less --
----------
function Less (Left, Right : Planned_Connection) return Boolean is
use type Ada.Calendar.Time;
function "+" (V : GNAT.Sockets.Sock_Addr_Type) return String
renames GNAT.Sockets.Image;
begin
return Left.Time < Right.Time
or else (Left.Time = Right.Time and +Left.Addr < +Right.Addr);
end Less;
--------------------
-- Read_Handshake --
--------------------
procedure Read_Handshake (Item : in out Accepted_Connection) is
use Torrent.Handshakes;
use type Ada.Streams.Stream_Element;
Last : Ada.Streams.Stream_Element_Count;
Job : Torrent.Downloaders.Downloader_Access;
begin
GNAT.Sockets.Receive_Socket
(Item.Socket,
Item.Data (Item.Last + 1 .. Item.Data'Last),
Last);
if Last <= Item.Last then
Item.Done := True; -- Connection closed
elsif Last = Item.Data'Last then
declare
Value : constant Handshake_Type := -Item.Data;
begin
Job := Context.Find_Download (Value.Info_Hash);
Item.Done := True;
if Value.Length = Header'Length
and then Value.Head = Header
and then Job not in null
then
Item.Session := Job.Create_Session (Item.Address);
Item.Session.Do_Handshake
(Item.Socket, Job.Completed, Inbound => True);
end if;
end;
else
Item.Last := Last;
end if;
exception
when E : GNAT.Sockets.Socket_Error =>
if GNAT.Sockets.Resolve_Exception (E) not in
GNAT.Sockets.Resource_Temporarily_Unavailable
then
Item.Done := True;
end if;
end Read_Handshake;
use type Ada.Calendar.Time;
Address : constant GNAT.Sockets.Sock_Addr_Type :=
(GNAT.Sockets.Family_Inet, GNAT.Sockets.Any_Inet_Addr,
GNAT.Sockets.Port_Type (Port));
Server : GNAT.Sockets.Socket_Type;
Plan : Planned_Connection_Sets.Set;
Work : Socket_Connection_Vectors.Vector;
Accepted : Accepted_Connection_Vectors.Vector;
Inbound : Connection_Sets.Set;
Selector : aliased GNAT.Sockets.Selector_Type;
Time : Ada.Calendar.Time := Ada.Calendar.Clock + 20.0;
W_Set : GNAT.Sockets.Socket_Set_Type;
R_Set : GNAT.Sockets.Socket_Set_Type;
Session : Torrent.Connections.Connection_Access;
begin
GNAT.Sockets.Create_Selector (Selector);
GNAT.Sockets.Create_Socket (Server);
GNAT.Sockets.Bind_Socket (Server, Address);
GNAT.Sockets.Listen_Socket (Server);
Top_Loop :
loop
loop
select
Recycle.Dequeue (Session);
if Inbound.Contains (Session) then
Inbound.Delete (Session);
Free (Session);
else
Time := Ada.Calendar.Clock;
Plan.Insert
((Time + 300.0,
Session.Peer,
Torrent.Downloaders.Downloader_Access
(Session.Downloader)));
end if;
else
exit;
end select;
end loop;
loop
select
accept Stop;
exit Top_Loop;
or
accept Connect
(Downloader : not null Torrent.Downloaders.Downloader_Access;
Address : GNAT.Sockets.Sock_Addr_Type)
do
Time := Ada.Calendar.Clock;
Plan.Insert ((Time, Address, Downloader));
end Connect;
or
delay until Time;
exit;
end select;
end loop;
while not Plan.Is_Empty loop
declare
Ignore : GNAT.Sockets.Selector_Status;
First : constant Planned_Connection := Plan.First_Element;
Socket : GNAT.Sockets.Socket_Type;
begin
exit when First.Time > Time;
if First.Job.Is_Leacher then
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
("Connecting: " & GNAT.Sockets.Image (First.Addr)));
GNAT.Sockets.Create_Socket (Socket);
GNAT.Sockets.Connect_Socket
(Socket => Socket,
Server => First.Addr,
Timeout => 0.0,
Status => Ignore);
Work.Append ((Socket, First.Addr, First.Job));
end if;
Plan.Delete_First;
end;
end loop;
GNAT.Sockets.Empty (W_Set);
GNAT.Sockets.Empty (R_Set);
GNAT.Sockets.Set (R_Set, Server);
for J of Accepted loop
GNAT.Sockets.Set (R_Set, J.Socket);
end loop;
for J of Work loop
GNAT.Sockets.Set (W_Set, J.Socket);
end loop;
if GNAT.Sockets.Is_Empty (W_Set)
and GNAT.Sockets.Is_Empty (R_Set)
then
Time := Ada.Calendar.Clock + 20.0;
else
declare
Status : GNAT.Sockets.Selector_Status;
begin
GNAT.Sockets.Check_Selector
(Selector,
R_Set,
W_Set,
Status,
Timeout => 0.2);
if Status in GNAT.Sockets.Completed then
declare
J : Positive := 1;
begin
if GNAT.Sockets.Is_Set (R_Set, Server) then
Accept_Connection (Server, Accepted);
end if;
while J <= Accepted.Last_Index loop
if GNAT.Sockets.Is_Set
(R_Set, Accepted (J).Socket)
then
Read_Handshake (Accepted (J));
if Accepted (J).Done then
if Accepted (J).Session in null then
GNAT.Sockets.Close_Socket
(Accepted (J).Socket);
else
Inbound.Insert (Accepted (J).Session);
Context.Connected
(Accepted (J).Session);
end if;
Accepted.Swap (J, Accepted.Last_Index);
Accepted.Delete_Last;
else
J := J + 1;
end if;
else
J := J + 1;
end if;
end loop;
J := 1;
while J <= Work.Last_Index loop
if GNAT.Sockets.Is_Set (W_Set, Work (J).Socket) then
declare
Conn : Torrent.Connections.Connection_Access :=
Work (J).Job.Create_Session (Work (J).Addr);
begin
Conn.Do_Handshake
(Work (J).Socket,
Work (J).Job.Completed,
Inbound => False);
if Conn.Connected then
Context.Connected (Conn);
else
Free (Conn);
Plan.Insert
((Time + 300.0,
Work (J).Addr,
Work (J).Job));
end if;
Work.Swap (J, Work.Last_Index);
Work.Delete_Last;
end;
else
J := J + 1;
end if;
end loop;
end;
end if;
Time := Ada.Calendar.Clock + 1.0;
end;
end if;
end loop Top_Loop;
exception
when E : others =>
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
("Initiator: " & Ada.Exceptions.Exception_Information (E)));
Ada.Text_IO.Put_Line
("Initiator: " & Ada.Exceptions.Exception_Information (E));
end Initiator;
end Torrent.Initiators;
|
with Atomic.Critical_Section; use Atomic.Critical_Section;
with System;
package body Atomic is
----------
-- Init --
----------
function Init (Val : Boolean) return Flag is
Ret : aliased Flag := 0;
Unused : Boolean;
begin
if Val then
Test_And_Set (Ret, Unused);
else
Clear (Ret);
end if;
return Ret;
end Init;
---------
-- Set --
---------
function Set (This : aliased Flag;
Order : Mem_Order := Seq_Cst)
return Boolean
is
Vol : Flag with Volatile, Address => This'Address;
State : Interrupt_State;
Result : Boolean;
begin
Critical_Section.Enter (State);
Result := Vol /= 0;
Critical_Section.Leave (State);
return Result;
end Set;
------------------
-- Test_And_Set --
------------------
procedure Test_And_Set (This : aliased in out Flag;
Result : out Boolean;
Order : Mem_Order := Seq_Cst)
is
Vol : Flag with Volatile, Address => This'Address;
State : Interrupt_State;
begin
Critical_Section.Enter (State);
Result := Vol /= 0;
Vol := 1;
Critical_Section.Leave (State);
end Test_And_Set;
-----------
-- Clear --
-----------
procedure Clear (This : aliased in out Flag;
Order : Mem_Order := Seq_Cst)
is
Vol : Flag with Volatile, Address => This'Address;
State : Interrupt_State;
begin
Critical_Section.Enter (State);
Vol := 0;
Critical_Section.Leave (State);
end Clear;
end Atomic;
|
with ada.text_io, ada.Integer_text_IO, Ada.Text_IO.Text_Streams, Ada.Strings.Fixed, Interfaces.C;
use ada.text_io, ada.Integer_text_IO, Ada.Strings, Ada.Strings.Fixed, Interfaces.C;
procedure euler17 is
type stringptr is access all char_array;
procedure PString(s : stringptr) is
begin
String'Write (Text_Streams.Stream (Current_Output), To_Ada(s.all));
end;
procedure PInt(i : in Integer) is
begin
String'Write (Text_Streams.Stream (Current_Output), Trim(Integer'Image(i), Left));
end;
one_to_twenty : Integer;
one_to_thirty : Integer;
one_to_ten : Integer;
one_to_sixty : Integer;
one_to_seventy : Integer;
one_to_ninety_nine : Integer;
one_to_ninety : Integer;
one_to_nine : Integer;
one_to_forty : Integer;
one_to_fifty : Integer;
one_to_eighty : Integer;
begin
PInt(3 + 16);
PString(new char_array'( To_C("" & Character'Val(10))));
one_to_nine := 3 + 33;
PInt(one_to_nine);
PString(new char_array'( To_C("" & Character'Val(10))));
one_to_ten := one_to_nine + 3;
one_to_twenty := one_to_ten + 73;
one_to_thirty := one_to_twenty + 6 * 9 + one_to_nine + 6;
one_to_forty := one_to_thirty + 6 * 9 + one_to_nine + 5;
one_to_fifty := one_to_forty + 5 * 9 + one_to_nine + 5;
one_to_sixty := one_to_fifty + 5 * 9 + one_to_nine + 5;
one_to_seventy := one_to_sixty + 5 * 9 + one_to_nine + 7;
one_to_eighty := one_to_seventy + 7 * 9 + one_to_nine + 6;
one_to_ninety := one_to_eighty + 6 * 9 + one_to_nine + 6;
one_to_ninety_nine := one_to_ninety + 6 * 9 + one_to_nine;
PInt(one_to_ninety_nine);
PString(new char_array'( To_C("" & Character'Val(10))));
PInt(100 * one_to_nine + one_to_ninety_nine * 10 + 10 * 9 * 99 + 7 * 9 + 11);
PString(new char_array'( To_C("" & Character'Val(10))));
end;
|
-- SipHash
-- an Ada implementation of the algorithm described in
-- "SipHash: a fast short-input PRF"
-- by Jean-Philippe Aumasson and Daniel J. Bernstein
-- Copyright (c) 2015, James Humphry - see LICENSE file for details
with System;
package body SipHash with
SPARK_Mode,
Refined_State => (Initial_Hash_State => Initial_State)
is
-- Short names for fundamental machine types
subtype Storage_Offset is System.Storage_Elements.Storage_Offset;
-- The initial state from the key passed as generic formal parameters is
-- stored here, so that static elaboration followed by a call of SetKey
-- can be used in situations where dynamic elaboration might be a problem.
-- This could really be in the private part of the package, but SPARK GPL
-- 2015 doesn't seem to like Part_Of in the private part of a package,
-- regardless of what the SPARK RM says...
Initial_State : SipHash_State := (k0 xor 16#736f6d6570736575#,
k1 xor 16#646f72616e646f6d#,
k0 xor 16#6c7967656e657261#,
k1 xor 16#7465646279746573#);
-----------------------
-- Get_Initial_State --
-----------------------
function Get_Initial_State return SipHash_State is
(Initial_State);
-----------------------
-- SArray8_to_U64_LE --
-----------------------
function SArray8_to_U64_LE (S : in SArray_8) return U64 is
(U64(S(0))
or Shift_Left(U64(S(1)), 8)
or Shift_Left(U64(S(2)), 16)
or Shift_Left(U64(S(3)), 24)
or Shift_Left(U64(S(4)), 32)
or Shift_Left(U64(S(5)), 40)
or Shift_Left(U64(S(6)), 48)
or Shift_Left(U64(S(7)), 56));
---------------------------
-- SArray_Tail_to_U64_LE --
---------------------------
function SArray_Tail_to_U64_LE (S : in SArray)
return U64 is
R : U64 := 0;
Shift : Natural := 0;
begin
for I in 0..(S'Length-1) loop
pragma Loop_Invariant (Shift = I * 8);
R := R or Shift_Left(U64(S(S'First + Storage_Offset(I))), Shift);
Shift := Shift + 8;
end loop;
return R;
end SArray_Tail_to_U64_LE;
---------------
-- Sip_Round --
---------------
procedure Sip_Round (v : in out SipHash_State) is
begin
v(0) := v(0) + v(1);
v(2) := v(2) + v(3);
v(1) := Rotate_Left(v(1), 13);
v(3) := Rotate_Left(v(3), 16);
v(1) := v(1) xor v(0);
v(3) := v(3) xor v(2);
v(0) := Rotate_Left(v(0), 32);
v(2) := v(2) + v(1);
v(0) := v(0) + v(3);
v(1) := Rotate_Left(v(1), 17);
v(3) := Rotate_Left(v(3), 21);
v(1) := v(1) xor v(2);
v(3) := v(3) xor v(0);
v(2) := Rotate_Left(v(2), 32);
end Sip_Round;
----------------------
-- Sip_Finalization --
----------------------
function Sip_Finalization (v : in SipHash_State)
return U64 is
vv : SipHash_State := v;
begin
vv(2) := vv(2) xor 16#ff#;
for I in 1..d_rounds loop
Sip_Round(vv);
end loop;
return (vv(0) xor vv(1) xor vv(2) xor vv(3));
end Sip_Finalization;
-------------
-- Set_Key --
-------------
procedure Set_Key (k0, k1 : U64) is
begin
Initial_State := (k0 xor 16#736f6d6570736575#,
k1 xor 16#646f72616e646f6d#,
k0 xor 16#6c7967656e657261#,
k1 xor 16#7465646279746573#);
end Set_Key;
procedure Set_Key (k : SipHash_Key) is
k0, k1 : U64;
begin
k0 := SArray8_to_U64_LE(k(k'First..k'First+7));
k1 := SArray8_to_U64_LE(k(k'First+8..k'Last));
Set_Key(k0, k1);
end Set_Key;
-------------
-- SipHash --
-------------
function SipHash (m : System.Storage_Elements.Storage_Array)
return U64
is
m_pos : Storage_Offset := 0;
m_i : U64;
v : SipHash_State := Initial_State;
w : constant Storage_Offset := (m'Length / 8) + 1;
begin
-- This compile-time check is useful for GNAT but in GNATprove it
-- currently just generates a warning that it can not yet prove
-- them correct.
pragma Warnings (GNATprove, Off, "Compile_Time_Error");
pragma Compile_Time_Error (System.Storage_Elements.Storage_Element'Size /= 8,
"This implementation of SipHash cannot work " &
"with Storage_Element'Size /= 8.");
pragma Warnings (GNATprove, On, "Compile_Time_Error");
for I in 1..w-1 loop
pragma Loop_Invariant (m_pos = (I - 1) * 8);
m_i := SArray8_to_U64_LE(m(m'First + m_pos..m'First + m_pos + 7));
v(3) := v(3) xor m_i;
for J in 1..c_rounds loop
Sip_Round(v);
end loop;
v(0) := v(0) xor m_i;
m_pos := m_pos + 8;
end loop;
if m_pos < m'Length then
m_i := SArray_Tail_to_U64_LE(m(m'First + m_pos .. m'Last));
else
m_i := 0;
end if;
m_i := m_i or Shift_Left(U64(m'Length mod 256), 56);
v(3) := v(3) xor m_i;
for J in 1..c_rounds loop
Sip_Round(v);
end loop;
v(0) := v(0) xor m_i;
return Sip_Finalization(v);
end SipHash;
end SipHash;
|
with Generator.Match_Pattern_Specific;
procedure Main_Generator is
begin
Generator.Match_Pattern_Specific.Main;
end Main_Generator;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUNTIME COMPONENTS --
-- --
-- I N T E R F A C E S . C P P --
-- --
-- S p e c --
-- --
-- $Revision$
-- --
-- Copyright (C) 1992-2000, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
-- MA 02111-1307, USA. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- Definitions for interfacing to C++ classes
with System;
with System.Storage_Elements;
package Interfaces.CPP is
package S renames System;
package SSE renames System.Storage_Elements;
-- This package corresponds to Ada.Tags but applied to tagged types
-- which are 'imported' from C++ and correspond to exactly to a C++
-- Class. GNAT doesn't know about the structure od the C++ dispatch
-- table (Vtable) but always access it through the procedural interface
-- defined below, thus the implementation of this package (the body) can
-- be customized to another C++ compiler without any change in the
-- compiler code itself as long as this procedural interface is
-- respected. Note that Ada.Tags defines a very similar procedural
-- interface to the regular Ada Dispatch Table.
type Vtable_Ptr is private;
function Expanded_Name (T : Vtable_Ptr) return String;
function External_Tag (T : Vtable_Ptr) return String;
private
procedure CPP_Set_Prim_Op_Address
(T : Vtable_Ptr;
Position : Positive;
Value : S.Address);
-- Given a pointer to a dispatch Table (T) and a position in the
-- dispatch Table put the address of the virtual function in it
-- (used for overriding)
function CPP_Get_Prim_Op_Address
(T : Vtable_Ptr;
Position : Positive)
return S.Address;
-- Given a pointer to a dispatch Table (T) and a position in the DT
-- this function returns the address of the virtual function stored
-- in it (used for dispatching calls)
procedure CPP_Set_Inheritance_Depth
(T : Vtable_Ptr;
Value : Natural);
-- Given a pointer to a dispatch Table, stores the value representing
-- the depth in the inheritance tree. Used during elaboration of the
-- tagged type.
function CPP_Get_Inheritance_Depth (T : Vtable_Ptr) return Natural;
-- Given a pointer to a dispatch Table, retreives the value representing
-- the depth in the inheritance tree. Used for membership.
procedure CPP_Set_TSD (T : Vtable_Ptr; Value : S.Address);
-- Given a pointer T to a dispatch Table, stores the address of the
-- record containing the Type Specific Data generated by GNAT
function CPP_Get_TSD (T : Vtable_Ptr) return S.Address;
-- Given a pointer T to a dispatch Table, retreives the address of the
-- record containing the Type Specific Data generated by GNAT
CPP_DT_Prologue_Size : constant SSE.Storage_Count :=
SSE.Storage_Count
(2 * (Standard'Address_Size / S.Storage_Unit));
-- Size of the first part of the dispatch table
CPP_DT_Entry_Size : constant SSE.Storage_Count :=
SSE.Storage_Count
(1 * (Standard'Address_Size / S.Storage_Unit));
-- Size of each primitive operation entry in the Dispatch Table.
CPP_TSD_Prologue_Size : constant SSE.Storage_Count :=
SSE.Storage_Count
(4 * (Standard'Address_Size / S.Storage_Unit));
-- Size of the first part of the type specific data
CPP_TSD_Entry_Size : constant SSE.Storage_Count :=
SSE.Storage_Count
(Standard'Address_Size / S.Storage_Unit);
-- Size of each ancestor tag entry in the TSD
procedure CPP_Inherit_DT
(Old_T : Vtable_Ptr;
New_T : Vtable_Ptr;
Entry_Count : Natural);
-- Entry point used to initialize the DT of a type knowing the
-- tag of the direct ancestor and the number of primitive ops that are
-- inherited (Entry_Count).
procedure CPP_Inherit_TSD
(Old_TSD : S.Address;
New_Tag : Vtable_Ptr);
-- Entry point used to initialize the TSD of a type knowing the
-- TSD of the direct ancestor.
function CPP_CW_Membership (Obj_Tag, Typ_Tag : Vtable_Ptr) return Boolean;
-- Given the tag of an object and the tag associated to a type, return
-- true if Obj is in Typ'Class.
procedure CPP_Set_External_Tag (T : Vtable_Ptr; Value : S.Address);
-- Set the address of the string containing the external tag
-- in the Dispatch table
function CPP_Get_External_Tag (T : Vtable_Ptr) return S.Address;
-- Retrieve the address of a null terminated string containing
-- the external name
procedure CPP_Set_Expanded_Name (T : Vtable_Ptr; Value : S.Address);
-- Set the address of the string containing the expanded name
-- in the Dispatch table
function CPP_Get_Expanded_Name (T : Vtable_Ptr) return S.Address;
-- Retrieve the address of a null terminated string containing
-- the expanded name
procedure CPP_Set_Remotely_Callable (T : Vtable_Ptr; Value : Boolean);
-- Since the notions of spec/body distinction and categorized packages
-- do not exist in C, this procedure will do nothing
function CPP_Get_Remotely_Callable (T : Vtable_Ptr) return Boolean;
-- This function will always return True for the reason explained above
procedure CPP_Set_RC_Offset (T : Vtable_Ptr; Value : SSE.Storage_Offset);
-- Sets the Offset of the implicit record controller when the object
-- has controlled components. Set to O otherwise.
function CPP_Get_RC_Offset (T : Vtable_Ptr) return SSE.Storage_Offset;
-- Return the Offset of the implicit record controller when the object
-- has controlled components. O otherwise.
function Displaced_This
(Current_This : S.Address;
Vptr : Vtable_Ptr;
Position : Positive)
return S.Address;
-- Compute the displacement on the "this" pointer in order to be
-- compatible with MI.
-- (used for virtual function calls)
type Vtable;
type Vtable_Ptr is access all Vtable;
pragma Inline (CPP_Set_Prim_Op_Address);
pragma Inline (CPP_Get_Prim_Op_Address);
pragma Inline (CPP_Set_Inheritance_Depth);
pragma Inline (CPP_Get_Inheritance_Depth);
pragma Inline (CPP_Set_TSD);
pragma Inline (CPP_Get_TSD);
pragma Inline (CPP_Inherit_DT);
pragma Inline (CPP_CW_Membership);
pragma Inline (CPP_Set_External_Tag);
pragma Inline (CPP_Get_External_Tag);
pragma Inline (CPP_Set_Expanded_Name);
pragma Inline (CPP_Get_Expanded_Name);
pragma Inline (CPP_Set_Remotely_Callable);
pragma Inline (CPP_Get_Remotely_Callable);
pragma Inline (Displaced_This);
end Interfaces.CPP;
|
with Ada.Characters.Handling; use Ada.Characters.Handling;
with Ada.Strings;
with Ada.Strings.Maps;
with Ada.Strings.Fixed;
with Ada.Wide_Text_IO; use Ada.Wide_Text_IO;
with Ada.Calendar;
with Ada.Calendar.Formatting;
with Ada.IO_Exceptions;
with Asis.Compilation_Units;
with Asis.Elements;
with Asis.Text;
with Asis.Extensions.Iterator;
with FP_Translation; use FP_Translation;
package body Unit_Processing is
procedure Recursive_Construct_Processing is new
Asis.Extensions.Iterator.Traverse_Unit
(State_Information => FP_Translation.Traversal_State,
Pre_Operation => FP_Translation.Pre_Op,
Post_Operation => FP_Translation.Post_Op);
------------------
-- Process_Unit --
------------------
procedure Process_Unit
(The_Unit : Asis.Compilation_Unit;
Trace : Boolean := False;
Output_Path : String)
is
Example_Element : Asis.Element := Asis.Elements.Unit_Declaration (The_Unit);
-- The top-level ctructural element of the library item or subunit
-- contained in The_Unit. Only needed as an example element from the
-- compilation unit so that we can obtain the span of the unit.
Unit_Span : Asis.Text.Span := Asis.Text.Compilation_Span(Example_Element);
-- Span is used to indicate a portion of the program text. Here we need
-- to span the whole text of the unit as that is the full scope of the translation.
Unit_Text_Name : String := To_String(Asis.Compilation_Units.Text_Name(The_Unit));
-- We assume that the text name is the full path of the .adb file
-- in which the unit is stored.
Last_Segment_Ix : Integer :=
Ada.Strings.Fixed.Index
(Source => Unit_Text_Name,
Set => Ada.Strings.Maps.To_Set("\\\\/"),
Going => Ada.Strings.Backward);
Output_File_Name : String :=
Output_Path &
Unit_Text_Name(Last_Segment_Ix..Unit_Text_Name'Last);
Process_Control : Asis.Traverse_Control := Asis.Continue;
Process_State : Traversal_State;
-- initialised later because it contains a file handle
begin
if Trace then
Put("Source text name: ");
Put(To_Wide_String(Unit_Text_Name));
New_Line;
end if;
-- Initialise the transversal state variable,
-- and open the appropriate output file:
Process_State.Span := Unit_Span;
Process_State.Trace := Trace;
declare
begin
Open(Process_State.Output_File, Out_File, Output_File_Name);
exception
when Ada.IO_Exceptions.Name_Error =>
Create(Process_State.Output_File, Out_File, Output_File_Name);
end;
if Trace then
Put("Target file name: ");
Put(To_Wide_String(Output_File_Name));
New_Line;
end if;
-- Write a header to the new file:
Put(Process_State.Output_File,
"-- This file has been modified by pp_fpops for floating-point verification.");
New_Line(Process_State.Output_File);
Put(Process_State.Output_File,
"-- pp_fpops is part of PolyPaver (https://github.com/michalkonecny/polypaver).");
New_Line(Process_State.Output_File);
Put(Process_State.Output_File,
"-- Generated on ");
Put(Process_State.Output_File,
To_Wide_String(Ada.Calendar.Formatting.Image(Ada.Calendar.Clock)));
Put(Process_State.Output_File,
" from the file:");
New_Line(Process_State.Output_File);
Put(Process_State.Output_File,
"-- ");
Put(Process_State.Output_File,
To_Wide_String(Unit_Text_Name));
New_Line(Process_State.Output_File);
Put(Process_State.Output_File,
"-- pp_fpops converted any floating-point operators to calls in the following packages:");
New_Line(Process_State.Output_File);
Put(Process_State.Output_File,
"with PP_SF_Rounded; with PP_F_Rounded; with PP_LF_Rounded;");
New_Line(Process_State.Output_File);
-- Put(Process_State.Output_File,
-- "--# inherit PP_SF_Rounded, PP_F_Rounded, PP_LF_Rounded;");
-- New_Line(Process_State.Output_File);
-- Recurse through the unit constructs.
-- When coming across an FP operator expression,
-- put all that precedes it and has not been printed yet,
-- and then put a translation of the FP operator expression.
Recursive_Construct_Processing
(Unit => The_Unit,
Control => Process_Control,
State => Process_State);
-- Put the remainder of the unit body.
-- If there are no FP operators in the body,
-- the span is the whole unit body text at the point
-- and the unit remains unchanged.
FP_Translation.Put_Current_Span(Example_Element, Process_State);
-- Close the output file:
Close(Process_State.Output_File);
end Process_Unit;
end Unit_Processing;
|
-----------------------------------------------------------------------
-- mat-commands -- Command support and execution
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Targets;
package MAT.Commands is
-- Exception raised to stop the program.
Stop_Interp : exception;
-- Exception raised to stop the command (program continues).
Stop_Command : exception;
-- Exception raised by a command when a filter expression is invalid.
Filter_Error : exception;
-- Exception raised by a command when some command argument is invalid.
Usage_Error : exception;
-- Procedure that defines a command handler.
type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Execute the command given in the line.
procedure Execute (Target : in out MAT.Targets.Target_Type'Class;
Line : in String);
-- Initialize the process targets by loading the MAT files.
procedure Initialize_Files (Target : in out MAT.Targets.Target_Type'Class);
-- Symbol command.
-- Load the symbols from the binary file.
procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Sizes command.
-- Collect statistics about the used memory slots and report the different slot
-- sizes with count.
procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Threads command.
-- Collect statistics about the threads and their allocation.
procedure Threads_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Events command.
-- Print the probe events.
procedure Events_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Event command.
-- Print the probe event with the stack frame.
procedure Event_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Info command to print symmary information about the program.
procedure Info_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Timeline command.
-- Identify the interesting timeline groups in the events and display them.
procedure Timeline_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Addr command to print a description of an address.
procedure Addr_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
end MAT.Commands;
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . C U _ I N F O 2 --
-- --
-- S p e c --
-- --
-- Copyright (c) 1995-1999, Free Software Foundation, Inc. --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 59 Temple Place --
-- - Suite 330, Boston, MA 02111-1307, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by Ada Core Technologies Inc --
-- (http://www.gnat.com). --
-- --
------------------------------------------------------------------------------
with Asis; use Asis;
with A4G.A_Types; use A4G.A_Types;
with Types; use Types;
-- This package contains the routines used to compute the unit attributes
-- during the second pass through the tree files, when ASIS operates in
-- Use_Pre_Created_Trees mode. There is some duplication of the
-- functionalities provided by this package and by A4G.C_U_Info and
-- A4G.S_U_Info; the last two packages were coded before for
-- Compile_On_The_Fly ASIS operation mode. The intent is to get rid of
-- A4G.C_U_Info and A4G.S_U_Info in the final ASIS version, so we do not
-- bother about these duplications for now.
-- ???THIS COMMENT HEADER SHOULD BE REVISED!!!???
package A4G.CU_Info2 is
procedure Set_Kind_and_Class
(C : Context_Id;
U : Unit_Id;
Top : Node_Id);
-- Taking the unit's subtree top node, this procedure computes and sets
-- the Unit Kind and the Unit Class for U. Because of some technical ,
-- reasons, it is more easy to define the Unit Kind and the Unit Class
-- in the same routine
procedure Get_Ada_Name (Top : Node_Id);
-- Computes (by traversing the tree) the fully expanded Ada name
-- of a compilation unit whose subtree contained as having Top as
-- its top node in the full tree currently being accessed. This name
-- then is set in A_Name_Buffer, and A_Name_Len is set as its length
procedure Set_S_F_Name_and_Origin
(Context : Context_Id;
Unit : Unit_Id;
Top : Node_Id);
-- This procedure obtains the source file name from the GNAT tree and
-- stores it in the Unit_Table. By analyzing the file name (this analysis
-- is based on the Fname.Is_Predefined_File_Name GNAt function, the
-- Unit_Origin for the Unit is defined and stored in the Unit table.
function Is_Main (Top : Node_Id; Kind : Unit_Kinds) return Boolean;
-- Defines if the Unit having Top as its N_Compilation_Unit node
-- can be a main subprogram for a partition. Asis Unit Kind is
-- used to optimize this computation
procedure Set_Dependencies
(C : Context_Id;
U : Unit_Id;
Top : Node_Id);
-- Taking the unit's subtree top node, this procedure computes and sets
-- all the dependency information needed for semantic queries from the
-- Asis.Compilation_Units package. This information is stored as unit
-- lists (see A4G.Unit_Rec). For now, we do not compute the lists of
-- *direct* supporters and *direct* dependents, because we think, that
-- these ASIS notions are ill-defined and cannot be mapped onto RM95
-- in a natural way.
end A4G.CU_Info2;
|
--
-- Raytracer implementation in Ada
-- by John Perry (github: johnperry-math)
-- 2021
--
-- specification for types, constants, and operators used throughout
--
-- Ada packages
with Interfaces;
-- @summary types, constants, and operators used throughout the project
-- @description
-- Makes precise the meaning of floating-point and integer types that we need.
--
package RayTracing_Constants is
type Float15 is digits 15;
-- floating point with 15 digit precision; i.e.,
-- 64-bit floating point will suffice
Far_Away: constant Float15 := 1_000_000.0;
-- an point too far away to be considered useful
subtype UInt8 is Interfaces.Unsigned_8;
function "="(First, Second: UInt8) return Boolean renames Interfaces."=";
subtype UInt16 is Interfaces.Unsigned_16;
function "+"(First, Second: UInt16) return UInt16 renames Interfaces."+";
function "*"(First, Second: UInt16) return UInt16 renames Interfaces."*";
subtype UInt32 is Interfaces.Unsigned_32;
function "+"(First, Second: UInt32) return UInt32 renames Interfaces."+";
subtype Int32 is Interfaces.Integer_32;
function "-"(It: Int32) return Int32 renames Interfaces."-";
function "+"(First, Second: Int32) return Int32 renames Interfaces."+";
function "-"(First, Second: Int32) return Int32 renames Interfaces."-";
function "*"(First, Second: Int32) return Int32 renames Interfaces."*";
function "/"(First, Second: Int32) return Int32 renames Interfaces."/";
end RayTracing_Constants;
|
------------------------------------------------------------------------------
-- Copyright (c) 2015-2019, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Natools.Web.Simple_Pages.Markdown_Pages extends simple pages with a new --
-- file format, starting with the usual simple-page S-expression embeded in --
-- a list, followed by markdown text which is rendered as the element --
-- named "markdown-text". --
------------------------------------------------------------------------------
with Natools.S_Expressions;
with Natools.Web.Sites;
private with Ada.Calendar;
private with Natools.S_Expressions.Atom_Refs;
package Natools.Web.Simple_Pages.Markdown_Pages is
type Loader is new Sites.Page_Loader with private;
overriding procedure Load
(Object : in out Loader;
Builder : in out Sites.Site_Builder;
Path : in S_Expressions.Atom);
not overriding procedure Force_Load
(Object : in out Loader;
Builder : in out Sites.Site_Builder;
Path : in S_Expressions.Atom);
function Create (File : in S_Expressions.Atom)
return Sites.Page_Loader'Class;
private
type Loader is new Sites.Page_Loader with record
File_Path : S_Expressions.Atom_Refs.Immutable_Reference;
File_Time : Ada.Calendar.Time;
Cache : Page_Ref;
end record;
end Natools.Web.Simple_Pages.Markdown_Pages;
|
------------------------------------------------------------------------------
-- Copyright (c) 2014-2017, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Natools.S_Expressions.Lockable.Tests;
with Natools.S_Expressions.Printers;
with Natools.S_Expressions.Test_Tools;
package body Natools.S_Expressions.Parsers.Tests is
generic
Name : String;
Source, Expected : Atom;
procedure Blackbox_Test (Report : in out NT.Reporter'Class);
-- Perform a simple blackbox test, feeding Source to a new parser
-- plugged on a canonical printer and comparing with Expected.
------------------------------
-- Local Helper Subprograms --
------------------------------
procedure Blackbox_Test (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item (Name);
begin
declare
Input, Output : aliased Test_Tools.Memory_Stream;
Printer : Printers.Canonical (Output'Access);
Parser : Parsers.Stream_Parser (Input'Access);
begin
Output.Set_Expected (Expected);
Input.Set_Data (Source);
Parser.Next;
Printers.Transfer (Parser, Printer);
Output.Check_Stream (Test);
end;
exception
when Error : others => Test.Report_Exception (Error);
end Blackbox_Test;
-------------------------
-- Complete Test Suite --
-------------------------
procedure All_Tests (Report : in out NT.Reporter'Class) is
begin
Canonical_Encoding (Report);
Atom_Encodings (Report);
Base64_Subexpression (Report);
Special_Subexpression (Report);
Nested_Subpexression (Report);
Number_Prefixes (Report);
Quoted_Escapes (Report);
Lockable_Interface (Report);
Reset (Report);
Locked_Next (Report);
Memory_Parser (Report);
Close_Current_List (Report);
end All_Tests;
-----------------------
-- Inidividual Tests --
-----------------------
procedure Atom_Encodings (Report : in out NT.Reporter'Class) is
procedure Test is new Blackbox_Test
(Name => "Basic atom encodings",
Source => To_Atom ("17:Verbatim encoding"
& """Quoted\040string"""
& "#48657861646563696d616c2064756d70#"
& "token "
& "|QmFzZS02NCBlbmNvZGluZw==|"),
Expected => To_Atom ("17:Verbatim encoding"
& "13:Quoted string"
& "16:Hexadecimal dump"
& "5:token"
& "16:Base-64 encoding"));
begin
Test (Report);
end Atom_Encodings;
procedure Base64_Subexpression (Report : in out NT.Reporter'Class) is
procedure Test is new Blackbox_Test
(Name => "Base-64 subexpression",
Source => To_Atom ("head({KDc6c3VibGlzdCk1OnRva2Vu})""tail"""),
Expected => To_Atom ("4:head((7:sublist)5:token)4:tail"));
begin
Test (Report);
end Base64_Subexpression;
procedure Canonical_Encoding (Report : in out NT.Reporter'Class) is
Sample_Image : constant String
:= "3:The(5:quick((5:brown3:fox)5:jumps))9:over3:the()4:lazy0:3:dog";
procedure Test is new Blackbox_Test
(Name => "Canonical encoding",
Source => To_Atom (Sample_Image),
Expected => To_Atom (Sample_Image));
begin
Test (Report);
end Canonical_Encoding;
procedure Close_Current_List (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Close_Current_List primitive");
begin
declare
Input : aliased Test_Tools.Memory_Stream;
Parser : Parsers.Stream_Parser (Input'Access);
begin
Input.Set_Data (To_Atom ("3:The(5:quick((5:brown3:fox)5:jumps))"
& "(4:over()3:the)4:lazy(0:3:dog)3:the3:end"));
Test_Tools.Next_And_Check (Test, Parser, To_Atom ("The"), 0);
Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 1);
Test_Tools.Next_And_Check (Test, Parser, To_Atom ("quick"), 1);
Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 2);
Parser.Close_Current_List;
Test_Tools.Next_And_Check (Test, Parser, Events.Close_List, 0);
Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 1);
Test_Tools.Next_And_Check (Test, Parser, To_Atom ("over"), 1);
Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 2);
Test_Tools.Next_And_Check (Test, Parser, Events.Close_List, 1);
Parser.Close_Current_List;
Test_Tools.Next_And_Check (Test, Parser, To_Atom ("lazy"), 0);
Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 1);
Test_Tools.Next_And_Check (Test, Parser, To_Atom (""), 1);
Parser.Close_Current_List;
Test_Tools.Next_And_Check (Test, Parser, To_Atom ("the"), 0);
Parser.Close_Current_List;
Check_Last_Event :
declare
Last_Event : constant Events.Event := Parser.Current_Event;
begin
if Last_Event /= Events.End_Of_Input then
Test.Fail ("Unexpected last event "
& Events.Event'Image (Last_Event));
end if;
end Check_Last_Event;
Parser.Close_Current_List;
Check_Byeond_Last_Event :
declare
Last_Event : constant Events.Event := Parser.Current_Event;
begin
if Last_Event /= Events.End_Of_Input then
Test.Fail ("Unexpected bayond-last event "
& Events.Event'Image (Last_Event));
end if;
end Check_Byeond_Last_Event;
end;
exception
when Error : others => Test.Report_Exception (Error);
end Close_Current_List;
procedure Lockable_Interface (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Lockable.Descriptor interface");
begin
declare
Input : aliased Test_Tools.Memory_Stream;
Parser : Parsers.Stream_Parser (Input'Access);
begin
Input.Set_Data (Lockable.Tests.Test_Expression);
Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 1);
Lockable.Tests.Test_Interface (Test, Parser);
end;
exception
when Error : others => Test.Report_Exception (Error);
end Lockable_Interface;
procedure Locked_Next (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Next on locked parser");
begin
declare
Input : aliased Test_Tools.Memory_Stream;
Parser : Parsers.Stream_Parser (Input'Access);
Lock_State : Lockable.Lock_State;
begin
Input.Set_Data (To_Atom ("(command (subcommand arg (arg list)))0:"));
Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 1);
Test_Tools.Next_And_Check (Test, Parser, To_Atom ("command"), 1);
Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 2);
Test_Tools.Next_And_Check (Test, Parser, To_Atom ("subcommand"), 2);
Parser.Lock (Lock_State);
Test_Tools.Test_Atom_Accessors
(Test, Parser, To_Atom ("subcommand"), 0);
Test_Tools.Next_And_Check (Test, Parser, To_Atom ("arg"), 0);
Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 1);
Test_Tools.Next_And_Check (Test, Parser, To_Atom ("arg"), 1);
Test_Tools.Next_And_Check (Test, Parser, To_Atom ("list"), 1);
Test_Tools.Next_And_Check (Test, Parser, Events.Close_List, 0);
Test_Tools.Next_And_Check (Test, Parser, Events.End_Of_Input, 0);
Test_Tools.Next_And_Check (Test, Parser, Events.End_Of_Input, 0);
Test_Tools.Next_And_Check (Test, Parser, Events.End_Of_Input, 0);
Parser.Unlock (Lock_State);
Test_Tools.Next_And_Check (Test, Parser, Events.Close_List, 0);
Test_Tools.Next_And_Check (Test, Parser, Null_Atom, 0);
end;
exception
when Error : others => Test.Report_Exception (Error);
end Locked_Next;
procedure Memory_Parser (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Memory-backed parser");
begin
declare
Parser : Parsers.Memory_Parser
:= Create_From_String ("(command (subcommand arg (arg list)))0:");
begin
Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 1);
Test_Tools.Next_And_Check (Test, Parser, To_Atom ("command"), 1);
Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 2);
Test_Tools.Next_And_Check (Test, Parser, To_Atom ("subcommand"), 2);
Test_Tools.Next_And_Check (Test, Parser, To_Atom ("arg"), 2);
Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 3);
Test_Tools.Next_And_Check (Test, Parser, To_Atom ("arg"), 3);
Test_Tools.Next_And_Check (Test, Parser, To_Atom ("list"), 3);
Test_Tools.Next_And_Check (Test, Parser, Events.Close_List, 2);
Test_Tools.Next_And_Check (Test, Parser, Events.Close_List, 1);
Test_Tools.Next_And_Check (Test, Parser, Events.Close_List, 0);
Test_Tools.Next_And_Check (Test, Parser, Null_Atom, 0);
Test_Tools.Next_And_Check (Test, Parser, Events.End_Of_Input, 0);
Test_Tools.Next_And_Check (Test, Parser, Events.End_Of_Input, 0);
end;
exception
when Error : others => Test.Report_Exception (Error);
end Memory_Parser;
procedure Nested_Subpexression (Report : in out NT.Reporter'Class) is
procedure Test is new Blackbox_Test
(Name => "Nested base-64 subepxressions",
Source => To_Atom ("(5:begin"
& "{KG5lc3RlZCB7S0dSbFpYQWdjR0Y1Ykc5aFpDaz19KQ==}"
& "end)"),
Expected => To_Atom ("(5:begin"
& "(6:nested(4:deep7:payload))"
& "3:end)"));
begin
Test (Report);
end Nested_Subpexression;
procedure Number_Prefixes (Report : in out NT.Reporter'Class) is
procedure Test is new Blackbox_Test
(Name => "Number prefixes",
Source => To_Atom ("8:verbatim"
& "(valid 6""quoted"" 11#68657861646563696d616c#"
& " 7|YmFzZS02NA==| 9{NzpleHByLTY0})"
& "(undefined 42 10% 123() 10)"
& "(invalid 10""quoted"" 3#68657861646563696d616c#"
& " 75|YmFzZS02NA==| 1{NzpleHByLTY0})"),
Expected => To_Atom ("8:verbatim"
& "(5:valid6:quoted11:hexadecimal7:base-647:expr-64)"
& "(9:undefined2:423:10%3:123()2:10)"
& "(7:invalid6:quoted11:hexadecimal7:base-647:expr-64)"));
begin
Test (Report);
end Number_Prefixes;
procedure Quoted_Escapes (Report : in out NT.Reporter'Class) is
CR : constant Character := Character'Val (13);
LF : constant Character := Character'Val (10);
procedure Test is new Blackbox_Test
(Name => "Escapes in quoted encoding",
Source => To_Atom ("(single-letters ""\b\t\n\v\f\r\\\k"")"
& "(newlines ""head\" & CR & "tail"" ""head\" & LF & "tail"""
& " ""head\" & CR & LF & "tail"" ""head\" & LF & CR & "tail"")"
& "(octal ""head\040\04\xtail"")"
& "(hexadecimal ""head\x20\x2a\x2D\x2gtail"")"
& "(special ""\x""1:"")"),
Expected => To_Atom ("(14:single-letters9:"
& Character'Val (8) & Character'Val (9)
& Character'Val (10) & Character'Val (11)
& Character'Val (12) & Character'Val (13)
& "\\k)"
& "(8:newlines8:headtail8:headtail8:headtail8:headtail)"
& "(5:octal14:head \04\xtail)"
& "(11:hexadecimal15:head *-\x2gtail)"
& "(7:special2:\x1:"")"));
begin
Test (Report);
end Quoted_Escapes;
procedure Reset (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Parser reset");
begin
declare
Input : aliased Test_Tools.Memory_Stream;
Parser : Parsers.Stream_Parser (Input'Access);
Empty : Parsers.Stream_Parser (Input'Access);
use type Atom_Buffers.Atom_Buffer;
use type Lockable.Lock_Stack;
begin
Input.Write (To_Atom ("(begin(first second"));
Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 1);
Test_Tools.Next_And_Check (Test, Parser, To_Atom ("begin"), 1);
Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 2);
Test_Tools.Next_And_Check (Test, Parser, To_Atom ("first"), 2);
Test_Tools.Next_And_Check (Test, Parser, Events.End_Of_Input, 2);
Parser.Reset (Hard => False);
Input.Write (To_Atom ("other(new list)end"));
Test_Tools.Next_And_Check (Test, Parser, To_Atom ("other"), 0);
Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 1);
Test_Tools.Next_And_Check (Test, Parser, To_Atom ("new"), 1);
Test_Tools.Next_And_Check (Test, Parser, To_Atom ("list"), 1);
Test_Tools.Next_And_Check (Test, Parser, Events.Close_List, 0);
Parser.Reset (Hard => True);
if Parser.Internal /= Empty.Internal
or else Parser.Next_Event /= Empty.Next_Event
or else Parser.Latest /= Empty.Latest
or else Parser.Pending.Capacity /= 0
or else Parser.Buffer.Capacity /= 0
or else Parser.Level /= Empty.Level
or else Parser.Lock_Stack /= Empty.Lock_Stack
or else Parser.Locked /= Empty.Locked
then
Test.Fail ("Parser after hard reset is not empty");
end if;
end;
exception
when Error : others => Test.Report_Exception (Error);
end Reset;
procedure Special_Subexpression (Report : in out NT.Reporter'Class) is
procedure Test is new Blackbox_Test
(Name => "Special base-64 subexpression",
Source => To_Atom ("(begin "
& "{aGlkZGVuLWVuZCkoaGlkZGVuLWJlZ2lu}"
& " end)"
& "({MTY6b3ZlcmZsb3dpbmc=} atom)"),
Expected => To_Atom ("(5:begin"
& "10:hidden-end)(12:hidden-begin"
& "3:end)"
& "(16:overflowing atom)"));
begin
Test (Report);
end Special_Subexpression;
end Natools.S_Expressions.Parsers.Tests;
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Complex_Text_IO; use Ada.Complex_Text_IO;
with Ada.Numerics.Complex_Types; use Ada.Numerics.Complex_Types;
with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays;
with Ada.Numerics.Complex_Arrays; use Ada.Numerics.Complex_Arrays;
with Ada.Numerics.Complex_Elementary_Functions; use Ada.Numerics.Complex_Elementary_Functions;
procedure Test_Matrix is
function "**" (A : Complex_Matrix; Power : Complex) return Complex_Matrix is
L : Real_Vector (A'Range (1));
X : Complex_Matrix (A'Range (1), A'Range (2));
R : Complex_Matrix (A'Range (1), A'Range (2));
RL : Complex_Vector (A'Range (1));
begin
Eigensystem (A, L, X);
for I in L'Range loop
RL (I) := (L (I), 0.0) ** Power;
end loop;
for I in R'Range (1) loop
for J in R'Range (2) loop
declare
Sum : Complex := (0.0, 0.0);
begin
for K in RL'Range (1) loop
Sum := Sum + X (K, I) * RL (K) * X (K, J);
end loop;
R (I, J) := Sum;
end;
end loop;
end loop;
return R;
end "**";
procedure Put (A : Complex_Matrix) is
begin
for I in A'Range (1) loop
for J in A'Range (1) loop
Put (A (I, J));
end loop;
New_Line;
end loop;
end Put;
M : Complex_Matrix (1..2, 1..2) := (((3.0,0.0),(2.0,1.0)),((2.0,-1.0),(1.0,0.0)));
begin
Put_Line ("M ="); Put (M);
Put_Line ("M**0 ="); Put (M**(0.0,0.0));
Put_Line ("M**1 ="); Put (M**(1.0,0.0));
Put_Line ("M**0.5 ="); Put (M**(0.5,0.0));
end Test_Matrix;
|
-- AOC 2020, Day 10
with Ada.Containers.Vectors;
package Day is
package Adaptors is new Ada.Containers.Vectors
(Index_Type => Natural,
Element_Type => Natural);
use Adaptors;
function load_file(filename : in String) return Adaptors.Vector;
function mult_1_3_differences(v : in Adaptors.Vector) return Natural;
function total_arrangments(v : in Adaptors.Vector) return Long_Integer;
end Day;
|
with Ada.Integer_Text_IO;
-- Copyright 2021 Melwyn Francis Carlo
procedure A023 is
use Ada.Integer_Text_IO;
Abundant_Numbers : array (Integer range 1 .. 10000) of Integer :=
(others => 0);
N : Integer := 1;
Count_Val : Integer := 1;
J_Max, K, Count_By_2, Proper_Divisors_Sum : Integer;
Abundant_Sum_Found : Boolean;
begin
for I in 2 .. 28123 loop
Proper_Divisors_Sum := 0;
J_Max := Integer (Float'Floor (Float (I) / 2.0));
for J in 1 .. J_Max loop
if (I mod J) = 0 then
Proper_Divisors_Sum := Proper_Divisors_Sum + J;
end if;
end loop;
if Proper_Divisors_Sum > I then
Abundant_Numbers (Count_Val) := I;
Count_Val := Count_Val + 1;
end if;
Count_By_2 := Integer (Float'Floor (Float (Count_Val) / 2.0));
Abundant_Sum_Found := False;
for J in 1 .. Count_By_2 loop
K := J;
while (Abundant_Numbers (J) + Abundant_Numbers (K)) < I loop
K := K + 1;
end loop;
if (Abundant_Numbers (J) + Abundant_Numbers (K)) = I then
Abundant_Sum_Found := True;
exit;
end if;
end loop;
if not Abundant_Sum_Found then
N := N + I;
end if;
end loop;
Put (N, Width => 0);
end A023;
|
with STM32.SPI; use STM32.SPI;
with HAL.SPI; use HAL.SPI;
package body Board is
procedure Initialize is
Pins : GPIO_Points := (LCD_RST, LCD_DC, LCD_CS);
begin
Enable_Clock (LCD_DIN & LCD_CLK);
Enable_Clock (Pins);
Set (Pins);
Configure_IO
(Pins,
(Resistors => Pull_Up,
Mode => Mode_Out,
Output_Type => Push_Pull,
Speed => Speed_25MHz));
Configure_IO
(LCD_DIN & LCD_CLK,
(Resistors => Pull_Up,
Mode => Mode_AF,
AF_Output_Type => Push_Pull,
AF_Speed => Speed_25MHz,
AF => GPIO_AF_SPI2_5));
Enable_Clock (SPI_2);
Configure
(SPI_2,
(Direction => D2Lines_FullDuplex,
Mode => Master,
Data_Size => Data_Size_8b,
Clock_Polarity => High,
Clock_Phase => P2Edge,
Slave_Management => Software_Managed,
Baud_Rate_Prescaler => BRP_8,
First_Bit => MSB,
CRC_Poly => 0));
Enable (SPI_2);
Display.Initialize;
Display.Set_Bias (3);
Display.Set_Contrast (60);
end Initialize;
end Board;
|
--------------------------------------------------------------------------------
-- --
-- Copyright (C) 2004, RISC OS Ada Library (RASCAL) developers. --
-- --
-- This library is free software; you can redistribute it and/or --
-- modify it under the terms of the GNU Lesser General Public --
-- License as published by the Free Software Foundation; either --
-- version 2.1 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 --
-- Lesser General Public License for more details. --
-- --
-- You should have received a copy of the GNU Lesser General Public --
-- License along with this library; if not, write to the Free Software --
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA --
-- --
--------------------------------------------------------------------------------
-- @brief Reading and Writing from/to file.
-- $Author$
-- $Date$
-- $Revision$
with RASCAL.Utility; use RASCAL.Utility;
with System; use System;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with System.Unsigned_Types; use System.Unsigned_Types;
with Ada.Finalization;
package RASCAL.FileInternal is
subtype Real_FileHandle_Type is System.Unsigned_Types.Unsigned;
type UString_Ptr is access UString;
type File_Access_Type is (Read,Write,ReadWrite);
type FileHandle_Type(File : UString_Ptr;
File_Access : File_Access_Type) is
new Ada.Finalization.Limited_Controlled with private;
type Line_List_Type is array (Natural range <>) of unbounded_string;
--
-- Returns true if end of file has been reached.
--
function Is_EOF (File : in FileHandle_Type) return boolean;
--
-- Returns the extent of the file. That is NOT the same as the filesize.
--
function Get_Extent (File : in FileHandle_Type) return natural;
--
-- Goto start of file.
--
procedure Goto_Start (File : in FileHandle_Type);
--
-- Goto end of file.
--
procedure Goto_End (File : in FileHandle_Type);
--
-- Returns file index.
--
function Get_Ptr (File : in FileHandle_Type) return Integer;
--
-- Sets file index to 'ptr'
--
procedure Set_Ptr (File : in FileHandle_Type;
Ptr : in integer);
--
-- Read a single byte from file.
--
function Get_Byte (File : in FileHandle_Type) return Integer;
--
-- Writes a single byte to file.
--
procedure Put_Byte (File : in FileHandle_Type;
Byte : in Integer);
--
-- Move a Nr of bytes forward in file.
--
procedure Skip_Bytes (File : in FileHandle_Type;
Nr : in Integer);
--
-- Reads a number (Length) of bytes from file.
--
procedure Get_Bytes (File : in FileHandle_Type;
Buffer : in Address;
Length : in Integer);
--
-- Writes a number (Length) of bytes to files.
--
procedure Put_Bytes (File : in FileHandle_Type;
Buffer : in Address;
Length : in Integer);
--
-- Writes a string (Line) to file.
--
procedure Put_String (File : in FileHandle_Type;
Line : in String;
Attach_LF : in Boolean := true);
--
-- Moves filepointer to beginning of next line containing other characters than space.
--
procedure Skip_EmptyLines (File : in FileHandle_Type);
--
-- Reads a line from file.
--
function Read_Line (File : in FileHandle_Type;
Trim : in boolean := false) return String;
--
-- Returns the number of lines in file.
--
function Get_Lines (File : in FileHandle_Type;
Trim : in boolean := true) return integer;
--
-- Ensures that the size of the 'File' is not less than 'Size'.
--Note that the extent is not changed.
--
procedure Ensure_Size (File : in FileHandle_Type;
Size : in Integer);
--
-- Loads file into 'Buffer'.
--
procedure Load_File (FileName : in String;
Buffer : in Address);
--
-- Saves 'Buffer' to file.
--
procedure Save_File (FileName : in String;
Buffer : in Address;
Bufferend : in Address;
FileType : in Integer);
--
-- Returns internal filehandle.
--
function Get_Real_FileHandle (File : in FileHandle_Type) return Real_FileHandle_Type;
--
-- Close file.
--
procedure Close (File : in FileHandle_Type);
private
procedure Initialize (The : in out FileHandle_Type);
procedure Finalize (The : in out FileHandle_Type);
type FileHandle_Type(File : UString_Ptr;
File_Access : File_Access_Type) is
new Ada.Finalization.Limited_Controlled with
record
Path : UString := File.all;
Access_Type : File_Access_Type := File_Access;
Handle : Real_FileHandle_Type := -1;
end record;
end RASCAL.FileInternal;
|
with Types; use Types;
package Gfx is
procedure Init_Draw;
procedure Draw_Keyboard(Mem : Memory);
procedure Draw_Key(Mem : Memory; X : Integer; Y : Integer);
procedure Draw_Key_Pixel(X : Integer; Y : Integer);
procedure Draw_Pixel(X : Integer; Y : Integer; Pixel : Boolean);
procedure Clear_Layer(Layer : Integer);
end Gfx;
|
package body STM32.CORDIC is
-------------------------
-- Set_CORDIC_Function --
-------------------------
procedure Set_CORDIC_Function
(This : in out CORDIC_Coprocessor;
Value : CORDIC_Function)
is
begin
This.CSR.FUNC := Value'Enum_Rep;
end Set_CORDIC_Function;
-------------------------
-- Get_CORDIC_Function --
-------------------------
function Get_CORDIC_Function (This : CORDIC_Coprocessor)
return CORDIC_Function
is
begin
return CORDIC_Function'Val (This.CSR.FUNC);
end Get_CORDIC_Function;
--------------------------
-- Set_CORDIC_Precision --
--------------------------
procedure Set_CORDIC_Precision
(This : in out CORDIC_Coprocessor;
Value : CORDIC_Iterations)
is
begin
This.CSR.PRECISION := Value'Enum_Rep;
end Set_CORDIC_Precision;
-------------------------------
-- Set_CORDIC_Scaling_Factor --
-------------------------------
procedure Set_CORDIC_Scaling_Factor
(This : in out CORDIC_Coprocessor;
Value : UInt3)
is
begin
This.CSR.SCALE := Value;
end Set_CORDIC_Scaling_Factor;
--------------------------
-- Set_CORDIC_Data_Size --
--------------------------
procedure Set_CORDIC_Data_Size
(This : in out CORDIC_Coprocessor;
Value : CORDIC_Data_Size)
is
begin
This.CSR.ARGSIZE := Value = Data_16_Bit;
This.CSR.RESSIZE := Value = Data_16_Bit;
end Set_CORDIC_Data_Size;
--------------------------
-- Get_CORDIC_Data_Size --
--------------------------
function Get_CORDIC_Data_Size
(This : CORDIC_Coprocessor)
return CORDIC_Data_Size
is
begin
return (if This.CSR.ARGSIZE then Data_16_Bit else Data_32_Bit);
end Get_CORDIC_Data_Size;
---------------------------------
-- Set_CORDIC_Arguments_Number --
---------------------------------
procedure Set_CORDIC_Arguments_Number
(This : in out CORDIC_Coprocessor;
Value : CORDIC_Arguments_Number)
is
begin
This.CSR.NARGS := Value = Two_32_Bit;
end Set_CORDIC_Arguments_Number;
---------------------------------
-- Get_CORDIC_Arguments_Number --
---------------------------------
function Get_CORDIC_Arguments_Number
(This : CORDIC_Coprocessor)
return CORDIC_Arguments_Number
is
begin
return (if This.CSR.NARGS then Two_32_Bit else One_32_Bit);
end Get_CORDIC_Arguments_Number;
-------------------------------
-- Set_CORDIC_Results_Number --
-------------------------------
procedure Set_CORDIC_Results_Number
(This : in out CORDIC_Coprocessor;
Value : CORDIC_Arguments_Number)
is
begin
This.CSR.NRES := Value = Two_32_Bit;
end Set_CORDIC_Results_Number;
-------------------------------
-- Get_CORDIC_Results_Number --
-------------------------------
function Get_CORDIC_Results_Number
(This : CORDIC_Coprocessor)
return CORDIC_Arguments_Number
is
begin
return (if This.CSR.NRES then Two_32_Bit else One_32_Bit);
end Get_CORDIC_Results_Number;
-----------------------------------
-- Configure_CORDIC_Coprocesssor --
-----------------------------------
procedure Configure_CORDIC_Coprocessor
(This : in out CORDIC_Coprocessor;
Operation : CORDIC_Function;
Precision : CORDIC_Iterations := Iteration_20;
Scaling : UInt3 := 0;
Data_Size : CORDIC_Data_Size)
is
begin
This.CSR.FUNC := Operation'Enum_Rep;
This.CSR.PRECISION := Precision'Enum_Rep;
This.CSR.SCALE := Scaling;
This.CSR.ARGSIZE := Data_Size = Data_16_Bit;
This.CSR.RESSIZE := Data_Size = Data_16_Bit;
case Operation is
when Cosine | Sine | Phase | Modulus =>
case Data_Size is
when Data_32_Bit =>
This.CSR.NARGS := True; -- Two_32_Bit Arguments
This.CSR.NRES := True; -- Two_32_Bit Results
when Data_16_Bit =>
This.CSR.NARGS := False; -- One_32_Bit Argument
This.CSR.NRES := False; -- One_32_Bit Result
end case;
when Hyperbolic_Cosine | Hyperbolic_Sine =>
case Data_Size is
when Data_32_Bit =>
This.CSR.NARGS := False; -- One_32_Bit Argument
This.CSR.NRES := True; -- Two_32_Bit Results
when Data_16_Bit =>
This.CSR.NARGS := False; -- One_32_Bit Argument
This.CSR.NRES := False; -- One_32_Bit Result
end case;
when Arctangent | Hyperbolic_Arctangent | Natural_Logarithm | Square_Root =>
case Data_Size is
when Data_32_Bit =>
This.CSR.NARGS := False; -- One_32_Bit Argument
This.CSR.NRES := False; -- One_32_Bit Result
when Data_16_Bit =>
This.CSR.NARGS := False; -- One_32_Bit Argument
This.CSR.NRES := False; -- One_32_Bit Result
end case;
end case;
end Configure_CORDIC_Coprocessor;
---------------------
-- Get_CORDIC_Data --
---------------------
function Get_CORDIC_Data (This : CORDIC_Coprocessor) return UInt32 is
begin
return This.RDATA;
end Get_CORDIC_Data;
------------
-- Status --
------------
function Status
(This : CORDIC_Coprocessor;
Flag : CORDIC_Status) return Boolean
is
begin
case Flag is
when Result_Ready =>
return This.CSR.RRDY;
end case;
end Status;
-------------------
-- Set_Interrupt --
-------------------
procedure Set_Interrupt
(This : in out CORDIC_Coprocessor;
Enable : Boolean)
is
begin
This.CSR.IEN := Enable;
end Set_Interrupt;
-----------------------
-- Interrupt_Enabled --
-----------------------
function Interrupt_Enabled
(This : CORDIC_Coprocessor) return Boolean
is
begin
return This.CSR.IEN;
end Interrupt_Enabled;
-------------
-- Set_DMA --
-------------
procedure Set_DMA
(This : in out CORDIC_Coprocessor;
DMA : CORDIC_DMA;
Enable : Boolean)
is
begin
case DMA is
when Read_DMA =>
This.CSR.DMAREN := Enable;
when Write_DMA =>
This.CSR.DMAWEN := Enable;
end case;
end Set_DMA;
-----------------
-- DMA_Enabled --
-----------------
function DMA_Enabled
(This : CORDIC_Coprocessor;
DMA : CORDIC_DMA)
return Boolean
is
begin
case DMA is
when Read_DMA =>
return This.CSR.DMAREN;
when Write_DMA =>
return This.CSR.DMAWEN;
end case;
end DMA_Enabled;
end STM32.CORDIC;
|
-- The Village of Vampire by YT, このソースコードはNYSLです
with Ada.Calendar;
with Ada.Streams;
with Ada.Strings.Unbounded;
with Web.HTML;
with Tabula.Casts;
with Tabula.Villages;
package Vampire.Forms is
type Base_Page is (Index_Page, User_Page, User_List_Page, Village_Page);
type Template_Set_Type is (For_Full, For_Mobile);
type Root_Form_Type is abstract tagged limited null record;
-- HTML / template set
function HTML_Version (Form : Root_Form_Type) return Web.HTML.HTML_Version is
abstract;
function Template_Set (Form : Root_Form_Type) return Template_Set_Type is
abstract;
-- 出力用
function Self return String;
function Parameters_To_Index_Page (
Form : Root_Form_Type;
User_Id : String;
User_Password : String)
return Web.Query_Strings is abstract;
function Parameters_To_User_Page (
Form : Root_Form_Type;
User_Id : String;
User_Password : String)
return Web.Query_Strings is abstract;
function Parameters_To_Village_Page (
Form : Root_Form_Type;
Village_Id : Villages.Village_Id;
Day : Integer := -1;
First : Tabula.Villages.Speech_Index'Base := -1;
Last : Tabula.Villages.Speech_Index'Base := -1;
Latest : Tabula.Villages.Speech_Positive_Count'Base := -1;
User_Id : String;
User_Password : String)
return Web.Query_Strings is abstract;
function Parameters_To_Base_Page (
Form : Root_Form_Type'Class;
Base_Page : Forms.Base_Page;
Village_Id : Villages.Village_Id;
User_Id : String;
User_Password : String)
return Web.Query_Strings;
procedure Write_Attribute_Name (
Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Name : in String);
procedure Write_Attribute_Open (
Stream : not null access Ada.Streams.Root_Stream_Type'Class);
procedure Write_Attribute_Close (
Stream : not null access Ada.Streams.Root_Stream_Type'Class);
procedure Write_In_HTML (
Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Form : in Root_Form_Type;
Item : in String;
Pre : in Boolean := False) is abstract;
procedure Write_In_Attribute (
Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Form : in Root_Form_Type;
Item : in String) is abstract;
procedure Write_Link (
Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Form : in Root_Form_Type'Class;
Current_Directory : in String;
Resource : in String;
Parameters : in Web.Query_Strings := Web.String_Maps.Empty_Map);
procedure Write_Link_To_Village_Page (
Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Form : in Root_Form_Type'Class;
Current_Directory : in String;
HTML_Directory : in String;
Log : in Boolean;
Village_Id : in Villages.Village_Id;
Day : Integer := -1;
First : Tabula.Villages.Speech_Index'Base := -1;
Last : Tabula.Villages.Speech_Index'Base := -1;
Latest : Tabula.Villages.Speech_Positive_Count'Base := -1;
User_Id : in String;
User_Password : in String);
function Paging (Form : Root_Form_Type) return Boolean is abstract;
function Speeches_Per_Page (Form : Root_Form_Type)
return Tabula.Villages.Speech_Positive_Count'Base is abstract;
-- ユーザー情報
function Get_User_Id (
Form : Root_Form_Type;
Query_Strings : Web.Query_Strings;
Cookie : Web.Cookie)
return String is abstract;
function Get_User_Password (
Form : Root_Form_Type;
Query_Strings : Web.Query_Strings;
Cookie : Web.Cookie)
return String is abstract;
function Get_New_User_Id (
Form : Root_Form_Type'Class;
Inputs : Web.Query_Strings)
return String;
function Get_New_User_Password (
Form : Root_Form_Type'Class;
Inputs : Web.Query_Strings)
return String;
function Get_New_User_Confirmation_Password (
Form : Root_Form_Type'Class;
Inputs : Web.Query_Strings)
return String;
procedure Set_User (
Form : in out Root_Form_Type;
Cookie : in out Web.Cookie;
New_User_Id : in String;
New_User_Password : in String) is abstract;
-- ページ
function Get_Base_Page (
Form : Root_Form_Type'Class;
Query_Strings : Web.Query_Strings;
Cookie : Web.Cookie)
return Base_Page;
-- 個人ページ
function Is_User_Page (
Form : Root_Form_Type;
Query_Strings : Web.Query_Strings;
Cookie : Web.Cookie)
return Boolean is abstract;
function Is_User_List_Page (
Form : Root_Form_Type'Class;
Query_Strings : Web.Query_Strings)
return Boolean;
-- 村
function Get_Village_Id (
Form : Root_Form_Type;
Query_Strings : Web.Query_Strings)
return Villages.Village_Id is abstract;
function Get_Day (
Form : Root_Form_Type;
Village : Villages.Village_Type'Class;
Query_Strings : Web.Query_Strings)
return Natural is abstract;
function Get_Range (
Form : Root_Form_Type;
Village : Villages.Village_Type'Class;
Day : Natural;
Now : Ada.Calendar.Time;
Query_Strings : Web.Query_Strings)
return Villages.Speech_Range_Type is abstract;
-- コマンド
function Get_Command (
Form : Root_Form_Type'Class;
Inputs : Web.Query_Strings)
return String;
function Get_New_Village_Name (
Form : Root_Form_Type;
Inputs : Web.Query_Strings)
return String is abstract;
function Get_Group (
Form : Root_Form_Type;
Inputs : Web.Query_Strings)
return Integer;
type Joining is record
Work_Index : Casts.Works.Cursor; -- "既定"はNo_Element
Name_Index : Casts.People.Cursor; -- No_Elementにはならない
Request : aliased Ada.Strings.Unbounded.Unbounded_String;
end record;
function Get_Joining (
Form : Root_Form_Type;
Inputs : Web.Query_Strings)
return Joining;
type Mark is (Missing, NG, OK);
function Get_Answered (
Form : Root_Form_Type;
Inputs : Web.Query_Strings)
return Mark;
function Get_Text (
Form : Root_Form_Type;
Inputs : Web.Query_Strings)
return String is abstract;
function Get_Reedit_Kind (
Form : Root_Form_Type'Class;
Inputs : Web.Query_Strings)
return String;
function Get_Action (
Form : Root_Form_Type'Class;
Inputs : Web.Query_Strings)
return String;
function Get_Target (
Form : Root_Form_Type'Class;
Inputs : Web.Query_Strings)
return Villages.Person_Index'Base;
function Get_Special (
Form : Root_Form_Type'Class;
Inputs : Web.Query_Strings)
return Boolean;
procedure Set_Rule (
Form : in Root_Form_Type'Class;
Village : in out Villages.Village_Type'Class;
Inputs : in Web.Query_Strings);
private
function Trim_Name (S : String) return String;
function Trim_Text (S : String) return String;
end Vampire.Forms;
|
-----------------------------------------------------------------------
-- servlet-filters -- Servlet Filters
-- Copyright (C) 2010, 2015 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Servlet.Requests;
with Servlet.Responses;
with Servlet.Core;
-- The <b>Servlet.Filters</b> package defines the servlet filter
-- interface described in Java Servlet Specification, JSR 315, 6. Filtering.
--
package Servlet.Filters is
-- ------------------------------
-- Filter interface
-- ------------------------------
-- The <b>Filter</b> interface defines one mandatory procedure through
-- which the request/response pair are passed.
--
-- The <b>Filter</b> instance must be registered in the <b>Servlet_Registry</b>
-- by using the <b>Add_Filter</b> procedure. The same filter instance is used
-- to process multiple requests possibly at the same time.
type Filter is limited interface;
type Filter_Access is access all Filter'Class;
type Filter_List is array (Natural range <>) of Filter_Access;
type Filter_List_Access is access all Filter_List;
-- The Do_Filter method of the Filter is called by the container each time
-- a request/response pair is passed through the chain due to a client request
-- for a resource at the end of the chain. The Filter_Chain passed in to this
-- method allows the Filter to pass on the request and response to the next
-- entity in the chain.
--
-- A typical implementation of this method would follow the following pattern:
-- 1. Examine the request
-- 2. Optionally wrap the request object with a custom implementation to
-- filter content or headers for input filtering
-- 3. Optionally wrap the response object with a custom implementation to
-- filter content or headers for output filtering
-- 4. Either invoke the next entity in the chain using the FilterChain
-- object (chain.Do_Filter()),
-- or, not pass on the request/response pair to the next entity in the
-- filter chain to block the request processing
-- 5. Directly set headers on the response after invocation of the next
-- entity in the filter chain.
procedure Do_Filter (F : in Filter;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class;
Chain : in out Servlet.Core.Filter_Chain) is abstract;
-- Called by the servlet container to indicate to a filter that the filter
-- instance is being placed into service.
procedure Initialize (Server : in out Filter;
Config : in Servlet.Core.Filter_Config) is null;
end Servlet.Filters;
|
-- pragma Locking_Policy (Ceiling_Locking);
with Ada.Text_IO;
with Ada.Real_Time; use Ada.Real_Time;
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with Epoch_Support; use Epoch_Support;
with System;
package body Logging_Support is
------------------------------------------------------------------------
-- | Body of Package for Logging tasks activity
-- | WITH-ed by the body of a package to provide an easy way to
-- | trace events related to task activation and completion
-- | Implemented as a modification to the Debugging_Support package
-- | from Michael B. Feldman, The George Washington University
-- | Author: Jorge Real
-- | Last Modified: December 2017
-- | - Adapted to STM32 board - no file output
-- | - Removed procedure Set_Log
-- | - Use of Epoch_Support
-- | November 2014
-- | - Added PO for serialised output
-------------------------------------------------------------------------
Two_Tabs : constant String := HT & HT;
Init : constant Time := Epoch;
protected Serialise
with Priority => System.Interrupt_Priority'Last
is
procedure Log (Event : in Event_Type; Message : in String := "");
end Serialise;
protected body Serialise is
procedure Log (Event : in Event_Type; Message : in String := "") is
Time_Stamp : Time_Span;
begin
Time_Stamp := Clock - Init;
if Event /= No_Event then
Ada.Text_IO.Put_Line (Event_Type'Image (Event) & Two_Tabs & Message & Two_Tabs &
Duration'Image (To_Duration (Time_Stamp)));
else
Ada.Text_IO.Put_Line (Message);
end if;
end Log;
end Serialise;
procedure Log (Event : in Event_Type; Message : in String := "") is
begin
Serialise.Log (Event, Message);
end Log;
end Logging_Support;
|
with Ada.Numerics.Complex_Arrays; use Ada.Numerics.Complex_Arrays;
with Ada.Complex_Text_IO; use Ada.Complex_Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Complex_Elementary_Functions;
with Generic_FFT;
procedure Example is
function FFT is new Generic_FFT (Ada.Numerics.Complex_Arrays);
X : Complex_Vector := (1..4 => (1.0, 0.0), 5..8 => (0.0, 0.0));
Y : Complex_Vector := FFT (X);
begin
Put_Line (" X FFT X ");
for I in Y'Range loop
Put (X (I - Y'First + X'First), Aft => 3, Exp => 0);
Put (" ");
Put (Y (I), Aft => 3, Exp => 0);
New_Line;
end loop;
end;
|
-----------------------------------------------------------------------
-- awa-audits-services -- AWA Audit Manager
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Indefinite_Hashed_Maps;
with ADO.Audits;
with ADO.Sessions;
limited with AWA.Applications;
package AWA.Audits.Services is
type Application_Access is access all AWA.Applications.Application'Class;
-- ------------------------------
-- Event manager
-- ------------------------------
-- The <b>Event_Manager</b> manages the dispatch of event to the right event queue
-- or to the event action. The event manager holds a list of actions that must be
-- triggered for a particular event/queue pair. Such list is created and initialized
-- when the application is configured. It never changes.
type Audit_Manager is limited new ADO.Audits.Audit_Manager with private;
type Audit_Manager_Access is access all Audit_Manager'Class;
-- Save the audit changes in the database.
overriding
procedure Save (Manager : in out Audit_Manager;
Session : in out ADO.Sessions.Master_Session'Class;
Object : in ADO.Audits.Auditable_Object_Record'Class;
Changes : in ADO.Audits.Audit_Array);
-- Find the audit field identification number from the entity type and field name.
function Get_Audit_Field (Manager : in Audit_Manager;
Name : in String;
Entity : in ADO.Entity_Type) return Integer;
-- Initialize the audit manager.
procedure Initialize (Manager : in out Audit_Manager;
App : in Application_Access);
private
type Field_Key (Len : Natural) is record
Entity : ADO.Entity_Type;
Name : String (1 .. Len);
end record;
function Hash (Item : in Field_Key) return Ada.Containers.Hash_Type;
package Audit_Field_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => Field_Key,
Element_Type => Integer,
Hash => Hash,
Equivalent_Keys => "=");
type Audit_Manager is limited new ADO.Audits.Audit_Manager with record
Fields : Audit_Field_Maps.Map;
end record;
end AWA.Audits.Services;
|
-----------------------------------------------------------------------
-- hestia-display -- Display manager
-- Copyright (C) 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with HAL.Bitmap;
with HAL.Touch_Panel;
with Ada.Real_Time;
with Net;
with UI.Buttons;
with UI.Graphs;
with UI.Displays;
package Hestia.Display is
-- Color to draw a separation line.
Line_Color : HAL.Bitmap.Bitmap_Color := HAL.Bitmap.Blue;
Hot_Color : HAL.Bitmap.Bitmap_Color := HAL.Bitmap.Red;
Cold_Color : HAL.Bitmap.Bitmap_Color := HAL.Bitmap.Blue;
Line_Sep_Color : HAL.Bitmap.Bitmap_Color := HAL.Bitmap.Royal_Blue;
private
B_MAIN : constant UI.Buttons.Button_Index := 1;
B_SETUP : constant UI.Buttons.Button_Index := 2;
B_STAT : constant UI.Buttons.Button_Index := 3;
function Format_Packets (Value : in Net.Uint32) return String;
function Format_Bytes (Value : in Net.Uint64) return String;
function Format_Bandwidth (Value : in Net.Uint32) return String;
-- Initialize the display.
procedure Initialize;
-- Draw the layout presentation frame.
procedure Draw_Frame (Buffer : in out HAL.Bitmap.Bitmap_Buffer'Class);
-- Display the current heat schedule and status.
procedure Display_Main (Buffer : in out HAL.Bitmap.Bitmap_Buffer'Class);
-- Display the schedule setup.
procedure Display_Setup (Buffer : in out HAL.Bitmap.Bitmap_Buffer'Class);
procedure Display_Time (Buffer : in out HAL.Bitmap.Bitmap_Buffer'Class;
Deadline : out Ada.Real_Time.Time);
-- Display a performance summary indicator.
procedure Display_Summary (Buffer : in out HAL.Bitmap.Bitmap_Buffer'Class);
end Hestia.Display;
|
with Ada.Numerics.Discrete_Random;
with Ada.Strings.Fixed;
with Gtk.Main;
with Gtk.Handlers;
with Gtk.Button;
with Gtk.Window;
with Gtk.GEntry;
with Gtk.Editable;
with Gtk.Box;
with Gtk.Widget;
with Glib.Values;
with Gtkada.Dialogs;
procedure Interaction is
The_Value : Natural := 0;
package Natural_Random is new Ada.Numerics.Discrete_Random (Natural);
RNG : Natural_Random.Generator;
Main_Window : Gtk.Window.Gtk_Window;
Content : Gtk.Box.Gtk_Vbox;
Increment_Button : Gtk.Button.Gtk_Button;
Random_Button : Gtk.Button.Gtk_Button;
Entry_Field : Gtk.GEntry.Gtk_Entry;
package Entry_Callbacks is new Gtk.Handlers.Callback
(Gtk.GEntry.Gtk_Entry_Record);
package Button_Callbacks is new Gtk.Handlers.Callback
(Gtk.Button.Gtk_Button_Record);
package Window_Callbacks is new Gtk.Handlers.Return_Callback
(Gtk.Window.Gtk_Window_Record, Boolean);
-- update displayed text
procedure Update_Entry is
begin
Gtk.GEntry.Set_Text
(The_Entry => Entry_Field,
Text =>
Ada.Strings.Fixed.Trim
(Source => Natural'Image (The_Value),
Side => Ada.Strings.Both));
end Update_Entry;
-- read from text entry
procedure Update_Value is
begin
The_Value := Natural'Value (Gtk.GEntry.Get_Text (Entry_Field));
exception
when Constraint_Error =>
The_Value := 0;
end Update_Value;
-- make sure that only numbers are entered
procedure On_Insert_Text
(Object : access Gtk.GEntry.Gtk_Entry_Record'Class;
Params : Glib.Values.GValues)
is
Length : constant Glib.Gint :=
Glib.Values.Get_Int (Glib.Values.Nth (Params, 2));
Text : constant String :=
Glib.Values.Get_String (Glib.Values.Nth (Params, 1), Length);
begin
declare
Number : Natural;
begin
Number := Natural'Value (Text);
exception
when Constraint_Error =>
-- refuse values that are not parsable
Gtk.Handlers.Emit_Stop_By_Name
(Object => Object,
Name => Gtk.Editable.Signal_Insert_Text);
end;
end On_Insert_Text;
-- Callback for click event
procedure On_Increment_Click
(Object : access Gtk.Button.Gtk_Button_Record'Class)
is
begin
Update_Value;
The_Value := The_Value + 1;
Update_Entry;
end On_Increment_Click;
-- Callback for click event
procedure On_Random_Click
(Object : access Gtk.Button.Gtk_Button_Record'Class)
is
use type Gtkada.Dialogs.Message_Dialog_Buttons;
begin
if Gtkada.Dialogs.Message_Dialog
(Msg => "Really reset to random value?",
Dialog_Type => Gtkada.Dialogs.Confirmation,
Buttons => Gtkada.Dialogs.Button_Yes or
Gtkada.Dialogs.Button_No,
Default_Button => Gtkada.Dialogs.Button_Yes) =
Gtkada.Dialogs.Button_Yes
then
The_Value := Natural_Random.Random (RNG);
Update_Entry;
end if;
end On_Random_Click;
-- Callback for delete event
function On_Main_Window_Delete
(Object : access Gtk.Window.Gtk_Window_Record'Class)
return Boolean
is
begin
Gtk.Main.Main_Quit;
return True;
end On_Main_Window_Delete;
begin
-- initialize random number generator
Natural_Random.Reset (RNG);
Gtk.Main.Init;
Gtk.GEntry.Gtk_New (Widget => Entry_Field);
Update_Entry;
Entry_Callbacks.Connect
(Widget => Entry_Field,
Name => Gtk.Editable.Signal_Insert_Text,
Cb => On_Insert_Text'Access);
Gtk.Button.Gtk_New (Button => Increment_Button, Label => "Increment");
Gtk.Button.Gtk_New (Button => Random_Button, Label => "Random");
Button_Callbacks.Connect
(Widget => Increment_Button,
Name => Gtk.Button.Signal_Clicked,
Marsh => Button_Callbacks.To_Marshaller (On_Increment_Click'Access));
Button_Callbacks.Connect
(Widget => Random_Button,
Name => Gtk.Button.Signal_Clicked,
Marsh => Button_Callbacks.To_Marshaller (On_Random_Click'Access));
Gtk.Box.Gtk_New_Vbox (Box => Content);
Gtk.Box.Add (Container => Content, Widget => Entry_Field);
Gtk.Box.Add (Container => Content, Widget => Increment_Button);
Gtk.Box.Add (Container => Content, Widget => Random_Button);
Gtk.Window.Gtk_New (Window => Main_Window);
Gtk.Window.Add (Container => Main_Window, Widget => Content);
Window_Callbacks.Connect
(Widget => Main_Window,
Name => Gtk.Widget.Signal_Delete_Event,
Cb => On_Main_Window_Delete'Access);
Gtk.Window.Show_All (Widget => Main_Window);
Gtk.Main.Main;
end Interaction;
|
-- { dg-do compile }
package access3 is
type TF is access function return access procedure (P1 : Integer);
type TAF is access protected function return access procedure (P1 : Integer);
type TAF2 is access
function return access protected procedure (P1 : Integer);
type TAF3 is access
protected function return access protected procedure (P1 : Integer);
type TAF_Inf is
access protected function return
access function return
access function return
access function return
access function return
access function return
access function return
access function return
access function return
Integer;
end access3;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Ada Modeling Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2010-2017, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
-- This file is generated, don't edit it.
------------------------------------------------------------------------------
with Matreshka.Internals.Strings;
package AMF.Internals.Tables.Standard_Profile_L3_String_Data_00 is
-- "extension_Metamodel"
MS_0000 : aliased Matreshka.Internals.Strings.Shared_String
:= (Capacity => 23,
Unused => 19,
Length => 19,
Value =>
(16#0065#, 16#0078#, 16#0074#, 16#0065#,
16#006E#, 16#0073#, 16#0069#, 16#006F#,
16#006E#, 16#005F#, 16#004D#, 16#0065#,
16#0074#, 16#0061#, 16#006D#, 16#006F#,
16#0064#, 16#0065#, 16#006C#,
others => 16#0000#),
others => <>);
-- "Model_SystemModel"
MS_0001 : aliased Matreshka.Internals.Strings.Shared_String
:= (Capacity => 23,
Unused => 17,
Length => 17,
Value =>
(16#004D#, 16#006F#, 16#0064#, 16#0065#,
16#006C#, 16#005F#, 16#0053#, 16#0079#,
16#0073#, 16#0074#, 16#0065#, 16#006D#,
16#004D#, 16#006F#, 16#0064#, 16#0065#,
16#006C#,
others => 16#0000#),
others => <>);
-- "extension_SystemModel"
MS_0002 : aliased Matreshka.Internals.Strings.Shared_String
:= (Capacity => 23,
Unused => 21,
Length => 21,
Value =>
(16#0065#, 16#0078#, 16#0074#, 16#0065#,
16#006E#, 16#0073#, 16#0069#, 16#006F#,
16#006E#, 16#005F#, 16#0053#, 16#0079#,
16#0073#, 16#0074#, 16#0065#, 16#006D#,
16#004D#, 16#006F#, 16#0064#, 16#0065#,
16#006C#,
others => 16#0000#),
others => <>);
-- "BuildComponent"
MS_0003 : aliased Matreshka.Internals.Strings.Shared_String
:= (Capacity => 15,
Unused => 14,
Length => 14,
Value =>
(16#0042#, 16#0075#, 16#0069#, 16#006C#,
16#0064#, 16#0043#, 16#006F#, 16#006D#,
16#0070#, 16#006F#, 16#006E#, 16#0065#,
16#006E#, 16#0074#,
others => 16#0000#),
others => <>);
-- "http://www.omg.org/spec/UML/20100901/StandardProfileL3"
MS_0004 : aliased Matreshka.Internals.Strings.Shared_String
:= (Capacity => 63,
Unused => 54,
Length => 54,
Value =>
(16#0068#, 16#0074#, 16#0074#, 16#0070#,
16#003A#, 16#002F#, 16#002F#, 16#0077#,
16#0077#, 16#0077#, 16#002E#, 16#006F#,
16#006D#, 16#0067#, 16#002E#, 16#006F#,
16#0072#, 16#0067#, 16#002F#, 16#0073#,
16#0070#, 16#0065#, 16#0063#, 16#002F#,
16#0055#, 16#004D#, 16#004C#, 16#002F#,
16#0032#, 16#0030#, 16#0031#, 16#0030#,
16#0030#, 16#0039#, 16#0030#, 16#0031#,
16#002F#, 16#0053#, 16#0074#, 16#0061#,
16#006E#, 16#0064#, 16#0061#, 16#0072#,
16#0064#, 16#0050#, 16#0072#, 16#006F#,
16#0066#, 16#0069#, 16#006C#, 16#0065#,
16#004C#, 16#0033#,
others => 16#0000#),
others => <>);
-- "base_Model"
MS_0005 : aliased Matreshka.Internals.Strings.Shared_String
:= (Capacity => 15,
Unused => 10,
Length => 10,
Value =>
(16#0062#, 16#0061#, 16#0073#, 16#0065#,
16#005F#, 16#004D#, 16#006F#, 16#0064#,
16#0065#, 16#006C#,
others => 16#0000#),
others => <>);
-- "base_Component"
MS_0006 : aliased Matreshka.Internals.Strings.Shared_String
:= (Capacity => 15,
Unused => 14,
Length => 14,
Value =>
(16#0062#, 16#0061#, 16#0073#, 16#0065#,
16#005F#, 16#0043#, 16#006F#, 16#006D#,
16#0070#, 16#006F#, 16#006E#, 16#0065#,
16#006E#, 16#0074#,
others => 16#0000#),
others => <>);
-- "SystemModel"
MS_0007 : aliased Matreshka.Internals.Strings.Shared_String
:= (Capacity => 15,
Unused => 11,
Length => 11,
Value =>
(16#0053#, 16#0079#, 16#0073#, 16#0074#,
16#0065#, 16#006D#, 16#004D#, 16#006F#,
16#0064#, 16#0065#, 16#006C#,
others => 16#0000#),
others => <>);
-- "StandardProfileL3"
MS_0008 : aliased Matreshka.Internals.Strings.Shared_String
:= (Capacity => 23,
Unused => 17,
Length => 17,
Value =>
(16#0053#, 16#0074#, 16#0061#, 16#006E#,
16#0064#, 16#0061#, 16#0072#, 16#0064#,
16#0050#, 16#0072#, 16#006F#, 16#0066#,
16#0069#, 16#006C#, 16#0065#, 16#004C#,
16#0033#,
others => 16#0000#),
others => <>);
-- "Model_Metamodel"
MS_0009 : aliased Matreshka.Internals.Strings.Shared_String
:= (Capacity => 23,
Unused => 15,
Length => 15,
Value =>
(16#004D#, 16#006F#, 16#0064#, 16#0065#,
16#006C#, 16#005F#, 16#004D#, 16#0065#,
16#0074#, 16#0061#, 16#006D#, 16#006F#,
16#0064#, 16#0065#, 16#006C#,
others => 16#0000#),
others => <>);
-- "org.omg.xmi.nsPrefix"
MS_000A : aliased Matreshka.Internals.Strings.Shared_String
:= (Capacity => 23,
Unused => 20,
Length => 20,
Value =>
(16#006F#, 16#0072#, 16#0067#, 16#002E#,
16#006F#, 16#006D#, 16#0067#, 16#002E#,
16#0078#, 16#006D#, 16#0069#, 16#002E#,
16#006E#, 16#0073#, 16#0050#, 16#0072#,
16#0065#, 16#0066#, 16#0069#, 16#0078#,
others => 16#0000#),
others => <>);
-- "Component_BuildComponent"
MS_000B : aliased Matreshka.Internals.Strings.Shared_String
:= (Capacity => 31,
Unused => 24,
Length => 24,
Value =>
(16#0043#, 16#006F#, 16#006D#, 16#0070#,
16#006F#, 16#006E#, 16#0065#, 16#006E#,
16#0074#, 16#005F#, 16#0042#, 16#0075#,
16#0069#, 16#006C#, 16#0064#, 16#0043#,
16#006F#, 16#006D#, 16#0070#, 16#006F#,
16#006E#, 16#0065#, 16#006E#, 16#0074#,
others => 16#0000#),
others => <>);
-- "extension_BuildComponent"
MS_000C : aliased Matreshka.Internals.Strings.Shared_String
:= (Capacity => 31,
Unused => 24,
Length => 24,
Value =>
(16#0065#, 16#0078#, 16#0074#, 16#0065#,
16#006E#, 16#0073#, 16#0069#, 16#006F#,
16#006E#, 16#005F#, 16#0042#, 16#0075#,
16#0069#, 16#006C#, 16#0064#, 16#0043#,
16#006F#, 16#006D#, 16#0070#, 16#006F#,
16#006E#, 16#0065#, 16#006E#, 16#0074#,
others => 16#0000#),
others => <>);
-- "Metamodel"
MS_000D : aliased Matreshka.Internals.Strings.Shared_String
:= (Capacity => 15,
Unused => 9,
Length => 9,
Value =>
(16#004D#, 16#0065#, 16#0074#, 16#0061#,
16#006D#, 16#006F#, 16#0064#, 16#0065#,
16#006C#,
others => 16#0000#),
others => <>);
end AMF.Internals.Tables.Standard_Profile_L3_String_Data_00;
|
with ObjectPack, AbstractStrategyCombinatorPackage, IntrospectorPackage, StrategyPackage;
use ObjectPack, AbstractStrategyCombinatorPackage, IntrospectorPackage, StrategyPackage;
package MuVarStrategy is
type MuVar is new AbstractStrategyCombinator and Object with
record
instance : StrategyPtr := null;
name : access String := null;
end record;
type MuVarPtr is access all MuVar;
----------------------------------------------------------------------------
-- Object implementation
----------------------------------------------------------------------------
function toString(c: MuVar) return String;
----------------------------------------------------------------------------
-- Strategy implementation
----------------------------------------------------------------------------
function visitLight(str:access MuVar; any: ObjectPtr; i: access Introspector'Class) return ObjectPtr;
function visit(str: access MuVar; i: access Introspector'Class) return Integer;
----------------------------------------------------------------------------
function newMuVar(s : access String) return StrategyPtr;
function newMuVar(s : String) return StrategyPtr;
function equals(m : access MuVar; o : ObjectPtr) return Boolean;
function hashCode(m : access MuVar) return Integer;
function getInstance(m: access MuVar) return StrategyPtr;
procedure setInstance(m: access MuVar; s: StrategyPtr);
procedure setName(m: access MuVar; n: access String);
function isExpanded(m: access Muvar) return Boolean;
function getName(m: access Muvar) return access String;
end MuVarStrategy;
|
---------------------------------------------------------------------------------
-- Copyright 2004-2005 © Luke A. Guest
--
-- This code is to be used for tutorial purposes only.
-- You may not redistribute this code in any form without my express permission.
---------------------------------------------------------------------------------
package Vector3 is
type Object is
record
X, Y, Z : Float;
end record;
-- The additive identity.
ZERO : constant Object := Object'(0.0, 0.0, 0.0);
function Length(Self : in Object) return Float;
procedure Normalise(Self : in out Object);
function Dot(Self, Operand : in Object) return Float;
function Cross(Self, Operand : in Object) return Object;
function "+"(Left, Right : in Object) return Object;
function "-"(Left, Right : in Object) return Object;
function "-"(Left : in Object) return Object;
function "*"(Left : in Object; Right : in Float) return Object;
function "/"(Left : in Object; Right : in Float) return Object;
function Output(Self : in Object) return String;
end Vector3;
|
-- Ada_GUI implementation based on Gnoga. Adapted 2021
-- --
-- GNOGA - The GNU Omnificent GUI for Ada --
-- --
-- G N O G A . S E R V E R . M O D E L . Q U E R I E S --
-- --
-- S p e c --
-- --
-- --
-- Copyright (C) 2014 David Botton --
-- --
-- This library is free software; you can redistribute it and/or modify --
-- it under terms of the GNU General Public License as published by the --
-- Free Software Foundation; either version 3, or (at your option) any --
-- later version. This library is distributed in the hope that it will be --
-- useful, but WITHOUT ANY WARRANTY; without even the implied warranty of --
-- 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/>. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
-- --
-- For more information please go to http://www.gnoga.com --
------------------------------------------------------------------------------
with Ada.Containers.Indefinite_Vectors;
package Ada_GUI.Gnoga.Server.Model.Queries is
package Active_Record_Array is
new Ada.Containers.Indefinite_Vectors (Positive, Active_Record'Class);
function Find_All
(Name : access String;
Connection : access Gnoga.Server.Database.Connection'Class;
Like : in String := "";
Order_By : in String := "")
return Active_Record_Array.Vector;
-- Return all matching records 'Like'
-- This version of Find_All returns Active_Records Types
-- Like is a valid SQL with clause
function Find_All (Template : Active_Record'Class;
Like : String := "";
Order_By : String := "")
return Active_Record_Array.Vector;
-- Return all matching records 'Like'
-- This version of Find_All duplicates the type of Template
-- Like is a valid SQL with clause
function Find_Items (Parent : in Active_Record'Class;
Child_Table : access String;
Like : in String := "";
Order_By : in String := "")
return Active_Record_Array.Vector;
-- Return all matching records in Child Table where:
-- Child_Table.PARENT_TABLE_NAME(with out s)_id = Child_Table.id
function Find_Items (Parent : Active_Record'Class;
Child_Template : Active_Record'Class;
Like : String := "";
Order_By : String := "")
return Active_Record_Array.Vector;
-- Return all matching records in Child Table where:
-- Child_Table.PARENT_TABLE_NAME(with out s)_id = Child_Table.id
end Ada_GUI.Gnoga.Server.Model.Queries;
|
with AVR.TIMERS;
-- =============================================================================
-- Package AVR.PWM_SIMPLEST
--
-- Implements Pulsed Wavelength Modulation for MCU in a simple way.
-- =============================================================================
package AVR.PWM_SIMPLEST is
-- ======================
-- General Public Section
-- ======================
-- Initialize the general parameters of the PWM on the Timer
procedure Initialize
(Timer : TIMERS.Timer_Type);
-- Set the value of the counter which defines the Duty_Cycle
procedure Set_Counter
(Timer : in TIMERS.Timer_Type;
Channel : in TIMERS.Channel_Type;
Counter : in Unsigned_8);
end AVR.PWM_SIMPLEST;
|
-- { dg-do run }
with Init11; use Init11;
with Text_IO; use Text_IO;
with Dump;
procedure Q11 is
A1 : R1 := My_R1;
B1 : R1 := My_R1;
A2 : R2 := My_R2;
B2 : R2 := My_R2;
begin
Put ("A1 :");
Dump (A1'Address, R1'Max_Size_In_Storage_Elements);
New_Line;
-- { dg-output "A1 : 78 56 34 12 12 00 ab 00 34 00 cd 00 56 00 ef 00.*\n" }
Put ("B1 :");
Dump (B1'Address, R1'Max_Size_In_Storage_Elements);
New_Line;
-- { dg-output "B1 : 78 56 34 12 12 00 ab 00 34 00 cd 00 56 00 ef 00.*\n" }
Put ("A2 :");
Dump (A2'Address, R2'Max_Size_In_Storage_Elements);
New_Line;
-- { dg-output "A2 : 12 34 56 78 00 ab 00 12 00 cd 00 34 00 ef 00 56.*\n" }
Put ("B2 :");
Dump (B2'Address, R2'Max_Size_In_Storage_Elements);
New_Line;
-- { dg-output "B2 : 12 34 56 78 00 ab 00 12 00 cd 00 34 00 ef 00 56.*\n"}
if A1.I /= B1.I or A1.A(1) /= B1.A(1) then
raise Program_Error;
end if;
if A2.I /= B2.I or A2.A(1) /= B2.A(1) then
raise Program_Error;
end if;
end;
|
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Ackermann is
function Ackermann (M, N : Natural) return Natural is
begin
if M = 0 then
return N + 1;
elsif N = 0 then
return Ackermann (M - 1, 1);
else
return Ackermann (M - 1, Ackermann (M, N - 1));
end if;
end Ackermann;
begin
for M in 0..3 loop
for N in 0..6 loop
Put (Natural'Image (Ackermann (M, N)));
end loop;
New_Line;
end loop;
end Test_Ackermann;
|
package Termbox_Package is
type Input_Mode is
(TB_INPUT_CURRENT, -- termbox.h:215
TB_INPUT_ESC, -- termbox.h:216
TB_INPUT_ALT, -- termbox.h:217
TB_INPUT_MOUSE -- termbox.h:218
);
type Output_Mode is
(TB_OUTPUT_CURRENT, -- termbox.h:239
TB_OUTPUT_NORMAL, -- termbox.h:240
TB_OUTPUT_256, -- termbox.h:241
TB_OUTPUT_216, -- termbox.h:242
TB_OUTPUT_GRAYSCALE, -- termbox.h:243
TB_OUTPUT_TRUECOLOR -- termbox.h:244
);
TB_REVERSE : constant := 16#04000000#;
function TB_Init return Integer; -- initialization
procedure TB_Shutdown; -- shutdown
pragma Import (C, TB_Shutdown, "tb_shutdown");
procedure TB_Width; -- width of the terminal screen
pragma Import (C, TB_Width, "tb_width");
procedure TB_Height; -- height of the terminal screen
pragma Import (C, TB_Height, "tb_height");
procedure TB_Clear; -- clear buffer
pragma Import (C, TB_Clear, "tb_clear");
procedure TB_Present; -- sync internal buffer with terminal
pragma Import (C, TB_Present, "tb_present");
procedure TB_Put_Cell;
pragma Import (C, TB_Put_Cell, "tb_put_cell");
procedure TB_Change_Cell;
pragma Import (C, TB_Change_Cell, "tb_change_cell");
procedure TB_Blit; -- drawing functions
pragma Import (C, TB_Blit, "tb_blit");
function TB_Select_Output_Mode (Mode : Output_Mode)
return Output_Mode; -- termbox.h:237
procedure TB_Peek_Event; -- peek a keyboard event
pragma Import (C, TB_Peek_Event, "tb_peek_event");
procedure TB_Poll_Event; -- wait for a keyboard event
pragma Import (C, TB_Poll_Event, "tb_poll_event");
end Termbox_Package;
|
-- { dg-do compile }
-- { dg-options "-gnatws -O3" }
-- { dg-options "-gnatws -O3 -msse" { target i?86-*-* x86_64-*-* } }
with System.Soft_Links;
package body Loop_Optimization9 is
package SSL renames System.Soft_Links;
First_Temp_File_Name : constant String := "GNAT-TEMP-000000.TMP";
Current_Temp_File_Name : String := First_Temp_File_Name;
Temp_File_Name_Last_Digit : constant Positive :=
First_Temp_File_Name'Last - 4;
function Argument_String_To_List
(Arg_String : String) return Argument_List_Access
is
Max_Args : constant Integer := Arg_String'Length;
New_Argv : Argument_List (1 .. Max_Args);
New_Argc : Natural := 0;
Idx : Integer;
begin
Idx := Arg_String'First;
loop
exit when Idx > Arg_String'Last;
declare
Quoted : Boolean := False;
Backqd : Boolean := False;
Old_Idx : Integer;
begin
Old_Idx := Idx;
loop
-- An unquoted space is the end of an argument
if not (Backqd or Quoted)
and then Arg_String (Idx) = ' '
then
exit;
-- Start of a quoted string
elsif not (Backqd or Quoted)
and then Arg_String (Idx) = '"'
then
Quoted := True;
-- End of a quoted string and end of an argument
elsif (Quoted and not Backqd)
and then Arg_String (Idx) = '"'
then
Idx := Idx + 1;
exit;
-- Following character is backquoted
elsif Arg_String (Idx) = '\' then
Backqd := True;
-- Turn off backquoting after advancing one character
elsif Backqd then
Backqd := False;
end if;
Idx := Idx + 1;
exit when Idx > Arg_String'Last;
end loop;
-- Found an argument
New_Argc := New_Argc + 1;
New_Argv (New_Argc) :=
new String'(Arg_String (Old_Idx .. Idx - 1));
end;
end loop;
return new Argument_List'(New_Argv (1 .. New_Argc));
end Argument_String_To_List;
procedure Create_Temp_File_Internal
(FD : out File_Descriptor;
Name : out String_Access)
is
Pos : Positive;
begin
File_Loop : loop
Locked : begin
Pos := Temp_File_Name_Last_Digit;
Digit_Loop :
loop
case Current_Temp_File_Name (Pos) is
when '0' .. '8' =>
Current_Temp_File_Name (Pos) :=
Character'Succ (Current_Temp_File_Name (Pos));
exit Digit_Loop;
when '9' =>
Current_Temp_File_Name (Pos) := '0';
Pos := Pos - 1;
when others =>
SSL.Unlock_Task.all;
FD := 0;
Name := null;
exit File_Loop;
end case;
end loop Digit_Loop;
end Locked;
end loop File_Loop;
end Create_Temp_File_Internal;
end Loop_Optimization9;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- Copyright (C) 2013-2020, AdaCore --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
pragma Restrictions (No_Elaboration_Code);
-- This subprogram is called before elaboration
with Board_Config; use Board_Config;
with Interfaces.SAM; use Interfaces.SAM;
with Interfaces.SAM.EFC; use Interfaces.SAM.EFC;
with Interfaces.SAM.PMC; use Interfaces.SAM.PMC;
with Interfaces.SAM.SYSC; use Interfaces.SAM.SYSC;
procedure Setup_Pll is
procedure Enable_Oscillator (Osc : Oscillators);
-- Enables a specific oscillator
-----------------------
-- Enable_Oscillator --
-----------------------
procedure Enable_Oscillator (Osc : Oscillators)
is
MR : Interfaces.SAM.SYSC.SUPC_MR_Register;
CR : Interfaces.SAM.SYSC.SUPC_CR_Register;
CKGR_MOR : Interfaces.SAM.PMC.CKGR_MOR_Register;
begin
case Osc is
when Internal_32k_RC =>
-- Nothing to do here: Enabled by default
null;
when External_32k_XTAL | External_32k_BYPASS =>
-- Set the SCK to the external 32k crystal
if Osc = External_32k_BYPASS then
MR := SUPC_Periph.MR;
MR.KEY := Passwd;
MR.OSCBYPASS := Bypass;
SUPC_Periph.MR := MR;
end if;
CR := SUPC_Periph.CR;
CR.KEY := Passwd;
CR.XTALSEL := Crystal_Sel;
SUPC_Periph.CR := CR;
-- wait for SCK ready
while SUPC_Periph.SR.OSCSEL /= Cryst
and then not PMC_Periph.PMC_SR.OSCSELS
loop
null;
end loop;
when Internal_8M_RC | Internal_16M_RC | Internal_24M_RC =>
-- This sets the MCK source to the internal oscillator.
-- Enable the internal oscillator
CKGR_MOR := PMC_Periph.CKGR_MOR;
CKGR_MOR.KEY := Passwd;
CKGR_MOR.MOSCRCEN := True;
PMC_Periph.CKGR_MOR := CKGR_MOR;
while not PMC_Periph.PMC_SR.MOSCRCS loop
null;
end loop;
-- Set the oscillator frequency
CKGR_MOR := PMC_Periph.CKGR_MOR;
CKGR_MOR.KEY := Passwd;
if Osc = Internal_8M_RC then
CKGR_MOR.MOSCRCF := CKGR_MOR_MOSCRCF_Field_8_Mhz;
elsif Osc = Internal_16M_RC then
CKGR_MOR.MOSCRCF := CKGR_MOR_MOSCRCF_Field_16_Mhz;
else
CKGR_MOR.MOSCRCF := CKGR_MOR_MOSCRCF_Field_24_Mhz;
end if;
PMC_Periph.CKGR_MOR := CKGR_MOR;
while not PMC_Periph.PMC_SR.MOSCRCS loop
null;
end loop;
-- Use the Fast RC as main clock input
CKGR_MOR := PMC_Periph.CKGR_MOR;
CKGR_MOR.KEY := Passwd;
CKGR_MOR.MOSCSEL := False; -- True for the external crystal
PMC_Periph.CKGR_MOR := CKGR_MOR;
-- Wait for the main clock status flag
while not PMC_Periph.PMC_SR.MOSCSELS loop
null;
end loop;
when External_XTAL | External_BYPASS =>
-- This sets the MCK source to the external oscillator.
-- Enable the main xtal oscillator
CKGR_MOR := PMC_Periph.CKGR_MOR;
CKGR_MOR.KEY := Passwd;
if Osc = External_BYPASS then
CKGR_MOR.MOSCXTEN := False;
CKGR_MOR.MOSCXTBY := True;
CKGR_MOR.MOSCSEL := True;
else
CKGR_MOR.MOSCXTEN := True;
CKGR_MOR.MOSCXTBY := False;
CKGR_MOR.MOSCXTST := External_Oscillator_Startup_Time;
end if;
PMC_Periph.CKGR_MOR := CKGR_MOR;
while not PMC_Periph.PMC_SR.MOSCXTS loop
null;
end loop;
-- Use the XTAL as main clock input
CKGR_MOR := PMC_Periph.CKGR_MOR;
CKGR_MOR.KEY := Passwd;
CKGR_MOR.MOSCSEL := True;
PMC_Periph.CKGR_MOR := CKGR_MOR;
-- Wait for the MOSCSELS flag
while not PMC_Periph.PMC_SR.MOSCSELS loop
null;
end loop;
end case;
end Enable_Oscillator;
Osc : Oscillators;
begin
-- 5 wait states for the flash
EFC_Periph.FMR.FWS := 5;
-- 18.17 Programming Sequence
-- 1-5: Configure the oscillator and select it as either Slow_Clk source
-- or Main_Clk source
pragma Warnings (Off, "*condition is always*");
if Master_Source = PLLA then
pragma Assert (PLLA_Enable);
Osc := PLLA_Source;
elsif Master_Source = PLLB then
pragma Assert (PLLB_Enable);
Osc := PLLB_Source;
else
Osc := Master_Source;
end if;
pragma Warnings (On, "*condition is always*");
-- Enable Osc and set it as source for the slow or main clock
case Osc is
when Internal_32k_RC | External_32k_XTAL | External_32k_BYPASS =>
-- Enable the oscillator
Enable_Oscillator (Osc);
when Internal_8M_RC | Internal_16M_RC | Internal_24M_RC |
External_XTAL | External_BYPASS =>
-- Enable the oscillator
Enable_Oscillator (Osc);
if Osc in External_XTAL .. External_BYPASS then
-- 5. Check the Main clock frequency
loop
exit when PMC_Periph.CKGR_MCFR.MAINFRDY;
end loop;
-- MAINF contains the number of Main ticks between two slow
-- clock ticks. If 0, this means that the external main clock is
-- not available.
if PMC_Periph.CKGR_MCFR.MAINF = 0 then
Osc := Internal_24M_RC;
Enable_Oscillator (Osc);
end if;
end if;
end case;
-- 6. Setting PLL and Divider:
-- All parameters needed to configure PLLA and the divider are
-- located in CKGR_PLLxR.
-- The DIV field is used to control the divider itself. It must be
-- set to 1 when PLL is used. By default, DIV parameter is set to
-- 0 which means that the divider is turned off.
-- The MUL field is the PLL multiplier factor. This parameter can
-- be programmed between 0 and 80. If MUL is set to 0, PLL will be
-- turned off, otherwise the PLL output frequency is PLL input
-- frequency multiplied by (MUL + 1).
-- The PLLCOUNT field specifies the number of slow clock cycles
-- before the LOCK bit is set in PMC_SR, after CKGR_PLLA(B)R has
-- been written.
-- First disable: MULA set to 0, DIVA set to 0
PMC_Periph.CKGR_PLLAR.PLLAEN := 0;
PMC_Periph.CKGR_PLLBR.PLLBEN := 0;
if PLLA_Enable then
PMC_Periph.CKGR_PLLAR :=
(ZERO => False,
MULA => PLLA_Mul,
PLLAEN => 1,
others => <>);
while not PMC_Periph.PMC_SR.LOCKA loop
null;
end loop;
end if;
if PLLB_Enable then
PMC_Periph.CKGR_PLLBR :=
(ZERO => False,
MULB => PLLB_Mul,
PLLBEN => 1,
others => <>);
while not PMC_Periph.PMC_SR.LOCKB loop
null;
end loop;
end if;
-- 4. Selection of Master Clock and Processor Clock
-- The Master Clock and the Processor Clock are configurable via
-- the Master Clock Register (PMC_MCKR).
-- The CSS field is used to select the Master Clock divider
-- source. By default, the selected clock source is main clock.
-- The PRES field is used to control the Master Clock
-- prescaler. The user can choose between different values (1, 2,
-- 3, 4, 8, 16, 32, 64). Master Clock output is prescaler input
-- divided by PRES parameter. By default, PRES parameter is set to
-- 1 which means that master clock is equal to main clock.
-- Once PMC_MCKR has been written, the user must wait for the
-- MCKRDY bit to be set in PMC_SR. This can be done either by
-- polling the status register or by waiting for the interrupt
-- line to be raised if the associated interrupt to MCKRDY has
-- been enabled in the PMC_IER register.
-- The PMC_MCKR must not be programmed in a single write
-- operation. The preferred programming sequence for PMC_MCKR is
-- as follows:
-- * If a new value for CSS field corresponds to PLL Clock,
-- * Program the PRES field in PMC_MCKR.
-- * Wait for the MCKRDY bit to be set in PMC_SR.
-- * Program the CSS field in PMC_MCKR.
-- * Wait for the MCKRDY bit to be set in PMC_SR.
-- * If a new value for CSS field corresponds to Main Clock
-- or Slow Clock,
-- * Program the CSS field in PMC_MCKR.
-- * Wait for the MCKRDY bit to be set in the PMC_SR.
-- * Program the PRES field in PMC_MCKR.
-- * Wait for the MCKRDY bit to be set in PMC_SR.
PMC_Periph.PMC_MCKR.PRES := Master_Prescaler;
while not PMC_Periph.PMC_SR.MCKRDY loop
null;
end loop;
case Master_Source is
when Internal_32k_RC | External_32k_XTAL | External_32k_BYPASS =>
-- Switch the system clock to the slow clock
PMC_Periph.PMC_MCKR.CSS := Slow_Clk;
when Internal_8M_RC | Internal_16M_RC | Internal_24M_RC |
External_XTAL | External_BYPASS =>
-- Switch the system clock to the main clock
PMC_Periph.PMC_MCKR.CSS := Main_Clk;
when PLLA =>
PMC_Periph.PMC_MCKR.CSS := Plla_Clk;
when PLLB =>
PMC_Periph.PMC_MCKR.CSS := Pllb_Clk;
end case;
while not PMC_Periph.PMC_SR.MCKRDY loop
null;
end loop;
-- If at some stage one of the following parameters, CSS or PRES
-- is modified, the MCKRDY bit will go low to indicate that the
-- Master Clock and the Processor Clock are not ready yet. The
-- user must wait for MCKRDY bit to be set again before using the
-- Master and Processor Clocks.
-- Note: IF PLLx clock was selected as the Master Clock and the
-- user decides to modify it by writing in CKGR_PLLR, the MCKRDY
-- flag will go low while PLL is unlocked. Once PLL is locked
-- again, LOCK goes high and MCKRDY is set.
-- While PLL is unlocked, the Master Clock selection is
-- automatically changed to Slow Clock. For further information,
-- see Section 28.2.14.2 "Clock Switching Waveforms" on page 467.
-- Code Example:
-- write_register(PMC_MCKR,0x00000001)
-- wait (MCKRDY=1)
-- write_register(PMC_MCKR,0x00000011)
-- wait (MCKRDY=1)
-- The Master Clock is main clock divided by 2.
-- The Processor Clock is the Master Clock.
-- 5. Selection of Programmable Clocks
-- Programmable clocks are controlled via registers, PMC_SCER,
-- PMC_SCDR and PMC_SCSR.
-- Programmable clocks can be enabled and/or disabled via PMC_SCER
-- and PMC_SCDR. 3 Programmable clocks can be enabled or
-- disabled. The PMC_SCSR provides a clear indication as to which
-- Programmable clock is enabled. By default all Programmable
-- clocks are disabled.
-- Programmable Clock Registers (PMC_PCKx) are used to configure
-- Programmable clocks.
-- The CSS field is used to select the Programmable clock divider
-- source. Four clock options are available: main clock, slow
-- clock, PLLACK, PLLBCK. By default, the clock source selected is
-- slow clock.
-- The PRES field is used to control the Programmable clock
-- prescaler. It is possible to choose between different values
-- (1, 2, 4, 8, 16, 32, 64). Programmable clock output is
-- prescaler input divided by PRES parameter. By default, the PRES
-- parameter is set to 0 which means that master clock is equal to
-- slow clock.
-- Once PMC_PCKx has been programmed, The corresponding
-- Programmable clock must be enabled and the user is constrained
-- to wait for the PCKRDYx bit to be set in PMC_SR. This can be
-- done either by polling the status register or by waiting the
-- interrupt line to be raised, if the associated interrupt to
-- PCKRDYx has been enabled in the PMC_IER register. All parameters in
-- PMC_PCKx can be programmed in a single write operation.
-- If the CSS and PRES parameters are to be modified, the
-- corresponding Programmable clock must be disabled first. The
-- parameters can then be modified. Once this has been done, the
-- user must re-enable the Programmable clock and wait for the
-- PCKRDYx bit to be set.
null;
-- 6. Enabling Peripheral Clocks
-- Once all of the previous steps have been completed, the
-- peripheral clocks can be enabled and/or disabled via registers
-- PMC_PCER0, PMC_PCER, PMC_PCDR0 and PMC_PCDR.
null;
-- Disable watchdog. The register can be written once, so this file has
-- to be modified to enable watchdog.
WDT_Periph.MR.WDDIS := True;
end Setup_Pll;
|
--
-- Copyright (C) 2016-2017 secunet Security Networks AG
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
with HW.GFX.GMA.Config;
with HW.GFX.GMA.Registers;
with HW.GFX.GMA.Config_Helpers;
package body HW.GFX.GMA.Port_Detect
is
PORT_DETECTED : constant := 1 * 2 ** 2;
PORTB_HOTPLUG_INT_EN : constant := 1 * 2 ** 29;
PORTC_HOTPLUG_INT_EN : constant := 1 * 2 ** 28;
PORTD_HOTPLUG_INT_EN : constant := 1 * 2 ** 27;
SDVOB_HOTPLUG_INT_EN : constant := 1 * 2 ** 26;
SDVOC_HOTPLUG_INT_EN : constant := 1 * 2 ** 25;
CRT_HOTPLUG_INT_EN : constant := 1 * 2 ** 9;
CRT_HOTPLUG_ACTIVATION_PERIOD_64 : constant := 1 * 2 ** 8;
type HDMI_Port_Value is array (GMCH_HDMI_Port) of Word32;
type DP_Port_Value is array (GMCH_DP_Port) of Word32;
HDMI_PORT_HOTPLUG_EN : constant HDMI_Port_Value :=
(DIGI_B => SDVOB_HOTPLUG_INT_EN,
DIGI_C => SDVOC_HOTPLUG_INT_EN);
DP_PORT_HOTPLUG_EN : constant DP_Port_Value :=
(DIGI_B => PORTB_HOTPLUG_INT_EN,
DIGI_C => PORTC_HOTPLUG_INT_EN,
DIGI_D => PORTD_HOTPLUG_INT_EN);
type HDMI_Regs is array (GMCH_HDMI_Port) of Registers.Registers_Index;
type DP_Regs is array (GMCH_DP_Port) of Registers.Registers_Index;
GMCH_HDMI : constant HDMI_Regs :=
(DIGI_B => Registers.GMCH_HDMIB,
DIGI_C => Registers.GMCH_HDMIC);
GMCH_DP : constant DP_Regs :=
(DIGI_B => Registers.GMCH_DP_B,
DIGI_C => Registers.GMCH_DP_C,
DIGI_D => Registers.GMCH_DP_D);
HOTPLUG_INT_STATUS : constant array (Active_Port_Type) of word32 :=
(DP1 => 3 * 2 ** 17,
DP2 => 3 * 2 ** 19,
DP3 => 3 * 2 ** 21,
HDMI1 => 1 * 2 ** 2,
HDMI2 => 1 * 2 ** 3,
Analog => 1 * 2 ** 11,
others => 0);
procedure Initialize
is
Detected : Boolean;
hotplug_mask_set : Word32 :=
CRT_HOTPLUG_INT_EN or CRT_HOTPLUG_ACTIVATION_PERIOD_64;
To_HDMI_Port : constant array (GMCH_HDMI_Port) of Port_Type :=
(DIGI_B => HDMI1,
DIGI_C => HDMI2);
To_DP_Port : constant array (GMCH_DP_Port) of Port_Type :=
(DIGI_B => DP1,
DIGI_C => DP2,
DIGI_D => DP3);
begin
for HDMI_Port in GMCH_HDMI_Port loop
Registers.Is_Set_Mask
(Register => GMCH_HDMI (HDMI_Port),
Mask => PORT_DETECTED,
Result => Detected);
Config.Valid_Port (To_HDMI_Port (HDMI_Port)) := Detected;
hotplug_mask_set := hotplug_mask_set or
(if Detected then HDMI_PORT_HOTPLUG_EN (HDMI_Port) else 0);
end loop;
for DP_Port in GMCH_DP_Port loop
Registers.Is_Set_Mask
(Register => GMCH_DP (DP_Port),
Mask => PORT_DETECTED,
Result => Detected);
Config.Valid_Port (To_DP_Port (DP_Port)) := Detected;
hotplug_mask_set := hotplug_mask_set or
(if Detected then DP_PORT_HOTPLUG_EN (DP_Port) else 0);
end loop;
Registers.Write
(Register => Registers.PORT_HOTPLUG_EN,
Value => hotplug_mask_set);
end Initialize;
procedure Hotplug_Detect (Port : in Active_Port_Type; Detected : out Boolean)
is
Ctl32 : Word32;
begin
Registers.Read (Register => Registers.PORT_HOTPLUG_STAT,
Value => Ctl32);
Detected := (Ctl32 and HOTPLUG_INT_STATUS (Port)) /= 0;
if Detected then
registers.Set_Mask
(Register => Registers.PORT_HOTPLUG_STAT,
Mask => HOTPLUG_INT_STATUS (Port));
end if;
end Hotplug_Detect;
procedure Clear_Hotplug_Detect (Port : Active_Port_Type)
is
Ignored_HPD : Boolean;
begin
pragma Warnings (GNATprove, Off, "unused assignment to ""Ignored_HPD""",
Reason => "We want to clear pending events only");
Port_Detect.Hotplug_Detect (Port, Ignored_HPD);
pragma Warnings (GNATprove, On, "unused assignment to ""Ignored_HPD""");
end Clear_Hotplug_Detect;
end HW.GFX.GMA.Port_Detect;
|
procedure If_Statement is
begin
if True then
null;
else
null;
end if;
end If_Statement;
|
------------------------------------------------------------------------------
-- A d a r u n - t i m e s p e c i f i c a t i o n --
-- ASIS implementation for Gela project, a portable Ada compiler --
-- http://gela.ada-ru.org --
-- - - - - - - - - - - - - - - - --
-- Read copyright and license at the end of ada.ads file --
------------------------------------------------------------------------------
-- $Revision: 209 $ $Date: 2013-11-30 21:03:24 +0200 (Сб., 30 нояб. 2013) $
with Ada.IO_Exceptions;
package Ada.Streams.Stream_IO is
type Stream_Access is access all Root_Stream_Type'Class;
type File_Type is limited private;
type File_Mode is (In_File, Out_File, Append_File);
type Count is range 0 .. implementation-defined;
subtype Positive_Count is Count range 1 .. Count'Last;
-- Index into file, in stream elements.
procedure Create (File : in out File_Type;
Mode : in File_Mode := Out_File;
Name : in String := "";
Form : in String := "");
procedure Open (File : in out File_Type;
Mode : in File_Mode;
Name : in String;
Form : in String := "");
procedure Close (File : in out File_Type);
procedure Delete (File : in out File_Type);
procedure Reset (File : in out File_Type; Mode : in File_Mode);
procedure Reset (File : in out File_Type);
function Mode (File : in File_Type) return File_Mode;
function Name (File : in File_Type) return String;
function Form (File : in File_Type) return String;
function Is_Open (File : in File_Type) return Boolean;
function End_Of_File (File : in File_Type) return Boolean;
function Stream (File : in File_Type) return Stream_Access;
-- Return stream access for use with T'Input and T'Output
-- Read array of stream elements from file
procedure Read (File : in File_Type;
Item : out Stream_Element_Array;
Last : out Stream_Element_Offset;
From : in Positive_Count);
procedure Read (File : in File_Type;
Item : out Stream_Element_Array;
Last : out Stream_Element_Offset);
-- Write array of stream elements into file
procedure Write (File : in File_Type;
Item : in Stream_Element_Array;
To : in Positive_Count);
procedure Write (File : in File_Type;
Item : in Stream_Element_Array);
-- Operations on position within file
procedure Set_Index(File : in File_Type; To : in Positive_Count);
function Index(File : in File_Type) return Positive_Count;
function Size (File : in File_Type) return Count;
procedure Set_Mode(File : in out File_Type; Mode : in File_Mode);
procedure Flush(File : in out File_Type);
-- exceptions
Status_Error : exception renames IO_Exceptions.Status_Error;
Mode_Error : exception renames IO_Exceptions.Mode_Error;
Name_Error : exception renames IO_Exceptions.Name_Error;
Use_Error : exception renames IO_Exceptions.Use_Error;
Device_Error : exception renames IO_Exceptions.Device_Error;
End_Error : exception renames IO_Exceptions.End_Error;
Data_Error : exception renames IO_Exceptions.Data_Error;
private
pragma Import (Ada, File_Type);
end Ada.Streams.Stream_IO;
|
-- SPDX-License-Identifier: MIT
--
-- Copyright (c) 2019 onox <denkpadje@gmail.com>
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
with Ada.Command_Line;
with Ada.Directories;
with Ada.Streams;
with Ada.Strings.Fixed;
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with DCF.Streams.Calendar;
with DCF.Zip.Compress;
with DCF.Zip.Create;
use Ada.Command_Line;
use Ada.Text_IO;
procedure ZipDCF is
package Dirs renames Ada.Directories;
package SU renames Ada.Strings.Unbounded;
Quiet : Boolean := False;
Add_Directories : Boolean := True;
Recursive : Boolean := False;
Junk_Directories : Boolean := False;
Comment : SU.Unbounded_String;
Compression_Method : DCF.Zip.Compress.Compression_Method := DCF.Zip.Compress.Deflate_2;
Last_Option : Natural := 0;
procedure Help is
begin
Put_Line ("ZipDCF " & DCF.Zip.Version & " - create document container files");
New_Line;
Put_Line ("Usage: zipdcf [-options] [-z comment] file list");
New_Line;
Put_Line (" -D no directory entries -q quiet mode");
Put_Line (" -r recurse into directories -j junk directory structure");
Put_Line (" -0 store files uncompressed");
Put_Line (" -1 use faster compression -z add archive file comment");
Put_Line (" -9 use better compression");
end Help;
function Maybe_Trash_Dir (Name : String) return String is
Index : constant Natural := Ada.Strings.Fixed.Index (Name, "/", Ada.Strings.Backward);
begin
return (if Junk_Directories then Name (Index + 1 .. Name'Last) else Name);
end Maybe_Trash_Dir;
begin
if Argument_Count = 0 then
Help;
return;
end if;
for I in 1 .. Argument_Count loop
if Argument (I) (1) = '-' then
if Last_Option = I then
null; -- Argument for a previous option
else
Last_Option := I;
if Argument (I)'Length = 1 then
Help;
return;
end if;
for J in 2 .. Argument (I)'Last loop
case Argument (I) (J) is
when 'D' =>
Add_Directories := False;
when 'r' =>
Recursive := True;
when '0' =>
Compression_Method := DCF.Zip.Compress.Store;
when '1' =>
Compression_Method := DCF.Zip.Compress.Deflate_1;
when '9' =>
Compression_Method := DCF.Zip.Compress.Deflate_3;
when 'q' =>
Quiet := True;
when 'j' =>
Junk_Directories := True;
when 'z' =>
if I = Argument_Count then
Help;
return;
end if;
Comment := SU.To_Unbounded_String (Argument (I + 1));
Last_Option := I + 1;
when others =>
Help;
return;
end case;
end loop;
end if;
end if;
end loop;
if Argument_Count = Last_Option then
Help;
return;
end if;
declare
Archive : constant String := Argument (Last_Option + 1);
begin
if Dirs.Exists (Archive) then
Put_Line ("Archive file '" & Archive & "' already exists");
return;
end if;
if not Quiet then
Put_Line ("Archive: " & Archive);
end if;
declare
Archive_Stream : aliased DCF.Streams.File_Zipstream
:= DCF.Streams.Create (Archive);
Info : DCF.Zip.Create.Zip_Create_Info;
procedure Add_File (Path : String) is
Name : constant String := Maybe_Trash_Dir (Path);
begin
if not Dirs.Exists (Path) then
Put_Line ("warning: " & Name & " does not exist");
return;
end if;
declare
use all type Dirs.File_Kind;
File_Is_Directory : constant Boolean := Dirs.Kind (Path) = Directory;
begin
if not File_Is_Directory then
if not Quiet then
Put_Line (" adding: " & Name);
end if;
declare
File_Stream : aliased DCF.Streams.File_Zipstream
:= DCF.Streams.Open (Path);
begin
DCF.Streams.Set_Name (File_Stream, Name);
DCF.Streams.Set_Time (File_Stream,
DCF.Streams.Calendar.Convert (Dirs.Modification_Time (Path)));
DCF.Zip.Create.Add_Stream (Info, File_Stream);
end;
else
if Add_Directories then
if not Quiet then
Put_Line (" adding: " & Name & '/');
end if;
declare
Empty_Array : aliased Ada.Streams.Stream_Element_Array := (1 .. 0 => <>);
Dir_Stream : aliased DCF.Streams.Array_Zipstream (Empty_Array'Access);
begin
DCF.Streams.Set_Name (Dir_Stream, Name & '/');
DCF.Streams.Set_Time (Dir_Stream,
DCF.Streams.Calendar.Convert (Dirs.Modification_Time (Path)));
DCF.Zip.Create.Add_Stream (Info, Dir_Stream);
end;
end if;
if Recursive then
declare
procedure Add_Entry (Next_Entry : Dirs.Directory_Entry_Type) is
Entry_Name : constant String := Dirs.Simple_Name (Next_Entry);
begin
if Entry_Name not in "." | ".." then
Add_File (Dirs.Compose (Path, Entry_Name));
end if;
end Add_Entry;
begin
Dirs.Search (Path, "", Process => Add_Entry'Access);
end;
end if;
end if;
end;
end Add_File;
use type SU.Unbounded_String;
String_Comment : constant String := SU.To_String (Comment);
begin
DCF.Zip.Create.Create
(Info, Archive_Stream'Unchecked_Access, Compress => Compression_Method);
for I in Last_Option + 2 .. Argument_Count loop
Add_File (Argument (I));
end loop;
-- Add optional archive file comment
if Comment /= "" then
if not Quiet then
Put_Line (" comment: " & String_Comment);
end if;
DCF.Zip.Create.Set_Comment (Info, String_Comment);
end if;
DCF.Zip.Create.Finish (Info);
end;
end;
end ZipDCF;
|
with Arduino_Nano_33_Ble_Sense.IOs;
with Ada.Real_Time; use Ada.Real_Time;
procedure Main is
TimeNow : Ada.Real_Time.Time := Ada.Real_Time.Clock;
begin
loop
--6 13 41 16 24
Arduino_Nano_33_Ble_Sense.IOs.DigitalWrite(13, True);
TimeNow := Ada.Real_Time.Clock;
delay until TimeNow + Ada.Real_Time.Milliseconds(50);
Arduino_Nano_33_Ble_Sense.IOs.DigitalWrite(41, True);
TimeNow := Ada.Real_Time.Clock;
delay until TimeNow + Ada.Real_Time.Milliseconds(50);
Arduino_Nano_33_Ble_Sense.IOs.DigitalWrite(6, False);
TimeNow := Ada.Real_Time.Clock;
delay until TimeNow + Ada.Real_Time.Milliseconds(50);
Arduino_Nano_33_Ble_Sense.IOs.DigitalWrite(13, False);
TimeNow := Ada.Real_Time.Clock;
delay until TimeNow + Ada.Real_Time.Milliseconds(50);
Arduino_Nano_33_Ble_Sense.IOs.DigitalWrite(41, False);
TimeNow := Ada.Real_Time.Clock;
delay until TimeNow + Ada.Real_Time.Milliseconds(50);
Arduino_Nano_33_Ble_Sense.IOs.DigitalWrite(6, True);
TimeNow := Ada.Real_Time.Clock;
delay until TimeNow + Ada.Real_Time.Milliseconds(50);
Arduino_Nano_33_Ble_Sense.IOs.DigitalWrite(13, True);
TimeNow := Ada.Real_Time.Clock;
delay until TimeNow + Ada.Real_Time.Milliseconds(50);
Arduino_Nano_33_Ble_Sense.IOs.DigitalWrite(41, True);
TimeNow := Ada.Real_Time.Clock;
delay until TimeNow + Ada.Real_Time.Milliseconds(50);
Arduino_Nano_33_Ble_Sense.IOs.DigitalWrite(16, False);
TimeNow := Ada.Real_Time.Clock;
delay until TimeNow + Ada.Real_Time.Milliseconds(50);
Arduino_Nano_33_Ble_Sense.IOs.DigitalWrite(13, False);
TimeNow := Ada.Real_Time.Clock;
delay until TimeNow + Ada.Real_Time.Milliseconds(50);
Arduino_Nano_33_Ble_Sense.IOs.DigitalWrite(41, False);
TimeNow := Ada.Real_Time.Clock;
delay until TimeNow + Ada.Real_Time.Milliseconds(50);
Arduino_Nano_33_Ble_Sense.IOs.DigitalWrite(16, True);
TimeNow := Ada.Real_Time.Clock;
delay until TimeNow + Ada.Real_Time.Milliseconds(50);
Arduino_Nano_33_Ble_Sense.IOs.DigitalWrite(13, True);
TimeNow := Ada.Real_Time.Clock;
delay until TimeNow + Ada.Real_Time.Milliseconds(50);
Arduino_Nano_33_Ble_Sense.IOs.DigitalWrite(41, True);
TimeNow := Ada.Real_Time.Clock;
delay until TimeNow + Ada.Real_Time.Milliseconds(50);
Arduino_Nano_33_Ble_Sense.IOs.DigitalWrite(24, False);
TimeNow := Ada.Real_Time.Clock;
delay until TimeNow + Ada.Real_Time.Milliseconds(50);
Arduino_Nano_33_Ble_Sense.IOs.DigitalWrite(13, False);
TimeNow := Ada.Real_Time.Clock;
delay until TimeNow + Ada.Real_Time.Milliseconds(50);
Arduino_Nano_33_Ble_Sense.IOs.DigitalWrite(41, False);
TimeNow := Ada.Real_Time.Clock;
delay until TimeNow + Ada.Real_Time.Milliseconds(50);
Arduino_Nano_33_Ble_Sense.IOs.DigitalWrite(24, True);
TimeNow := Ada.Real_Time.Clock;
delay until TimeNow + Ada.Real_Time.Milliseconds(50);
end loop;
end Main;
|
-- Copyright (c) 2019 Maxim Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with Ada.Streams.Stream_IO;
with Ada.Strings.UTF_Encoding.Wide_Wide_Strings;
with Interfaces;
with Program.Scanners;
package body Program.Plain_Source_Buffers is
subtype UTF_8_String is Ada.Strings.UTF_Encoding.UTF_8_String;
----------------
-- Initialize --
----------------
not overriding procedure Initialize
(Self : in out Source_Buffer;
Name : Program.Text)
is
procedure Read_File (Text : in out UTF_8_String);
Input : Ada.Streams.Stream_IO.File_Type;
---------------
-- Read_File --
---------------
procedure Read_File (Text : in out UTF_8_String) is
Data : Ada.Streams.Stream_Element_Array (1 .. Text'Length)
with Import, Convention => Ada, Address => Text'Address;
Last : Ada.Streams.Stream_Element_Offset;
begin
Ada.Streams.Stream_IO.Read (Input, Data, Last);
end Read_File;
File_Size : Natural;
File_Name : constant UTF_8_String :=
Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Encode (Name);
begin
Ada.Streams.Stream_IO.Open
(Input, Ada.Streams.Stream_IO.In_File, File_Name);
File_Size := Natural (Ada.Streams.Stream_IO.Size (Input));
Self.Text := new UTF_8_String (1 .. File_Size);
Read_File (Self.Text.all);
Ada.Streams.Stream_IO.Close (Input);
Self.Rewind;
end Initialize;
----------
-- Read --
----------
overriding procedure Read
(Self : in out Source_Buffer;
Data : out Program.Source_Buffers.Character_Info_Array;
Last : out Natural)
is
use all type Interfaces.Unsigned_32;
procedure Add
(Value : in out Interfaces.Unsigned_32;
Continuation : String);
---------
-- Add --
---------
procedure Add
(Value : in out Interfaces.Unsigned_32;
Continuation : String)
is
Code : Interfaces.Unsigned_32 range 2#10_000000# .. 2#10_111111#;
begin
for Next of Continuation loop
Code := Character'Pos (Next);
Value := Shift_Left (Value, 6) or (Code and 2#00_111111#);
end loop;
end Add;
Index : Positive := Data'First;
Min : constant Natural := Natural'Min
(Data'Length, Self.Text'Last - Self.From + 1);
Char : Interfaces.Unsigned_32;
begin
Last := Data'First + Min - 1;
while Index <= Last and Self.From <= Self.Text'Last loop
Char := Character'Pos (Self.Text (Self.From));
case Char is
when 0 .. 16#7F# =>
Data (Index).Length := 1;
when 2#110_00000# .. 2#110_11111# =>
Char := Char and 2#000_11111#;
Data (Index).Length := 2;
when 2#1110_0000# .. 2#1110_1111# =>
Char := Char and 2#0000_1111#;
Data (Index).Length := 3;
when 2#11110_000# .. 2#11110_111# =>
Char := Char and 2#00000_111#;
Data (Index).Length := 4;
when others =>
raise Constraint_Error with "Wrong UTF-8 data";
end case;
Add
(Char,
Self.Text (Self.From + 1 .. Self.From + Data (Index).Length - 1));
Data (Index).Class :=
Program.Scanners.Tables.To_Class (Natural (Char));
Self.From := Self.From + Data (Index).Length;
Index := Index + 1;
end loop;
end Read;
------------
-- Rewind --
------------
overriding procedure Rewind (Self : in out Source_Buffer) is
begin
Self.From := 1;
end Rewind;
----------
-- Text --
----------
overriding function Text
(Self : Source_Buffer;
Span : Program.Source_Buffers.Span) return Program.Text is
begin
return Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Decode
(Self.Text (Span.From .. Span.To));
end Text;
end Program.Plain_Source_Buffers;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.