content stringlengths 23 1.05M |
|---|
with Ada.Text_IO;
use Ada.Text_IO;
with Ada.Integer_Text_IO;
use Ada.Integer_Text_IO;
with Ada.Containers.Vectors;
with Ada.Numerics.Discrete_Random;
procedure Maze (Size : Integer) is
-- A grid is a 2d array of cells. A cell can either be Fresh (not
-- inspected), Front (Inspected but not set), Clear (inspected and
-- traversable), Blocked (inspected and not traversable), Start or Finish.
type Cell is (Fresh, Front, Clear, Blocked, Start, Finish);
type Grid is array(NATURAL range 1..Size, NATURAL range 1..Size) of Cell;
-- Coordinates are a vector of them are used to to keep track of the
-- frontier.
type Coord is array(NATURAL range 1..2) of NATURAL;
package Coord_Vector is new Ada.Containers.Vectors
(Index_Type => Natural,
Element_Type => Coord);
Start_Coord : Coord := (2, 2);
End_Coord : Coord := (Size-1, Size-1);
Maze_Grid : Grid;
-- Frontier cells are any uninspected cell adjacent to an inspected cell.
Frontier : Coord_Vector.Vector;
Frontier_Cursor : Coord_Vector.Cursor;
-- Set every sell to Fresh, and resets frontier vector.
procedure Clear_Maze is
begin
for I in Maze_Grid'Range (1) loop
for J in Maze_Grid'Range (2) loop
Maze_Grid (I, J) := Fresh;
end loop;
end loop;
Frontier.Clear;
Frontier.Append (Start_Coord);
Maze_Grid (Start_Coord (1), Start_Coord (2)) := Front;
end Clear_Maze;
-- Draw a single cell given the enumerate representation.
procedure Put_Cell (C : Cell) is
begin
if C = Clear then
Put (" ");
elsif C = Blocked then
Put ("██");
elsif C = Start then
Put ("S ");
elsif C = Finish then
Put ("F ");
else
Put (" ");
end if;
end Put_Cell;
-- Draw the full maze in its current form.
procedure Put_Maze is
begin
New_Line(1);
for I in Maze_Grid'Range (1) loop
for J in Maze_Grid'Range (2) loop
Put_Cell (Maze_Grid (I, J));
end loop;
New_Line (1);
end loop;
end Put_Maze;
-- Generate the outside barrier of the maze.
procedure Set_Border is
begin
for I in 1 .. Size loop
Maze_Grid (1, I) := Blocked;
Maze_Grid (Size, I) := Blocked;
Maze_Grid (I, 1) := Blocked;
Maze_Grid (I, Size) := Blocked;
end loop;
end Set_Border;
-- Inspect and act on adjacent cells to a frontier coordinate.
procedure Check_Frontier (C : Coord) is
C_Y : Integer := C (1);
C_X : Integer := C (2);
Y : Integer;
X : Integer;
type Coord_Quad is array(NATURAL range 1..4) of Coord;
New_Coords : Coord_Quad := ((C_Y - 2, C_X), (C_Y, C_X + 2),
(C_Y + 2, C_X), (C_Y, C_X - 2));
New_C : Coord;
begin
for I in New_Coords'Range loop
New_C := New_Coords (I);
Y := New_C (1);
X := New_C (2);
-- Only consider the node if it is within the bounds of the grid.
if Y >= 2 and Y <= Size - 1 and X >= 2 and X <= Size - 1 then
-- If the new node is a frontier then draw a 3-width barrier
-- between, from the direction of the original node to the new
-- node.
if Maze_Grid(Y, X) = Front then
if C_Y > Y then
Maze_Grid(Y + 1, X - 1) := Blocked;
Maze_Grid(Y + 1, X) := Blocked;
Maze_Grid(Y + 1, X + 1) := Blocked;
elsif C_Y < Y then
Maze_Grid(Y - 1, X - 1) := Blocked;
Maze_Grid(Y - 1, X) := Blocked;
Maze_Grid(Y - 1, X + 1) := Blocked;
end if;
if C_X > X then
Maze_Grid(Y + 1, X + 1) := Blocked;
Maze_Grid(Y, X + 1) := Blocked;
Maze_Grid(Y - 1, X + 1) := Blocked;
elsif C_X < X then
Maze_Grid(Y + 1, X - 1) := Blocked;
Maze_Grid(Y, X - 1) := Blocked;
Maze_Grid(Y - 1, X - 1) := Blocked;
end if;
elsif Maze_Grid(Y, X) = Fresh then
Maze_Grid(Y, X) := Front;
Frontier.Append (New_C);
end if;
end if;
end loop;
end Check_Frontier;
-- Selects a random coordinate from the frontier.
Function Rand_Int (Max : Integer) Return Integer is
subtype Int_Range is Integer range 1 .. Max;
package R is new Ada.Numerics.Discrete_Random (Int_Range);
use R;
G : Generator;
Begin
Reset (G);
Return Random(G);
End Rand_Int;
-- Proceeds with a step through the breadth-first search generation.
-- 1. Select a random frontier node from the list of frontier nodes.
-- 2. For all nodes adjacent to this node:
-- a. If the node is already a fontier, place a barrier between the two.
-- b. If the node has not been traversed, and add it to the list.
-- 3. Mark the selected node as traversable and remove it from the list.
procedure Find_Route is
C : Coord;
Search : Integer;
begin
while Integer (Frontier.Length) > 0 loop
Search := Rand_Int (Integer (Frontier.Length));
C := Frontier.Element (Search - 1);
Check_Frontier (C);
Maze_Grid (C (1), C (2)) := Clear;
Frontier.Delete (Search - 1, 1);
end loop;
Maze_Grid (Start_Coord (1), Start_Coord (2)) := Start;
Maze_Grid (End_Coord (1), End_Coord (2)) := Finish;
end Find_Route;
begin
clear_maze;
Set_Border;
Find_Route;
Put_Maze;
end Maze;
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
-- Auteur:
-- Gérer un stock de matériel informatique.
--
package body Stocks_Materiel is
-- Helpers
function Indice(Stock: in T_Stock; Numero_Serie: in Integer) return Integer is
begin
for J in 1..Stock.Nombre loop
if Stock.Materiels(J).Numero_Serie = Numero_Serie then
return J;
end if;
end loop;
return -1; -- Non trouvé, on retourne -1
end;
procedure Afficher_Materiel(Materiel: in T_Materiel) is
begin
Put("Matériel de numéro ");
Put(Materiel.Numero_Serie, 1);
Put_Line(":");
Put_Line("Type: " & T_Nature'Image(Materiel.Nature));
Put("Année: ");
Put(Materiel.Annee_Achat, 1);
New_Line;
if Materiel.Est_Fonctionnel then
Put_Line("Ce matériel est fonctionnel!");
else
Put_Line("Ce matériel est défectueux!");
end if;
end;
-- Sous Programmes du Module.
procedure Creer (Stock : out T_Stock) is
begin
Stock.Nombre := 0;
end Creer;
function Nb_Materiels (Stock: in T_Stock) return Integer is
begin
return Stock.Nombre;
end;
procedure Enregistrer (
Stock : in out T_Stock;
Numero_Serie : in Integer;
Nature : in T_Nature;
Annee_Achat : in Integer
) is
begin
Stock.Nombre := Stock.Nombre + 1;
Stock.Materiels(Stock.Nombre).Numero_Serie := Numero_Serie;
Stock.Materiels(Stock.Nombre).Nature := Nature;
Stock.Materiels(Stock.Nombre).Annee_Achat := Annee_Achat;
Stock.Materiels(Stock.Nombre).Est_Fonctionnel := True;
end;
function Nb_Defectueux (Stock: in T_Stock) return Integer is
Nbr: Integer := 0;
begin
for J in 1..Stock.Nombre loop
if not Stock.Materiels(J).Est_Fonctionnel then
Nbr := Nbr + 1;
end if;
end loop;
return Nbr;
end;
procedure Mettre_A_Jour (
Stock: in out T_Stock;
Numero_Serie: in Integer;
Est_Fonctionnel: in Boolean
) is
Position: Integer;
begin
Position := Indice(Stock, Numero_Serie);
Stock.Materiels(Position).Est_Fonctionnel := Est_Fonctionnel;
end;
procedure Supprimer (
Stock: in out T_Stock;
Numero_Serie: in Integer
) is
Position: Integer;
begin
Position := Indice(Stock, Numero_Serie);
for J in Position..Nb_Materiels(Stock) loop
Stock.Materiels(J) := Stock.Materiels(J+1);
end loop;
Stock.Nombre := Stock.Nombre - 1;
end;
function Existe(Stock: in T_Stock; Numero_Serie: in Integer) return Boolean is
begin
return Indice(Stock, Numero_Serie) > 0;
end;
procedure Afficher (Stock: in T_Stock) is
begin
for J in 1..Nb_Materiels(Stock) loop
Afficher_Materiel(Stock.Materiels(J));
New_Line;
end loop;
end;
procedure Nettoyer(Stock: in out T_Stock) is
Index: Integer;
begin
if Nb_Defectueux(Stock) = 0 then
return;
end if;
Index := 1;
while Index <= Nb_Materiels(Stock) loop
if not Stock.Materiels(Index).Est_Fonctionnel then
Supprimer(Stock, Stock.Materiels(Index).Numero_Serie);
else
Index := Index + 1;
end if;
end loop;
end;
end Stocks_Materiel;
|
--------------------------------------------
-- --
-- PACKAGE GAME - PARTIE ADA --
-- --
-- GAME.ADS --
-- --
-- Gestion des outils de base --
-- --
-- Créateur : CAPELLE Mikaël --
-- Adresse : capelle.mikael@gmail.com --
-- --
-- Dernière modification : 14 / 06 / 2011 --
-- --
--------------------------------------------
with Interfaces.C; use Interfaces.C;
with Ada.Finalization;
package Game is
-- Les différentes erreurs pouvant être levé par la librairie
-- Elles sont en générales accompagnés d'une instruction détaillé (pour plus d'info, voir
-- le package Ada.Exceptions)
-- La fonction error est (en général) appelé directement lorsque ces exceptions sont levées,
-- mais vous pouvez l'utilisez vous même si vous en avez besoin
Init_Error : exception;
Video_Error : exception;
Surface_Error : exception;
Audio_Error : exception;
Font_Error : exception;
Draw_Error : exception;
-- Type servant à stocker des surfaces graphique
-- ne peut être utilisé directement, vous devez passer par les fonctions
type Surface is private;
Null_Surface : constant Surface;
-- Initialise la librairie
-- Sans argument la fonction initialise tout
-- Lève l'exception Init_Error si une erreur survient
procedure Init(Timer : in Boolean := True;
Video : in Boolean := True;
Audio : in Boolean := True;
Font : in Boolean := True;
Frequency : in Positive := 44100);
-- Ferme la librairie (à utiliser à la fin du programme)
procedure Quit;
-- Change le titre ou l'icone de la fenêtre
procedure Change_Title (Name : in String);
procedure Change_Icon (Name : in String);
procedure Change_Icon (Surf : in Surface);
-- Retourne une indication sur la dernière erreur survenue
function Error return String;
private
package AF renames Ada.Finalization;
type SDL_Surface is access all Int;
Null_SDL_Surface : constant SDL_Surface := null;
C_Screen : SDL_Surface := Null_SDL_Surface; -- Ecran principale (pour faciliter Get_Screen)
-- Libère la mémoire alloué par une surface
procedure Free_Surface (S : in out Surface);
type Surface is new AF.Controlled with
record
Surf : SDL_Surface;
end record;
procedure Initialize (S : in out Surface);
procedure Adjust (S : in out Surface);
procedure Finalize (S : in out Surface);
Null_Surface : constant Surface := (AF.Controlled with Null_SDL_Surface);
end Game;
|
-- { dg-do run }
with Aggr21_Pkg; use Aggr21_Pkg;
procedure Aggr21 is
V : Rec;
begin
V.A := 12;
V.S (1 .. 10) := "Hello init";
V.N := 123;
Init (V);
-- Probably not reliable, but the compiler is supposed not to modify V.S
pragma Assert (V.s (1 .. 5) = "Hello");
end;
|
------------------------------------------------------------------------------
-- --
-- Modular Hash Infrastructure --
-- --
-- SHA1 --
-- --
-- ------------------------------------------------------------------------ --
-- --
-- Copyright (C) 2018-2021, ANNEXI-STRAYLINE Trans-Human Ltd. --
-- All rights reserved. --
-- --
-- Original Contributors: --
-- * Ensi Martini (ANNEXI-STRAYLINE) --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- --
-- * Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A --
-- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with Interfaces;
with Ada.Streams;
package Modular_Hashing.SHA1 is
type SHA1_Hash is new Hash with private;
-- The final hash is a 160-bit message digest, which can also be displayed
-- as a 40 character hex string and is 20 bytes long
overriding function "<" (Left, Right : SHA1_Hash) return Boolean;
overriding function ">" (Left, Right : SHA1_Hash) return Boolean;
overriding function "=" (Left, Right : SHA1_Hash) return Boolean;
SHA1_Hash_Bytes: constant := 20;
overriding function Binary_Bytes (Value: SHA1_Hash) return Positive is
(SHA1_Hash_Bytes);
overriding function Binary (Value: SHA1_Hash) return Hash_Binary_Value with
Post => Binary'Result'Length = SHA1_Hash_Bytes;
type SHA1_Engine is new Hash_Algorithm with private;
overriding
procedure Write (Stream : in out SHA1_Engine;
Item : in Ada.Streams.Stream_Element_Array);
overriding procedure Reset (Engine : in out SHA1_Engine);
overriding function Digest (Engine : in out SHA1_Engine)
return Hash'Class;
private
use Ada.Streams, Interfaces;
type Message_Digest is array (1 .. 5) of Unsigned_32;
type SHA1_Hash is new Hash with
record
Digest: Message_Digest;
end record;
-----------------
-- SHA1_Engine --
-----------------
-- SHA-1 Defined initialization constants
H0_Initial: constant := 16#67452301#;
H1_Initial: constant := 16#EFCDAB89#;
H2_Initial: constant := 16#98BADCFE#;
H3_Initial: constant := 16#10325476#;
H4_Initial: constant := 16#C3D2E1F0#;
type SHA1_Engine is new Hash_Algorithm with record
Last_Element_Index : Stream_Element_Offset := 0;
Buffer : Stream_Element_Array(1 .. 64);
Message_Length : Unsigned_64 := 0;
H0 : Unsigned_32 := H0_Initial;
H1 : Unsigned_32 := H1_Initial;
H2 : Unsigned_32 := H2_Initial;
H3 : Unsigned_32 := H3_Initial;
H4 : Unsigned_32 := H4_Initial;
end record;
end Modular_Hashing.SHA1;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../../License.txt
with AdaBase.Results.Converters;
package body AdaBase.Results.Field is
package ARC renames AdaBase.Results.Converters;
-- [1] For several conversions, the string equivalents in both ASCII
-- and UTF-8 must be identical. For this, just skip the conversion
-- from UTF-8 to ASCII as the extract step makes no differnce
-- [2] For types with textual components (e.g. enum types), convert
-- UTF-8 data to ASCII first
-----------------
-- as_nbyte0 --
-----------------
function as_nbyte0 (field : Std_Field) return NByte0
is
begin
case field.native.datatype is
when ft_nbyte0 => return field.native.v00;
when ft_nbyte1 => return ARC.convert (field.native.v01);
when ft_nbyte2 => return ARC.convert (field.native.v02);
when ft_nbyte3 => return ARC.convert (field.native.v03);
when ft_nbyte4 => return ARC.convert (field.native.v04);
when ft_nbyte8 => return ARC.convert (field.native.v05);
when ft_byte1 => return ARC.convert (field.native.v06);
when ft_byte2 => return ARC.convert (field.native.v07);
when ft_byte3 => return ARC.convert (field.native.v08);
when ft_byte4 => return ARC.convert (field.native.v09);
when ft_byte8 => return ARC.convert (field.native.v10);
when ft_textual => return ARC.convert (field.native.v13);
when ft_widetext => return ARC.convert (field.native.v14);
when ft_supertext => return ARC.convert (field.native.v15);
when ft_utf8 => return ARC.convert (field.native.v21); -- [1]
when ft_chain =>
declare
cadena : Chain := ARC.convert (field.native.v17);
begin
return ARC.convert (cadena);
end;
when ft_bits =>
declare
cadena : Bits := ARC.convert (field.native.v20);
begin
return ARC.convert (cadena);
end;
when ft_real9 |
ft_real18 |
ft_geometry |
ft_timestamp |
ft_enumtype |
ft_settype => raise UNSUPPORTED_CONVERSION;
end case;
end as_nbyte0;
-----------------
-- as_nbyte1 --
-----------------
function as_nbyte1 (field : Std_Field) return NByte1
is
begin
case field.native.datatype is
when ft_nbyte0 => return ARC.convert (field.native.v00);
when ft_nbyte1 => return field.native.v01;
when ft_nbyte2 => return ARC.convert (field.native.v02);
when ft_nbyte3 => return ARC.convert (field.native.v03);
when ft_nbyte4 => return ARC.convert (field.native.v04);
when ft_nbyte8 => return ARC.convert (field.native.v05);
when ft_byte1 => return ARC.convert (field.native.v06);
when ft_byte2 => return ARC.convert (field.native.v07);
when ft_byte3 => return ARC.convert (field.native.v08);
when ft_byte4 => return ARC.convert (field.native.v09);
when ft_byte8 => return ARC.convert (field.native.v10);
when ft_textual => return ARC.convert (field.native.v13);
when ft_widetext => return ARC.convert (field.native.v14);
when ft_supertext => return ARC.convert (field.native.v15);
when ft_utf8 => return ARC.convert (field.native.v21); -- [1]
when ft_chain =>
declare
cadena : Chain := ARC.convert (field.native.v17);
begin
return ARC.convert (cadena);
end;
when ft_bits =>
declare
cadena : Bits := ARC.convert (field.native.v20);
begin
return ARC.convert (cadena);
end;
when ft_real9 |
ft_real18 |
ft_geometry |
ft_timestamp |
ft_enumtype |
ft_settype => raise UNSUPPORTED_CONVERSION;
end case;
end as_nbyte1;
-----------------
-- as_nbyte2 --
-----------------
function as_nbyte2 (field : Std_Field) return NByte2
is
begin
case field.native.datatype is
when ft_nbyte0 => return ARC.convert (field.native.v00);
when ft_nbyte1 => return ARC.convert (field.native.v01);
when ft_nbyte2 => return field.native.v02;
when ft_nbyte3 => return ARC.convert (field.native.v03);
when ft_nbyte4 => return ARC.convert (field.native.v04);
when ft_nbyte8 => return ARC.convert (field.native.v05);
when ft_byte1 => return ARC.convert (field.native.v06);
when ft_byte2 => return ARC.convert (field.native.v07);
when ft_byte3 => return ARC.convert (field.native.v08);
when ft_byte4 => return ARC.convert (field.native.v09);
when ft_byte8 => return ARC.convert (field.native.v10);
when ft_textual => return ARC.convert (field.native.v13);
when ft_widetext => return ARC.convert (field.native.v14);
when ft_supertext => return ARC.convert (field.native.v15);
when ft_utf8 => return ARC.convert (field.native.v21); -- [1]
when ft_chain =>
declare
cadena : Chain := ARC.convert (field.native.v17);
begin
return ARC.convert (cadena);
end;
when ft_bits =>
declare
cadena : Bits := ARC.convert (field.native.v20);
begin
return ARC.convert (cadena);
end;
when ft_real9 |
ft_real18 |
ft_geometry |
ft_timestamp |
ft_enumtype |
ft_settype => raise UNSUPPORTED_CONVERSION;
end case;
end as_nbyte2;
-----------------
-- as_nbyte3 --
-----------------
function as_nbyte3 (field : Std_Field) return NByte3
is
begin
case field.native.datatype is
when ft_nbyte0 => return ARC.convert (field.native.v00);
when ft_nbyte1 => return ARC.convert (field.native.v01);
when ft_nbyte2 => return ARC.convert (field.native.v02);
when ft_nbyte3 => return field.native.v03;
when ft_nbyte4 => return ARC.convert (field.native.v04);
when ft_nbyte8 => return ARC.convert (field.native.v05);
when ft_byte1 => return ARC.convert (field.native.v06);
when ft_byte2 => return ARC.convert (field.native.v07);
when ft_byte3 => return ARC.convert (field.native.v08);
when ft_byte4 => return ARC.convert (field.native.v09);
when ft_byte8 => return ARC.convert (field.native.v10);
when ft_textual => return ARC.convert (field.native.v13);
when ft_widetext => return ARC.convert (field.native.v14);
when ft_supertext => return ARC.convert (field.native.v15);
when ft_utf8 => return ARC.convert (field.native.v21); -- [1]
when ft_chain =>
declare
cadena : Chain := ARC.convert (field.native.v17);
begin
return ARC.convert (cadena);
end;
when ft_bits =>
declare
cadena : Bits := ARC.convert (field.native.v20);
begin
return ARC.convert (cadena);
end;
when ft_real9 |
ft_real18 |
ft_geometry |
ft_timestamp |
ft_enumtype |
ft_settype => raise UNSUPPORTED_CONVERSION;
end case;
end as_nbyte3;
-----------------
-- as_nbyte4 --
-----------------
function as_nbyte4 (field : Std_Field) return NByte4
is
begin
case field.native.datatype is
when ft_nbyte0 => return ARC.convert (field.native.v00);
when ft_nbyte1 => return ARC.convert (field.native.v01);
when ft_nbyte2 => return ARC.convert (field.native.v02);
when ft_nbyte3 => return ARC.convert (field.native.v03);
when ft_nbyte4 => return field.native.v04;
when ft_nbyte8 => return ARC.convert (field.native.v05);
when ft_byte1 => return ARC.convert (field.native.v06);
when ft_byte2 => return ARC.convert (field.native.v07);
when ft_byte3 => return ARC.convert (field.native.v08);
when ft_byte4 => return ARC.convert (field.native.v09);
when ft_byte8 => return ARC.convert (field.native.v10);
when ft_textual => return ARC.convert (field.native.v13);
when ft_widetext => return ARC.convert (field.native.v14);
when ft_supertext => return ARC.convert (field.native.v15);
when ft_utf8 => return ARC.convert (field.native.v21); -- [1]
when ft_chain =>
declare
cadena : Chain := ARC.convert (field.native.v17);
begin
return ARC.convert (cadena);
end;
when ft_bits =>
declare
cadena : Bits := ARC.convert (field.native.v20);
begin
return ARC.convert (cadena);
end;
when ft_real9 |
ft_real18 |
ft_geometry |
ft_timestamp |
ft_enumtype |
ft_settype => raise UNSUPPORTED_CONVERSION;
end case;
end as_nbyte4;
-----------------
-- as_nbyte8 --
-----------------
function as_nbyte8 (field : Std_Field) return NByte8
is
begin
case field.native.datatype is
when ft_nbyte0 => return ARC.convert (field.native.v00);
when ft_nbyte1 => return ARC.convert (field.native.v01);
when ft_nbyte2 => return ARC.convert (field.native.v02);
when ft_nbyte3 => return ARC.convert (field.native.v03);
when ft_nbyte4 => return ARC.convert (field.native.v04);
when ft_nbyte8 => return field.native.v05;
when ft_byte1 => return ARC.convert (field.native.v06);
when ft_byte2 => return ARC.convert (field.native.v07);
when ft_byte3 => return ARC.convert (field.native.v08);
when ft_byte4 => return ARC.convert (field.native.v09);
when ft_byte8 => return ARC.convert (field.native.v10);
when ft_textual => return ARC.convert (field.native.v13);
when ft_widetext => return ARC.convert (field.native.v14);
when ft_supertext => return ARC.convert (field.native.v15);
when ft_utf8 => return ARC.convert (field.native.v21); -- [1]
when ft_chain =>
declare
cadena : Chain := ARC.convert (field.native.v17);
begin
return ARC.convert (cadena);
end;
when ft_bits =>
declare
cadena : Bits := ARC.convert (field.native.v20);
begin
return ARC.convert (cadena);
end;
when ft_real9 |
ft_real18 |
ft_geometry |
ft_timestamp |
ft_enumtype |
ft_settype => raise UNSUPPORTED_CONVERSION;
end case;
end as_nbyte8;
----------------
-- as_byte1 --
----------------
function as_byte1 (field : Std_Field) return Byte1
is
begin
case field.native.datatype is
when ft_nbyte0 => return ARC.convert (field.native.v00);
when ft_nbyte1 => return ARC.convert (field.native.v01);
when ft_nbyte2 => return ARC.convert (field.native.v02);
when ft_nbyte3 => return ARC.convert (field.native.v03);
when ft_nbyte4 => return ARC.convert (field.native.v04);
when ft_nbyte8 => return ARC.convert (field.native.v05);
when ft_byte1 => return field.native.v06;
when ft_byte2 => return ARC.convert (field.native.v07);
when ft_byte3 => return ARC.convert (field.native.v08);
when ft_byte4 => return ARC.convert (field.native.v09);
when ft_byte8 => return ARC.convert (field.native.v10);
when ft_textual => return ARC.convert (field.native.v13);
when ft_widetext => return ARC.convert (field.native.v14);
when ft_supertext => return ARC.convert (field.native.v15);
when ft_utf8 => return ARC.convert (field.native.v21); -- [1]
when ft_real9 |
ft_real18 |
ft_geometry |
ft_timestamp |
ft_chain |
ft_bits |
ft_enumtype |
ft_settype => raise UNSUPPORTED_CONVERSION;
end case;
end as_byte1;
----------------
-- as_byte2 --
----------------
function as_byte2 (field : Std_Field) return Byte2
is
begin
case field.native.datatype is
when ft_nbyte0 => return ARC.convert (field.native.v00);
when ft_nbyte1 => return ARC.convert (field.native.v01);
when ft_nbyte2 => return ARC.convert (field.native.v02);
when ft_nbyte3 => return ARC.convert (field.native.v03);
when ft_nbyte4 => return ARC.convert (field.native.v04);
when ft_nbyte8 => return ARC.convert (field.native.v05);
when ft_byte1 => return ARC.convert (field.native.v06);
when ft_byte2 => return field.native.v07;
when ft_byte3 => return ARC.convert (field.native.v08);
when ft_byte4 => return ARC.convert (field.native.v09);
when ft_byte8 => return ARC.convert (field.native.v10);
when ft_textual => return ARC.convert (field.native.v13);
when ft_widetext => return ARC.convert (field.native.v14);
when ft_supertext => return ARC.convert (field.native.v15);
when ft_utf8 => return ARC.convert (field.native.v21); -- [1]
when ft_real9 |
ft_real18 |
ft_geometry |
ft_timestamp |
ft_chain |
ft_bits |
ft_enumtype |
ft_settype => raise UNSUPPORTED_CONVERSION;
end case;
end as_byte2;
----------------
-- as_byte3 --
----------------
function as_byte3 (field : Std_Field) return Byte3
is
begin
case field.native.datatype is
when ft_nbyte0 => return ARC.convert (field.native.v00);
when ft_nbyte1 => return ARC.convert (field.native.v01);
when ft_nbyte2 => return ARC.convert (field.native.v02);
when ft_nbyte3 => return ARC.convert (field.native.v03);
when ft_nbyte4 => return ARC.convert (field.native.v04);
when ft_nbyte8 => return ARC.convert (field.native.v05);
when ft_byte1 => return ARC.convert (field.native.v06);
when ft_byte2 => return ARC.convert (field.native.v07);
when ft_byte3 => return field.native.v08;
when ft_byte4 => return ARC.convert (field.native.v09);
when ft_byte8 => return ARC.convert (field.native.v10);
when ft_textual => return ARC.convert (field.native.v13);
when ft_widetext => return ARC.convert (field.native.v14);
when ft_supertext => return ARC.convert (field.native.v15);
when ft_utf8 => return ARC.convert (field.native.v21); -- [1]
when ft_real9 |
ft_real18 |
ft_geometry |
ft_timestamp |
ft_chain |
ft_bits |
ft_enumtype |
ft_settype => raise UNSUPPORTED_CONVERSION;
end case;
end as_byte3;
----------------
-- as_byte4 --
----------------
function as_byte4 (field : Std_Field) return Byte4
is
begin
case field.native.datatype is
when ft_nbyte0 => return ARC.convert (field.native.v00);
when ft_nbyte1 => return ARC.convert (field.native.v01);
when ft_nbyte2 => return ARC.convert (field.native.v02);
when ft_nbyte3 => return ARC.convert (field.native.v03);
when ft_nbyte4 => return ARC.convert (field.native.v04);
when ft_nbyte8 => return ARC.convert (field.native.v05);
when ft_byte1 => return ARC.convert (field.native.v06);
when ft_byte2 => return ARC.convert (field.native.v07);
when ft_byte3 => return ARC.convert (field.native.v08);
when ft_byte4 => return field.native.v09;
when ft_byte8 => return ARC.convert (field.native.v10);
when ft_textual => return ARC.convert (field.native.v13);
when ft_widetext => return ARC.convert (field.native.v14);
when ft_supertext => return ARC.convert (field.native.v15);
when ft_utf8 => return ARC.convert (field.native.v21); -- [1]
when ft_real9 |
ft_real18 |
ft_geometry |
ft_timestamp |
ft_chain |
ft_bits |
ft_enumtype |
ft_settype => raise UNSUPPORTED_CONVERSION;
end case;
end as_byte4;
----------------
-- as_byte8 --
----------------
function as_byte8 (field : Std_Field) return Byte8
is
begin
case field.native.datatype is
when ft_nbyte0 => return ARC.convert (field.native.v00);
when ft_nbyte1 => return ARC.convert (field.native.v01);
when ft_nbyte2 => return ARC.convert (field.native.v02);
when ft_nbyte3 => return ARC.convert (field.native.v03);
when ft_nbyte4 => return ARC.convert (field.native.v04);
when ft_nbyte8 => return ARC.convert (field.native.v05);
when ft_byte1 => return ARC.convert (field.native.v06);
when ft_byte2 => return ARC.convert (field.native.v07);
when ft_byte3 => return ARC.convert (field.native.v08);
when ft_byte4 => return ARC.convert (field.native.v09);
when ft_byte8 => return field.native.v10;
when ft_textual => return ARC.convert (field.native.v13);
when ft_widetext => return ARC.convert (field.native.v14);
when ft_supertext => return ARC.convert (field.native.v15);
when ft_utf8 => return ARC.convert (field.native.v21); -- [1]
when ft_real9 |
ft_real18 |
ft_geometry |
ft_timestamp |
ft_chain |
ft_bits |
ft_enumtype |
ft_settype => raise UNSUPPORTED_CONVERSION;
end case;
end as_byte8;
----------------
-- as_real9 --
----------------
function as_real9 (field : Std_Field) return Real9
is
begin
case field.native.datatype is
when ft_nbyte0 => return ARC.convert (field.native.v00);
when ft_nbyte1 => return ARC.convert (field.native.v01);
when ft_nbyte2 => return ARC.convert (field.native.v02);
when ft_nbyte3 => return ARC.convert (field.native.v03);
when ft_nbyte4 => return ARC.convert (field.native.v04);
when ft_nbyte8 => return ARC.convert (field.native.v05);
when ft_byte1 => return ARC.convert (field.native.v06);
when ft_byte2 => return ARC.convert (field.native.v07);
when ft_byte3 => return ARC.convert (field.native.v08);
when ft_byte4 => return ARC.convert (field.native.v09);
when ft_byte8 => return ARC.convert (field.native.v10);
when ft_real9 => return field.native.v11;
when ft_real18 => return ARC.convert (field.native.v12);
when ft_textual => return ARC.convert (field.native.v13);
when ft_widetext => return ARC.convert (field.native.v14);
when ft_supertext => return ARC.convert (field.native.v15);
when ft_utf8 => return ARC.convert (field.native.v21); -- [1]
when ft_timestamp |
ft_chain |
ft_bits |
ft_geometry |
ft_enumtype |
ft_settype => raise UNSUPPORTED_CONVERSION;
end case;
end as_real9;
-----------------
-- as_real18 --
-----------------
function as_real18 (field : Std_Field) return Real18
is
begin
case field.native.datatype is
when ft_nbyte0 => return ARC.convert (field.native.v00);
when ft_nbyte1 => return ARC.convert (field.native.v01);
when ft_nbyte2 => return ARC.convert (field.native.v02);
when ft_nbyte3 => return ARC.convert (field.native.v03);
when ft_nbyte4 => return ARC.convert (field.native.v04);
when ft_nbyte8 => return ARC.convert (field.native.v05);
when ft_byte1 => return ARC.convert (field.native.v06);
when ft_byte2 => return ARC.convert (field.native.v07);
when ft_byte3 => return ARC.convert (field.native.v08);
when ft_byte4 => return ARC.convert (field.native.v09);
when ft_byte8 => return ARC.convert (field.native.v10);
when ft_real9 => return ARC.convert (field.native.v11);
when ft_real18 => return field.native.v12;
when ft_textual => return ARC.convert (field.native.v13);
when ft_widetext => return ARC.convert (field.native.v14);
when ft_supertext => return ARC.convert (field.native.v15);
when ft_utf8 => return ARC.convert (field.native.v21); -- [1]
when ft_timestamp |
ft_chain |
ft_bits |
ft_geometry |
ft_enumtype |
ft_settype => raise UNSUPPORTED_CONVERSION;
end case;
end as_real18;
-----------------
-- as_string --
-----------------
function as_string (field : Std_Field) return String
is
begin
case field.native.datatype is
when ft_nbyte0 => return ARC.convert (field.native.v00);
when ft_nbyte1 => return ARC.convert (field.native.v01);
when ft_nbyte2 => return ARC.convert (field.native.v02);
when ft_nbyte3 => return ARC.convert (field.native.v03);
when ft_nbyte4 => return ARC.convert (field.native.v04);
when ft_nbyte8 => return ARC.convert (field.native.v05);
when ft_byte1 => return ARC.convert (field.native.v06);
when ft_byte2 => return ARC.convert (field.native.v07);
when ft_byte3 => return ARC.convert (field.native.v08);
when ft_byte4 => return ARC.convert (field.native.v09);
when ft_byte8 => return ARC.convert (field.native.v10);
when ft_real9 => return ARC.convert (field.native.v11);
when ft_real18 => return ARC.convert (field.native.v12);
when ft_textual => return ARC.convert (field.native.v13);
when ft_widetext => return ARC.convert (field.native.v14);
when ft_supertext => return ARC.convert (field.native.v15);
when ft_timestamp => return ARC.convert (field.native.v16);
when ft_chain => return ARC.convert (field.native.v17);
when ft_enumtype => return ARC.convert (field.native.v18);
when ft_settype => return ARC.convert (field.native.v19);
when ft_bits => return ARC.convert (field.native.v20);
when ft_utf8 => return ARC.cvu2str (CT.USS (field.native.v21));
when ft_geometry => return WKB.produce_WKT (field.native.v22);
end case;
end as_string;
------------------
-- as_wstring --
------------------
function as_wstring (field : Std_Field) return Wide_String
is
begin
case field.native.datatype is
when ft_nbyte0 => return ARC.convert (field.native.v00);
when ft_nbyte1 => return ARC.convert (field.native.v01);
when ft_nbyte2 => return ARC.convert (field.native.v02);
when ft_nbyte3 => return ARC.convert (field.native.v03);
when ft_nbyte4 => return ARC.convert (field.native.v04);
when ft_nbyte8 => return ARC.convert (field.native.v05);
when ft_byte1 => return ARC.convert (field.native.v06);
when ft_byte2 => return ARC.convert (field.native.v07);
when ft_byte3 => return ARC.convert (field.native.v08);
when ft_byte4 => return ARC.convert (field.native.v09);
when ft_byte8 => return ARC.convert (field.native.v10);
when ft_real9 => return ARC.convert (field.native.v11);
when ft_real18 => return ARC.convert (field.native.v12);
when ft_textual => return ARC.convert (field.native.v13);
when ft_widetext => return ARC.convert (field.native.v14);
when ft_supertext => return ARC.convert (field.native.v15);
when ft_timestamp => return ARC.convert (field.native.v16);
when ft_chain => return ARC.convert (field.native.v17);
when ft_enumtype => return ARC.convert (field.native.v18);
when ft_settype => return ARC.convert (field.native.v19);
when ft_bits => return ARC.convert (field.native.v20);
when ft_utf8 => return ARC.cvu2str (CT.USS (field.native.v21));
when ft_geometry =>
return ARC.convert (WKB.produce_WKT (field.native.v22));
end case;
end as_wstring;
-------------------
-- as_wwstring --
-------------------
function as_wwstring (field : Std_Field) return Wide_Wide_String
is
begin
case field.native.datatype is
when ft_nbyte0 => return ARC.convert (field.native.v00);
when ft_nbyte1 => return ARC.convert (field.native.v01);
when ft_nbyte2 => return ARC.convert (field.native.v02);
when ft_nbyte3 => return ARC.convert (field.native.v03);
when ft_nbyte4 => return ARC.convert (field.native.v04);
when ft_nbyte8 => return ARC.convert (field.native.v05);
when ft_byte1 => return ARC.convert (field.native.v06);
when ft_byte2 => return ARC.convert (field.native.v07);
when ft_byte3 => return ARC.convert (field.native.v08);
when ft_byte4 => return ARC.convert (field.native.v09);
when ft_byte8 => return ARC.convert (field.native.v10);
when ft_real9 => return ARC.convert (field.native.v11);
when ft_real18 => return ARC.convert (field.native.v12);
when ft_textual => return ARC.convert (field.native.v13);
when ft_widetext => return ARC.convert (field.native.v14);
when ft_supertext => return ARC.convert (field.native.v15);
when ft_timestamp => return ARC.convert (field.native.v16);
when ft_chain => return ARC.convert (field.native.v17);
when ft_enumtype => return ARC.convert (field.native.v18);
when ft_settype => return ARC.convert (field.native.v19);
when ft_bits => return ARC.convert (field.native.v20);
when ft_utf8 => return ARC.cvu2str (CT.USS (field.native.v21));
when ft_geometry =>
return ARC.convert (WKB.produce_WKT (field.native.v22));
end case;
end as_wwstring;
-----------------
-- as_time --
-----------------
function as_time (field : Std_Field) return AC.Time is
begin
case field.native.datatype is
when ft_timestamp => return field.native.v16;
when ft_textual => return ARC.convert (field.native.v13);
when ft_widetext => return ARC.convert (field.native.v14);
when ft_supertext => return ARC.convert (field.native.v15);
when ft_utf8 => return ARC.convert (field.native.v21);
when others => raise UNSUPPORTED_CONVERSION;
end case;
end as_time;
------------------
-- as_geometry --
------------------
function as_geometry (field : Std_Field) return GEO.Geometry is
begin
case field.native.datatype is
when ft_geometry =>
return WKB.Translate_WKB (CT.USS (field.native.v22));
when ft_chain =>
return WKB.Translate_WKB (ARC.convert (field.native.v22));
when others => raise UNSUPPORTED_CONVERSION;
end case;
end as_geometry;
----------------
-- as_chain --
----------------
function as_chain (field : Std_Field) return Chain
is
begin
case field.native.datatype is
when ft_nbyte0 => return ARC.convert (field.native.v00);
when ft_nbyte1 => return ARC.convert (field.native.v01);
when ft_nbyte2 => return ARC.convert (field.native.v02);
when ft_nbyte3 => return ARC.convert (field.native.v03);
when ft_nbyte4 => return ARC.convert (field.native.v04);
when ft_nbyte8 => return ARC.convert (field.native.v05);
when ft_textual => return ARC.convert (field.native.v13);
when ft_widetext => return ARC.convert (field.native.v14);
when ft_supertext => return ARC.convert (field.native.v15);
when ft_chain => return ARC.convert (field.native.v17);
when ft_geometry => return ARC.convert (field.native.v22);
when ft_bits =>
declare
target_bits : Bits := ARC.convert (field.native.v20);
begin
return ARC.convert (target_bits);
end;
when ft_byte1 |
ft_byte2 |
ft_byte3 |
ft_byte4 |
ft_byte8 |
ft_real9 |
ft_real18 |
ft_utf8 |
ft_enumtype |
ft_settype |
ft_timestamp => raise UNSUPPORTED_CONVERSION;
end case;
end as_chain;
-------------------
-- as_enumtype --
-------------------
function as_enumtype (field : Std_Field) return Enumtype
is
begin
case field.native.datatype is
when ft_enumtype => return field.native.v18;
when ft_textual => return ARC.convert (field.native.v13);
when ft_widetext => return ARC.convert (field.native.v14);
when ft_supertext => return ARC.convert (field.native.v15);
when ft_utf8 =>
declare
txt : Textual := ARC.cvu2str (field.native.v21); -- [2]
begin
return ARC.convert (txt);
end;
when others => raise UNSUPPORTED_CONVERSION;
end case;
end as_enumtype;
-----------------
-- as_settype --
-----------------
function as_settype (field : Std_Field) return Settype
is
begin
case field.native.datatype is
when ft_textual => return ARC.convert (field.native.v13);
when ft_widetext => return ARC.convert (field.native.v14);
when ft_supertext => return ARC.convert (field.native.v15);
when ft_settype => return ARC.convert (field.native.v19);
when ft_utf8 =>
declare
txt : Textual := ARC.cvu2str (field.native.v21); -- [2]
begin
return ARC.convert (field.native.v21);
end;
when others => raise UNSUPPORTED_CONVERSION;
end case;
end as_settype;
---------------
-- as_bits --
---------------
function as_bits (field : Std_Field) return Bits
is
begin
case field.native.datatype is
when ft_nbyte0 => return ARC.convert (field.native.v00);
when ft_nbyte1 => return ARC.convert (field.native.v01);
when ft_nbyte2 => return ARC.convert (field.native.v02);
when ft_nbyte3 => return ARC.convert (field.native.v03);
when ft_nbyte4 => return ARC.convert (field.native.v04);
when ft_nbyte8 => return ARC.convert (field.native.v05);
when ft_textual => return ARC.convert (field.native.v13);
when ft_widetext => return ARC.convert (field.native.v14);
when ft_supertext => return ARC.convert (field.native.v15);
when ft_chain => return ARC.convert (field.native.v17);
when ft_bits => return ARC.convert (field.native.v20);
when ft_byte1 |
ft_byte2 |
ft_byte3 |
ft_byte4 |
ft_byte8 |
ft_real9 |
ft_real18 |
ft_utf8 |
ft_geometry |
ft_enumtype |
ft_settype |
ft_timestamp => raise UNSUPPORTED_CONVERSION;
end case;
end as_bits;
---------------
-- as_utf8 --
---------------
function as_utf8 (field : Std_Field) return Text_UTF8
is
begin
case field.native.datatype is
when ft_nbyte0 => return ARC.cv2utf8 (field.native.v00);
when ft_nbyte1 => return ARC.cv2utf8 (field.native.v01);
when ft_nbyte2 => return ARC.cv2utf8 (field.native.v02);
when ft_nbyte3 => return ARC.cv2utf8 (field.native.v03);
when ft_nbyte4 => return ARC.cv2utf8 (field.native.v04);
when ft_nbyte8 => return ARC.cv2utf8 (field.native.v05);
when ft_byte1 => return ARC.cv2utf8 (field.native.v06);
when ft_byte2 => return ARC.cv2utf8 (field.native.v07);
when ft_byte3 => return ARC.cv2utf8 (field.native.v08);
when ft_byte4 => return ARC.cv2utf8 (field.native.v09);
when ft_byte8 => return ARC.cv2utf8 (field.native.v10);
when ft_real9 => return ARC.cv2utf8 (field.native.v11);
when ft_real18 => return ARC.cv2utf8 (field.native.v12);
when ft_textual => return ARC.cv2utf8 (field.native.v13);
when ft_widetext => return ARC.cv2utf8 (field.native.v14);
when ft_supertext => return ARC.cv2utf8 (field.native.v15);
when ft_timestamp => return ARC.cv2utf8 (field.native.v16);
when ft_enumtype => return ARC.cv2utf8 (field.native.v18);
when ft_settype => return ARC.cv2utf8 (field.native.v19);
when ft_utf8 => return Text_UTF8 (CT.USS (field.native.v21));
when ft_geometry =>
return ARC.cv2utf8 (WKB.produce_WKT (field.native.v22));
when ft_chain |
ft_bits => raise UNSUPPORTED_CONVERSION;
end case;
end as_utf8;
---------------
-- is_null --
---------------
function is_null (field : Std_Field) return Boolean is
begin
return field.explicit_null;
end is_null;
-------------------
-- native_type --
-------------------
function native_type (field : Std_Field) return field_types is
begin
return field.native.datatype;
end native_type;
----------------------
-- spawn_field #1 --
----------------------
function spawn_field (data : Variant; null_data : Boolean := False)
return Std_Field
is
result : Std_Field;
begin
result.set (data => data, exnull => null_data);
return result;
end spawn_field;
----------------------
-- spawn_field #2 --
----------------------
function spawn_field (binob : Chain) return Std_Field
is
result : Std_Field;
chainstr : constant String := ARC.convert (binob);
begin
result.set (data => (ft_chain, CT.SUS (chainstr)), exnull => False);
return result;
end spawn_field;
----------------------
-- spawn_field #3 --
----------------------
function spawn_field (enumset : String) return Std_Field
is
result : Std_Field;
begin
result.set (data => (ft_settype, CT.SUS (enumset)), exnull => False);
return result;
end spawn_field;
------------------------
-- spawn_bits_field --
------------------------
function spawn_bits_field (bitstring : String) return Std_Field
is
result : Std_Field;
begin
result.set (data => (ft_bits, CT.SUS (bitstring)), exnull => False);
return result;
end spawn_bits_field;
------------------------
-- spawn_null_field --
------------------------
function spawn_null_field (data_type : field_types) return Std_Field
is
result : Std_Field;
begin
case data_type is
when ft_nbyte0 => result.set ((ft_nbyte0, PARAM_IS_BOOLEAN), True);
when ft_nbyte1 => result.set ((ft_nbyte1, PARAM_IS_NBYTE_1), True);
when ft_nbyte2 => result.set ((ft_nbyte2, PARAM_IS_NBYTE_2), True);
when ft_nbyte3 => result.set ((ft_nbyte3, PARAM_IS_NBYTE_3), True);
when ft_nbyte4 => result.set ((ft_nbyte4, PARAM_IS_NBYTE_4), True);
when ft_nbyte8 => result.set ((ft_nbyte8, PARAM_IS_NBYTE_8), True);
when ft_byte1 => result.set ((ft_byte1, PARAM_IS_BYTE_1), True);
when ft_byte2 => result.set ((ft_byte2, PARAM_IS_BYTE_2), True);
when ft_byte3 => result.set ((ft_byte3, PARAM_IS_BYTE_3), True);
when ft_byte4 => result.set ((ft_byte4, PARAM_IS_BYTE_4), True);
when ft_byte8 => result.set ((ft_byte8, PARAM_IS_BYTE_8), True);
when ft_real9 => result.set ((ft_real9, PARAM_IS_REAL_9), True);
when ft_real18 => result.set ((ft_real18, PARAM_IS_REAL_18), True);
when ft_textual => result.set ((ft_textual, PARAM_IS_TEXTUAL), True);
when ft_widetext => result.set ((ft_widetext, PARAM_IS_TEXTWIDE), True);
when ft_supertext => result.set ((ft_supertext, PARAM_IS_TEXTSUPER), True);
when ft_timestamp => result.set ((ft_timestamp, PARAM_IS_TIMESTAMP), True);
when ft_chain => result.set ((ft_chain, PARAM_IS_TEXTUAL), True);
when ft_enumtype => result.set ((ft_enumtype, PARAM_IS_ENUM), True);
when ft_settype => result.set ((ft_settype, PARAM_IS_TEXTUAL), True);
when ft_bits => result.set ((ft_bits, PARAM_IS_TEXTUAL), True);
when ft_utf8 => result.set ((ft_utf8, PARAM_IS_TEXTUAL), True);
when ft_geometry => result.set ((ft_geometry, PARAM_IS_TEXTUAL), True);
end case;
return result;
end spawn_null_field;
-----------
-- set --
-----------
procedure set (field : out Std_Field; data : Variant; exnull : Boolean) is
begin
case data.datatype is
when ft_nbyte0 => field.native := (ft_nbyte0, data.v00);
when ft_nbyte1 => field.native := (ft_nbyte1, data.v01);
when ft_nbyte2 => field.native := (ft_nbyte2, data.v02);
when ft_nbyte3 => field.native := (ft_nbyte3, data.v03);
when ft_nbyte4 => field.native := (ft_nbyte4, data.v04);
when ft_nbyte8 => field.native := (ft_nbyte8, data.v05);
when ft_byte1 => field.native := (ft_byte1, data.v06);
when ft_byte2 => field.native := (ft_byte2, data.v07);
when ft_byte3 => field.native := (ft_byte3, data.v08);
when ft_byte4 => field.native := (ft_byte4, data.v09);
when ft_byte8 => field.native := (ft_byte8, data.v10);
when ft_real9 => field.native := (ft_real9, data.v11);
when ft_real18 => field.native := (ft_real18, data.v12);
when ft_textual => field.native := (ft_textual, data.v13);
when ft_widetext => field.native := (ft_widetext, data.v14);
when ft_supertext => field.native := (ft_supertext, data.v15);
when ft_timestamp => field.native := (ft_timestamp, data.v16);
when ft_chain => field.native := (ft_chain, data.v17);
when ft_enumtype => field.native := (ft_enumtype, data.v18);
when ft_settype => field.native := (ft_settype, data.v19);
when ft_bits => field.native := (ft_bits, data.v20);
when ft_utf8 => field.native := (ft_utf8, data.v21);
when ft_geometry => field.native := (ft_geometry, data.v22);
end case;
field.explicit_null := exnull;
end set;
end AdaBase.Results.Field;
|
-- Copyright (c) 2020-2021 Bartek thindil Jasicki <thindil@laeran.pl>
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
with Ada.Characters.Handling; use Ada.Characters.Handling;
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with Ada.Strings; use Ada.Strings;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Ada.Strings.UTF_Encoding.Wide_Strings;
use Ada.Strings.UTF_Encoding.Wide_Strings;
with Ada.Text_IO; use Ada.Text_IO;
with Interfaces.C.Strings; use Interfaces.C.Strings;
with GNAT.Directory_Operations; use GNAT.Directory_Operations;
with Tcl.Ada; use Tcl.Ada;
with Tcl.Tk.Ada; use Tcl.Tk.Ada;
with Tcl.Tk.Ada.Grid;
with Tcl.Tk.Ada.Pack;
with Tcl.Tk.Ada.Widgets; use Tcl.Tk.Ada.Widgets;
with Tcl.Tk.Ada.Widgets.Text; use Tcl.Tk.Ada.Widgets.Text;
with Tcl.Tk.Ada.Widgets.Toplevel.MainWindow;
use Tcl.Tk.Ada.Widgets.Toplevel.MainWindow;
with Tcl.Tk.Ada.Widgets.TtkButton; use Tcl.Tk.Ada.Widgets.TtkButton;
with Tcl.Tk.Ada.Widgets.TtkEntry.TtkComboBox;
use Tcl.Tk.Ada.Widgets.TtkEntry.TtkComboBox;
with Tcl.Tk.Ada.Widgets.TtkFrame; use Tcl.Tk.Ada.Widgets.TtkFrame;
with Tcl.Tk.Ada.Widgets.TtkLabel; use Tcl.Tk.Ada.Widgets.TtkLabel;
with Tcl.Tk.Ada.Widgets.TtkPanedWindow; use Tcl.Tk.Ada.Widgets.TtkPanedWindow;
with Tcl.Tk.Ada.Widgets.TtkWidget; use Tcl.Tk.Ada.Widgets.TtkWidget;
with Tcl.Tk.Ada.Winfo; use Tcl.Tk.Ada.Winfo;
with Tcl.Tk.Ada.Wm; use Tcl.Tk.Ada.Wm;
with Tcl.Tklib.Ada.Tooltip; use Tcl.Tklib.Ada.Tooltip;
with Bases; use Bases;
with Bases.LootUI;
with Bases.RecruitUI;
with Bases.SchoolUI;
with Bases.ShipyardUI;
with Bases.UI;
with BasesTypes; use BasesTypes;
with Config; use Config;
with Crafts.UI;
with CoreUI; use CoreUI;
with Crew; use Crew;
with Dialogs; use Dialogs;
with DebugUI; use DebugUI;
with Factions; use Factions;
with GameOptions;
with Help.UI; use Help.UI;
with Items; use Items;
with Knowledge; use Knowledge;
with Log;
with Maps.UI.Commands;
with Messages; use Messages;
with Messages.UI; use Messages.UI;
with Missions.UI; use Missions.UI;
with OrdersMenu;
with ShipModules; use ShipModules;
with Ships.Cargo; use Ships.Cargo;
with Ships.Movement; use Ships.Movement;
with Ships.UI; use Ships.UI;
with Statistics; use Statistics;
with Statistics.UI;
with Stories; use Stories;
with Trades.UI;
with Themes; use Themes;
with Utils.UI; use Utils.UI;
with WaitMenu;
package body Maps.UI is
procedure CreateGameMenu is
begin
Delete(GameMenu, "0", "end");
Menu.Add
(GameMenu, "command",
"-label {Ship information} -command ShowShipInfo");
Menu.Add
(GameMenu, "command", "-label {Ship orders} -command ShowOrders");
Menu.Add(GameMenu, "command", "-label {Crafting} -command ShowCrafting");
Menu.Add
(GameMenu, "command",
"-label {Last messages} -command ShowLastMessages");
Menu.Add
(GameMenu, "command",
"-label {Knowledge lists} -command ShowKnowledge");
Menu.Add(GameMenu, "command", "-label {Wait orders} -command ShowWait");
Menu.Add
(GameMenu, "command", "-label {Game statistics} -command ShowStats");
Menu.Add
(GameMenu, "command", "-label {Help} -command {ShowHelp general}");
Menu.Add
(GameMenu, "command", "-label {Game options} -command ShowOptions");
Menu.Add
(GameMenu, "command", "-label {Quit from game} -command QuitGame");
Menu.Add
(GameMenu, "command", "-label {Resign from game} -command ResignGame");
Menu.Add(GameMenu, "command", "-label Close -accelerator Escape");
Set_Accelerators_Loop :
for I in MenuAccelerators'Range loop
Entry_Configure
(GameMenu, Natural'Image(I - 1),
"-accelerator {" & To_String(MenuAccelerators(I)) & "}");
end loop Set_Accelerators_Loop;
end CreateGameMenu;
procedure UpdateHeader is
HaveWorker, HaveGunner: Boolean := True;
NeedCleaning, NeedRepairs, NeedWorker, HavePilot, HaveEngineer,
HaveTrader, HaveUpgrader, HaveCleaner, HaveRepairman: Boolean := False;
ItemAmount: Natural := 0;
Label: Ttk_Label := Get_Widget(Game_Header & ".time");
Frame: constant Ttk_Frame := Get_Widget(Main_Paned & ".combat");
begin
configure(Label, "-text {" & FormatedTime & "}");
if Game_Settings.Show_Numbers then
configure
(Label,
"-text {" & FormatedTime & " Speed:" &
Natural'Image((RealSpeed(Player_Ship) * 60) / 1_000) & " km/h}");
Add(Label, "Game time and current ship speed.");
end if;
Label.Name := New_String(Game_Header & ".nofuel");
Tcl.Tk.Ada.Grid.Grid_Remove(Label);
ItemAmount := GetItemAmount(Fuel_Type);
if ItemAmount = 0 then
configure(Label, "-style Headerred.TLabel");
Add
(Label,
"You can't travel anymore, because you don't have any fuel for ship.");
Tcl.Tk.Ada.Grid.Grid(Label);
elsif ItemAmount <= Game_Settings.Low_Fuel then
configure(Label, "-style TLabel");
Add
(Label,
"Low level of fuel on ship. Only" & Natural'Image(ItemAmount) &
" left.");
Tcl.Tk.Ada.Grid.Grid(Label);
end if;
Label.Name := New_String(Game_Header & ".nodrink");
Tcl.Tk.Ada.Grid.Grid_Remove(Label);
ItemAmount := GetItemsAmount("Drinks");
if ItemAmount = 0 then
configure(Label, "-style Headerred.TLabel");
Add
(Label,
"You don't have any drinks in ship but your crew needs them to live.");
Tcl.Tk.Ada.Grid.Grid(Label);
elsif ItemAmount <= Game_Settings.Low_Drinks then
configure(Label, "-style TLabel");
Add
(Label,
"Low level of drinks on ship. Only" & Natural'Image(ItemAmount) &
" left.");
Tcl.Tk.Ada.Grid.Grid(Label);
end if;
Label.Name := New_String(Game_Header & ".nofood");
Tcl.Tk.Ada.Grid.Grid_Remove(Label);
ItemAmount := GetItemsAmount("Food");
if ItemAmount = 0 then
configure(Label, "-style Headerred.TLabel");
Add
(Label,
"You don't have any food in ship but your crew needs it to live.");
Tcl.Tk.Ada.Grid.Grid(Label);
elsif ItemAmount <= Game_Settings.Low_Food then
configure(Label, "-style TLabel");
Add
(Label,
"Low level of food on ship. Only" & Natural'Image(ItemAmount) &
" left.");
Tcl.Tk.Ada.Grid.Grid(Label);
end if;
for Member of Player_Ship.Crew loop
case Member.Order is
when Pilot =>
HavePilot := True;
when Engineer =>
HaveEngineer := True;
when Talk =>
HaveTrader := True;
when Upgrading =>
HaveUpgrader := True;
when Clean =>
HaveCleaner := True;
when Repair =>
HaveRepairman := True;
when others =>
null;
end case;
end loop;
Label.Name := New_String(Game_Header & ".overloaded");
Tcl.Tk.Ada.Grid.Grid_Remove(Label);
if HavePilot and
(HaveEngineer or
Factions_List(Player_Ship.Crew(1).Faction).Flags.Contains
(To_Unbounded_String("sentientships"))) and
(Winfo_Get(Frame, "exists") = "0"
or else (Winfo_Get(Frame, "ismapped") = "0")) then
declare
type SpeedType is digits 2;
Speed: constant SpeedType :=
(if Player_Ship.Speed /= DOCKED then
(SpeedType(RealSpeed(Player_Ship)) / 1_000.0)
else (SpeedType(RealSpeed(Player_Ship, True)) / 1_000.0));
begin
if Speed < 0.5 then
configure(Label, "-style Headerred.TLabel");
Add
(Label,
"You can't fly with your ship, because it is overloaded.");
Tcl.Tk.Ada.Grid.Grid(Label);
end if;
end;
end if;
Check_Workers_Loop :
for Module of Player_Ship.Modules loop
case Modules_List(Module.Proto_Index).MType is
when GUN | HARPOON_GUN =>
if Module.Owner(1) = 0 then
HaveGunner := False;
elsif Player_Ship.Crew(Module.Owner(1)).Order /= Gunner then
HaveGunner := False;
end if;
when ALCHEMY_LAB .. GREENHOUSE =>
if Module.Crafting_Index /= Null_Unbounded_String then
NeedWorker := True;
Check_Owners_Loop :
for Owner of Module.Owner loop
if Owner = 0 then
HaveWorker := False;
elsif Player_Ship.Crew(Owner).Order /= Craft then
HaveWorker := False;
end if;
exit Check_Owners_Loop when not HaveWorker;
end loop Check_Owners_Loop;
end if;
when CABIN =>
if Module.Cleanliness /= Module.Quality then
NeedCleaning := True;
end if;
when others =>
null;
end case;
if Module.Durability /= Module.Max_Durability then
NeedRepairs := True;
end if;
end loop Check_Workers_Loop;
Label.Name := New_String(Game_Header & ".pilot");
if HavePilot then
Tcl.Tk.Ada.Grid.Grid_Remove(Label);
else
if not Factions_List(Player_Ship.Crew(1).Faction).Flags.Contains
(To_Unbounded_String("sentientships")) then
configure(Label, "-style Headerred.TLabel");
Add(Label, "No pilot assigned. Ship can't move.");
else
configure(Label, "-style TLabel");
Add(Label, "No pilot assigned. Ship fly on it own.");
end if;
Tcl.Tk.Ada.Grid.Grid(Label);
end if;
Label.Name := New_String(Game_Header & ".engineer");
if HaveEngineer then
Tcl.Tk.Ada.Grid.Grid_Remove(Label);
else
if not Factions_List(Player_Ship.Crew(1).Faction).Flags.Contains
(To_Unbounded_String("sentientships")) then
configure(Label, "-style Headerred.TLabel");
Add(Label, "No engineer assigned. Ship can't move.");
else
configure(Label, "-style TLabel");
Add(Label, "No engineer assigned. Ship fly on it own.");
end if;
Tcl.Tk.Ada.Grid.Grid(Label);
end if;
Label.Name := New_String(Game_Header & ".gunner");
if HaveGunner then
Tcl.Tk.Ada.Grid.Grid_Remove(Label);
else
configure(Label, "-style Headerred.TLabel");
Add(Label, "One or more guns don't have a gunner.");
Tcl.Tk.Ada.Grid.Grid(Label);
end if;
Label.Name := New_String(Game_Header & ".repairs");
if NeedRepairs then
if HaveRepairman then
configure(Label, "-style Headergreen.TLabel");
Add(Label, "The ship is being repaired.");
else
configure(Label, "-style Headerred.TLabel");
Add(Label, "The ship needs repairs but no one is working them.");
end if;
Tcl.Tk.Ada.Grid.Grid(Label);
else
Tcl.Tk.Ada.Grid.Grid_Remove(Label);
end if;
Label.Name := New_String(Game_Header & ".crafting");
if NeedWorker then
if HaveWorker then
configure(Label, "-style Headergreen.TLabel");
Add(Label, "All crafting orders are being executed.");
else
configure(Label, "-style Headerred.TLabel");
Add
(Label,
"You need to assign crew members to begin manufacturing.");
end if;
Tcl.Tk.Ada.Grid.Grid(Label);
else
Tcl.Tk.Ada.Grid.Grid_Remove(Label);
end if;
Label.Name := New_String(Game_Header & ".upgrade");
if Player_Ship.Upgrade_Module > 0 then
if HaveUpgrader then
configure(Label, "-style Headergreen.TLabel");
Add(Label, "A ship module upgrade in progress.");
else
configure(Label, "-style Headerred.TLabel");
Add
(Label,
"A ship module upgrade is in progress but no one is working on it.");
end if;
Tcl.Tk.Ada.Grid.Grid(Label);
else
Tcl.Tk.Ada.Grid.Grid_Remove(Label);
end if;
Label.Name := New_String(Game_Header & ".talk");
if HaveTrader then
Tcl.Tk.Ada.Grid.Grid_Remove(Label);
elsif SkyMap(Player_Ship.Sky_X, Player_Ship.Sky_Y).BaseIndex > 0 then
configure(Label, "-style Headerred.TLabel");
Add(Label, "No trader assigned. You need one to talk/trade.");
Tcl.Tk.Ada.Grid.Grid(Label);
elsif SkyMap(Player_Ship.Sky_X, Player_Ship.Sky_Y).EventIndex > 0 then
if Events_List
(SkyMap(Player_Ship.Sky_X, Player_Ship.Sky_Y).EventIndex)
.EType =
FriendlyShip then
configure(Label, "-style Headerred.TLabel");
Add(Label, "No trader assigned. You need one to talk/trade.");
Tcl.Tk.Ada.Grid.Grid(Label);
else
Tcl.Tk.Ada.Grid.Grid_Remove(Label);
end if;
else
Tcl.Tk.Ada.Grid.Grid_Remove(Label);
end if;
Label.Name := New_String(Game_Header & ".clean");
if NeedCleaning then
if HaveCleaner then
configure(Label, "-style Headergreen.TLabel");
Add(Label, "Ship is cleaned.");
else
configure(Label, "-style Headerred.TLabel");
Add(Label, "Ship is dirty but no one is cleaning it.");
end if;
Tcl.Tk.Ada.Grid.Grid(Label);
else
Tcl.Tk.Ada.Grid.Grid_Remove(Label);
end if;
if Player_Ship.Crew(1).Health = 0 then
ShowQuestion
("You are dead. Would you like to see your game statistics?",
"showstats");
end if;
end UpdateHeader;
-- ****iv* MUI/MUI.MapView
-- FUNCTION
-- Text widget with the sky map
-- SOURCE
MapView: Tk_Text;
-- ****
procedure DrawMap is
MapChar: Wide_Character;
EndX, EndY: Integer;
MapHeight, MapWidth: Positive;
MapTag: Unbounded_String;
StoryX, StoryY: Natural := 1;
CurrentTheme: constant Theme_Record :=
Themes_List(To_String(Game_Settings.Interface_Theme));
begin
configure(MapView, "-state normal");
Delete(MapView, "1.0", "end");
MapHeight := Positive'Value(cget(MapView, "-height"));
MapWidth := Positive'Value(cget(MapView, "-width"));
StartY := CenterY - (MapHeight / 2);
StartX := CenterX - (MapWidth / 2);
EndY := CenterY + (MapHeight / 2);
EndX := CenterX + (MapWidth / 2);
if StartY < 1 then
StartY := 1;
EndY := MapHeight;
end if;
if StartX < 1 then
StartX := 1;
EndX := MapWidth;
end if;
if EndY > 1_024 then
EndY := 1_024;
StartY := 1_025 - MapHeight;
end if;
if EndX > 1_024 then
EndX := 1_024;
StartX := 1_025 - MapWidth;
end if;
if CurrentStory.Index /= Null_Unbounded_String then
GetStoryLocation(StoryX, StoryY);
if StoryX = Player_Ship.Sky_X and StoryY = Player_Ship.Sky_Y then
StoryX := 0;
StoryY := 0;
end if;
end if;
if Player_Ship.Speed = DOCKED and
SkyMap(Player_Ship.Sky_X, Player_Ship.Sky_Y).BaseIndex = 0 then
Player_Ship.Speed := Ships.FULL_STOP;
end if;
Draw_Map_Loop :
for Y in StartY .. EndY loop
for X in StartX .. EndX loop
MapTag := Null_Unbounded_String;
if X = Player_Ship.Sky_X and Y = Player_Ship.Sky_Y then
MapChar := CurrentTheme.Player_Ship_Icon;
else
MapChar := CurrentTheme.Empty_Map_Icon;
MapTag :=
(if SkyMap(X, Y).Visited then To_Unbounded_String("black")
else To_Unbounded_String("unvisited gray"));
if X = Player_Ship.Destination_X and
Y = Player_Ship.Destination_Y then
MapChar := CurrentTheme.Target_Icon;
MapTag :=
(if SkyMap(X, Y).Visited then Null_Unbounded_String
else To_Unbounded_String("unvisited"));
elsif CurrentStory.Index /= Null_Unbounded_String
and then (X = StoryX and Y = StoryY) then
MapChar := CurrentTheme.Story_Icon;
MapTag := To_Unbounded_String("green");
elsif SkyMap(X, Y).MissionIndex > 0 then
case AcceptedMissions(SkyMap(X, Y).MissionIndex).MType is
when Deliver =>
MapChar := CurrentTheme.Deliver_Icon;
MapTag := To_Unbounded_String("yellow");
when Destroy =>
MapChar := CurrentTheme.Destroy_Icon;
MapTag := To_Unbounded_String("red");
when Patrol =>
MapChar := CurrentTheme.Patrol_Icon;
MapTag := To_Unbounded_String("lime");
when Explore =>
MapChar := CurrentTheme.Explore_Icon;
MapTag := To_Unbounded_String("green");
when Passenger =>
MapChar := CurrentTheme.Passenger_Icon;
MapTag := To_Unbounded_String("cyan");
end case;
if not SkyMap(X, Y).Visited then
Append(MapTag, " unvisited");
end if;
elsif SkyMap(X, Y).EventIndex > 0 then
if SkyMap(X, Y).EventIndex > Events_List.Last_Index then
SkyMap(X, Y).EventIndex := 0;
else
case Events_List(SkyMap(X, Y).EventIndex).EType is
when EnemyShip =>
MapChar := CurrentTheme.Enemy_Ship_Icon;
MapTag := To_Unbounded_String("red");
when AttackOnBase =>
MapChar := CurrentTheme.Attack_On_Base_Icon;
MapTag := To_Unbounded_String("red2");
when EnemyPatrol =>
MapChar := CurrentTheme.Enemy_Patrol_Icon;
MapTag := To_Unbounded_String("red3");
when Disease =>
MapChar := CurrentTheme.Disease_Icon;
MapTag := To_Unbounded_String("yellow");
when FullDocks =>
MapChar := CurrentTheme.Full_Docks_Icon;
MapTag := To_Unbounded_String("cyan");
when DoublePrice =>
MapChar := CurrentTheme.Double_Price_Icon;
MapTag := To_Unbounded_String("lime");
when Trader =>
MapChar := CurrentTheme.Trader_Icon;
MapTag := To_Unbounded_String("green");
when FriendlyShip =>
MapChar := CurrentTheme.Friendly_Ship_Icon;
MapTag := To_Unbounded_String("green2");
when others =>
null;
end case;
end if;
if not SkyMap(X, Y).Visited then
Append(MapTag, " unvisited");
end if;
elsif SkyMap(X, Y).BaseIndex > 0 then
MapChar := CurrentTheme.Not_Visited_Base_Icon;
if Sky_Bases(SkyMap(X, Y).BaseIndex).Known then
if Sky_Bases(SkyMap(X, Y).BaseIndex).Visited.Year > 0 then
MapChar :=
Factions_List
(Sky_Bases(SkyMap(X, Y).BaseIndex).Owner)
.BaseIcon;
MapTag := Sky_Bases(SkyMap(X, Y).BaseIndex).Base_Type;
else
MapTag := To_Unbounded_String("unvisited");
end if;
else
MapTag := To_Unbounded_String("unvisited gray");
end if;
end if;
end if;
Insert
(MapView, "end",
Encode("" & MapChar) & " [list " & To_String(MapTag) & "]");
end loop;
if Y < EndY then
Insert(MapView, "end", "{" & LF & "}");
end if;
end loop Draw_Map_Loop;
configure(MapView, "-state disable");
end DrawMap;
procedure UpdateMapInfo
(X: Positive := Player_Ship.Sky_X; Y: Positive := Player_Ship.Sky_Y) is
MapInfoText, EventInfoText: Unbounded_String;
MapInfo: constant Ttk_Label :=
Get_Widget(Main_Paned & ".mapframe.info.info");
EventInfo: constant Ttk_Label :=
Get_Widget(Main_Paned & ".mapframe.info.eventinfo");
begin
Append
(MapInfoText, "X:" & Positive'Image(X) & " Y:" & Positive'Image(Y));
if Player_Ship.Sky_X /= X or Player_Ship.Sky_Y /= Y then
declare
Distance: constant Positive := CountDistance(X, Y);
begin
Append(MapInfoText, LF & "Distance:" & Positive'Image(Distance));
Travel_Info(MapInfoText, Distance);
end;
end if;
if SkyMap(X, Y).BaseIndex > 0 then
declare
BaseIndex: constant Bases_Range := SkyMap(X, Y).BaseIndex;
begin
if Sky_Bases(BaseIndex).Known then
Append
(MapInfoText,
LF & "Base info:" & LF & To_Unbounded_String("Name: ") &
Sky_Bases(BaseIndex).Name);
end if;
if Sky_Bases(BaseIndex).Visited.Year > 0 then
Append
(MapInfoText,
LF & "Type: " &
To_String
(Bases_Types_List(Sky_Bases(BaseIndex).Base_Type).Name));
if Sky_Bases(BaseIndex).Population > 0 then
Append(MapInfoText, LF);
end if;
if Sky_Bases(BaseIndex).Population > 0 and
Sky_Bases(BaseIndex).Population < 150 then
Append(MapInfoText, "Population: small");
elsif Sky_Bases(BaseIndex).Population > 149 and
Sky_Bases(BaseIndex).Population < 300 then
Append(MapInfoText, "Population: medium");
elsif Sky_Bases(BaseIndex).Population > 299 then
Append(MapInfoText, "Population: large");
end if;
Append
(MapInfoText,
LF & "Size: " &
To_Lower(Bases_Size'Image(Sky_Bases(BaseIndex).Size)) & LF);
if Sky_Bases(BaseIndex).Population > 0 then
Append
(MapInfoText,
"Owner: " &
To_String
(Factions_List(Sky_Bases(BaseIndex).Owner).Name));
else
Append(MapInfoText, "Base is abandoned");
end if;
if Sky_Bases(BaseIndex).Population > 0 then
Append(MapInfoText, LF);
case Sky_Bases(BaseIndex).Reputation(1) is
when -100 .. -75 =>
Append(MapInfoText, "You are hated here");
when -74 .. -50 =>
Append(MapInfoText, "You are outlawed here");
when -49 .. -25 =>
Append(MapInfoText, "You are disliked here");
when -24 .. -1 =>
Append(MapInfoText, "They are unfriendly to you");
when 0 =>
Append(MapInfoText, "You are unknown here");
when 1 .. 25 =>
Append(MapInfoText, "You are know here as visitor");
when 26 .. 50 =>
Append(MapInfoText, "You are know here as trader");
when 51 .. 75 =>
Append(MapInfoText, "You are know here as friend");
when 76 .. 100 =>
Append(MapInfoText, "You are well known here");
when others =>
null;
end case;
end if;
if BaseIndex = Player_Ship.Home_Base then
Append(MapInfoText, LF & "It is your home base");
end if;
end if;
end;
end if;
if SkyMap(X, Y).EventIndex > 0 then
declare
EventIndex: constant Events_Container.Extended_Index :=
SkyMap(X, Y).EventIndex;
begin
if Events_List(EventIndex).EType /= BaseRecovery then
Append(EventInfoText, LF);
end if;
case Events_List(EventIndex).EType is
when EnemyShip | Trader | FriendlyShip =>
Append
(EventInfoText,
Proto_Ships_List(Events_List(EventIndex).ShipIndex).Name);
when FullDocks =>
Append(EventInfoText, "Full docks in base");
when AttackOnBase =>
Append(EventInfoText, "Base is under attack");
when Disease =>
Append(EventInfoText, "Disease in base");
when EnemyPatrol =>
Append(EventInfoText, "Enemy patrol");
when DoublePrice =>
Append
(EventInfoText,
"Double price for " &
To_String
(Items_List(Events_List(EventIndex).ItemIndex).Name));
when None | BaseRecovery =>
null;
end case;
if Events_List(EventIndex).EType in DoublePrice | FriendlyShip |
Trader then
configure
(EventInfo,
"-text {" & To_String(EventInfoText) &
"} -style MapInfoGreen.TLabel");
else
configure
(EventInfo,
"-text {" & To_String(EventInfoText) &
"} -style MapInfoRed.TLabel");
end if;
end;
end if;
if SkyMap(X, Y).MissionIndex > 0 then
declare
MissionIndex: constant Mission_Container.Extended_Index :=
SkyMap(X, Y).MissionIndex;
begin
Append(MapInfoText, LF);
if SkyMap(X, Y).BaseIndex > 0 or SkyMap(X, Y).EventIndex > 0 then
Append(MapInfoText, LF);
end if;
case AcceptedMissions(MissionIndex).MType is
when Deliver =>
Append
(MapInfoText,
"Deliver " &
To_String
(Items_List(AcceptedMissions(MissionIndex).ItemIndex)
.Name));
when Destroy =>
Append
(MapInfoText,
"Destroy " &
To_String
(Proto_Ships_List
(AcceptedMissions(MissionIndex).ShipIndex)
.Name));
when Patrol =>
Append(MapInfoText, "Patrol area");
when Explore =>
Append(MapInfoText, "Explore area");
when Passenger =>
Append(MapInfoText, "Transport passenger");
end case;
end;
end if;
if CurrentStory.Index /= Null_Unbounded_String then
declare
StoryX, StoryY: Natural := 1;
FinishCondition: StepConditionType;
begin
GetStoryLocation(StoryX, StoryY);
if StoryX = Player_Ship.Sky_X and StoryY = Player_Ship.Sky_Y then
StoryX := 0;
StoryY := 0;
end if;
if X = StoryX and Y = StoryY then
FinishCondition :=
(if CurrentStory.CurrentStep = 0 then
Stories_List(CurrentStory.Index).StartingStep
.FinishCondition
elsif CurrentStory.CurrentStep > 0 then
Stories_List(CurrentStory.Index).Steps
(CurrentStory.CurrentStep)
.FinishCondition
else Stories_List(CurrentStory.Index).FinalStep
.FinishCondition);
if FinishCondition in ASKINBASE | DESTROYSHIP | EXPLORE then
Append(MapInfoText, LF & "Story leads you here");
end if;
end if;
end;
end if;
if X = Player_Ship.Sky_X and Y = Player_Ship.Sky_Y then
Append(MapInfoText, LF & "You are here");
end if;
configure(MapInfo, "-text {" & To_String(MapInfoText) & "}");
if EventInfoText /= Null_Unbounded_String then
Tcl.Tk.Ada.Grid.Grid(EventInfo, "-sticky nwes");
else
Tcl.Tk.Ada.Grid.Grid_Remove(EventInfo);
end if;
end UpdateMapInfo;
procedure UpdateMoveButtons is
MoveButtonsNames: constant array(1 .. 8) of Unbounded_String :=
(To_Unbounded_String("nw"), To_Unbounded_String("n"),
To_Unbounded_String("ne"), To_Unbounded_String("w"),
To_Unbounded_String("e"), To_Unbounded_String("sw"),
To_Unbounded_String("s"), To_Unbounded_String("se"));
MoveButtonsTooltips: constant array(1 .. 8) of Unbounded_String :=
(To_Unbounded_String("Move ship north and west"),
To_Unbounded_String("Move ship north"),
To_Unbounded_String("Move ship north and east"),
To_Unbounded_String("Move ship west"),
To_Unbounded_String("Move ship east"),
To_Unbounded_String("Move ship south and west"),
To_Unbounded_String("Move ship south"),
To_Unbounded_String("Move ship south and east"));
Button: Ttk_Button;
FrameName: constant String := Main_Paned & ".controls.buttons";
Speedbox: constant Ttk_ComboBox := Get_Widget(FrameName & ".speed");
begin
Button.Interp := Get_Context;
if Player_Ship.Speed = DOCKED then
Tcl.Tk.Ada.Grid.Grid_Remove(Speedbox);
Button.Name := New_String(FrameName & ".moveto");
Tcl.Tk.Ada.Grid.Grid_Remove(Button);
Button.Name := New_String(FrameName & ".wait");
configure(Button, "-text Wait");
Add(Button, "Wait 1 minute.");
Disable_Move_Buttons_Loop :
for ButtonName of MoveButtonsNames loop
Button.Name := New_String(FrameName & "." & To_String(ButtonName));
State(Button, "disabled");
Add
(Button,
"You have to give order 'Undock' from\nMenu->Ship orders first to move ship.");
end loop Disable_Move_Buttons_Loop;
else
Current
(Speedbox, Natural'Image(Ship_Speed'Pos(Player_Ship.Speed) - 1));
Tcl.Tk.Ada.Grid.Grid(Speedbox);
if Player_Ship.Destination_X > 0 and
Player_Ship.Destination_Y > 0 then
Button.Name := New_String(FrameName & ".moveto");
Tcl.Tk.Ada.Grid.Grid(Button);
Tcl.Tk.Ada.Grid.Grid_Configure(Speedbox, "-columnspan 2");
Button.Name := New_String(FrameName & ".wait");
configure(Button, "-text Move");
Add(Button, "Move ship one map field toward destination.");
Tcl.Tk.Ada.Grid.Grid(Button);
else
Button.Name := New_String(FrameName & ".moveto");
Tcl.Tk.Ada.Grid.Grid_Remove(Button);
Tcl.Tk.Ada.Grid.Grid_Configure(Speedbox, "-columnspan 3");
Button.Name := New_String(FrameName & ".wait");
configure(Button, "-text Wait");
Add(Button, "Wait 1 minute.");
end if;
Enable_Move_Buttons_Loop :
for I in MoveButtonsNames'Range loop
Button.Name :=
New_String(FrameName & "." & To_String(MoveButtonsNames(I)));
State(Button, "!disabled");
Add(Button, To_String(MoveButtonsTooltips(I)));
end loop Enable_Move_Buttons_Loop;
end if;
end UpdateMoveButtons;
procedure CreateGameUI is
use Log;
GameFrame: constant Ttk_Frame := Get_Widget(".gameframe");
Paned: constant Ttk_PanedWindow := Get_Widget(GameFrame & ".paned");
Button: constant Ttk_Button :=
Get_Widget(Paned & ".mapframe.buttons.hide");
SteamSky_Map_Error: exception;
Header: constant Ttk_Frame := Get_Widget(GameFrame & ".header");
MessagesFrame: constant Ttk_Frame :=
Get_Widget(Paned & ".controls.messages");
PanedPosition: Natural;
begin
GameMenu := Get_Widget(".gamemenu");
MapView := Get_Widget(Paned & ".mapframe.map");
if Winfo_Get(GameMenu, "exists") = "0" then
declare
KeysFile: File_Type;
begin
Open(KeysFile, In_File, To_String(Save_Directory) & "keys.cfg");
Set_Menu_Accelerators_Loop :
for Key of MenuAccelerators loop
Key := To_Unbounded_String(Get_Line(KeysFile));
end loop Set_Menu_Accelerators_Loop;
Set_Map_Accelerators_Loop :
for Key of MapAccelerators loop
Key := To_Unbounded_String(Get_Line(KeysFile));
end loop Set_Map_Accelerators_Loop;
FullScreenAccel := To_Unbounded_String(Get_Line(KeysFile));
Close(KeysFile);
exception
when others =>
if Dir_Separator = '\' then
MapAccelerators(5) := To_Unbounded_String(Source => "Home");
MapAccelerators(6) := To_Unbounded_String(Source => "Up");
MapAccelerators(7) := To_Unbounded_String(Source => "Prior");
MapAccelerators(8) := To_Unbounded_String(Source => "Left");
MapAccelerators(9) := To_Unbounded_String(Source => "Clear");
MapAccelerators(10) :=
To_Unbounded_String(Source => "Right");
MapAccelerators(11) := To_Unbounded_String(Source => "End");
MapAccelerators(12) := To_Unbounded_String(Source => "Down");
MapAccelerators(13) := To_Unbounded_String(Source => "Next");
MapAccelerators(14) :=
To_Unbounded_String(Source => "slash");
MapAccelerators(17) :=
To_Unbounded_String(Source => "Shift-Home");
MapAccelerators(18) :=
To_Unbounded_String(Source => "Shift-Up");
MapAccelerators(19) :=
To_Unbounded_String(Source => "Shift-Prior");
MapAccelerators(20) :=
To_Unbounded_String(Source => "Shift-Left");
MapAccelerators(21) :=
To_Unbounded_String(Source => "Shift-Right");
MapAccelerators(22) :=
To_Unbounded_String(Source => "Shift-End");
MapAccelerators(23) :=
To_Unbounded_String(Source => "Shift-Down");
MapAccelerators(24) :=
To_Unbounded_String(Source => "Shift-Next");
MapAccelerators(25) :=
To_Unbounded_String(Source => "Control-Home");
MapAccelerators(26) :=
To_Unbounded_String(Source => "Control-Up");
MapAccelerators(27) :=
To_Unbounded_String(Source => "Control-Prior");
MapAccelerators(28) :=
To_Unbounded_String(Source => "Control-Left");
MapAccelerators(29) :=
To_Unbounded_String(Source => "Control-Right");
MapAccelerators(30) :=
To_Unbounded_String(Source => "Control-End");
MapAccelerators(31) :=
To_Unbounded_String(Source => "Control-Down");
MapAccelerators(32) :=
To_Unbounded_String(Source => "Control-Next");
end if;
end;
Tcl_EvalFile
(Get_Context,
To_String(Data_Directory) & "ui" & Dir_Separator & "game.tcl");
Main_Paned := Paned;
Game_Header := Header;
Close_Button := Get_Widget(Game_Header & ".closebutton");
Set_Theme;
OrdersMenu.AddCommands;
Maps.UI.Commands.AddCommands;
WaitMenu.AddCommands;
Help.UI.AddCommands;
Ships.UI.AddCommands;
Crafts.UI.AddCommands;
Messages.UI.AddCommands;
GameOptions.AddCommands;
Trades.UI.AddCommands;
SchoolUI.AddCommands;
RecruitUI.AddCommands;
Bases.UI.AddCommands;
ShipyardUI.AddCommands;
LootUI.AddCommands;
Knowledge.AddCommands;
Missions.UI.AddCommands;
Statistics.UI.AddCommands;
Bind(MessagesFrame, "<Configure>", "ResizeLastMessages");
Bind(MapView, "<Configure>", "DrawMap");
Bind(MapView, "<Motion>", "{UpdateMapInfo %x %y}");
Bind
(MapView,
"<Button-" & (if Game_Settings.Right_Button then "3" else "1") &
">",
"{ShowDestinationMenu %X %Y}");
Bind
(MapView, "<MouseWheel>",
"{if {%D > 0} {ZoomMap raise} else {ZoomMap lower}}");
Bind(MapView, "<Button-4>", "{ZoomMap raise}");
Bind(MapView, "<Button-5>", "{ZoomMap lower}");
SetKeys;
if Log.Debug_Mode = Log.MENU then
ShowDebugUI;
end if;
else
Tcl.Tk.Ada.Pack.Pack(GameFrame, "-fill both -expand true");
end if;
Wm_Set(Get_Main_Window(Get_Context), "title", "{Steam Sky}");
if Game_Settings.Full_Screen then
Wm_Set(Get_Main_Window(Get_Context), "attributes", "-fullscreen 1");
end if;
CreateGameMenu;
Set_Accelerators_Loop :
for I in MenuAccelerators'Range loop
Bind_To_Main_Window
(Get_Context,
"<" &
To_String
(Insert
(MenuAccelerators(I),
Index(MenuAccelerators(I), "-", Backward) + 1,
"KeyPress-")) &
">",
"{InvokeMenu " & To_String(MenuAccelerators(I)) & "}");
Bind
(GameMenu,
"<" &
To_String
(Insert
(MenuAccelerators(I),
Index(MenuAccelerators(I), "-", Backward) + 1,
"KeyPress-")) &
">",
"{InvokeMenu " & To_String(MenuAccelerators(I)) & "}");
end loop Set_Accelerators_Loop;
Bind(GameMenu, "<KeyPress-Escape>", "{InvokeMenu 12}");
if Index
(Tcl.Tk.Ada.Grid.Grid_Slaves(Get_Main_Window(Get_Context)),
".gameframe.header") =
0 then
Tcl.Tk.Ada.Grid.Grid(Header);
end if;
UpdateHeader;
CenterX := Player_Ship.Sky_X;
CenterY := Player_Ship.Sky_Y;
Set_Tags_Loop :
for I in Bases_Types_List.Iterate loop
Tag_Configure
(MapView, To_String(BasesTypes_Container.Key(I)),
"-foreground #" & Bases_Types_List(I).Color);
end loop Set_Tags_Loop;
PanedPosition :=
(if Game_Settings.Window_Height - Game_Settings.Messages_Position < 0
then Game_Settings.Window_Height
else Game_Settings.Window_Height - Game_Settings.Messages_Position);
SashPos(Paned, "0", Natural'Image(PanedPosition));
if Index
(Tcl.Tk.Ada.Grid.Grid_Slaves(Get_Main_Window(Get_Context)),
".gameframe.paned") =
0 then
Tcl.Tk.Ada.Grid.Grid(Paned);
end if;
if Invoke(Button) /= "" then
raise SteamSky_Map_Error with "Can't hide map buttons";
end if;
Bind_To_Main_Window
(Get_Context, "<Escape>", "{InvokeButton " & Close_Button & "}");
Update_Messages;
UpdateMoveButtons;
UpdateMapInfo;
if not Game_Settings.Show_Last_Messages then
Tcl.Tk.Ada.Grid.Grid_Remove(MessagesFrame);
end if;
Tcl_SetVar(Get_Context, "shipname", To_String(Player_Ship.Name));
end CreateGameUI;
procedure ShowSkyMap(Clear: Boolean := False) is
begin
if Clear then
Show_Screen("mapframe");
end if;
UpdateHeader;
Tcl_Eval(Get_Context, "DrawMap");
UpdateMoveButtons;
Tcl_Eval(Get_Context, "update");
Update_Messages;
if CurrentStory.Index /= Null_Unbounded_String and
CurrentStory.ShowText then
if CurrentStory.CurrentStep > -2 then
ShowInfo(Text => To_String(GetCurrentStoryText), Title => "Story");
else
FinishStory;
if Player_Ship.Crew(1).Health = 0 then
ShowQuestion
("You are dead. Would you like to see your game statistics?",
"showstats");
end if;
end if;
CurrentStory.ShowText := False;
end if;
end ShowSkyMap;
procedure SetKeys is
Commands: constant array(MapAccelerators'Range) of Unbounded_String :=
(To_Unbounded_String
("{if {[winfo class [focus]] != {TEntry} && [tk busy status " &
Game_Header & "] == 0} {tk_popup " & GameMenu & " %X %Y}}"),
To_Unbounded_String
("{" & Main_Paned & ".mapframe.buttons.wait invoke}"),
To_Unbounded_String("{ZoomMap raise}"),
To_Unbounded_String("{ZoomMap lower}"),
To_Unbounded_String("{InvokeButton $bframe.nw}"),
To_Unbounded_String("{InvokeButton $bframe.n}"),
To_Unbounded_String("{InvokeButton $bframe.ne}"),
To_Unbounded_String("{InvokeButton $bframe.w}"),
To_Unbounded_String("{InvokeButton $bframe.wait}"),
To_Unbounded_String("{InvokeButton $bframe.e}"),
To_Unbounded_String("{InvokeButton $bframe.sw}"),
To_Unbounded_String("{InvokeButton $bframe.s}"),
To_Unbounded_String("{InvokeButton $bframe.se}"),
To_Unbounded_String("{InvokeButton $bframe.moveto}"),
To_Unbounded_String("{MoveMap centeronship}"),
To_Unbounded_String("{MoveMap centeronhome}"),
To_Unbounded_String("{MoveMap nw}"),
To_Unbounded_String("{MoveMap n}"),
To_Unbounded_String("{MoveMap ne}"),
To_Unbounded_String("{MoveMap w}"),
To_Unbounded_String("{MoveMap e}"),
To_Unbounded_String("{MoveMap sw}"),
To_Unbounded_String("{MoveMap s}"),
To_Unbounded_String("{MoveMap se}"),
To_Unbounded_String("{MoveCursor nw %x %y}"),
To_Unbounded_String("{MoveCursor n %x %y}"),
To_Unbounded_String("{MoveCursor ne %x %y}"),
To_Unbounded_String("{MoveCursor w %x %y}"),
To_Unbounded_String("{MoveCursor e %x %y}"),
To_Unbounded_String("{MoveCursor sw %x %y}"),
To_Unbounded_String("{MoveCursor s %x %y}"),
To_Unbounded_String("{MoveCursor se %x %y}"),
To_Unbounded_String("{MoveCursor click %x %y}"),
To_Unbounded_String
("{" & Main_Paned & ".controls.buttons.speed current 0}"),
To_Unbounded_String
("{" & Main_Paned & ".controls.buttons.speed current 1}"),
To_Unbounded_String
("{" & Main_Paned & ".controls.buttons.speed current 2}"),
To_Unbounded_String
("{" & Main_Paned & ".controls.buttons.speed current 3}"));
begin
for I in Commands'Range loop
Bind_To_Main_Window
(Get_Context,
"<" &
To_String
(Insert
(MapAccelerators(I),
Index(MapAccelerators(I), "-", Backward) + 1, "KeyPress-")) &
">",
To_String(Commands(I)));
end loop;
Bind_To_Main_Window
(Get_Context,
"<" &
To_String
(Insert
(FullScreenAccel, Index(FullScreenAccel, "-", Backward) + 1,
"KeyPress-")) &
">",
"{ToggleFullScreen}");
end SetKeys;
procedure FinishStory is
begin
GameStats.Points := GameStats.Points + (10_000 * CurrentStory.MaxSteps);
ClearCurrentStory;
ShowQuestion
(To_String(Stories_List(CurrentStory.Index).EndText) &
" Are you want to finish game?",
"retire");
end FinishStory;
end Maps.UI;
|
package body Ada.Containers.Composites is
function LE (Left, Right : Element_Type) return Boolean is
begin
return not (Right < Left);
end LE;
function GT (Left, Right : Element_Type) return Boolean is
begin
return Right < Left;
end GT;
function GE (Left, Right : Element_Type) return Boolean is
begin
return not (Left < Right);
end GE;
function Compare (Left, Right : Element_Type) return Integer is
begin
if Left < Right then
return -1;
elsif Right < Left then
return 1;
else
return 0;
end if;
end Compare;
function Composite (A : A_Type) return R_Type is
begin
return F2 (F1 (A));
end Composite;
function XXR_Bind_1st (A2 : A2_Type) return R_Type is
begin
return F (A1, A2);
end XXR_Bind_1st;
function XXR_Bind_2nd (A1 : A1_Type) return R_Type is
begin
return F (A1, A2);
end XXR_Bind_2nd;
function XR_Not (A1 : A1_Type) return Boolean is
begin
return not F (A1);
end XR_Not;
procedure XZ_Inout_1st (A1 : in out A1_Type; A2 : out A2_Type) is
pragma Unmodified (A1);
begin
P (A1, A2);
end XZ_Inout_1st;
end Ada.Containers.Composites;
|
with RASCAL.ToolboxQuit; use RASCAL.ToolboxQuit;
with RASCAL.TaskManager; use RASCAL.TaskManager;
with RASCAL.OS; use RASCAL.OS;
with RASCAL.Bugz; use RASCAL.Bugz;
package Controller_Bugz is
type MEL_Message_Bugz_Query is new AMEL_Message_Bugz_Query with null record;
type TEL_CreateReport_Type is new Toolbox_UserEventListener(16#21#,-1,-1) with null record;
--
-- A request from the Bugz application.
--
procedure Handle (The : in MEL_Message_Bugz_Query);
--
-- The user wants to create a bug report using !Bugz
--
procedure Handle (The : in TEL_CreateReport_Type);
end Controller_Bugz;
|
-- { dg-do compile }
package body overriding_ops is
task body Light_Programmer is
begin
accept Set_Name (Name : Name_Type);
end Light_Programmer;
protected body Light is
procedure Set_Name (Name : Name_Type) is
begin
L_Name := Name;
end Set_Name;
end Light;
end overriding_ops;
|
-- part of OpenGLAda, (c) 2017 Felix Krause
-- released under the terms of the MIT license, see the file "COPYING"
with GL.API;
with GL.Enums.Getter;
package body GL.Blending is
procedure Set_Blend_Func (Src_Factor, Dst_Factor : Blend_Factor) is
begin
API.Blend_Func (Src_Factor, Dst_Factor);
Raise_Exception_On_OpenGL_Error;
end Set_Blend_Func;
procedure Set_Blend_Func (Draw_Buffer : Buffers.Draw_Buffer_Index;
Src_Factor, Dst_Factor : Blend_Factor) is
begin
API.Blend_Func_I (Draw_Buffer, Src_Factor, Dst_Factor);
Raise_Exception_On_OpenGL_Error;
end Set_Blend_Func;
procedure Set_Blend_Func_Separate (Src_RGB, Dst_RGB, Src_Alpha, Dst_Alpha
: Blend_Factor) is
begin
API.Blend_Func_Separate (Src_RGB, Dst_RGB, Src_Alpha, Dst_Alpha);
Raise_Exception_On_OpenGL_Error;
end Set_Blend_Func_Separate;
procedure Set_Blend_Func_Separate (Draw_Buffer : Buffers.Draw_Buffer_Index;
Src_RGB, Dst_RGB, Src_Alpha, Dst_Alpha
: Blend_Factor) is
begin
API.Blend_Func_Separate_I (Draw_Buffer, Src_RGB, Dst_RGB,
Src_Alpha, Dst_Alpha);
Raise_Exception_On_OpenGL_Error;
end Set_Blend_Func_Separate;
function Blend_Func_Src_RGB return Blend_Factor is
Ret : aliased Blend_Factor;
begin
API.Get_Blend_Factor (Enums.Getter.Blend_Src_RGB, Ret'Access);
Raise_Exception_On_OpenGL_Error;
return Ret;
end Blend_Func_Src_RGB;
function Blend_Func_Src_Alpha return Blend_Factor is
Ret : aliased Blend_Factor;
begin
API.Get_Blend_Factor (Enums.Getter.Blend_Src_Alpha, Ret'Access);
Raise_Exception_On_OpenGL_Error;
return Ret;
end Blend_Func_Src_Alpha;
function Blend_Func_Dst_RGB return Blend_Factor is
Ret : aliased Blend_Factor;
begin
API.Get_Blend_Factor (Enums.Getter.Blend_Dst_RGB, Ret'Access);
Raise_Exception_On_OpenGL_Error;
return Ret;
end Blend_Func_Dst_RGB;
function Blend_Func_Dst_Alpha return Blend_Factor is
Ret : aliased Blend_Factor;
begin
API.Get_Blend_Factor (Enums.Getter.Blend_Dst_Alpha, Ret'Access);
Raise_Exception_On_OpenGL_Error;
return Ret;
end Blend_Func_Dst_Alpha;
procedure Set_Blend_Color (Value : Types.Colors.Color) is
use Types.Colors;
begin
API.Blend_Color (Value (R), Value (G), Value (B), Value (A));
Raise_Exception_On_OpenGL_Error;
end Set_Blend_Color;
function Blend_Color return Types.Colors.Color is
Ret : Types.Colors.Color;
begin
API.Get_Color (Enums.Getter.Blend_Color, Ret);
return Ret;
end Blend_Color;
procedure Set_Blend_Equation (Value : Equation) is
begin
API.Blend_Equation (Value);
Raise_Exception_On_OpenGL_Error;
end Set_Blend_Equation;
procedure Set_Blend_Equation (Draw_Buffer : Buffers.Draw_Buffer_Index;
Value : Equation) is
begin
API.Blend_Equation_I (Draw_Buffer, Value);
Raise_Exception_On_OpenGL_Error;
end Set_Blend_Equation;
procedure Set_Blend_Equation_Separate (RGB, Alpha : Equation) is
begin
API.Blend_Equation_Separate (RGB, Alpha);
Raise_Exception_On_OpenGL_Error;
end Set_Blend_Equation_Separate;
procedure Set_Blend_Equation_Separate
(Draw_Buffer : Buffers.Draw_Buffer_Index; RGB, Alpha : Equation) is
begin
API.Blend_Equation_Separate_I (Draw_Buffer, RGB, Alpha);
Raise_Exception_On_OpenGL_Error;
end Set_Blend_Equation_Separate;
function Blend_Equation_RGB return Equation is
Ret : aliased Equation;
begin
API.Get_Blend_Equation (Enums.Getter.Blend_Equation_RGB, Ret'Access);
Raise_Exception_On_OpenGL_Error;
return Ret;
end Blend_Equation_RGB;
function Blend_Equation_Alpha return Equation is
Ret : aliased Equation;
begin
API.Get_Blend_Equation (Enums.Getter.Blend_Equation_Alpha, Ret'Access);
Raise_Exception_On_OpenGL_Error;
return Ret;
end Blend_Equation_Alpha;
end GL.Blending;
|
with Ada.Command_Line, Ada.Text_IO;
procedure Command_Name is
begin
Ada.Text_IO.Put_Line(Ada.Command_Line.Command_Name);
end Command_Name;
|
-- { dg-do compile }
with Aggr4_Pkg; use Aggr4_Pkg;
package Aggr4 is
C : constant Rec3 := (Data => (D => One, Value => Zero));
end Aggr4;
|
-- part of AdaYaml, (c) 2017 Felix Krause
-- released under the terms of the MIT license, see the file "copying.txt"
with Yaml.Dom.Vectors;
with Yaml.Source;
with Yaml.Stream_Concept;
package Yaml.Dom.Loading is
-- equivalent to the composition of the "Parse" and "Compose" steps in the
-- YAML spec
function From_Source (Input : Source.Pointer) return Document_Reference;
function From_Source (Input : Source.Pointer) return Vectors.Vector;
-- as above, but does not read from an external source but from a String
function From_String (Input : String) return Document_Reference;
function From_String (Input : String) return Vectors.Vector;
generic
with package Stream is new Stream_Concept (<>);
package Stream_Loading is
-- equivalent to the "Compose" step in the YAML spec. Expects the input
-- to contain exactly one document, will raise a Compose_Error if the
-- stream contains multiple documents.
function Load_One (Input : in out Stream.Instance;
Pool : Text.Pool.Reference :=
Text.Pool.With_Capacity (Text.Pool.Default_Size))
return Document_Reference;
-- as above, but allows for multiple documents in a stream
function Load_All (Input : in out Stream.Instance;
Pool : Text.Pool.Reference :=
Text.Pool.With_Capacity (Text.Pool.Default_Size))
return Vectors.Vector
with Post => Integer (Load_All'Result.Length) > 0;
end Stream_Loading;
end Yaml.Dom.Loading;
|
-- { dg-do run }
-- { dg-options "-O3" }
-- PR tree-optimization/71083
with Loop_Optimization23_Pkg;
use Loop_Optimization23_Pkg;
procedure Loop_Optimization23 is
Test : ArrayOfStructB;
begin
Test (0).b.b := 9999;
Foo (Test);
if Test (100).b.b /= 9999 then
raise Program_Error;
end if;
end;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Localization, Internationalization, Globalization for Ada --
-- --
-- Tools Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2012-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$
------------------------------------------------------------------------------
with UAFLEX.Nodes;
with Ada.Containers;
with Ada.Containers.Ordered_Maps;
with Ada.Strings.Wide_Wide_Fixed;
with Ada.Wide_Wide_Text_IO;
with League.Character_Sets;
with Matreshka.Internals.Unicode.Ucd;
with Matreshka.Internals.Graphs;
-- with Debug;
package body UAFLEX.Generator.Tables is
package Char_Set_Vectors renames
Matreshka.Internals.Finite_Automatons.Vectors;
package Start_Maps renames Matreshka.Internals.Finite_Automatons.Start_Maps;
package State_Maps renames Matreshka.Internals.Finite_Automatons.State_Maps;
subtype State is Matreshka.Internals.Finite_Automatons.State;
use type State;
subtype Character_Class is Matreshka.Internals.Graphs.Edge_Identifier'Base;
subtype First_Stage_Index is
Matreshka.Internals.Unicode.Ucd.First_Stage_Index;
subtype Second_Stage_Index is
Matreshka.Internals.Unicode.Ucd.Second_Stage_Index;
type First_Stage_Array is array (First_Stage_Index) of Natural;
type Second_Stage_Array is array (Second_Stage_Index) of Character_Class;
package Second_Stage_Array_Maps is new Ada.Containers.Ordered_Maps
(Second_Stage_Array, Natural);
--------
-- Go --
--------
procedure Go
(DFA : Matreshka.Internals.Finite_Automatons.DFA;
Dead_End_Map : State_Map;
First_Dead_End : Matreshka.Internals.Finite_Automatons.State;
First_Final : Matreshka.Internals.Finite_Automatons.State;
Unit : League.Strings.Universal_String;
File : String;
Types : League.Strings.Universal_String;
Scanner : League.Strings.Universal_String;
Classes : Matreshka.Internals.Finite_Automatons.Vectors.Vector)
is
pragma Unreferenced (Types);
procedure P (Text : Wide_Wide_String);
procedure N (Text : Wide_Wide_String);
procedure Print_Char_Classes;
procedure Print_Switch;
procedure Print_Rules;
procedure Print_Classes
(Id : Matreshka.Internals.Graphs.Edge_Identifier;
Count : in out Natural);
function Get_Second (X : First_Stage_Index) return Second_Stage_Array;
Output : Ada.Wide_Wide_Text_IO.File_Type;
Length : Natural := 0; -- Length of last output line
Indent : Natural := 0; -- Last indent
----------------
-- Get_Second --
----------------
function Get_Second (X : First_Stage_Index) return Second_Stage_Array is
Result : Second_Stage_Array := (others => 0);
Char : Wide_Wide_Character;
begin
for J in Result'Range loop
Char := Wide_Wide_Character'Val (Natural (X) * 256 + Natural (J));
for C in Classes.First_Index .. Classes.Last_Index loop
if Classes.Element (C).Has (Char) then
Result (J) := C;
exit;
end if;
end loop;
end loop;
return Result;
end Get_Second;
procedure N (Text : Wide_Wide_String) is
use Ada.Strings.Wide_Wide_Fixed;
begin
if Length = 0 then
Indent := Ada.Strings.Wide_Wide_Fixed.Index_Non_Blank
(Text & ".");
end if;
if Length + Text'Length > 74 then
Ada.Wide_Wide_Text_IO.Put_Line
(Output, Trim (Text, Ada.Strings.Right));
Ada.Wide_Wide_Text_IO.Put (Output, Indent * ' ');
Length := Indent;
else
Ada.Wide_Wide_Text_IO.Put (Output, Text);
Length := Length + Text'Length;
end if;
end N;
procedure P (Text : Wide_Wide_String) is
begin
if Length = 0 then
Indent := Ada.Strings.Wide_Wide_Fixed.Index_Non_Blank (Text);
end if;
Ada.Wide_Wide_Text_IO.Put_Line (Output, Text);
Length := 0;
end P;
procedure Print_Char_Classes is
use Second_Stage_Array_Maps;
use type First_Stage_Index;
use type Second_Stage_Index;
Known : Map;
Pos : Cursor;
First : First_Stage_Array;
Second : Second_Stage_Array;
begin
for F in First_Stage_Index loop
Second := Get_Second (F);
Pos := Known.Find (Second);
if Has_Element (Pos) then
First (F) := Element (Pos);
else
First (F) := Natural (Known.Length);
Known.Insert (Second, First (F));
P (" S_" & Image (First (F)) &
" : aliased constant Second_Stage_Array :=");
for J in Second_Stage_Index'Range loop
if J = 0 then
N (" (");
elsif J mod 8 = 0 then
P ("");
N (" ");
else
N (" ");
end if;
N (Image (Natural (Second (J))));
if J = Second_Stage_Index'Last then
P (");");
P ("");
else
N (",");
end if;
end loop;
end if;
end loop;
P (" First : constant First_Stage_Array :=");
for F in First_Stage_Index loop
if F = 0 then
N (" (");
elsif F mod 4 = 0 then
P ("");
N (" ");
else
N (" ");
end if;
N ("S_" & Image (First (F)) & "'Access");
if F = First_Stage_Index'Last then
P (");");
P ("");
else
N (",");
end if;
end loop;
end Print_Char_Classes;
procedure Print_Classes
(Id : Matreshka.Internals.Graphs.Edge_Identifier;
Count : in out Natural)
is
Set : constant League.Character_Sets.Universal_Character_Set :=
DFA.Edge_Char_Set.Element (Id);
First : Boolean := True;
begin
for J in Classes.First_Index .. Classes.Last_Index loop
if Classes.Element (J).Is_Subset (Set) then
if First then
First := False;
else
N (" | ");
end if;
N (Image (Positive (J)));
Count := Count + 1;
end if;
end loop;
end Print_Classes;
procedure Print_Rules is
procedure Each_Rule (Cursor : State_Maps.Cursor);
Count : Natural := 0;
procedure Each_Rule (Cursor : State_Maps.Cursor) is
begin
if Count = 0 then
N (" (");
elsif Count mod 6 = 0 then
P (",");
N (" ");
else
N (", ");
end if;
N (Image (Natural (Dead_End_Map (State_Maps.Key (Cursor))) - 1) &
" => " & Image (State_Maps.Element (Cursor)));
Count := Count + 1;
end Each_Rule;
begin
P (" Rule_Table : constant array (State range " &
Image (Positive (First_Final) - 1) & " .. " &
Image (Positive (DFA.Graph.Node_Count) - 1) &
") of Rule_Index :=");
DFA.Final.Iterate (Each_Rule'Access);
P (");");
P ("");
end Print_Rules;
procedure Print_Switch is
First : Boolean := True;
begin
P (" Switch_Table : constant array " &
"(State range 0 .. " &
Image (Positive (First_Dead_End) - 2) & ",");
P (" Character_Class range 0 .. " &
Image (Positive (Classes.Length)) &
") of State :=");
for J in 1 .. DFA.Graph.Node_Count loop
declare
use type Matreshka.Internals.Graphs.Edge_Index;
Count : Natural := 0;
Edge : Matreshka.Internals.Graphs.Edge;
Item : constant Matreshka.Internals.Graphs.Node :=
DFA.Graph.Get_Node (J);
F : constant Matreshka.Internals.Graphs.Edge_Index :=
Item.First_Edge_Index;
L : constant Matreshka.Internals.Graphs.Edge_List_Length :=
Item.Last_Edge_Index;
begin
if Dead_End_Map (J) < First_Dead_End then
if First then
N (" (");
First := False;
else
P (",");
N (" ");
end if;
P (Image (Positive (Dead_End_Map (J)) - 1) & " =>");
for K in F .. L loop
Edge := DFA.Graph.Get_Edge (K);
if K = F then
N (" (");
else
N (" ");
end if;
Print_Classes (Edge.Edge_Id, Count);
N (" =>");
N (State'Wide_Wide_Image
(Dead_End_Map (Edge.Target_Node.Index) - 1));
if K /= L then
N (",");
end if;
end loop;
if Count /= Positive (Classes.Length) + 1 then
if Count = 0 then
N (" (");
elsif Length > 65 then
P ("");
N (" , ");
else
N (", ");
end if;
N ("others =>" &
State'Wide_Wide_Image (DFA.Graph.Node_Count));
end if;
N (")");
end if;
end;
end loop;
P (");");
P ("");
end Print_Switch;
begin
Ada.Wide_Wide_Text_IO.Create (Output, Name => File);
P ("with Matreshka.Internals.Unicode.Ucd;");
P ("");
P ("separate (" & Scanner.To_Wide_Wide_String & ")");
P ("package body " & Unit.To_Wide_Wide_String & " is");
P (" subtype First_Stage_Index is");
P (" Matreshka.Internals.Unicode.Ucd.First_Stage_Index;");
P ("");
P (" subtype Second_Stage_Index is");
P (" Matreshka.Internals.Unicode.Ucd.Second_Stage_Index;");
P ("");
P (" type Second_Stage_Array is array (Second_Stage_Index) " &
"of Character_Class;");
P ("");
P (" type Second_Stage_Array_Access is");
P (" not null access constant Second_Stage_Array;");
P ("");
P (" type First_Stage_Array is");
P (" array (First_Stage_Index) of Second_Stage_Array_Access;");
P ("");
Print_Char_Classes;
Print_Switch;
Print_Rules;
P (" function Rule (S : State) return Rule_Index is");
P (" begin");
P (" return Rule_Table (S);");
P (" end Rule;");
P ("");
P (" function Switch (S : State; Class : Character_Class) " &
"return State is");
P (" begin");
P (" return Switch_Table (S, Class);");
P (" end Switch;");
P ("");
P (" function To_Class (Value : " &
"Matreshka.Internals.Unicode.Code_Point)");
P (" return Character_Class");
P (" is");
P (" function Element is new " &
"Matreshka.Internals.Unicode.Ucd.Generic_Element");
P (" (Character_Class, Second_Stage_Array,");
P (" Second_Stage_Array_Access, First_Stage_Array);");
P (" begin");
P (" return Element (First, Value);");
P (" end To_Class;");
P ("");
P ("end " & Unit.To_Wide_Wide_String & ";");
end Go;
---------------------------
-- Remap_Final_Dead_Ends --
---------------------------
procedure Map_Final_Dead_Ends
(DFA : Matreshka.Internals.Finite_Automatons.DFA;
First_Dead_End : out Matreshka.Internals.Finite_Automatons.State;
First_Final : out Matreshka.Internals.Finite_Automatons.State;
Dead_End_Map : out State_Map)
is
Dead_End_Index : Matreshka.Internals.Finite_Automatons.State;
Final_Index : Matreshka.Internals.Finite_Automatons.State;
Free_Index : Matreshka.Internals.Finite_Automatons.State;
begin
First_Dead_End := Dead_End_Map'Last + 1;
First_Final := First_Dead_End;
for J in Dead_End_Map'Range loop
if DFA.Final.Contains (J) then
First_Final := First_Final - 1;
if DFA.Graph.Get_Node (J).Outgoing_Edges'Length = 0 then
First_Dead_End := First_Dead_End - 1;
end if;
end if;
end loop;
Dead_End_Index := First_Dead_End;
Final_Index := First_Final;
Free_Index := 1;
for J in Dead_End_Map'Range loop
if not DFA.Final.Contains (J) then
Dead_End_Map (J) := Free_Index;
Free_Index := Free_Index + 1;
elsif DFA.Graph.Get_Node (J).Outgoing_Edges'Length > 0 then
Dead_End_Map (J) := Final_Index;
Final_Index := Final_Index + 1;
else
Dead_End_Map (J) := Dead_End_Index;
Dead_End_Index := Dead_End_Index + 1;
end if;
end loop;
end Map_Final_Dead_Ends;
-----------------------
-- Split_To_Distinct --
-----------------------
procedure Split_To_Distinct
(List : Char_Set_Vectors.Vector;
Result : out Char_Set_Vectors.Vector) is
begin
for J in List.First_Index .. List.Last_Index loop
declare
use League.Character_Sets;
Rest : Universal_Character_Set := List.Element (J);
begin
for K in Result.First_Index .. Result.Last_Index loop
declare
Item : constant Universal_Character_Set :=
Result.Element (K);
Intersection : constant Universal_Character_Set :=
Item and Rest;
begin
if not Intersection.Is_Empty then
declare
Extra : constant Universal_Character_Set :=
Item - Rest;
begin
if not Extra.Is_Empty then
Result.Append (Extra);
end if;
Result.Replace_Element (K, Intersection);
Rest := Rest - Item;
exit when Rest.Is_Empty;
end;
end if;
end;
end loop;
if not Rest.Is_Empty then
Result.Append (Rest);
end if;
end;
end loop;
end Split_To_Distinct;
-----------
-- Types --
-----------
procedure Types
(DFA : Matreshka.Internals.Finite_Automatons.DFA;
Dead_End_Map : State_Map;
First_Dead_End : Matreshka.Internals.Finite_Automatons.State;
First_Final : Matreshka.Internals.Finite_Automatons.State;
Unit : League.Strings.Universal_String;
File : String;
Classes : Char_Set_Vectors.Vector)
is
use type Ada.Containers.Count_Type;
procedure P (Text : Wide_Wide_String);
procedure Print_Start (Cursor : Start_Maps.Cursor);
Output : Ada.Wide_Wide_Text_IO.File_Type;
procedure P (Text : Wide_Wide_String) is
begin
-- Ada.Wide_Wide_Text_IO.Put_Line (Text);
Ada.Wide_Wide_Text_IO.Put_Line (Output, Text);
end P;
procedure Print_Start (Cursor : Start_Maps.Cursor) is
begin
P (" " & Start_Maps.Key (Cursor).To_Wide_Wide_String &
" : constant State :=" &
State'Wide_Wide_Image
(Dead_End_Map (Start_Maps.Element (Cursor)) - 1) &
";");
end Print_Start;
begin
Ada.Wide_Wide_Text_IO.Create (Output, Name => File);
-- Debug.Print_Character_Classes (Classes);
P ("package " & Unit.To_Wide_Wide_String & " is");
P (" pragma Preelaborate;");
P ("");
P (" type State is mod +" &
Image (Positive (DFA.Graph.Node_Count + 1)) &
";");
P (" subtype Looping_State is State range 0 .. " &
Image (Positive (First_Dead_End) - 2) & ";");
P (" subtype Final_State is State range " &
Image (Positive (First_Final) - 1) &
" .. State'Last - 1;");
P ("");
P (" Error_State : constant State := State'Last;");
P ("");
DFA.Start.Iterate (Print_Start'Access);
P ("");
P (" type Character_Class is mod +" &
Image (Positive (Classes.Length + 1)) &
";");
P ("");
P (" type Rule_Index is range 0 .." &
Natural'Wide_Wide_Image (Nodes.Rules.Length) &
";");
P ("");
P ("end " & Unit.To_Wide_Wide_String & ";");
end Types;
end UAFLEX.Generator.Tables;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- F N A M E . U F --
-- --
-- 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 Alloc;
with Debug; use Debug;
with Fmap; use Fmap;
with Krunch;
with Opt; use Opt;
with Osint; use Osint;
with Table;
with Uname; use Uname;
with Widechar; use Widechar;
with GNAT.HTable;
package body Fname.UF is
--------------------------------------------------------
-- Declarations for Handling Source_File_Name pragmas --
--------------------------------------------------------
type SFN_Entry is record
U : Unit_Name_Type; -- Unit name
F : File_Name_Type; -- Spec/Body file name
Index : Nat; -- Index from SFN pragma (0 if none)
end record;
-- Record single Unit_Name type call to Set_File_Name
package SFN_Table is new Table.Table (
Table_Component_Type => SFN_Entry,
Table_Index_Type => Int,
Table_Low_Bound => 0,
Table_Initial => Alloc.SFN_Table_Initial,
Table_Increment => Alloc.SFN_Table_Increment,
Table_Name => "SFN_Table");
-- Table recording all Unit_Name calls to Set_File_Name
type SFN_Header_Num is range 0 .. 100;
function SFN_Hash (F : Unit_Name_Type) return SFN_Header_Num;
-- Compute hash index for use by Simple_HTable
No_Entry : constant Int := -1;
-- Signals no entry in following table
package SFN_HTable is new GNAT.HTable.Simple_HTable (
Header_Num => SFN_Header_Num,
Element => Int,
No_Element => No_Entry,
Key => Unit_Name_Type,
Hash => SFN_Hash,
Equal => "=");
-- Hash table allowing rapid access to SFN_Table, the element value is an
-- index into this table.
type SFN_Pattern_Entry is record
Pat : String_Ptr; -- File name pattern (with asterisk in it)
Typ : Character; -- 'S'/'B'/'U' for spec/body/subunit
Dot : String_Ptr; -- Dot_Separator string
Cas : Casing_Type; -- Upper/Lower/Mixed
end record;
-- Records single call to Set_File_Name_Patterm
package SFN_Patterns is new Table.Table (
Table_Component_Type => SFN_Pattern_Entry,
Table_Index_Type => Int,
Table_Low_Bound => 1,
Table_Initial => 10,
Table_Increment => 100,
Table_Name => "SFN_Patterns");
-- Table recording calls to Set_File_Name_Pattern. Note that the first two
-- entries are set to represent the standard GNAT rules for file naming.
-----------------------
-- File_Name_Of_Body --
-----------------------
function File_Name_Of_Body (Name : Name_Id) return File_Name_Type is
begin
Get_Name_String (Name);
Name_Buffer (Name_Len + 1 .. Name_Len + 2) := "%b";
Name_Len := Name_Len + 2;
return Get_File_Name (Name_Enter, Subunit => False);
end File_Name_Of_Body;
-----------------------
-- File_Name_Of_Spec --
-----------------------
function File_Name_Of_Spec (Name : Name_Id) return File_Name_Type is
begin
Get_Name_String (Name);
Name_Buffer (Name_Len + 1 .. Name_Len + 2) := "%s";
Name_Len := Name_Len + 2;
return Get_File_Name (Name_Enter, Subunit => False);
end File_Name_Of_Spec;
----------------------------
-- Get_Expected_Unit_Type --
----------------------------
function Get_Expected_Unit_Type
(Fname : File_Name_Type) return Expected_Unit_Type
is
begin
-- In syntax checking only mode or in multiple unit per file mode, there
-- can be more than one unit in a file, so the file name is not a useful
-- guide to the nature of the unit.
if Operating_Mode = Check_Syntax
or else Multiple_Unit_Index /= 0
then
return Unknown;
end if;
-- Search the file mapping table, if we find an entry for this file we
-- know whether it is a spec or a body.
for J in SFN_Table.First .. SFN_Table.Last loop
if Fname = SFN_Table.Table (J).F then
if Is_Body_Name (SFN_Table.Table (J).U) then
return Expect_Body;
else
return Expect_Spec;
end if;
end if;
end loop;
-- If no entry in file naming table, assume .ads/.adb for spec/body and
-- return unknown if we have neither of these two cases.
Get_Name_String (Fname);
if Name_Len > 4 then
if Name_Buffer (Name_Len - 3 .. Name_Len) = ".ads" then
return Expect_Spec;
elsif Name_Buffer (Name_Len - 3 .. Name_Len) = ".adb" then
return Expect_Body;
end if;
end if;
return Unknown;
end Get_Expected_Unit_Type;
-------------------
-- Get_File_Name --
-------------------
function Get_File_Name
(Uname : Unit_Name_Type;
Subunit : Boolean;
May_Fail : Boolean := False) return File_Name_Type
is
Unit_Char : Character;
-- Set to 's' or 'b' for spec or body or to 'u' for a subunit
Unit_Char_Search : Character;
-- Same as Unit_Char, except that in the case of 'u' for a subunit, we
-- set Unit_Char_Search to 'b' if we do not find a subunit match.
N : Int;
Pname : File_Name_Type := No_File;
Fname : File_Name_Type := No_File;
-- Path name and File name for mapping
begin
-- Null or error name means that some previous error occurred. This is
-- an unrecoverable error, so signal it.
if Uname in Error_Unit_Name_Or_No_Unit_Name then
raise Unrecoverable_Error;
end if;
-- Look in the map from unit names to file names
Fname := Mapped_File_Name (Uname);
-- If the unit name is already mapped, return the corresponding file
-- name from the map.
if Fname /= No_File then
return Fname;
end if;
-- If there is a specific SFN pragma, return the corresponding file name
N := SFN_HTable.Get (Uname);
if N /= No_Entry then
return SFN_Table.Table (N).F;
end if;
-- Here for the case where the name was not found in the table
Get_Decoded_Name_String (Uname);
-- A special fudge, normally we don't have operator symbols present,
-- since it is always an error to do so. However, if we do, at this
-- stage it has a leading double quote.
-- What we do in this case is to go back to the undecoded name, which
-- is of the form, for example:
-- Oand%s
-- and build a file name that looks like:
-- _and_.ads
-- which is bit peculiar, but we keep it that way. This means that we
-- avoid bombs due to writing a bad file name, and we get expected error
-- processing downstream, e.g. a compilation following gnatchop.
if Name_Buffer (1) = '"' then
Get_Name_String (Uname);
Name_Len := Name_Len + 1;
Name_Buffer (Name_Len) := Name_Buffer (Name_Len - 1);
Name_Buffer (Name_Len - 1) := Name_Buffer (Name_Len - 2);
Name_Buffer (Name_Len - 2) := '_';
Name_Buffer (1) := '_';
end if;
-- Deal with spec or body suffix
Unit_Char := Name_Buffer (Name_Len);
pragma Assert (Unit_Char = 'b' or else Unit_Char = 's');
pragma Assert (Name_Len >= 3 and then Name_Buffer (Name_Len - 1) = '%');
Name_Len := Name_Len - 2;
if Subunit then
Unit_Char := 'u';
end if;
-- Now we need to find the proper translation of the name
declare
Uname : constant String (1 .. Name_Len) :=
Name_Buffer (1 .. Name_Len);
Pent : Nat;
Plen : Natural;
Fnam : File_Name_Type := No_File;
J : Natural;
Dot : String_Ptr;
Dotl : Natural;
Is_Predef : Boolean;
-- Set True for predefined file
function C (N : Natural) return Character;
-- Return N'th character of pattern
function C (N : Natural) return Character is
begin
return SFN_Patterns.Table (Pent).Pat (N);
end C;
-- Start of search through pattern table
begin
-- Search pattern table to find a matching entry. In the general case
-- we do two complete searches. The first time through we stop only
-- if a matching file is found, the second time through we accept the
-- first match regardless. Note that there will always be a match the
-- second time around, because of the default entries at the end of
-- the table.
for No_File_Check in False .. True loop
Unit_Char_Search := Unit_Char;
<<Repeat_Search>>
-- The search is repeated with Unit_Char_Search set to b, if an
-- initial search for the subunit case fails to find any match.
Pent := SFN_Patterns.First;
while Pent <= SFN_Patterns.Last loop
if SFN_Patterns.Table (Pent).Typ = Unit_Char_Search then
-- Determine if we have a predefined file name
Is_Predef :=
Is_Predefined_Unit_Name
(Uname, Renamings_Included => True);
-- Found a match, execute the pattern
Name_Len := Uname'Length;
Name_Buffer (1 .. Name_Len) := Uname;
-- Apply casing, except that we do not do this for the case
-- of a predefined library file. For the latter, we always
-- use the all lower case name, regardless of the setting.
if not Is_Predef then
Set_Casing (SFN_Patterns.Table (Pent).Cas);
end if;
-- If dot translation required do it
Dot := SFN_Patterns.Table (Pent).Dot;
Dotl := Dot.all'Length;
if Dot.all /= "." then
J := 1;
while J <= Name_Len loop
if Name_Buffer (J) = '.' then
if Dotl = 1 then
Name_Buffer (J) := Dot (Dot'First);
else
Name_Buffer (J + Dotl .. Name_Len + Dotl - 1) :=
Name_Buffer (J + 1 .. Name_Len);
Name_Buffer (J .. J + Dotl - 1) := Dot.all;
Name_Len := Name_Len + Dotl - 1;
end if;
J := J + Dotl;
-- Skip past wide char sequences to avoid messing with
-- dot characters that are part of a sequence.
elsif Name_Buffer (J) = ASCII.ESC
or else (Upper_Half_Encoding
and then
Name_Buffer (J) in Upper_Half_Character)
then
Skip_Wide (Name_Buffer, J);
else
J := J + 1;
end if;
end loop;
end if;
-- Here move result to right if preinsertion before *
Plen := SFN_Patterns.Table (Pent).Pat'Length;
for K in 1 .. Plen loop
if C (K) = '*' then
if K /= 1 then
Name_Buffer (1 + K - 1 .. Name_Len + K - 1) :=
Name_Buffer (1 .. Name_Len);
for L in 1 .. K - 1 loop
Name_Buffer (L) := C (L);
end loop;
Name_Len := Name_Len + K - 1;
end if;
for L in K + 1 .. Plen loop
Name_Len := Name_Len + 1;
Name_Buffer (Name_Len) := C (L);
end loop;
exit;
end if;
end loop;
-- Execute possible crunch on constructed name. The krunch
-- operation excludes any extension that may be present.
J := Name_Len;
while J > 1 loop
exit when Name_Buffer (J) = '.';
J := J - 1;
end loop;
-- Case of extension present
if J > 1 then
declare
Ext : constant String := Name_Buffer (J .. Name_Len);
begin
-- Remove extension
Name_Len := J - 1;
-- Krunch what's left
Krunch
(Name_Buffer,
Name_Len,
Integer (Maximum_File_Name_Length),
Debug_Flag_4);
-- Replace extension
Name_Buffer
(Name_Len + 1 .. Name_Len + Ext'Length) := Ext;
Name_Len := Name_Len + Ext'Length;
end;
-- Case of no extension present, straight krunch on the
-- entire file name.
else
Krunch
(Name_Buffer,
Name_Len,
Integer (Maximum_File_Name_Length),
Debug_Flag_4);
end if;
Fnam := Name_Find;
-- If we are in the second search of the table, we accept
-- the file name without checking, because we know that the
-- file does not exist, except when May_Fail is True, in
-- which case we return No_File.
if No_File_Check then
if May_Fail then
return No_File;
else
return Fnam;
end if;
-- Otherwise we check if the file exists
else
Pname := Find_File (Fnam, Source);
-- If it does exist, we add it to the mappings and return
-- the file name.
if Pname /= No_File then
-- Add to mapping, so that we don't do another path
-- search in Find_File for this file name and, if we
-- use a mapping file, we are ready to update it at
-- the end of this compilation for the benefit of
-- other compilation processes.
Add_To_File_Map (Get_File_Name.Uname, Fnam, Pname);
return Fnam;
-- If there are only two entries, they are those of the
-- default GNAT naming scheme. The file does not exist,
-- but there is no point doing the second search, because
-- we will end up with the same file name. Just return
-- the file name, or No_File if May_Fail is True.
elsif SFN_Patterns.Last = 2 then
if May_Fail then
return No_File;
else
return Fnam;
end if;
-- The file does not exist, but there may be other naming
-- scheme. Keep on searching.
else
Fnam := No_File;
end if;
end if;
end if;
Pent := Pent + 1;
end loop;
-- If search failed, and was for a subunit, repeat the search with
-- Unit_Char_Search reset to 'b', since in the normal case we
-- simply treat subunits as bodies.
if Fnam = No_File and then Unit_Char_Search = 'u' then
Unit_Char_Search := 'b';
goto Repeat_Search;
end if;
-- Repeat entire search in No_File_Check mode if necessary
end loop;
-- Something is wrong if search fails completely, since the default
-- entries should catch all possibilities at this stage.
raise Program_Error;
end;
end Get_File_Name;
--------------------
-- Get_Unit_Index --
--------------------
function Get_Unit_Index (Uname : Unit_Name_Type) return Nat is
N : constant Int := SFN_HTable.Get (Uname);
begin
if N /= No_Entry then
return SFN_Table.Table (N).Index;
else
return 0;
end if;
end Get_Unit_Index;
----------------
-- Initialize --
----------------
procedure Initialize is
begin
SFN_Table.Init;
SFN_Patterns.Init;
-- Add default entries to SFN_Patterns.Table to represent the standard
-- default GNAT rules for file name translation.
SFN_Patterns.Append (New_Val =>
(Pat => new String'("*.ads"),
Typ => 's',
Dot => new String'("-"),
Cas => All_Lower_Case));
SFN_Patterns.Append (New_Val =>
(Pat => new String'("*.adb"),
Typ => 'b',
Dot => new String'("-"),
Cas => All_Lower_Case));
end Initialize;
----------
-- Lock --
----------
procedure Lock is
begin
SFN_Table.Release;
SFN_Table.Locked := True;
end Lock;
-------------------
-- Set_File_Name --
-------------------
procedure Set_File_Name
(U : Unit_Name_Type;
F : File_Name_Type;
Index : Nat)
is
begin
SFN_Table.Increment_Last;
SFN_Table.Table (SFN_Table.Last) := (U, F, Index);
SFN_HTable.Set (U, SFN_Table.Last);
end Set_File_Name;
---------------------------
-- Set_File_Name_Pattern --
---------------------------
procedure Set_File_Name_Pattern
(Pat : String_Ptr;
Typ : Character;
Dot : String_Ptr;
Cas : Casing_Type)
is
L : constant Nat := SFN_Patterns.Last;
begin
SFN_Patterns.Increment_Last;
-- Move up the last two entries (the default ones) and then put the new
-- entry into the table just before them (we always have the default
-- entries be the last ones).
SFN_Patterns.Table (L + 1) := SFN_Patterns.Table (L);
SFN_Patterns.Table (L) := SFN_Patterns.Table (L - 1);
SFN_Patterns.Table (L - 1) := (Pat, Typ, Dot, Cas);
end Set_File_Name_Pattern;
--------------
-- SFN_Hash --
--------------
function SFN_Hash (F : Unit_Name_Type) return SFN_Header_Num is
begin
return SFN_Header_Num (Int (F) mod SFN_Header_Num'Range_Length);
end SFN_Hash;
begin
-- We call the initialization routine from the package body, so that
-- Fname.Init only needs to be called explicitly to reinitialize.
Fname.UF.Initialize;
end Fname.UF;
|
-- Adobe Experience Manager (AEM) API
-- Swagger AEM is an OpenAPI specification for Adobe Experience Manager (AEM) API
--
-- The version of the OpenAPI document: 3.5.0_pre.0
-- Contact: opensource@shinesolutions.com
--
-- NOTE: This package is auto generated by OpenAPI-Generator 5.2.1.
-- https://openapi-generator.tech
-- Do not edit the class manually.
package body .Models is
pragma Style_Checks ("-mr");
pragma Warnings (Off, "*use clause for package*");
use Swagger.Streams;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in InstallStatusStatus_Type) is
begin
Into.Start_Entity (Name);
Into.Write_Entity ("finished", Value.Finished);
Into.Write_Entity ("itemCount", Value.Item_Count);
Into.End_Entity (Name);
end Serialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in InstallStatusStatus_Type_Vectors.Vector) is
begin
Into.Start_Array (Name);
for Item of Value loop
Serialize (Into, "", Item);
end loop;
Into.End_Array (Name);
end Serialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out InstallStatusStatus_Type) is
Object : Swagger.Value_Type;
begin
Swagger.Streams.Deserialize (From, Name, Object);
Swagger.Streams.Deserialize (Object, "finished", Value.Finished);
Swagger.Streams.Deserialize (Object, "itemCount", Value.Item_Count);
end Deserialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out InstallStatusStatus_Type_Vectors.Vector) is
List : Swagger.Value_Array_Type;
Item : InstallStatusStatus_Type;
begin
Value.Clear;
Swagger.Streams.Deserialize (From, Name, List);
for Data of List loop
Deserialize (Data, "", Item);
Value.Append (Item);
end loop;
end Deserialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in InstallStatus_Type) is
begin
Into.Start_Entity (Name);
Serialize (Into, "status", Value.Status);
Into.End_Entity (Name);
end Serialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in InstallStatus_Type_Vectors.Vector) is
begin
Into.Start_Array (Name);
for Item of Value loop
Serialize (Into, "", Item);
end loop;
Into.End_Array (Name);
end Serialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out InstallStatus_Type) is
Object : Swagger.Value_Type;
begin
Swagger.Streams.Deserialize (From, Name, Object);
Deserialize (Object, "status", Value.Status);
end Deserialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out InstallStatus_Type_Vectors.Vector) is
List : Swagger.Value_Array_Type;
Item : InstallStatus_Type;
begin
Value.Clear;
Swagger.Streams.Deserialize (From, Name, List);
for Data of List loop
Deserialize (Data, "", Item);
Value.Append (Item);
end loop;
end Deserialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in SamlConfigurationPropertyItemsString_Type) is
begin
Into.Start_Entity (Name);
Into.Write_Entity ("name", Value.Name);
Into.Write_Entity ("optional", Value.Optional);
Into.Write_Entity ("is_set", Value.Is_Set);
Into.Write_Entity ("type", Value.P_Type);
Into.Write_Entity ("value", Value.Value);
Into.Write_Entity ("description", Value.Description);
Into.End_Entity (Name);
end Serialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in SamlConfigurationPropertyItemsString_Type_Vectors.Vector) is
begin
Into.Start_Array (Name);
for Item of Value loop
Serialize (Into, "", Item);
end loop;
Into.End_Array (Name);
end Serialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out SamlConfigurationPropertyItemsString_Type) is
Object : Swagger.Value_Type;
begin
Swagger.Streams.Deserialize (From, Name, Object);
Swagger.Streams.Deserialize (Object, "name", Value.Name);
Swagger.Streams.Deserialize (Object, "optional", Value.Optional);
Swagger.Streams.Deserialize (Object, "is_set", Value.Is_Set);
Swagger.Streams.Deserialize (Object, "type", Value.P_Type);
Swagger.Streams.Deserialize (Object, "value", Value.Value);
Swagger.Streams.Deserialize (Object, "description", Value.Description);
end Deserialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out SamlConfigurationPropertyItemsString_Type_Vectors.Vector) is
List : Swagger.Value_Array_Type;
Item : SamlConfigurationPropertyItemsString_Type;
begin
Value.Clear;
Swagger.Streams.Deserialize (From, Name, List);
for Data of List loop
Deserialize (Data, "", Item);
Value.Append (Item);
end loop;
end Deserialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in SamlConfigurationPropertyItemsBoolean_Type) is
begin
Into.Start_Entity (Name);
Into.Write_Entity ("name", Value.Name);
Into.Write_Entity ("optional", Value.Optional);
Into.Write_Entity ("is_set", Value.Is_Set);
Into.Write_Entity ("type", Value.P_Type);
Into.Write_Entity ("value", Value.Value);
Into.Write_Entity ("description", Value.Description);
Into.End_Entity (Name);
end Serialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in SamlConfigurationPropertyItemsBoolean_Type_Vectors.Vector) is
begin
Into.Start_Array (Name);
for Item of Value loop
Serialize (Into, "", Item);
end loop;
Into.End_Array (Name);
end Serialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out SamlConfigurationPropertyItemsBoolean_Type) is
Object : Swagger.Value_Type;
begin
Swagger.Streams.Deserialize (From, Name, Object);
Swagger.Streams.Deserialize (Object, "name", Value.Name);
Swagger.Streams.Deserialize (Object, "optional", Value.Optional);
Swagger.Streams.Deserialize (Object, "is_set", Value.Is_Set);
Swagger.Streams.Deserialize (Object, "type", Value.P_Type);
Swagger.Streams.Deserialize (Object, "value", Value.Value);
Swagger.Streams.Deserialize (Object, "description", Value.Description);
end Deserialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out SamlConfigurationPropertyItemsBoolean_Type_Vectors.Vector) is
List : Swagger.Value_Array_Type;
Item : SamlConfigurationPropertyItemsBoolean_Type;
begin
Value.Clear;
Swagger.Streams.Deserialize (From, Name, List);
for Data of List loop
Deserialize (Data, "", Item);
Value.Append (Item);
end loop;
end Deserialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in TruststoreItems_Type) is
begin
Into.Start_Entity (Name);
Into.Write_Entity ("alias", Value.Alias);
Into.Write_Entity ("entryType", Value.Entry_Type);
Into.Write_Entity ("subject", Value.Subject);
Into.Write_Entity ("issuer", Value.Issuer);
Into.Write_Entity ("notBefore", Value.Not_Before);
Into.Write_Entity ("notAfter", Value.Not_After);
Into.Write_Entity ("serialNumber", Value.Serial_Number);
Into.End_Entity (Name);
end Serialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in TruststoreItems_Type_Vectors.Vector) is
begin
Into.Start_Array (Name);
for Item of Value loop
Serialize (Into, "", Item);
end loop;
Into.End_Array (Name);
end Serialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out TruststoreItems_Type) is
Object : Swagger.Value_Type;
begin
Swagger.Streams.Deserialize (From, Name, Object);
Swagger.Streams.Deserialize (Object, "alias", Value.Alias);
Swagger.Streams.Deserialize (Object, "entryType", Value.Entry_Type);
Swagger.Streams.Deserialize (Object, "subject", Value.Subject);
Swagger.Streams.Deserialize (Object, "issuer", Value.Issuer);
Swagger.Streams.Deserialize (Object, "notBefore", Value.Not_Before);
Swagger.Streams.Deserialize (Object, "notAfter", Value.Not_After);
Swagger.Streams.Deserialize (Object, "serialNumber", Value.Serial_Number);
end Deserialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out TruststoreItems_Type_Vectors.Vector) is
List : Swagger.Value_Array_Type;
Item : TruststoreItems_Type;
begin
Value.Clear;
Swagger.Streams.Deserialize (From, Name, List);
for Data of List loop
Deserialize (Data, "", Item);
Value.Append (Item);
end loop;
end Deserialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in TruststoreInfo_Type) is
begin
Into.Start_Entity (Name);
Serialize (Into, "aliases", Value.Aliases);
Into.Write_Entity ("exists", Value.Exists);
Into.End_Entity (Name);
end Serialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in TruststoreInfo_Type_Vectors.Vector) is
begin
Into.Start_Array (Name);
for Item of Value loop
Serialize (Into, "", Item);
end loop;
Into.End_Array (Name);
end Serialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out TruststoreInfo_Type) is
Object : Swagger.Value_Type;
begin
Swagger.Streams.Deserialize (From, Name, Object);
Deserialize (Object, "aliases", Value.Aliases);
Swagger.Streams.Deserialize (Object, "exists", Value.Exists);
end Deserialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out TruststoreInfo_Type_Vectors.Vector) is
List : Swagger.Value_Array_Type;
Item : TruststoreInfo_Type;
begin
Value.Clear;
Swagger.Streams.Deserialize (From, Name, List);
for Data of List loop
Deserialize (Data, "", Item);
Value.Append (Item);
end loop;
end Deserialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in KeystoreChainItems_Type) is
begin
Into.Start_Entity (Name);
Into.Write_Entity ("subject", Value.Subject);
Into.Write_Entity ("issuer", Value.Issuer);
Into.Write_Entity ("notBefore", Value.Not_Before);
Into.Write_Entity ("notAfter", Value.Not_After);
Into.Write_Entity ("serialNumber", Value.Serial_Number);
Into.End_Entity (Name);
end Serialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in KeystoreChainItems_Type_Vectors.Vector) is
begin
Into.Start_Array (Name);
for Item of Value loop
Serialize (Into, "", Item);
end loop;
Into.End_Array (Name);
end Serialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out KeystoreChainItems_Type) is
Object : Swagger.Value_Type;
begin
Swagger.Streams.Deserialize (From, Name, Object);
Swagger.Streams.Deserialize (Object, "subject", Value.Subject);
Swagger.Streams.Deserialize (Object, "issuer", Value.Issuer);
Swagger.Streams.Deserialize (Object, "notBefore", Value.Not_Before);
Swagger.Streams.Deserialize (Object, "notAfter", Value.Not_After);
Swagger.Streams.Deserialize (Object, "serialNumber", Value.Serial_Number);
end Deserialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out KeystoreChainItems_Type_Vectors.Vector) is
List : Swagger.Value_Array_Type;
Item : KeystoreChainItems_Type;
begin
Value.Clear;
Swagger.Streams.Deserialize (From, Name, List);
for Data of List loop
Deserialize (Data, "", Item);
Value.Append (Item);
end loop;
end Deserialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in KeystoreItems_Type) is
begin
Into.Start_Entity (Name);
Into.Write_Entity ("alias", Value.Alias);
Into.Write_Entity ("entryType", Value.Entry_Type);
Into.Write_Entity ("algorithm", Value.Algorithm);
Into.Write_Entity ("format", Value.Format);
Serialize (Into, "chain", Value.Chain);
Into.End_Entity (Name);
end Serialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in KeystoreItems_Type_Vectors.Vector) is
begin
Into.Start_Array (Name);
for Item of Value loop
Serialize (Into, "", Item);
end loop;
Into.End_Array (Name);
end Serialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out KeystoreItems_Type) is
Object : Swagger.Value_Type;
begin
Swagger.Streams.Deserialize (From, Name, Object);
Swagger.Streams.Deserialize (Object, "alias", Value.Alias);
Swagger.Streams.Deserialize (Object, "entryType", Value.Entry_Type);
Swagger.Streams.Deserialize (Object, "algorithm", Value.Algorithm);
Swagger.Streams.Deserialize (Object, "format", Value.Format);
Deserialize (Object, "chain", Value.Chain);
end Deserialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out KeystoreItems_Type_Vectors.Vector) is
List : Swagger.Value_Array_Type;
Item : KeystoreItems_Type;
begin
Value.Clear;
Swagger.Streams.Deserialize (From, Name, List);
for Data of List loop
Deserialize (Data, "", Item);
Value.Append (Item);
end loop;
end Deserialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in KeystoreInfo_Type) is
begin
Into.Start_Entity (Name);
Serialize (Into, "aliases", Value.Aliases);
Into.Write_Entity ("exists", Value.Exists);
Into.End_Entity (Name);
end Serialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in KeystoreInfo_Type_Vectors.Vector) is
begin
Into.Start_Array (Name);
for Item of Value loop
Serialize (Into, "", Item);
end loop;
Into.End_Array (Name);
end Serialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out KeystoreInfo_Type) is
Object : Swagger.Value_Type;
begin
Swagger.Streams.Deserialize (From, Name, Object);
Deserialize (Object, "aliases", Value.Aliases);
Swagger.Streams.Deserialize (Object, "exists", Value.Exists);
end Deserialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out KeystoreInfo_Type_Vectors.Vector) is
List : Swagger.Value_Array_Type;
Item : KeystoreInfo_Type;
begin
Value.Clear;
Swagger.Streams.Deserialize (From, Name, List);
for Data of List loop
Deserialize (Data, "", Item);
Value.Append (Item);
end loop;
end Deserialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in SamlConfigurationPropertyItemsArray_Type) is
begin
Into.Start_Entity (Name);
Into.Write_Entity ("name", Value.Name);
Into.Write_Entity ("optional", Value.Optional);
Into.Write_Entity ("is_set", Value.Is_Set);
Into.Write_Entity ("type", Value.P_Type);
Serialize (Into, "values", Value.Values);
Into.Write_Entity ("description", Value.Description);
Into.End_Entity (Name);
end Serialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in SamlConfigurationPropertyItemsArray_Type_Vectors.Vector) is
begin
Into.Start_Array (Name);
for Item of Value loop
Serialize (Into, "", Item);
end loop;
Into.End_Array (Name);
end Serialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out SamlConfigurationPropertyItemsArray_Type) is
Object : Swagger.Value_Type;
begin
Swagger.Streams.Deserialize (From, Name, Object);
Swagger.Streams.Deserialize (Object, "name", Value.Name);
Swagger.Streams.Deserialize (Object, "optional", Value.Optional);
Swagger.Streams.Deserialize (Object, "is_set", Value.Is_Set);
Swagger.Streams.Deserialize (Object, "type", Value.P_Type);
Swagger.Streams.Deserialize (Object, "values", Value.Values);
Swagger.Streams.Deserialize (Object, "description", Value.Description);
end Deserialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out SamlConfigurationPropertyItemsArray_Type_Vectors.Vector) is
List : Swagger.Value_Array_Type;
Item : SamlConfigurationPropertyItemsArray_Type;
begin
Value.Clear;
Swagger.Streams.Deserialize (From, Name, List);
for Data of List loop
Deserialize (Data, "", Item);
Value.Append (Item);
end loop;
end Deserialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in SamlConfigurationPropertyItemsLong_Type) is
begin
Into.Start_Entity (Name);
Into.Write_Entity ("name", Value.Name);
Into.Write_Entity ("optional", Value.Optional);
Into.Write_Entity ("is_set", Value.Is_Set);
Into.Write_Entity ("type", Value.P_Type);
Into.Write_Entity ("value", Value.Value);
Into.Write_Entity ("description", Value.Description);
Into.End_Entity (Name);
end Serialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in SamlConfigurationPropertyItemsLong_Type_Vectors.Vector) is
begin
Into.Start_Array (Name);
for Item of Value loop
Serialize (Into, "", Item);
end loop;
Into.End_Array (Name);
end Serialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out SamlConfigurationPropertyItemsLong_Type) is
Object : Swagger.Value_Type;
begin
Swagger.Streams.Deserialize (From, Name, Object);
Swagger.Streams.Deserialize (Object, "name", Value.Name);
Swagger.Streams.Deserialize (Object, "optional", Value.Optional);
Swagger.Streams.Deserialize (Object, "is_set", Value.Is_Set);
Swagger.Streams.Deserialize (Object, "type", Value.P_Type);
Swagger.Streams.Deserialize (Object, "value", Value.Value);
Swagger.Streams.Deserialize (Object, "description", Value.Description);
end Deserialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out SamlConfigurationPropertyItemsLong_Type_Vectors.Vector) is
List : Swagger.Value_Array_Type;
Item : SamlConfigurationPropertyItemsLong_Type;
begin
Value.Clear;
Swagger.Streams.Deserialize (From, Name, List);
for Data of List loop
Deserialize (Data, "", Item);
Value.Append (Item);
end loop;
end Deserialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in SamlConfigurationProperties_Type) is
begin
Into.Start_Entity (Name);
Serialize (Into, "path", Value.Path);
Serialize (Into, "service.ranking", Value.Service_Ranking);
Serialize (Into, "idpUrl", Value.Idp_Url);
Serialize (Into, "idpCertAlias", Value.Idp_Cert_Alias);
Serialize (Into, "idpHttpRedirect", Value.Idp_Http_Redirect);
Serialize (Into, "serviceProviderEntityId", Value.Service_Provider_Entity_Id);
Serialize (Into, "assertionConsumerServiceURL", Value.Assertion_Consumer_Service_URL);
Serialize (Into, "spPrivateKeyAlias", Value.Sp_Private_Key_Alias);
Serialize (Into, "keyStorePassword", Value.Key_Store_Password);
Serialize (Into, "defaultRedirectUrl", Value.Default_Redirect_Url);
Serialize (Into, "userIDAttribute", Value.User_IDAttribute);
Serialize (Into, "useEncryption", Value.Use_Encryption);
Serialize (Into, "createUser", Value.Create_User);
Serialize (Into, "addGroupMemberships", Value.Add_Group_Memberships);
Serialize (Into, "groupMembershipAttribute", Value.Group_Membership_Attribute);
Serialize (Into, "defaultGroups", Value.Default_Groups);
Serialize (Into, "nameIdFormat", Value.Name_Id_Format);
Serialize (Into, "synchronizeAttributes", Value.Synchronize_Attributes);
Serialize (Into, "handleLogout", Value.Handle_Logout);
Serialize (Into, "logoutUrl", Value.Logout_Url);
Serialize (Into, "clockTolerance", Value.Clock_Tolerance);
Serialize (Into, "digestMethod", Value.Digest_Method);
Serialize (Into, "signatureMethod", Value.Signature_Method);
Serialize (Into, "userIntermediatePath", Value.User_Intermediate_Path);
Into.End_Entity (Name);
end Serialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in SamlConfigurationProperties_Type_Vectors.Vector) is
begin
Into.Start_Array (Name);
for Item of Value loop
Serialize (Into, "", Item);
end loop;
Into.End_Array (Name);
end Serialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out SamlConfigurationProperties_Type) is
Object : Swagger.Value_Type;
begin
Swagger.Streams.Deserialize (From, Name, Object);
Deserialize (Object, "path", Value.Path);
Deserialize (Object, "service.ranking", Value.Service_Ranking);
Deserialize (Object, "idpUrl", Value.Idp_Url);
Deserialize (Object, "idpCertAlias", Value.Idp_Cert_Alias);
Deserialize (Object, "idpHttpRedirect", Value.Idp_Http_Redirect);
Deserialize (Object, "serviceProviderEntityId", Value.Service_Provider_Entity_Id);
Deserialize (Object, "assertionConsumerServiceURL", Value.Assertion_Consumer_Service_URL);
Deserialize (Object, "spPrivateKeyAlias", Value.Sp_Private_Key_Alias);
Deserialize (Object, "keyStorePassword", Value.Key_Store_Password);
Deserialize (Object, "defaultRedirectUrl", Value.Default_Redirect_Url);
Deserialize (Object, "userIDAttribute", Value.User_IDAttribute);
Deserialize (Object, "useEncryption", Value.Use_Encryption);
Deserialize (Object, "createUser", Value.Create_User);
Deserialize (Object, "addGroupMemberships", Value.Add_Group_Memberships);
Deserialize (Object, "groupMembershipAttribute", Value.Group_Membership_Attribute);
Deserialize (Object, "defaultGroups", Value.Default_Groups);
Deserialize (Object, "nameIdFormat", Value.Name_Id_Format);
Deserialize (Object, "synchronizeAttributes", Value.Synchronize_Attributes);
Deserialize (Object, "handleLogout", Value.Handle_Logout);
Deserialize (Object, "logoutUrl", Value.Logout_Url);
Deserialize (Object, "clockTolerance", Value.Clock_Tolerance);
Deserialize (Object, "digestMethod", Value.Digest_Method);
Deserialize (Object, "signatureMethod", Value.Signature_Method);
Deserialize (Object, "userIntermediatePath", Value.User_Intermediate_Path);
end Deserialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out SamlConfigurationProperties_Type_Vectors.Vector) is
List : Swagger.Value_Array_Type;
Item : SamlConfigurationProperties_Type;
begin
Value.Clear;
Swagger.Streams.Deserialize (From, Name, List);
for Data of List loop
Deserialize (Data, "", Item);
Value.Append (Item);
end loop;
end Deserialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in SamlConfigurationInfo_Type) is
begin
Into.Start_Entity (Name);
Into.Write_Entity ("pid", Value.Pid);
Into.Write_Entity ("title", Value.Title);
Into.Write_Entity ("description", Value.Description);
Into.Write_Entity ("bundle_location", Value.Bundle_Location);
Into.Write_Entity ("service_location", Value.Service_Location);
Serialize (Into, "properties", Value.Properties);
Into.End_Entity (Name);
end Serialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in SamlConfigurationInfo_Type_Vectors.Vector) is
begin
Into.Start_Array (Name);
for Item of Value loop
Serialize (Into, "", Item);
end loop;
Into.End_Array (Name);
end Serialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out SamlConfigurationInfo_Type) is
Object : Swagger.Value_Type;
begin
Swagger.Streams.Deserialize (From, Name, Object);
Swagger.Streams.Deserialize (Object, "pid", Value.Pid);
Swagger.Streams.Deserialize (Object, "title", Value.Title);
Swagger.Streams.Deserialize (Object, "description", Value.Description);
Swagger.Streams.Deserialize (Object, "bundle_location", Value.Bundle_Location);
Swagger.Streams.Deserialize (Object, "service_location", Value.Service_Location);
Deserialize (Object, "properties", Value.Properties);
end Deserialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out SamlConfigurationInfo_Type_Vectors.Vector) is
List : Swagger.Value_Array_Type;
Item : SamlConfigurationInfo_Type;
begin
Value.Clear;
Swagger.Streams.Deserialize (From, Name, List);
for Data of List loop
Deserialize (Data, "", Item);
Value.Append (Item);
end loop;
end Deserialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in BundleDataProp_Type) is
begin
Into.Start_Entity (Name);
Into.Write_Entity ("key", Value.Key);
Into.Write_Entity ("value", Value.Value);
Into.End_Entity (Name);
end Serialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in BundleDataProp_Type_Vectors.Vector) is
begin
Into.Start_Array (Name);
for Item of Value loop
Serialize (Into, "", Item);
end loop;
Into.End_Array (Name);
end Serialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out BundleDataProp_Type) is
Object : Swagger.Value_Type;
begin
Swagger.Streams.Deserialize (From, Name, Object);
Swagger.Streams.Deserialize (Object, "key", Value.Key);
Swagger.Streams.Deserialize (Object, "value", Value.Value);
end Deserialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out BundleDataProp_Type_Vectors.Vector) is
List : Swagger.Value_Array_Type;
Item : BundleDataProp_Type;
begin
Value.Clear;
Swagger.Streams.Deserialize (From, Name, List);
for Data of List loop
Deserialize (Data, "", Item);
Value.Append (Item);
end loop;
end Deserialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in BundleData_Type) is
begin
Into.Start_Entity (Name);
Into.Write_Entity ("id", Value.Id);
Into.Write_Entity ("name", Value.Name);
Into.Write_Entity ("fragment", Value.Fragment);
Into.Write_Entity ("stateRaw", Value.State_Raw);
Into.Write_Entity ("state", Value.State);
Into.Write_Entity ("version", Value.Version);
Into.Write_Entity ("symbolicName", Value.Symbolic_Name);
Into.Write_Entity ("category", Value.Category);
Serialize (Into, "props", Value.Props);
Into.End_Entity (Name);
end Serialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in BundleData_Type_Vectors.Vector) is
begin
Into.Start_Array (Name);
for Item of Value loop
Serialize (Into, "", Item);
end loop;
Into.End_Array (Name);
end Serialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out BundleData_Type) is
Object : Swagger.Value_Type;
begin
Swagger.Streams.Deserialize (From, Name, Object);
Swagger.Streams.Deserialize (Object, "id", Value.Id);
Swagger.Streams.Deserialize (Object, "name", Value.Name);
Swagger.Streams.Deserialize (Object, "fragment", Value.Fragment);
Swagger.Streams.Deserialize (Object, "stateRaw", Value.State_Raw);
Swagger.Streams.Deserialize (Object, "state", Value.State);
Swagger.Streams.Deserialize (Object, "version", Value.Version);
Swagger.Streams.Deserialize (Object, "symbolicName", Value.Symbolic_Name);
Swagger.Streams.Deserialize (Object, "category", Value.Category);
Deserialize (Object, "props", Value.Props);
end Deserialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out BundleData_Type_Vectors.Vector) is
List : Swagger.Value_Array_Type;
Item : BundleData_Type;
begin
Value.Clear;
Swagger.Streams.Deserialize (From, Name, List);
for Data of List loop
Deserialize (Data, "", Item);
Value.Append (Item);
end loop;
end Deserialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in BundleInfo_Type) is
begin
Into.Start_Entity (Name);
Into.Write_Entity ("status", Value.Status);
Serialize (Into, "s", Value.S);
Serialize (Into, "data", Value.Data);
Into.End_Entity (Name);
end Serialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String;
Value : in BundleInfo_Type_Vectors.Vector) is
begin
Into.Start_Array (Name);
for Item of Value loop
Serialize (Into, "", Item);
end loop;
Into.End_Array (Name);
end Serialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out BundleInfo_Type) is
Object : Swagger.Value_Type;
begin
Swagger.Streams.Deserialize (From, Name, Object);
Swagger.Streams.Deserialize (Object, "status", Value.Status);
Swagger.Streams.Deserialize (Object, "s", Value.S);
Deserialize (Object, "data", Value.Data);
end Deserialize;
procedure Deserialize (From : in Swagger.Value_Type;
Name : in String;
Value : out BundleInfo_Type_Vectors.Vector) is
List : Swagger.Value_Array_Type;
Item : BundleInfo_Type;
begin
Value.Clear;
Swagger.Streams.Deserialize (From, Name, List);
for Data of List loop
Deserialize (Data, "", Item);
Value.Append (Item);
end loop;
end Deserialize;
end .Models;
|
msg : string := "hello world";
empty : string := ""; -- an empty string
|
-- { dg-do compile }
-- { dg-options "-flto" { target lto } }
with Ada.Streams; use Ada.Streams;
package body Lto11 is
procedure Write
(S : not null access Root_Stream_Type'Class;
V : Vector)
is
subtype M_SEA is Stream_Element_Array (1 .. V'Size / Stream_Element'Size);
Bytes : M_SEA;
for Bytes'Address use V'Address;
pragma Import (Ada, Bytes);
begin
Ada.Streams.Write (S.all, Bytes);
end;
end Lto11;
|
-- Copyright 2019 Simon Symeonidis (psyomn)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Exceptions; use Ada.Exceptions;
with Listeners; use Listeners;
with CLI; use CLI;
procedure Main is
Listener_Task : Launch_Listener;
l1 : Listeners.Listener :=
Make_Listener
(Port => 3000,
Root => "./www1",
Host => "localhost");
begin
Process_Command_Line_Arguments (l1);
Listener_Task.Construct (l1);
Listener_Task.Start;
Listener_Task.Stop;
exception
when E : CLI_Argument_Exception =>
Put_Line ("error: " & Exception_Message (E));
New_Line;
Put_Line ("example usage: ");
Put_Line ("ash [-h host] [-p port] [-r rootdir]");
when E : others =>
Put_Line (
"error:" & Exception_Message (E) & " " &
"");
end Main;
|
pragma License (Unrestricted);
package Ada is
pragma Pure;
-- extended
-- This package creates usable debug output.
-- It is placed in the package Ada directly,
-- therefore it does not need to write any additional "with" clause.
package Debug is
function File return String
with Import, Convention => Intrinsic;
function Line return Positive
with Import, Convention => Intrinsic;
function Source_Location return String
with Import, Convention => Intrinsic;
function Enclosing_Entity return String
with Import, Convention => Intrinsic;
function Compilation_ISO_Date return String
with Import, Convention => Intrinsic;
function Compilation_Date return String
with Import, Convention => Intrinsic;
function Compilation_Time return String
with Import, Convention => Intrinsic;
procedure Put (
S : String;
Source_Location : String := Debug.Source_Location;
Enclosing_Entity : String := Debug.Enclosing_Entity)
with Import, Convention => Ada, External_Name => "__drake_debug_put";
function Put (
S : String;
Source_Location : String := Debug.Source_Location;
Enclosing_Entity : String := Debug.Enclosing_Entity)
return Boolean -- always True to use in pragma Assert/Check
with Import, Convention => Ada, External_Name => "__drake_debug_put";
end Debug;
end Ada;
|
pragma Ada_2012;
pragma Style_Checks (Off);
pragma Warnings ("U");
with Interfaces.C; use Interfaces.C;
package svm_defines_h is
type arm_ml_kernel_type is
(ARM_ML_KERNEL_LINEAR,
ARM_ML_KERNEL_POLYNOMIAL,
ARM_ML_KERNEL_RBF,
ARM_ML_KERNEL_SIGMOID)
with Convention => C; -- ../CMSIS_5/CMSIS/DSP/Include/dsp/svm_defines.h:44
end svm_defines_h;
|
function Compute(x, y: IN Integer) return Integer is
Result : Integer;
I : Integer;
J : Integer;
begin
Result := 0;
I := X;
Outer:
loop
J := Y;
while J > X loop
Result := Result + 1;
exit Outer when I mod J = 2;
J := J-1;
end loop;
I := I+1;
end loop Outer;
if X < Y then
for Z in reverse X .. Y loop
Result := abs Result - 1;
if Result rem 2 = 0 then
exit;
end if;
end loop;
end if;
return Result;
end Compute;
|
with Ada.Text_IO;
procedure Main is
package Float_IO is new Ada.Text_IO.Float_IO (Float);
function Van_Der_Corput (N : Natural; Base : Positive := 2) return Float is
Value : Natural := N;
Result : Float := 0.0;
Exponent : Positive := 1;
begin
while Value > 0 loop
Result := Result +
Float (Value mod Base) / Float (Base ** Exponent);
Value := Value / Base;
Exponent := Exponent + 1;
end loop;
return Result;
end Van_Der_Corput;
begin
for Base in 2 .. 5 loop
Ada.Text_IO.Put ("Base" & Integer'Image (Base) & ":");
for N in 1 .. 10 loop
Ada.Text_IO.Put (' ');
Float_IO.Put (Item => Van_Der_Corput (N, Base), Exp => 0);
end loop;
Ada.Text_IO.New_Line;
end loop;
end Main;
|
pragma License (Unrestricted);
-- extended unit
with Ada.Environment_Encoding.Generic_Strings;
package Ada.Environment_Encoding.Wide_Wide_Strings is
new Generic_Strings (
Wide_Wide_Character,
Wide_Wide_String);
-- Encoding / decoding between Wide_Wide_String and various encodings.
pragma Preelaborate (Ada.Environment_Encoding.Wide_Wide_Strings);
|
-- { dg-do compile }
-- { dg-options "-O -gnatp -fdump-tree-optimized" }
package body Array7 is
package body Range_Subtype is
function Get_Arr (Nbr : My_Range) return Arr_Acc is
begin
return new Arr (1 .. Nbr);
end;
end;
package body Range_Type is
function Get_Arr (Nbr : My_Range) return Arr_Acc is
begin
return new Arr (1 .. Nbr);
end;
end;
end Array7;
-- { dg-final { scan-tree-dump-not "MAX_EXPR" "optimized" } }
|
-- { dg-do compile }
with anon1;
procedure anon2 is
begin
if anon1.F /= null then
null;
end if;
end anon2;
|
pragma License (Unrestricted);
-- extended unit
package Ada.References is
-- Returning access values to sliced arrays from functions.
pragma Pure;
-- magic to carry out ARRAY (F .. L)'Access to out of subprogram
generic
type Index_Type is range <>;
type Element_Type is limited private;
type Array_Type is array (Index_Type range <>) of Element_Type;
package Generic_Slicing is
type Constant_Reference_Type (
Element : not null access constant Array_Type) is limited private
with Implicit_Dereference => Element;
function Constant_Slice (
Item : aliased Array_Type;
First : Index_Type;
Last : Index_Type'Base)
return Constant_Reference_Type;
type Reference_Type (
Element : not null access Array_Type) is limited private
with Implicit_Dereference => Element;
function Slice (
Item : aliased in out Array_Type;
First : Index_Type;
Last : Index_Type'Base)
return Reference_Type;
pragma Inline (Slice);
private
type Constant_Reference_Type (
Element : not null access constant Array_Type) is limited
record
First : Index_Type;
Last : Index_Type'Base;
end record;
pragma Suppress_Initialization (Constant_Reference_Type);
type Reference_Type (
Element : not null access Array_Type) is limited
record
First : Index_Type;
Last : Index_Type'Base;
end record;
pragma Suppress_Initialization (Reference_Type);
end Generic_Slicing;
end Ada.References;
|
pragma License (Unrestricted);
-- Ada 2012
-- with Ada.Interrupts;
package Ada.Execution_Time.Interrupts is
-- function Clock (Interrupt : Ada.Interrupts.Interrupt_Id) return CPU_Time;
-- function Supported (Interrupt : Ada.Interrupts.Interrupt_Id)
-- return Boolean;
end Ada.Execution_Time.Interrupts;
|
with Ada.Containers.Ordered_Maps;
with EU_Projects.Nodes.Partners;
package EU_Projects.Efforts is
use type Nodes.Partners.Partner_Label;
type Person_Months is new Natural;
package Effort_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => Nodes.Partners.Partner_Label,
Element_Type => Person_Months);
function Parse (Spec : String) return Effort_Maps.Map;
Bad_Effort_List : exception;
end EU_Projects.Efforts;
|
-- C38104A.ADA
-- Grant of Unlimited Rights
--
-- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687,
-- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained
-- unlimited rights in the software and documentation contained herein.
-- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making
-- this public release, the Government intends to confer upon all
-- recipients unlimited rights equal to those held by the Government.
-- These rights include rights to use, duplicate, release or disclose the
-- released technical data and computer software in whole or in part, in
-- any manner and for any purpose whatsoever, and to have or permit others
-- to do so.
--
-- DISCLAIMER
--
-- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR
-- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED
-- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE
-- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE
-- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A
-- PARTICULAR PURPOSE OF SAID MATERIAL.
--*
-- OBJECTIVE:
-- CHECK THAT AN INCOMPLETE TYPE WITH DISCRIMINANTS CAN BE
-- USED IN AN ACCESS TYPE DEFINITION WITH A COMPATIBLE DISCRIMINANT
-- CONSTRAINT.
-- HISTORY:
-- PMW 09/01/88 CREATED ORIGINAL TEST BY RENAMING E38104A.ADA.
WITH REPORT; USE REPORT;
PROCEDURE C38104A IS
BEGIN
TEST ("C38104A","INCOMPLETELY DECLARED TYPE CAN BE USED AS TYPE " &
"MARK IN ACCESS TYPE DEFINITION, AND CAN BE CONSTRAINED " &
"THERE OR LATER IF INCOMPLETE TYPE HAD DISCRIMINANT(S)");
DECLARE
TYPE T1;
TYPE T1_NAME IS ACCESS T1;
TYPE T1 IS
RECORD
COMP : INTEGER;
END RECORD;
TYPE T2(DISC : INTEGER := 5);
TYPE T2_NAME1 IS ACCESS T2(5);
TYPE T2_NAME2 IS ACCESS T2;
SUBTYPE SUB_T2_NAME2 IS T2_NAME2(5);
TYPE T2_NAME2_NAME IS ACCESS T2_NAME2(5);
X : T2_NAME2(5);
TYPE T2(DISC : INTEGER := 5) IS
RECORD
COMP : T2_NAME2(DISC);
END RECORD;
X1N : T1_NAME;
X2A,X2B : T2;
X2N2 : T2_NAME2;
BEGIN
IF EQUAL(3,3) THEN
X1N := NEW T1 '(COMP => 5);
END IF;
IF X1N.COMP /= 5 THEN
FAILED ("ASSIGNMENT FAILED - 1");
END IF;
X2A := (DISC => IDENT_INT(7), COMP => NULL);
X2N2 := NEW T2(IDENT_INT(7));
X2N2.ALL := X2A;
IF EQUAL(3,3) THEN
X2B := (DISC => IDENT_INT(7), COMP => X2N2);
END IF;
IF X2B.COMP.COMP /= NULL
OR X2B.COMP.DISC /= 7 THEN
FAILED ("ASSIGNMENT FAILED - 2");
END IF;
EXCEPTION
WHEN OTHERS =>
FAILED ("EXCEPTION RAISED");
END;
RESULT;
END C38104A;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- I N T E R F A C E S . O S 2 L I B --
-- --
-- S p e c --
-- --
-- $Revision$
-- --
-- Copyright (C) 1993-1997 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. --
-- --
------------------------------------------------------------------------------
-- This package (and children) provide interface definitions to the standard
-- OS/2 Library. They are merely a translation of the various <bse*.h> files.
-- It is intended that higher level interfaces (with better names, and
-- stronger typing!) be built on top of this one for Ada (i.e. clean)
-- programming.
-- We have chosen to keep names, types, etc. as close as possible to the
-- C definition to provide easier reference to the documentation. The main
-- exception is when a formal and its type (in C) differed only by the case
-- of letters (like in HMUX hmux). In this case, we have prepended "F_" to
-- the formal (i.e. F_hmux : HMUX).
with Interfaces.C;
with Interfaces.C.Strings;
with System;
package Interfaces.OS2Lib is
pragma Preelaborate (OS2Lib);
package IC renames Interfaces.C;
package ICS renames Interfaces.C.Strings;
-------------------
-- General Types --
-------------------
type APIRET is new IC.unsigned_long;
type APIRET16 is new IC.unsigned_short;
subtype APIRET32 is APIRET;
subtype PSZ is ICS.chars_ptr;
subtype PCHAR is ICS.chars_ptr;
subtype PVOID is System.Address;
type PPVOID is access all PVOID;
type BOOL32 is new IC.unsigned_long;
False32 : constant BOOL32 := 0;
True32 : constant BOOL32 := 1;
type UCHAR is new IC.unsigned_char;
type USHORT is new IC.unsigned_short;
type ULONG is new IC.unsigned_long;
type PULONG is access all ULONG;
-- Coprocessor stack register element.
type FPREG is record
losig : ULONG; -- Low 32-bits of the mantissa
hisig : ULONG; -- High 32-bits of the mantissa
signexp : USHORT; -- Sign and exponent
end record;
pragma Convention (C, FPREG);
type AULONG is array (IC.size_t range <>) of ULONG;
type AFPREG is array (IC.size_t range <>) of FPREG;
type LHANDLE is new IC.unsigned_long;
NULLHANDLE : constant := 0;
---------------------
-- Time Management --
---------------------
function DosSleep (How_long : ULONG) return APIRET;
pragma Import (C, DosSleep, "DosSleep");
type DATETIME is record
hours : UCHAR;
minutes : UCHAR;
seconds : UCHAR;
hundredths : UCHAR;
day : UCHAR;
month : UCHAR;
year : USHORT;
timezone : IC.short;
weekday : UCHAR;
end record;
type PDATETIME is access all DATETIME;
function DosGetDateTime (pdt : PDATETIME) return APIRET;
pragma Import (C, DosGetDateTime, "DosGetDateTime");
function DosSetDateTime (pdt : PDATETIME) return APIRET;
pragma Import (C, DosSetDateTime, "DosSetDateTime");
----------------------------
-- Miscelleneous Features --
----------------------------
-- Features which do not fit any child
function DosBeep (Freq : ULONG; Dur : ULONG) return APIRET;
pragma Import (C, DosBeep, "DosBeep");
procedure Must_Not_Fail (Return_Code : OS2Lib.APIRET);
pragma Inline (Must_Not_Fail);
-- Many OS/2 functions return APIRET and are not supposed to fail. In C
-- style, these would be called as procedures, disregarding the returned
-- value. This procedure can be used to achieve the same effect with a
-- call of the form: Must_Not_Fail (Some_OS2_Function (...));
procedure Sem_Must_Not_Fail (Return_Code : OS2Lib.APIRET);
pragma Inline (Sem_Must_Not_Fail);
-- Similar to Must_Not_Fail, but used in the case of DosPostEventSem,
-- where the "error" code ERROR_ALREADY_POSTED is not really an error.
end Interfaces.OS2Lib;
|
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
package Opt41_Pkg is
type Enum is (One, Two, Three, Four, Five, Six);
type Rec (D : Enum) is record
case D is
when One =>
I : Integer;
when Two | Five | Six =>
S : Unbounded_String;
case D is
when Two => B : Boolean;
when others => null;
end case;
when others =>
null;
end case;
end record;
type Rec_Ptr is access all Rec;
function Rec_Write (R : Rec) return Unbounded_String;
function Rec_Read (Str : String_Access) return Rec;
end Opt41_Pkg;
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT INTERFACE COMPONENTS --
-- --
-- A S I S . A D A _ E N V I R O N M E N T S . C O N T A I N E R S --
-- --
-- S p e c --
-- --
-- Copyright (c) 1995-2006, Free Software Foundation, Inc. --
-- --
-- This specification is derived from the Ada Semantic Interface --
-- Specification Standard (ISO/IEC 15291) for use with GNAT. The copyright --
-- notice above, and the license provisions that follow apply solely to the --
-- contents of the part following the private keyword. --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 51 Franklin --
-- Street, Fifth Floor, Boston, MA 02110-1301, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by AdaCore --
-- (http://www.adacore.com). --
-- --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- 9 package Asis.Ada_Environments.Containers
------------------------------------------------------------------------------
------------------------------------------------------------------------------
package Asis.Ada_Environments.Containers is
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Asis.Ada_Environments.Containers
--
-- If an Ada implementation supports the notion of a program library or
-- "library" as specified in Subclause 10(2) of the Ada Reference Manual,
-- then an ASIS Context value can be mapped onto one or more implementor
-- libraries represented by Containers.
--
------------------------------------------------------------------------------
-- 9.1 type Container
------------------------------------------------------------------------------
--
-- The Container abstraction is a logical collection of compilation units.
-- For example, one container might hold compilation units which include Ada
-- predefined library units, another container might hold
-- implementation-defined packages. Alternatively, there might be 26
-- containers, each holding compilation units that begin with their respective
-- letter of the alphabet. The point is that no implementation-independent
-- semantics are associated with a container; it is simply a logical
-- collection.
--
-- ASIS implementations shall minimally map the Asis.Context to a list of
-- one ASIS Container whose Name is that of the Asis.Context Name.
------------------------------------------------------------------------------
type Container is private;
Nil_Container : constant Container;
function "="
(Left : Container;
Right : Container)
return Boolean is abstract;
------------------------------------------------------------------------------
-- 9.2 type Container_List
------------------------------------------------------------------------------
type Container_List is array (List_Index range <>) of Container;
------------------------------------------------------------------------------
-- 9.3 function Defining_Containers
------------------------------------------------------------------------------
function Defining_Containers
(The_Context : Asis.Context)
return Container_List;
------------------------------------------------------------------------------
-- The_Context - Specifies the Context to define
--
-- Returns a Container_List value that defines the single environment Context.
-- Each Container will have an Enclosing_Context that Is_Identical to the
-- argument The_Context. The order of Container values in the list is not
-- defined.
--
-- Returns a minimal list of length one if the ASIS Ada implementation does
-- not support the concept of a program library. In this case, the Container
-- will have the same name as the given Context.
--
-- Raises ASIS_Inappropriate_Context if The_Context is not open.
--
------------------------------------------------------------------------------
-- 9.4 function Enclosing_Context
------------------------------------------------------------------------------
function Enclosing_Context
(The_Container : Container)
return Asis.Context;
------------------------------------------------------------------------------
-- The_Container - Specifies the Container to query
--
-- Returns the Context value associated with the Container.
--
-- Returns the Context for which the Container value was originally obtained.
-- Container values obtained through the Defining_Containers query will always
-- remember the Context from which they were defined.
--
-- Because Context is limited private, this function is only intended to be
-- used to supply a Context parameter for other queries.
--
-- Raises ASIS_Inappropriate_Container if the Container is a Nil_Container.
--
------------------------------------------------------------------------------
-- 9.5 function Library_Unit_Declaration
------------------------------------------------------------------------------
function Library_Unit_Declarations
(The_Container : Container)
return Asis.Compilation_Unit_List;
------------------------------------------------------------------------------
-- The_Container - Specifies the Container to query
--
-- Returns a list of all library_unit_declaration and
-- library_unit_renaming_declaration elements contained in the Container.
-- Individual units will appear only once in an order that is not defined.
--
-- A Nil_Compilation_Unit_List is returned if there are no declarations of
-- library units within the Container.
--
-- This query will never return a unit with A_Configuration_Compilation or
-- a Nonexistent unit kind. It will never return a unit with A_Procedure_Body
-- or A_Function_Body unit kind even though the unit is interpreted as both
-- the declaration and body of a library procedure or library function.
-- (Reference Manual 10.1.4(4).
--
-- All units in the result will have an Enclosing_Container value that
-- Is_Identical to the Container.
--
-- Raises ASIS_Inappropriate_Context if the Enclosing_Context(Container)
-- is not open.
--
------------------------------------------------------------------------------
-- 9.6 function Compilation_Unit_Bodies
------------------------------------------------------------------------------
function Compilation_Unit_Bodies
(The_Container : Container)
return Asis.Compilation_Unit_List;
------------------------------------------------------------------------------
-- The_Container - Specifies the Container to query
--
-- Returns a list of all library_unit_body and subunit elements contained in
-- the Container. Individual units will appear only once in an order that is
-- not defined.
--
-- A Nil_Compilation_Unit_List is returned if there are no bodies within the
-- Container.
--
-- This query will never return a unit with A_Configuration_Compilation or
-- a nonexistent unit kind.
--
-- All units in the result will have an Enclosing_Container value that
-- Is_Identical to the Container.
--
-- Raises ASIS_Inappropriate_Context if the Enclosing_Context(Container)
-- is not open.
--
------------------------------------------------------------------------------
-- 9.7 function Compilation_Units
------------------------------------------------------------------------------
function Compilation_Units
(The_Container : Container)
return Asis.Compilation_Unit_List;
------------------------------------------------------------------------------
-- The_Container - Specifies the Container to query
--
-- Returns a list of all compilation units contained in the Container.
-- Individual units will appear only once in an order that is not defined.
--
-- A Nil_Compilation_Unit_List is returned if there are no units within the
-- Container.
--
-- This query will never return a unit with A_Configuration_Compilation or
-- a nonexistent unit kind.
--
-- All units in the result will have an Enclosing_Container value that
-- Is_Identical to the Container.
--
-- Raises ASIS_Inappropriate_Context if the Enclosing_Context(Container)
-- is not open.
--
------------------------------------------------------------------------------
-- 9.8 function Is_Equal
------------------------------------------------------------------------------
function Is_Equal
(Left : Container;
Right : Container)
return Boolean;
------------------------------------------------------------------------------
-- Left - Specifies the first Container
-- Right - Specifies the second Container
--
-- Returns True if Left and Right designate Container values that contain the
-- same set of compilation units. The Container values may have been defined
-- from different Context values.
--
------------------------------------------------------------------------------
-- 9.9 function Is_Identical
------------------------------------------------------------------------------
function Is_Identical
(Left : Container;
Right : Container)
return Boolean;
------------------------------------------------------------------------------
-- Left - Specifies the first Container
-- Right - Specifies the second Container
--
-- Returns True if Is_Equal(Left, Right) and the Container values have been
-- defined from Is_Equal Context values.
--
------------------------------------------------------------------------------
-- 9.10 function Name
------------------------------------------------------------------------------
function Name (The_Container : Container) return Wide_String;
------------------------------------------------------------------------------
-- The_Container - Specifies the Container to name
--
-- Returns the Name value associated with the Container.
--
-- Returns a null string if the Container is a Nil_Container.
private
type Container is record
Id : Container_Id := Nil_Container_Id;
Cont_Id : Context_Id := Non_Associated;
Obtained : ASIS_OS_Time := Nil_ASIS_OS_Time;
end record;
Nil_Container : constant Container :=
(Id => Nil_Container_Id,
Cont_Id => Non_Associated,
Obtained => Nil_ASIS_OS_Time);
end Asis.Ada_Environments.Containers;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- S Y S T E M . M M A P --
-- --
-- S p e c --
-- --
-- Copyright (C) 2007-2016, AdaCore --
-- --
-- This library is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 3, or (at your option) any later --
-- version. This library is distributed in the hope that it will be useful, --
-- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- --
-- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package provides memory mapping of files. Depending on your operating
-- system, this might provide a more efficient method for accessing the
-- contents of files.
-- A description of memory-mapping is available on the sqlite page, at:
-- http://www.sqlite.org/mmap.html
--
-- The traditional method for reading a file is to allocate a buffer in the
-- application address space, then open the file and copy its contents. When
-- memory mapping is available though, the application asks the operating
-- system to return a pointer to the requested page, if possible. If the
-- requested page has been or can be mapped into the application address
-- space, the system returns a pointer to that page for the application to
-- use without having to copy anything. Skipping the copy step is what makes
-- memory mapped I/O faster.
--
-- When memory mapping is not available, this package automatically falls
-- back to the traditional copy method.
--
-- Example of use for this package, when reading a file that can be fully
-- mapped
--
-- declare
-- File : Mapped_File;
-- Str : Str_Access;
-- begin
-- File := Open_Read ("/tmp/file_on_disk");
-- Read (File); -- read the whole file
-- Str := Data (File);
-- for S in 1 .. Last (File) loop
-- Put (Str (S));
-- end loop;
-- Close (File);
-- end;
--
-- When the file is big, or you only want to access part of it at a given
-- time, you can use the following type of code.
-- declare
-- File : Mapped_File;
-- Str : Str_Access;
-- Offs : File_Size := 0;
-- Page : constant Integer := Get_Page_Size;
-- begin
-- File := Open_Read ("/tmp/file_on_disk");
-- while Offs < Length (File) loop
-- Read (File, Offs, Length => Long_Integer (Page) * 4);
-- Str := Data (File);
--
-- -- Print characters for this chunk:
-- for S in Integer (Offs - Offset (File)) + 1 .. Last (File) loop
-- Put (Str (S));
-- end loop;
--
-- -- Since we are reading multiples of Get_Page_Size, we can simplify
-- -- with
-- -- for S in 1 .. Last (File) loop ...
--
-- Offs := Offs + Long_Integer (Last (File));
-- end loop;
with Interfaces.C;
with System.Strings;
package System.Mmap is
type Mapped_File is private;
-- File to be mapped in memory.
-- This package will use the fastest possible algorithm to load the
-- file in memory. On systems that support it, the file is not really
-- loaded in memory. Instead, a call to the mmap() system call (or
-- CreateFileMapping()) will keep the file on disk, but make it
-- accessible as if it was in memory.
-- When the system does not support it, the file is actually loaded in
-- memory through calls to read(), and written back with write() when you
-- close it. This is of course much slower.
-- Legacy: each mapped file has a "default" mapped region in it.
type Mapped_Region is private;
-- A representation of part of a file in memory. Actual reading/writing
-- is done through a mapped region. After being returned by Read, a mapped
-- region must be free'd when done. If the original Mapped_File was open
-- for reading, it can be closed before the mapped region is free'd.
Invalid_Mapped_File : constant Mapped_File;
Invalid_Mapped_Region : constant Mapped_Region;
type Unconstrained_String is new String (Positive);
type Str_Access is access all Unconstrained_String;
pragma No_Strict_Aliasing (Str_Access);
type File_Size is new Interfaces.C.size_t;
function To_Str_Access
(Str : System.Strings.String_Access) return Str_Access;
-- Convert Str. The returned value points to the same memory block, but no
-- longer includes the bounds, which you need to manage yourself
function Open_Read
(Filename : String;
Use_Mmap_If_Available : Boolean := True) return Mapped_File;
-- Open a file for reading. The same file can be shared by multiple
-- processes, that will see each others's changes as they occur.
-- Any attempt to write the data might result in a segmentation fault,
-- depending on how the file is open.
-- Name_Error is raised if the file does not exist.
-- Filename should be compatible with the filesystem.
function Open_Read_No_Exception
(Filename : String;
Use_Mmap_If_Available : Boolean := True) return Mapped_File;
-- Like Open_Read but return Invalid_Mapped_File in case of error
function Open_Write
(Filename : String;
Use_Mmap_If_Available : Boolean := True) return Mapped_File;
-- Open a file for writing.
-- You cannot change the length of the file.
-- Name_Error is raised if the file does not exist
-- Filename should be compatible with the filesystem.
procedure Close (File : in out Mapped_File);
-- Close the file, and unmap the memory that is used for the region
-- contained in File. If the system does not support the unmmap() system
-- call or equivalent, or these were not available for the file itself,
-- then the file is written back to the disk if it was opened for writing.
procedure Free (Region : in out Mapped_Region);
-- Unmap the memory that is used for this region and deallocate the region
procedure Read
(File : Mapped_File;
Region : in out Mapped_Region;
Offset : File_Size := 0;
Length : File_Size := 0;
Mutable : Boolean := False);
-- Read a specific part of File and set Region to the corresponding mapped
-- region, or re-use it if possible.
-- Offset is the number of bytes since the beginning of the file at which
-- we should start reading. Length is the number of bytes that should be
-- read. If set to 0, as much of the file as possible is read (presumably
-- the whole file unless you are reading a _huge_ file).
-- Note that no (un)mapping is is done if that part of the file is already
-- available through Region.
-- If the file was opened for writing, any modification you do to the
-- data stored in File will be stored on disk (either immediately when the
-- file is opened through a mmap() system call, or when the file is closed
-- otherwise).
-- Mutable is processed only for reading files. If set to True, the
-- data can be modified, even through it will not be carried through the
-- underlying file, nor it is guaranteed to be carried through remapping.
-- This function takes care of page size alignment issues. The accessors
-- below only expose the region that has been requested by this call, even
-- if more bytes were actually mapped by this function.
-- TODO??? Enable to have a private copy for readable files
function Read
(File : Mapped_File;
Offset : File_Size := 0;
Length : File_Size := 0;
Mutable : Boolean := False) return Mapped_Region;
-- Likewise, return a new mapped region
procedure Read
(File : Mapped_File;
Offset : File_Size := 0;
Length : File_Size := 0;
Mutable : Boolean := False);
-- Likewise, use the legacy "default" region in File
function Length (File : Mapped_File) return File_Size;
-- Size of the file on the disk
function Offset (Region : Mapped_Region) return File_Size;
-- Return the offset, in the physical file on disk, corresponding to the
-- requested mapped region. The first byte in the file has offest 0.
function Offset (File : Mapped_File) return File_Size;
-- Likewise for the region contained in File
function Last (Region : Mapped_Region) return Integer;
-- Return the number of requested bytes mapped in this region. It is
-- erroneous to access Data for indices outside 1 .. Last (Region).
-- Such accesses may cause Storage_Error to be raised.
function Last (File : Mapped_File) return Integer;
-- Return the number of requested bytes mapped in the region contained in
-- File. It is erroneous to access Data for indices outside of 1 .. Last
-- (File); such accesses may cause Storage_Error to be raised.
function Data (Region : Mapped_Region) return Str_Access;
-- The data mapped in Region as requested. The result is an unconstrained
-- string, so you cannot use the usual 'First and 'Last attributes.
-- Instead, these are respectively 1 and Size.
function Data (File : Mapped_File) return Str_Access;
-- Likewise for the region contained in File
function Is_Mutable (Region : Mapped_Region) return Boolean;
-- Return whether it is safe to change bytes in Data (Region). This is true
-- for regions from writeable files, for regions mapped with the "Mutable"
-- flag set, and for regions that are copied in a buffer. Note that it is
-- not specified whether empty regions are mutable or not, since there is
-- no byte no modify.
function Is_Mmapped (File : Mapped_File) return Boolean;
-- Whether regions for this file are opened through an mmap() system call
-- or equivalent. This is in general irrelevant to your application, unless
-- the file can be accessed by multiple concurrent processes or tasks. In
-- such a case, and if the file is indeed mmap-ed, then the various parts
-- of the file can be written simulatenously, and thus you cannot ensure
-- the integrity of the file. If the file is not mmapped, the latest
-- process to Close it overwrite what other processes have done.
function Get_Page_Size return Integer;
-- Returns the number of bytes in a page. Once a file is mapped from the
-- disk, its offset and Length should be multiples of this page size (which
-- is ensured by this package in any case). Knowing this page size allows
-- you to map as much memory as possible at once, thus potentially reducing
-- the number of system calls to read the file by chunks.
function Read_Whole_File
(Filename : String;
Empty_If_Not_Found : Boolean := False)
return System.Strings.String_Access;
-- Returns the whole contents of the file.
-- The returned string must be freed by the user.
-- This is a convenience function, which is of course slower than the ones
-- above since we also need to allocate some memory, actually read the file
-- and copy the bytes.
-- If the file does not exist, null is returned. However, if
-- Empty_If_Not_Found is True, then the empty string is returned instead.
-- Filename should be compatible with the filesystem.
private
pragma Inline (Data, Length, Last, Offset, Is_Mmapped, To_Str_Access);
type Mapped_File_Record;
type Mapped_File is access Mapped_File_Record;
type Mapped_Region_Record;
type Mapped_Region is access Mapped_Region_Record;
Invalid_Mapped_File : constant Mapped_File := null;
Invalid_Mapped_Region : constant Mapped_Region := null;
end System.Mmap;
|
with EU_Projects.Nodes;
with EU_Projects.Times.Time_Expressions;
with Eu_Projects.Event_Names;
with EU_Projects.Node_Tables;
package Eu_Projects.Nodes.Timed_Nodes.Project_Infos is
type Project_Info is new Timed_Node with private;
type Info_Access is access all Project_Info;
function Create (Label : Node_Label;
Name : String;
Short_Name : String;
Stop_At : String;
Node_Dir : in out Node_Tables.Node_Table)
return Info_Access;
procedure Add_WP (Info : in out Project_Info;
WP : Node_Label);
overriding function Full_Index (Item : Project_Info;
Prefixed : Boolean) return String;
overriding function Get_Symbolic_Instant (Item : Project_Info;
Var : Simple_Identifier)
return Times.Time_Expressions.Symbolic_Instant;
overriding function Get_Symbolic_Duration (Item : Project_Info;
Var : Simple_Identifier)
return Times.Time_Expressions.Symbolic_Duration;
overriding function Dependency_List (Item : Project_Info)
return Node_Label_Lists.Vector;
overriding function Dependency_Ready_Var (Item : Project_Info) return String
is ("end");
function Variables (Item : Project_Info) return Variable_List
is ((1 => To_Id("end")));
overriding function Is_A (Item : Project_Info;
Var : Simple_Identifier;
Class : Times.Time_Type)
return Boolean
is (case Class is
when Times.Instant_Value =>
Var = "end",
when Times.Duration_Value =>
False);
private
type Project_Info is new Timed_Node
with
record
WPs : Node_Label_Lists.Vector;
end record;
overriding function Dependency_List (Item : Project_Info)
return Node_Label_Lists.Vector
is (Item.Wps);
overriding function Get_Symbolic_Instant
(Item : Project_Info;
Var : Simple_Identifier)
return Times.Time_Expressions.Symbolic_Instant
is (if Var = Event_Names.End_Name then
Item.Expected_Symbolic
else
raise Unknown_Instant_Var);
overriding function Get_Symbolic_Duration
(Item : Project_Info;
Var : Simple_Identifier)
return Times.Time_Expressions.Symbolic_Duration
is (raise Unknown_Duration_Var);
overriding function Full_Index (Item : Project_Info;
Prefixed : Boolean) return String
is ("");
end Eu_Projects.Nodes.Timed_Nodes.Project_Infos;
|
-- Copyright 2017-2021 Bartek thindil Jasicki
--
-- This file is part of Steam Sky.
--
-- Steam Sky is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Steam Sky is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with Steam Sky. If not, see <http://www.gnu.org/licenses/>.
with Ada.Containers; use Ada.Containers;
with Maps; use Maps;
with Messages; use Messages;
with Ships.Cargo; use Ships.Cargo;
with Ships.Crew; use Ships.Crew;
with Events; use Events;
with Crew; use Crew;
with Game; use Game;
with Utils; use Utils;
with Bases.Cargo; use Bases.Cargo;
with BasesTypes; use BasesTypes;
package body Trades is
procedure BuyItems
(BaseItemIndex: BaseCargo_Container.Extended_Index; Amount: String) is
BuyAmount, Price: Positive;
BaseIndex: constant Extended_Base_Range :=
SkyMap(Player_Ship.Sky_X, Player_Ship.Sky_Y).BaseIndex;
Cost: Natural;
MoneyIndex2: Inventory_Container.Extended_Index;
EventIndex: constant Events_Container.Extended_Index :=
SkyMap(Player_Ship.Sky_X, Player_Ship.Sky_Y).EventIndex;
ItemName, ItemIndex: Unbounded_String;
TraderIndex: constant Crew_Container.Extended_Index := FindMember(Talk);
begin
BuyAmount := Positive'Value(Amount);
if TraderIndex = 0 then
raise Trade_No_Trader;
end if;
if BaseIndex > 0 then
ItemIndex := Sky_Bases(BaseIndex).Cargo(BaseItemIndex).Proto_Index;
ItemName := Items_List(ItemIndex).Name;
Price := Sky_Bases(BaseIndex).Cargo(BaseItemIndex).Price;
if EventIndex > 0
and then
(Events_List(EventIndex).EType = DoublePrice and
Events_List(EventIndex).ItemIndex = ItemIndex) then
Price := Price * 2;
end if;
else
ItemIndex := TraderCargo(BaseItemIndex).Proto_Index;
ItemName := Items_List(ItemIndex).Name;
if TraderCargo(BaseItemIndex).Amount < BuyAmount then
raise Trade_Buying_Too_Much with To_String(ItemName);
end if;
Price := TraderCargo(BaseItemIndex).Price;
end if;
Cost := BuyAmount * Price;
Count_Price(Cost, TraderIndex);
MoneyIndex2 := FindItem(Player_Ship.Cargo, Money_Index);
if FreeCargo(Cost - (Items_List(ItemIndex).Weight * BuyAmount)) < 0 then
raise Trade_No_Free_Cargo;
end if;
if MoneyIndex2 = 0 then
raise Trade_No_Money with To_String(ItemName);
end if;
if Cost > Player_Ship.Cargo(MoneyIndex2).Amount then
raise Trade_Not_Enough_Money with To_String(ItemName);
end if;
UpdateCargo
(Ship => Player_Ship, CargoIndex => MoneyIndex2, Amount => (0 - Cost));
if BaseIndex > 0 then
Update_Base_Cargo(Money_Index, Cost);
else
TraderCargo(1).Amount := TraderCargo(1).Amount + Cost;
end if;
if BaseIndex > 0 then
UpdateCargo
(Ship => Player_Ship, ProtoIndex => ItemIndex, Amount => BuyAmount,
Durability => Sky_Bases(BaseIndex).Cargo(BaseItemIndex).Durability,
Price => Price);
Update_Base_Cargo
(Cargo_Index => BaseItemIndex, Amount => (0 - BuyAmount),
Durability =>
Sky_Bases(BaseIndex).Cargo.Element(BaseItemIndex).Durability);
Gain_Rep(BaseIndex, 1);
else
UpdateCargo
(Ship => Player_Ship, ProtoIndex => ItemIndex, Amount => BuyAmount,
Durability => TraderCargo(BaseItemIndex).Durability,
Price => Price);
TraderCargo(BaseItemIndex).Amount :=
TraderCargo(BaseItemIndex).Amount - BuyAmount;
if TraderCargo(BaseItemIndex).Amount = 0 then
TraderCargo.Delete(Index => BaseItemIndex);
end if;
end if;
GainExp(1, Talking_Skill, TraderIndex);
AddMessage
("You bought" & Positive'Image(BuyAmount) & " " & To_String(ItemName) &
" for" & Positive'Image(Cost) & " " & To_String(Money_Name) & ".",
TradeMessage);
if BaseIndex = 0 and EventIndex > 0 then
Events_List(EventIndex).Time := Events_List(EventIndex).Time + 5;
end if;
Update_Game(5);
exception
when Constraint_Error =>
raise Trade_Invalid_Amount;
end BuyItems;
procedure SellItems
(ItemIndex: Inventory_Container.Extended_Index; Amount: String) is
SellAmount: Positive;
BaseIndex: constant Extended_Base_Range :=
SkyMap(Player_Ship.Sky_X, Player_Ship.Sky_Y).BaseIndex;
ProtoIndex: constant Unbounded_String :=
Player_Ship.Cargo(ItemIndex).ProtoIndex;
ItemName: constant String := To_String(Items_List(ProtoIndex).Name);
Price: Positive;
EventIndex: constant Events_Container.Extended_Index :=
SkyMap(Player_Ship.Sky_X, Player_Ship.Sky_Y).EventIndex;
BaseItemIndex: Natural := 0;
CargoAdded: Boolean := False;
TraderIndex: constant Crew_Container.Extended_Index := FindMember(Talk);
Profit: Integer;
begin
SellAmount := Positive'Value(Amount);
if TraderIndex = 0 then
raise Trade_No_Trader;
end if;
if BaseIndex > 0 then
BaseItemIndex := Find_Base_Cargo(ProtoIndex);
else
Find_Base_Index_Loop :
for I in TraderCargo.Iterate loop
if TraderCargo(I).Proto_Index = ProtoIndex then
BaseItemIndex := BaseCargo_Container.To_Index(I);
exit Find_Base_Index_Loop;
end if;
end loop Find_Base_Index_Loop;
end if;
if BaseItemIndex = 0 then
Price := Get_Price(Sky_Bases(BaseIndex).Base_Type, ProtoIndex);
else
Price :=
(if BaseIndex > 0 then
Sky_Bases(BaseIndex).Cargo(BaseItemIndex).Price
else TraderCargo(BaseItemIndex).Price);
end if;
if EventIndex > 0 and then Events_List(EventIndex).EType = DoublePrice
and then Events_List(EventIndex).ItemIndex = ProtoIndex then
Price := Price * 2;
end if;
Profit := Price * SellAmount;
if Player_Ship.Cargo(ItemIndex).Durability < 100 then
Profit :=
Positive
(Float'Floor
(Float(Profit) *
(Float(Player_Ship.Cargo(ItemIndex).Durability) / 100.0)));
end if;
Count_Price(Profit, TraderIndex, False);
Pay_Trade_Profit_Loop :
for I in Player_Ship.Crew.Iterate loop
if Player_Ship.Crew(I).Payment(2) = 0 then
goto End_Of_Loop;
end if;
if Profit < 1 then
UpdateMorale
(Player_Ship, Crew_Container.To_Index(I), Get_Random(-25, -5));
AddMessage
(To_String(Player_Ship.Crew(I).Name) &
" is sad because doesn't get own part of profit.",
TradeMessage, RED);
Profit := 0;
goto End_Of_Loop;
end if;
Profit :=
Profit -
Positive
(Float'Ceiling
(Float(Profit) *
(Float(Player_Ship.Crew(I).Payment(2)) / 100.0)));
if Profit < 1 then
if Profit < 0 then
UpdateMorale
(Player_Ship, Crew_Container.To_Index(I),
Get_Random(-12, -2));
AddMessage
(To_String(Player_Ship.Crew(I).Name) &
" is sad because doesn't get own part of profit.",
TradeMessage, RED);
end if;
Profit := 0;
end if;
<<End_Of_Loop>>
end loop Pay_Trade_Profit_Loop;
if FreeCargo((Items_List(ProtoIndex).Weight * SellAmount) - Profit) <
0 then
raise Trade_No_Free_Cargo;
end if;
if BaseIndex > 0 then
if Profit > Sky_Bases(BaseIndex).Cargo(1).Amount then
raise Trade_No_Money_In_Base with ItemName;
end if;
Update_Base_Cargo
(ProtoIndex, SellAmount,
Player_Ship.Cargo.Element(ItemIndex).Durability);
else
if Profit > TraderCargo(1).Amount then
raise Trade_No_Money_In_Base with ItemName;
end if;
Update_Trader_Cargo_Loop :
for I in TraderCargo.Iterate loop
if TraderCargo(I).Proto_Index = ProtoIndex and
TraderCargo(I).Durability =
Player_Ship.Cargo(ItemIndex).Durability then
TraderCargo(I).Amount := TraderCargo(I).Amount + SellAmount;
CargoAdded := True;
exit Update_Trader_Cargo_Loop;
end if;
end loop Update_Trader_Cargo_Loop;
if not CargoAdded then
TraderCargo.Append
(New_Item =>
(Proto_Index => ProtoIndex, Amount => SellAmount,
Durability => Player_Ship.Cargo(ItemIndex).Durability,
Price => Items_List(ProtoIndex).Price));
end if;
end if;
UpdateCargo
(Ship => Player_Ship, CargoIndex => ItemIndex,
Amount => (0 - SellAmount),
Price => Player_Ship.Cargo.Element(ItemIndex).Price);
UpdateCargo(Player_Ship, Money_Index, Profit);
if BaseIndex > 0 then
Update_Base_Cargo(Money_Index, (0 - Profit));
Gain_Rep(BaseIndex, 1);
if Items_List(ProtoIndex).Reputation >
Sky_Bases(BaseIndex).Reputation(1) then
Gain_Rep(BaseIndex, 1);
end if;
else
TraderCargo(1).Amount := TraderCargo(1).Amount - Profit;
end if;
GainExp(1, Talking_Skill, TraderIndex);
AddMessage
("You sold" & Positive'Image(SellAmount) & " " & ItemName & " for" &
Positive'Image(Profit) & " " & To_String(Money_Name) & ".",
TradeMessage);
if BaseIndex = 0 and EventIndex > 0 then
Events_List(EventIndex).Time := Events_List(EventIndex).Time + 5;
end if;
Update_Game(5);
exception
when Constraint_Error =>
raise Trade_Invalid_Amount;
end SellItems;
procedure GenerateTraderCargo(ProtoIndex: Unbounded_String) is
TraderShip: Ship_Record :=
Create_Ship
(ProtoIndex, Null_Unbounded_String, Player_Ship.Sky_X,
Player_Ship.Sky_Y, FULL_STOP);
CargoAmount: Natural range 0 .. 10 :=
(if TraderShip.Crew.Length < 5 then Get_Random(1, 3)
elsif TraderShip.Crew.Length < 10 then Get_Random(1, 5)
else Get_Random(1, 10));
CargoItemIndex, ItemIndex: Inventory_Container.Extended_Index;
ItemAmount: Positive range 1 .. 1_000;
NewItemIndex: Unbounded_String;
begin
TraderCargo.Clear;
Add_Items_To_Cargo_Loop :
for Item of TraderShip.Cargo loop
TraderCargo.Append
(New_Item =>
(Proto_Index => Item.ProtoIndex, Amount => Item.Amount,
Durability => 100, Price => Items_List(Item.ProtoIndex).Price));
end loop Add_Items_To_Cargo_Loop;
Generate_Cargo_Loop :
while CargoAmount > 0 loop
ItemAmount :=
(if TraderShip.Crew.Length < 5 then Get_Random(1, 100)
elsif TraderShip.Crew.Length < 10 then Get_Random(1, 500)
else Get_Random(1, 1_000));
ItemIndex := Get_Random(1, Positive(Items_List.Length));
Find_Item_Index_Loop :
for I in Items_List.Iterate loop
ItemIndex := ItemIndex - 1;
if ItemIndex = 0 then
NewItemIndex := Objects_Container.Key(I);
exit Find_Item_Index_Loop;
end if;
end loop Find_Item_Index_Loop;
CargoItemIndex := FindItem(TraderShip.Cargo, NewItemIndex);
if CargoItemIndex > 0 then
TraderCargo(CargoItemIndex).Amount :=
TraderCargo(CargoItemIndex).Amount + ItemAmount;
TraderShip.Cargo(CargoItemIndex).Amount :=
TraderShip.Cargo(CargoItemIndex).Amount + ItemAmount;
else
if FreeCargo(0 - (Items_List(NewItemIndex).Weight * ItemAmount)) >
-1 then
TraderCargo.Append
(New_Item =>
(Proto_Index => NewItemIndex, Amount => ItemAmount,
Durability => 100,
Price => Items_List(NewItemIndex).Price));
TraderShip.Cargo.Append
(New_Item =>
(ProtoIndex => NewItemIndex, Amount => ItemAmount,
Durability => 100, Name => Null_Unbounded_String,
Price => 0));
else
CargoAmount := 1;
end if;
end if;
CargoAmount := CargoAmount - 1;
end loop Generate_Cargo_Loop;
end GenerateTraderCargo;
end Trades;
|
-- Standard Ada library specification
-- Copyright (c) 2003-2018 Maxim Reznik <reznikmm@gmail.com>
-- 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
---------------------------------------------------------------------------
with System;
package Ada.Execution_Time.Group_Budgets is
type Group_Budget is tagged limited private;
type Group_Budget_Handler is
access protected procedure (GB : in out Group_Budget);
type Task_Array is
array (Positive range <>) of Ada.Task_Identification.Task_Id;
Min_Handler_Ceiling : constant System.Any_Priority
:= implementation_defined;
procedure Add_Task (GB : in out Group_Budget;
T : in Ada.Task_Identification.Task_Id);
procedure Remove_Task (GB : in out Group_Budget;
T : in Ada.Task_Identification.Task_Id);
function Is_Member (GB : in Group_Budget;
T : in Ada.Task_Identification.Task_Id)
return Boolean;
function Is_A_Group_Member (T : in Ada.Task_Identification.Task_Id)
return Boolean;
function Members (GB : in Group_Budget) return Task_Array;
procedure Replenish (GB : in out Group_Budget;
To : in Ada.Real_Time.Time_Span);
procedure Add (GB : in out Group_Budget;
Interval : in Ada.Real_Time.Time_Span);
function Budget_Has_Expired (GB : in Group_Budget) return Boolean;
function Budget_Remaining (GB : in Group_Budget)
return Ada.Real_Time.Time_Span;
procedure Set_Handler (GB : in out Group_Budget;
Handler : in Group_Budget_Handler);
function Current_Handler (GB : in Group_Budget) return Group_Budget_Handler;
procedure Cancel_Handler (GB : in out Group_Budget;
Cancelled : out Boolean);
Group_Budget_Error : exception;
private
pragma Import (Ada, Group_Budget);
end Ada.Execution_Time.Group_Budgets;
|
-- This spec has been automatically generated from msp430g2553.svd
pragma Restrictions (No_Elaboration_Code);
pragma Ada_2012;
pragma Style_Checks (Off);
with System;
-- USCI_B0 I2C Mode
package MSP430_SVD.USCI_B0_I2C_MODE is
pragma Preelaborate;
---------------
-- Registers --
---------------
-- Sync. Mode: USCI Mode 1
type UCB0CTL0_UCMODE_Field is
(-- Sync. Mode: USCI Mode: 0
Ucmode_0,
-- Sync. Mode: USCI Mode: 1
Ucmode_1,
-- Sync. Mode: USCI Mode: 2
Ucmode_2,
-- Sync. Mode: USCI Mode: 3
Ucmode_3)
with Size => 2;
for UCB0CTL0_UCMODE_Field use
(Ucmode_0 => 0,
Ucmode_1 => 1,
Ucmode_2 => 2,
Ucmode_3 => 3);
-- USCI B0 Control Register 0
type UCB0CTL0_Register is record
-- Sync-Mode 0:UART-Mode / 1:SPI-Mode
UCSYNC : MSP430_SVD.Bit := 16#0#;
-- Sync. Mode: USCI Mode 1
UCMODE : UCB0CTL0_UCMODE_Field :=
MSP430_SVD.USCI_B0_I2C_MODE.Ucmode_0;
-- Sync. Mode: Master Select
UCMST : MSP430_SVD.Bit := 16#0#;
-- unspecified
Reserved_4_4 : MSP430_SVD.Bit := 16#0#;
-- Multi-Master Environment
UCMM : MSP430_SVD.Bit := 16#0#;
-- 10-bit Slave Address Mode
UCSLA10 : MSP430_SVD.Bit := 16#0#;
-- 10-bit Address Mode
UCA10 : MSP430_SVD.Bit := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 8,
Bit_Order => System.Low_Order_First;
for UCB0CTL0_Register use record
UCSYNC at 0 range 0 .. 0;
UCMODE at 0 range 1 .. 2;
UCMST at 0 range 3 .. 3;
Reserved_4_4 at 0 range 4 .. 4;
UCMM at 0 range 5 .. 5;
UCSLA10 at 0 range 6 .. 6;
UCA10 at 0 range 7 .. 7;
end record;
-- USCI 1 Clock Source Select 1
type UCB0CTL1_UCSSEL_Field is
(-- USCI 0 Clock Source: 0
Ucssel_0,
-- USCI 0 Clock Source: 1
Ucssel_1,
-- USCI 0 Clock Source: 2
Ucssel_2,
-- USCI 0 Clock Source: 3
Ucssel_3)
with Size => 2;
for UCB0CTL1_UCSSEL_Field use
(Ucssel_0 => 0,
Ucssel_1 => 1,
Ucssel_2 => 2,
Ucssel_3 => 3);
-- USCI B0 Control Register 1
type UCB0CTL1_Register is record
-- USCI Software Reset
UCSWRST : MSP430_SVD.Bit := 16#0#;
-- Transmit START
UCTXSTT : MSP430_SVD.Bit := 16#0#;
-- Transmit STOP
UCTXSTP : MSP430_SVD.Bit := 16#0#;
-- Transmit NACK
UCTXNACK : MSP430_SVD.Bit := 16#0#;
-- Transmit/Receive Select/Flag
UCTR : MSP430_SVD.Bit := 16#0#;
-- unspecified
Reserved_5_5 : MSP430_SVD.Bit := 16#0#;
-- USCI 1 Clock Source Select 1
UCSSEL : UCB0CTL1_UCSSEL_Field :=
MSP430_SVD.USCI_B0_I2C_MODE.Ucssel_0;
end record
with Volatile_Full_Access, Object_Size => 8,
Bit_Order => System.Low_Order_First;
for UCB0CTL1_Register use record
UCSWRST at 0 range 0 .. 0;
UCTXSTT at 0 range 1 .. 1;
UCTXSTP at 0 range 2 .. 2;
UCTXNACK at 0 range 3 .. 3;
UCTR at 0 range 4 .. 4;
Reserved_5_5 at 0 range 5 .. 5;
UCSSEL at 0 range 6 .. 7;
end record;
-- USCI B0 I2C Interrupt Enable Register
type UCB0I2CIE_Register is record
-- Arbitration Lost interrupt enable
UCALIE : MSP430_SVD.Bit := 16#0#;
-- START Condition interrupt enable
UCSTTIE : MSP430_SVD.Bit := 16#0#;
-- STOP Condition interrupt enable
UCSTPIE : MSP430_SVD.Bit := 16#0#;
-- NACK Condition interrupt enable
UCNACKIE : MSP430_SVD.Bit := 16#0#;
-- unspecified
Reserved_4_7 : MSP430_SVD.UInt4 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 8,
Bit_Order => System.Low_Order_First;
for UCB0I2CIE_Register use record
UCALIE at 0 range 0 .. 0;
UCSTTIE at 0 range 1 .. 1;
UCSTPIE at 0 range 2 .. 2;
UCNACKIE at 0 range 3 .. 3;
Reserved_4_7 at 0 range 4 .. 7;
end record;
-- USCI B0 Status Register
type UCB0STAT_Register is record
-- Arbitration Lost interrupt Flag
UCALIFG : MSP430_SVD.Bit := 16#0#;
-- START Condition interrupt Flag
UCSTTIFG : MSP430_SVD.Bit := 16#0#;
-- STOP Condition interrupt Flag
UCSTPIFG : MSP430_SVD.Bit := 16#0#;
-- NAK Condition interrupt Flag
UCNACKIFG : MSP430_SVD.Bit := 16#0#;
-- Bus Busy Flag
UCBBUSY : MSP430_SVD.Bit := 16#0#;
-- General Call address received Flag
UCGC : MSP430_SVD.Bit := 16#0#;
-- SCL low
UCSCLLOW : MSP430_SVD.Bit := 16#0#;
-- USCI Listen mode
UCLISTEN : MSP430_SVD.Bit := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 8,
Bit_Order => System.Low_Order_First;
for UCB0STAT_Register use record
UCALIFG at 0 range 0 .. 0;
UCSTTIFG at 0 range 1 .. 1;
UCSTPIFG at 0 range 2 .. 2;
UCNACKIFG at 0 range 3 .. 3;
UCBBUSY at 0 range 4 .. 4;
UCGC at 0 range 5 .. 5;
UCSCLLOW at 0 range 6 .. 6;
UCLISTEN at 0 range 7 .. 7;
end record;
-- UCB0I2COA_UCOA array
type UCB0I2COA_UCOA_Field_Array is array (0 .. 9) of MSP430_SVD.Bit
with Component_Size => 1, Size => 10;
-- Type definition for UCB0I2COA_UCOA
type UCB0I2COA_UCOA_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- UCOA as a value
Val : MSP430_SVD.UInt10;
when True =>
-- UCOA as an array
Arr : UCB0I2COA_UCOA_Field_Array;
end case;
end record
with Unchecked_Union, Size => 10;
for UCB0I2COA_UCOA_Field use record
Val at 0 range 0 .. 9;
Arr at 0 range 0 .. 9;
end record;
-- USCI B0 I2C Own Address
type UCB0I2COA_Register is record
-- I2C Own Address 0
UCOA : UCB0I2COA_UCOA_Field :=
(As_Array => False, Val => 16#0#);
-- unspecified
Reserved_10_14 : MSP430_SVD.UInt5 := 16#0#;
-- I2C General Call enable
UCGCEN : MSP430_SVD.Bit := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 16,
Bit_Order => System.Low_Order_First;
for UCB0I2COA_Register use record
UCOA at 0 range 0 .. 9;
Reserved_10_14 at 0 range 10 .. 14;
UCGCEN at 0 range 15 .. 15;
end record;
-- UCB0I2CSA_UCSA array
type UCB0I2CSA_UCSA_Field_Array is array (0 .. 9) of MSP430_SVD.Bit
with Component_Size => 1, Size => 10;
-- Type definition for UCB0I2CSA_UCSA
type UCB0I2CSA_UCSA_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- UCSA as a value
Val : MSP430_SVD.UInt10;
when True =>
-- UCSA as an array
Arr : UCB0I2CSA_UCSA_Field_Array;
end case;
end record
with Unchecked_Union, Size => 10;
for UCB0I2CSA_UCSA_Field use record
Val at 0 range 0 .. 9;
Arr at 0 range 0 .. 9;
end record;
-- USCI B0 I2C Slave Address
type UCB0I2CSA_Register is record
-- I2C Slave Address 0
UCSA : UCB0I2CSA_UCSA_Field :=
(As_Array => False, Val => 16#0#);
-- unspecified
Reserved_10_15 : MSP430_SVD.UInt6 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 16,
Bit_Order => System.Low_Order_First;
for UCB0I2CSA_Register use record
UCSA at 0 range 0 .. 9;
Reserved_10_15 at 0 range 10 .. 15;
end record;
-----------------
-- Peripherals --
-----------------
-- USCI_B0 I2C Mode
type USCI_B0_I2C_MODE_Peripheral is record
-- USCI B0 Control Register 0
UCB0CTL0 : aliased UCB0CTL0_Register;
-- USCI B0 Control Register 1
UCB0CTL1 : aliased UCB0CTL1_Register;
-- USCI B0 Baud Rate 0
UCB0BR0 : aliased MSP430_SVD.Byte;
-- USCI B0 Baud Rate 1
UCB0BR1 : aliased MSP430_SVD.Byte;
-- USCI B0 I2C Interrupt Enable Register
UCB0I2CIE : aliased UCB0I2CIE_Register;
-- USCI B0 Status Register
UCB0STAT : aliased UCB0STAT_Register;
-- USCI B0 Receive Buffer
UCB0RXBUF : aliased MSP430_SVD.Byte;
-- USCI B0 Transmit Buffer
UCB0TXBUF : aliased MSP430_SVD.Byte;
-- USCI B0 I2C Own Address
UCB0I2COA : aliased UCB0I2COA_Register;
-- USCI B0 I2C Slave Address
UCB0I2CSA : aliased UCB0I2CSA_Register;
end record
with Volatile;
for USCI_B0_I2C_MODE_Peripheral use record
UCB0CTL0 at 16#0# range 0 .. 7;
UCB0CTL1 at 16#1# range 0 .. 7;
UCB0BR0 at 16#2# range 0 .. 7;
UCB0BR1 at 16#3# range 0 .. 7;
UCB0I2CIE at 16#4# range 0 .. 7;
UCB0STAT at 16#5# range 0 .. 7;
UCB0RXBUF at 16#6# range 0 .. 7;
UCB0TXBUF at 16#7# range 0 .. 7;
UCB0I2COA at 16#B0# range 0 .. 15;
UCB0I2CSA at 16#B2# range 0 .. 15;
end record;
-- USCI_B0 I2C Mode
USCI_B0_I2C_MODE_Periph : aliased USCI_B0_I2C_MODE_Peripheral
with Import, Address => USCI_B0_I2C_MODE_Base;
end MSP430_SVD.USCI_B0_I2C_MODE;
|
-- This package has been generated automatically by GNATtest.
-- You are allowed to add your code to the bodies of test routines.
-- Such changes will be kept during further regeneration of this file.
-- All code placed outside of test routine bodies will be lost. The
-- code intended to set up and tear down the test environment should be
-- placed into Crew.Inventory.Test_Data.
with AUnit.Assertions; use AUnit.Assertions;
with System.Assertions;
-- begin read only
-- id:2.2/00/
--
-- This section can be used to add with clauses if necessary.
--
-- end read only
-- begin read only
-- end read only
package body Crew.Inventory.Test_Data.Tests is
-- begin read only
-- id:2.2/01/
--
-- This section can be used to add global variables and other elements.
--
-- end read only
-- begin read only
-- end read only
-- begin read only
procedure Wrap_Test_UpdateInventory_5fa756_83591c
(MemberIndex: Positive; Amount: Integer;
ProtoIndex: Unbounded_String := Null_Unbounded_String;
Durability: Items_Durability := 0;
InventoryIndex, Price: Natural := 0) is
begin
begin
pragma Assert
((MemberIndex <= Player_Ship.Crew.Last_Index and
InventoryIndex <=
Player_Ship.Crew(MemberIndex).Inventory.Last_Index));
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"req_sloc(crew-inventory.ads:0):Test_UpdateInventory test requirement violated");
end;
GNATtest_Generated.GNATtest_Standard.Crew.Inventory.UpdateInventory
(MemberIndex, Amount, ProtoIndex, Durability, InventoryIndex, Price);
begin
pragma Assert(True);
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"ens_sloc(crew-inventory.ads:0:):Test_UpdateInventory test commitment violated");
end;
end Wrap_Test_UpdateInventory_5fa756_83591c;
-- end read only
-- begin read only
procedure Test_UpdateInventory_test_updateinventory
(Gnattest_T: in out Test);
procedure Test_UpdateInventory_5fa756_83591c
(Gnattest_T: in out Test) renames
Test_UpdateInventory_test_updateinventory;
-- id:2.2/5fa7563a0327adb0/UpdateInventory/1/0/test_updateinventory/
procedure Test_UpdateInventory_test_updateinventory
(Gnattest_T: in out Test) is
procedure UpdateInventory
(MemberIndex: Positive; Amount: Integer;
ProtoIndex: Unbounded_String := Null_Unbounded_String;
Durability: Items_Durability := 0;
InventoryIndex, Price: Natural := 0) renames
Wrap_Test_UpdateInventory_5fa756_83591c;
-- end read only
pragma Unreferenced(Gnattest_T);
Amount: constant Positive :=
Positive(Player_Ship.Crew(1).Inventory.Length);
begin
UpdateInventory(1, 1, To_Unbounded_String("1"));
Assert
(Positive(Player_Ship.Crew(1).Inventory.Length) = Amount + 1,
"Failed to add item to crew member inventory.");
UpdateInventory(1, -1, To_Unbounded_String("1"));
Assert
(Positive(Player_Ship.Crew(1).Inventory.Length) = Amount,
"Failed to remove item from crew member inventory.");
begin
UpdateInventory(1, 10_000, To_Unbounded_String("1"));
Assert
(False,
"Failed to not add too much items to the crew member inventory.");
exception
when Crew_No_Space_Error =>
null;
when others =>
Assert
(False,
"Exception when trying to add more items than crew member can take.");
end;
-- begin read only
end Test_UpdateInventory_test_updateinventory;
-- end read only
-- begin read only
function Wrap_Test_FreeInventory_df8fe5_1b9261
(MemberIndex: Positive; Amount: Integer) return Integer is
begin
begin
pragma Assert(MemberIndex <= Player_Ship.Crew.Last_Index);
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"req_sloc(crew-inventory.ads:0):Test_FreeInventory test requirement violated");
end;
declare
Test_FreeInventory_df8fe5_1b9261_Result: constant Integer :=
GNATtest_Generated.GNATtest_Standard.Crew.Inventory.FreeInventory
(MemberIndex, Amount);
begin
begin
pragma Assert(True);
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"ens_sloc(crew-inventory.ads:0:):Test_FreeInventory test commitment violated");
end;
return Test_FreeInventory_df8fe5_1b9261_Result;
end;
end Wrap_Test_FreeInventory_df8fe5_1b9261;
-- end read only
-- begin read only
procedure Test_FreeInventory_test_freeinventory(Gnattest_T: in out Test);
procedure Test_FreeInventory_df8fe5_1b9261(Gnattest_T: in out Test) renames
Test_FreeInventory_test_freeinventory;
-- id:2.2/df8fe5d066a1fde9/FreeInventory/1/0/test_freeinventory/
procedure Test_FreeInventory_test_freeinventory(Gnattest_T: in out Test) is
function FreeInventory
(MemberIndex: Positive; Amount: Integer) return Integer renames
Wrap_Test_FreeInventory_df8fe5_1b9261;
-- end read only
pragma Unreferenced(Gnattest_T);
begin
if FreeInventory(1, 0) /= 0 then
Assert(True, "This test can only crash.");
end if;
-- begin read only
end Test_FreeInventory_test_freeinventory;
-- end read only
-- begin read only
procedure Wrap_Test_TakeOffItem_a8b09e_af73e9
(MemberIndex, ItemIndex: Positive) is
begin
begin
pragma Assert
((MemberIndex <= Player_Ship.Crew.Last_Index and
ItemIndex <= Player_Ship.Crew(MemberIndex).Inventory.Last_Index));
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"req_sloc(crew-inventory.ads:0):Test_TakeOffItem test requirement violated");
end;
GNATtest_Generated.GNATtest_Standard.Crew.Inventory.TakeOffItem
(MemberIndex, ItemIndex);
begin
pragma Assert(True);
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"ens_sloc(crew-inventory.ads:0:):Test_TakeOffItem test commitment violated");
end;
end Wrap_Test_TakeOffItem_a8b09e_af73e9;
-- end read only
-- begin read only
procedure Test_TakeOffItem_test_takeoffitem(Gnattest_T: in out Test);
procedure Test_TakeOffItem_a8b09e_af73e9(Gnattest_T: in out Test) renames
Test_TakeOffItem_test_takeoffitem;
-- id:2.2/a8b09e84477e626f/TakeOffItem/1/0/test_takeoffitem/
procedure Test_TakeOffItem_test_takeoffitem(Gnattest_T: in out Test) is
procedure TakeOffItem(MemberIndex, ItemIndex: Positive) renames
Wrap_Test_TakeOffItem_a8b09e_af73e9;
-- end read only
pragma Unreferenced(Gnattest_T);
begin
TakeOffItem(1, 1);
Assert
(not ItemIsUsed(1, 1),
"Failed to take off item from the player character.");
-- begin read only
end Test_TakeOffItem_test_takeoffitem;
-- end read only
-- begin read only
function Wrap_Test_ItemIsUsed_9a8ce5_329a6e
(MemberIndex, ItemIndex: Positive) return Boolean is
begin
begin
pragma Assert
((MemberIndex <= Player_Ship.Crew.Last_Index and
ItemIndex <= Player_Ship.Crew(MemberIndex).Inventory.Last_Index));
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"req_sloc(crew-inventory.ads:0):Test_ItemIsUsed test requirement violated");
end;
declare
Test_ItemIsUsed_9a8ce5_329a6e_Result: constant Boolean :=
GNATtest_Generated.GNATtest_Standard.Crew.Inventory.ItemIsUsed
(MemberIndex, ItemIndex);
begin
begin
pragma Assert(True);
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"ens_sloc(crew-inventory.ads:0:):Test_ItemIsUsed test commitment violated");
end;
return Test_ItemIsUsed_9a8ce5_329a6e_Result;
end;
end Wrap_Test_ItemIsUsed_9a8ce5_329a6e;
-- end read only
-- begin read only
procedure Test_ItemIsUsed_test_itemisused(Gnattest_T: in out Test);
procedure Test_ItemIsUsed_9a8ce5_329a6e(Gnattest_T: in out Test) renames
Test_ItemIsUsed_test_itemisused;
-- id:2.2/9a8ce5527fb6a663/ItemIsUsed/1/0/test_itemisused/
procedure Test_ItemIsUsed_test_itemisused(Gnattest_T: in out Test) is
function ItemIsUsed
(MemberIndex, ItemIndex: Positive) return Boolean renames
Wrap_Test_ItemIsUsed_9a8ce5_329a6e;
-- end read only
pragma Unreferenced(Gnattest_T);
begin
Assert
(ItemIsUsed(1, 1) = False, "Failed to detect that item is not used.");
Assert(ItemIsUsed(1, 2) = True, "Failed to detect that item is used.");
-- begin read only
end Test_ItemIsUsed_test_itemisused;
-- end read only
-- begin read only
function Wrap_Test_FindTools_9ef8ba_dbafa3
(MemberIndex: Positive; ItemType: Unbounded_String; Order: Crew_Orders;
ToolQuality: Positive := 100) return Natural is
begin
begin
pragma Assert
((MemberIndex <= Player_Ship.Crew.Last_Index and
ItemType /= Null_Unbounded_String));
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"req_sloc(crew-inventory.ads:0):Test_FindTools test requirement violated");
end;
declare
Test_FindTools_9ef8ba_dbafa3_Result: constant Natural :=
GNATtest_Generated.GNATtest_Standard.Crew.Inventory.FindTools
(MemberIndex, ItemType, Order, ToolQuality);
begin
begin
pragma Assert(True);
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"ens_sloc(crew-inventory.ads:0:):Test_FindTools test commitment violated");
end;
return Test_FindTools_9ef8ba_dbafa3_Result;
end;
end Wrap_Test_FindTools_9ef8ba_dbafa3;
-- end read only
-- begin read only
procedure Test_FindTools_test_findtools(Gnattest_T: in out Test);
procedure Test_FindTools_9ef8ba_dbafa3(Gnattest_T: in out Test) renames
Test_FindTools_test_findtools;
-- id:2.2/9ef8baa51d571ac0/FindTools/1/0/test_findtools/
procedure Test_FindTools_test_findtools(Gnattest_T: in out Test) is
function FindTools
(MemberIndex: Positive; ItemType: Unbounded_String; Order: Crew_Orders;
ToolQuality: Positive := 100) return Natural renames
Wrap_Test_FindTools_9ef8ba_dbafa3;
-- end read only
pragma Unreferenced(Gnattest_T);
begin
Assert
(FindTools(1, To_Unbounded_String("Bucket"), Clean) > 0,
"Failed to find tools for cleaning.");
Assert
(FindTools(1, To_Unbounded_String("sdfsdfds"), Talk) = 0,
"Failed to not find non-existing tools.");
-- begin read only
end Test_FindTools_test_findtools;
-- end read only
-- begin read only
-- id:2.2/02/
--
-- This section can be used to add elaboration code for the global state.
--
begin
-- end read only
null;
-- begin read only
-- end read only
end Crew.Inventory.Test_Data.Tests;
|
package Opt44 is
type Sarray is array (1 .. 4) of Float;
for Sarray'Alignment use 16;
procedure Addsub (X, Y : Sarray; R : out Sarray; N : Integer);
end Opt44;
|
-- The Village of Vampire by YT, このソースコードはNYSLです
procedure Vampire.R3.Refresh_Page (
Output : not null access Ada.Streams.Root_Stream_Type'Class;
Form : in Forms.Root_Form_Type'Class;
URI : in String) is
begin
case Form.Template_Set is
when Forms.For_Full =>
String'Write (
Output,
"<meta http-equiv=""REFRESH"" content=""0;URL=");
Forms.Write_In_Attribute (Output, Form, URI);
String'Write (
Output,
""" />"
& "<style>body{background-color:black;}</style>");
when Forms.For_Mobile =>
String'Write (
Output,
"<html>"
& "<head>"
& "<meta http-equiv=""CONTENT-TYPE"" content=""text/html; charset=SJIS"">"
& "<title>" & "The Village of Vampire" & "</title>"
& "</head>"
& "<body>"
& "<h1>" & "The Village of Vampire" & "</h1>"
& "<hr>"
& "<div>");
Forms.Write_In_HTML (Output, Form, "受理しました。");
String'Write (
Output,
"</div>"
& "<hr>"
& "<div><a href=""");
Forms.Write_In_Attribute (Output, Form, URI);
String'Write (
Output,
""">");
Forms.Write_In_HTML (Output, Form, "戻る");
String'Write (
Output,
"</a></div>"
& "</body>"
& "</html>");
end case;
end Vampire.R3.Refresh_Page;
|
--
--
--
with Sessions;
with Actions;
package Action_Algorithms is
subtype Session_Type is Sessions.Session_Type;
subtype Action_Record is Actions.Action_Record;
function Compute_Action (Session : Session_Type;
Action : Action_Record)
return Integer;
-- Given an action, compute the integer value for that action
-- which is to be put in the action table of the generated machine.
-- Return negative if no action should be generated.
end Action_Algorithms;
|
procedure Variant2 is
type POWER is (GAS, STEAM, DIESEL, NONE);
type VEHICLE (Engine : POWER := NONE) is
record
Model_Year : INTEGER range 1888..1992;
Wheels : INTEGER range 2..18;
case Engine is
when GAS => Cylinders : INTEGER range 1..16;
when STEAM => Boiler_Size : INTEGER range 5..22;
Coal_Burner : BOOLEAN;
when DIESEL => Fuel_Inject : BOOLEAN;
when NONE => Speeds : INTEGER range 1..15;
end case;
end record;
Ford, Truck, Schwinn : VEHICLE;
Stanley : VEHICLE(STEAM);
begin
Ford := (GAS, 1956, 4, 8);
Ford := (DIESEL, 1985, Fuel_Inject => TRUE, Wheels => 8);
Truck := (DIESEL, 1966, 18, TRUE);
Truck.Model_Year := 1968;
Truck.Fuel_Inject := FALSE;
Stanley.Model_Year := 1908; -- This is constant as STEAM
Stanley.Wheels := 4;
Stanley.Boiler_Size := 21;
Stanley.Coal_Burner := FALSE;
Schwinn.Speeds := 10; -- This defaults to NONE
Schwinn.Wheels := 2;
Schwinn.Model_Year := 1985;
end Variant2;
|
with Ada.Streams;
with Ada.Text_IO.Text_Streams;
with iconv.Streams;
procedure stream_w is
use type Ada.Streams.Stream_Element_Offset;
Std_Input : constant Ada.Text_IO.Text_Streams.Stream_Access :=
Ada.Text_IO.Text_Streams.Stream (Ada.Text_IO.Standard_Input.all);
Std_Output : constant Ada.Text_IO.Text_Streams.Stream_Access :=
Ada.Text_IO.Text_Streams.Stream (Ada.Text_IO.Standard_Output.all);
iconv_Converter : aliased iconv.Converter :=
iconv.Open (To => "UTF-8", From => "ISO-2022-JP-3");
iconv_Output : aliased iconv.Streams.Out_Type :=
iconv.Streams.Open (iconv_Converter, Stream => Std_Output);
S : Ada.Streams.Stream_Element_Array (1 .. 1);
Last : Ada.Streams.Stream_Element_Count;
begin
loop
Ada.Streams.Read (Std_Input.all, S, Last);
exit when Last = 0;
Ada.Streams.Write (iconv.Streams.Stream (iconv_Output).all, S);
end loop;
iconv.Streams.Finish (iconv_Output);
end stream_w;
|
-- C74302B.ADA
-- Grant of Unlimited Rights
--
-- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687,
-- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained
-- unlimited rights in the software and documentation contained herein.
-- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making
-- this public release, the Government intends to confer upon all
-- recipients unlimited rights equal to those held by the Government.
-- These rights include rights to use, duplicate, release or disclose the
-- released technical data and computer software in whole or in part, in
-- any manner and for any purpose whatsoever, and to have or permit others
-- to do so.
--
-- DISCLAIMER
--
-- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR
-- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED
-- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE
-- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE
-- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A
-- PARTICULAR PURPOSE OF SAID MATERIAL.
--*
-- OBJECTIVE:
-- CHECK THAT WHEN THE FULL DECLARATION OF A DEFERRED CONSTANT IS
-- GIVEN AS A MULTIPLE DECLARATION, THE INITIALIZATION EXPRESSION
-- IS EVALUATED ONCE FOR EACH DEFERRED CONSTANT. (USE ENUMERATION,
-- INTEGER, FIXED POINT, FLOATING POINT, ARRAY, RECORD (INCLUDING
-- USE OF DEFAULT EXPRESSIONS FOR COMPONENTS), ACCESS, AND PRIVATE
-- TYPES AS FULL DECLARATION OF PRIVATE TYPE)
-- HISTORY:
-- BCB 07/25/88 CREATED ORIGINAL TEST.
WITH REPORT; USE REPORT;
PROCEDURE C74302B IS
TYPE ARR_RAN IS RANGE 1..2;
BUMP : INTEGER := IDENT_INT(0);
GENERIC
TYPE DT IS (<>);
FUNCTION F1 RETURN DT;
GENERIC
TYPE FE IS DELTA <>;
FUNCTION F2 RETURN FE;
GENERIC
TYPE FLE IS DIGITS <>;
FUNCTION F3 RETURN FLE;
GENERIC
TYPE CA IS ARRAY(ARR_RAN) OF INTEGER;
FUNCTION F4 RETURN CA;
GENERIC
TYPE GP IS LIMITED PRIVATE;
FUNCTION F5 (V : GP) RETURN GP;
GENERIC
TYPE GP1 IS LIMITED PRIVATE;
FUNCTION F6 (V1 : GP1) RETURN GP1;
GENERIC
TYPE AC IS ACCESS INTEGER;
FUNCTION F7 RETURN AC;
GENERIC
TYPE PP IS PRIVATE;
FUNCTION F8 (P1 : PP) RETURN PP;
FUNCTION F1 RETURN DT IS
BEGIN
BUMP := BUMP + 1;
RETURN DT'VAL(BUMP);
END F1;
FUNCTION F2 RETURN FE IS
BEGIN
BUMP := BUMP + 1;
RETURN FE(BUMP);
END F2;
FUNCTION F3 RETURN FLE IS
BEGIN
BUMP := BUMP + 1;
RETURN FLE(BUMP);
END F3;
FUNCTION F4 RETURN CA IS
BEGIN
BUMP := BUMP + 1;
RETURN ((BUMP,BUMP-1));
END F4;
FUNCTION F5 (V : GP) RETURN GP IS
BEGIN
BUMP := BUMP + 1;
RETURN V;
END F5;
FUNCTION F6 (V1 : GP1) RETURN GP1 IS
BEGIN
BUMP := BUMP + 1;
RETURN V1;
END F6;
FUNCTION F7 RETURN AC IS
VAR : AC;
BEGIN
BUMP := BUMP + 1;
VAR := NEW INTEGER'(BUMP);
RETURN VAR;
END F7;
FUNCTION F8 (P1 : PP) RETURN PP IS
BEGIN
BUMP := BUMP + 1;
RETURN P1;
END F8;
PACKAGE PACK IS
TYPE SP IS PRIVATE;
CONS : CONSTANT SP;
PRIVATE
TYPE SP IS RANGE 1 .. 100;
CONS : CONSTANT SP := 50;
END PACK;
USE PACK;
PACKAGE P IS
TYPE INT IS PRIVATE;
TYPE ENUM IS PRIVATE;
TYPE FIX IS PRIVATE;
TYPE FLT IS PRIVATE;
TYPE CON_ARR IS PRIVATE;
TYPE REC IS PRIVATE;
TYPE REC1 IS PRIVATE;
TYPE ACC IS PRIVATE;
TYPE PRIV IS PRIVATE;
GENERIC
TYPE LP IS PRIVATE;
FUNCTION GEN_EQUAL (Z1, Z2 : LP) RETURN BOOLEAN;
I1, I2, I3, I4 : CONSTANT INT;
E1, E2, E3, E4 : CONSTANT ENUM;
FI1, FI2, FI3, FI4 : CONSTANT FIX;
FL1, FL2, FL3, FL4 : CONSTANT FLT;
CA1, CA2, CA3, CA4 : CONSTANT CON_ARR;
R1, R2, R3, R4 : CONSTANT REC;
R1A, R2A, R3A, R4A : CONSTANT REC1;
A1, A2, A3, A4 : CONSTANT ACC;
PR1, PR2, PR3, PR4 : CONSTANT PRIV;
PRIVATE
TYPE INT IS RANGE 1 .. 100;
TYPE ENUM IS (ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE);
TYPE FIX IS DELTA 2.0**(-1) RANGE -100.0 .. 100.0;
TYPE FLT IS DIGITS 5 RANGE -100.0 .. 100.0;
TYPE CON_ARR IS ARRAY(ARR_RAN) OF INTEGER;
TYPE REC IS RECORD
COMP1 : INTEGER;
COMP2 : INTEGER;
COMP3 : BOOLEAN;
END RECORD;
TYPE REC1 IS RECORD
COMP1 : INTEGER := 10;
COMP2 : INTEGER := 20;
COMP3 : BOOLEAN := FALSE;
END RECORD;
TYPE ACC IS ACCESS INTEGER;
TYPE PRIV IS NEW SP;
FUNCTION DDT IS NEW F1 (INT);
FUNCTION EDT IS NEW F1 (ENUM);
FUNCTION FDT IS NEW F2 (FIX);
FUNCTION FLDT IS NEW F3 (FLT);
FUNCTION CADT IS NEW F4 (CON_ARR);
FUNCTION RDT IS NEW F5 (REC);
FUNCTION R1DT IS NEW F6 (REC1);
FUNCTION ADT IS NEW F7 (ACC);
FUNCTION PDT IS NEW F8 (PRIV);
REC_OBJ : REC := (1,2,TRUE);
REC1_OBJ : REC1 := (3,4,FALSE);
I1, I2, I3, I4 : CONSTANT INT := DDT;
E1, E2, E3, E4 : CONSTANT ENUM := EDT;
FI1, FI2, FI3, FI4 : CONSTANT FIX := FDT;
FL1, FL2, FL3, FL4 : CONSTANT FLT := FLDT;
CA1, CA2, CA3, CA4 : CONSTANT CON_ARR := CADT;
R1, R2, R3, R4 : CONSTANT REC := RDT(REC_OBJ);
R1A, R2A, R3A, R4A : CONSTANT REC1 := R1DT(REC1_OBJ);
A1, A2, A3, A4 : CONSTANT ACC := ADT;
PR1, PR2, PR3, PR4 : CONSTANT PRIV := PDT(PRIV(CONS));
END P;
PACKAGE BODY P IS
AVAR1 : ACC := NEW INTEGER'(29);
AVAR2 : ACC := NEW INTEGER'(30);
AVAR3 : ACC := NEW INTEGER'(31);
AVAR4 : ACC := NEW INTEGER'(32);
FUNCTION GEN_EQUAL (Z1, Z2 : LP) RETURN BOOLEAN IS
BEGIN
RETURN Z1 = Z2;
END GEN_EQUAL;
FUNCTION INT_EQUAL IS NEW GEN_EQUAL (INT);
FUNCTION ENUM_EQUAL IS NEW GEN_EQUAL (ENUM);
FUNCTION FIX_EQUAL IS NEW GEN_EQUAL (FIX);
FUNCTION FLT_EQUAL IS NEW GEN_EQUAL (FLT);
FUNCTION ARR_EQUAL IS NEW GEN_EQUAL (CON_ARR);
FUNCTION REC_EQUAL IS NEW GEN_EQUAL (REC);
FUNCTION REC1_EQUAL IS NEW GEN_EQUAL (REC1);
FUNCTION ACC_EQUAL IS NEW GEN_EQUAL (INTEGER);
FUNCTION PRIV_EQUAL IS NEW GEN_EQUAL (PRIV);
BEGIN
TEST ("C74302B", "CHECK THAT WHEN THE FULL DECLARATION OF " &
"A DEFERRED CONSTANT IS GIVEN AS A " &
"MULTIPLE DECLARATION, THE INITIALIZATION " &
"EXPRESSION IS EVALUATED ONCE FOR EACH " &
"DEFERRED CONSTANT");
IF NOT EQUAL(BUMP,36) THEN
FAILED ("IMPROPER RESULTS FROM INITIALIZATION OF " &
"DEFERRED CONSTANTS IN A MULIPLE DECLARATION");
END IF;
IF NOT INT_EQUAL(I1,1) OR NOT INT_EQUAL(I2,2) OR
NOT INT_EQUAL(I3,3) OR NOT INT_EQUAL(I4,4) THEN
FAILED ("IMPROPER RESULTS FROM INITIALIZATION OF " &
"DEFERRED INTEGER CONSTANTS");
END IF;
IF NOT ENUM_EQUAL(E1,SIX) OR NOT ENUM_EQUAL(E2,SEVEN) OR
NOT ENUM_EQUAL(E3,EIGHT) OR NOT ENUM_EQUAL(E4,NINE) THEN
FAILED ("IMPROPER RESULTS FROM INITIALIZATION OF " &
"DEFERRED ENUMERATION CONSTANTS");
END IF;
IF NOT FIX_EQUAL(FI1,9.0) OR NOT FIX_EQUAL(FI2,10.0) OR
NOT FIX_EQUAL(FI3,11.0) OR NOT FIX_EQUAL(FI4,12.0) THEN
FAILED ("IMPROPER RESULTS FROM INITIALIZATION OF " &
"DEFERRED FIXED POINT CONSTANTS");
END IF;
IF NOT FLT_EQUAL(FL1,13.0) OR NOT FLT_EQUAL(FL2,14.0) OR
NOT FLT_EQUAL(FL3,15.0) OR NOT FLT_EQUAL(FL4,16.0) THEN
FAILED ("IMPROPER RESULTS FROM INITIALIZATION OF " &
"DEFERRED FLOATING POINT CONSTANTS");
END IF;
IF NOT ARR_EQUAL(CA1,(17,16)) OR NOT ARR_EQUAL(CA2,(18,17))
OR NOT ARR_EQUAL(CA3,(19,18)) OR NOT ARR_EQUAL(CA4,(20,19))
THEN FAILED ("IMPROPER RESULTS FROM INITIALIZATION OF " &
"DEFERRED ARRAY CONSTANTS");
END IF;
IF NOT REC_EQUAL(R1,REC_OBJ) OR NOT REC_EQUAL(R2,REC_OBJ)
OR NOT REC_EQUAL(R3,REC_OBJ) OR NOT REC_EQUAL(R4,REC_OBJ)
THEN FAILED ("IMPROPER RESULTS FROM INITIALIZATION OF " &
"DEFERRED RECORD CONSTANTS");
END IF;
IF NOT REC1_EQUAL(R1A,REC1_OBJ) OR NOT REC1_EQUAL(R2A,
REC1_OBJ) OR NOT REC1_EQUAL(R3A,REC1_OBJ) OR NOT
REC1_EQUAL(R4A,REC1_OBJ) THEN
FAILED ("IMPROPER RESULTS FROM INITIALIZATION OF " &
"DEFERRED RECORD CONSTANTS WITH DEFAULT " &
"EXPRESSIONS");
END IF;
IF NOT ACC_EQUAL(A1.ALL,AVAR1.ALL) OR NOT ACC_EQUAL(A2.ALL,
AVAR2.ALL) OR NOT ACC_EQUAL(A3.ALL,AVAR3.ALL) OR NOT
ACC_EQUAL(A4.ALL,AVAR4.ALL) THEN
FAILED ("IMPROPER RESULTS FROM INITIALIZATION OF " &
"DEFERRED ACCESS CONSTANTS");
END IF;
IF NOT PRIV_EQUAL(PR1,PRIV(CONS)) OR NOT PRIV_EQUAL(PR2,
PRIV(CONS)) OR NOT PRIV_EQUAL(PR3,PRIV(CONS)) OR NOT
PRIV_EQUAL(PR4,PRIV(CONS)) THEN
FAILED ("IMPROPER RESULTS FROM INITIALIZATION OF " &
"DEFERRED PRIVATE CONSTANTS");
END IF;
RESULT;
END P;
USE P;
BEGIN
NULL;
END C74302B;
|
-- Copyright (c) 2021 Bartek thindil Jasicki <thindil@laeran.pl>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Interfaces.C.Strings; use Interfaces.C.Strings;
-- ****h* Tashy2/Tashy2
-- FUNCTION
-- Various utility code not related to any Tcl command or API
-- SOURCE
package Tashy2 is
-- ****
pragma Warnings (Off, "no Global Contract available");
-- ****f* Utils/Utils.To_C_String
-- FUNCTION
-- Convert Ada String to C characters array
-- PARAMETERS
-- Str - Ada String to convert
-- RESULT
-- C characters array with converted String content
-- HISTORY
-- 8.6.0 - Added
-- EXAMPLE
-- -- Convert "Hello world" String to C characters array
-- C_String: constant chars_ptr := To_C_String("Hello world");
-- SEE ALSO
-- Utils.From_C_String
-- SOURCE
function To_C_String(Str: String) return chars_ptr is
(New_String(Str => Str)) with
Global => null,
Test_Case => (Name => "Test_To_C_String", Mode => Nominal);
-- ****
-- ****f* Utils/Utils.From_C_String
-- FUNCTION
-- Convert C characters array to Ada String
-- PARAMETERS
-- Item - C characters array to convert
-- RESULT
-- Ada String with converted C characters array content
-- HISTORY
-- 8.6.0 - Added
-- EXAMPLE
-- -- Convert "Hello world" C characters array to Ada String
-- Ada_String: constant String := From_C_String(To_C_String("Hello world"));
-- SEE ALSO
-- Utils.To_C_String
-- SOURCE
function From_C_String(Item: chars_ptr) return String is
(Value(Item => Item)) with
Global => null,
Test_Case => (Name => "Test_From_C_String", Mode => Nominal);
-- ****
pragma Warnings (On, "no Global Contract available");
end Tashy2;
|
with casillero,aspiradora,direccion;
use casillero,aspiradora,direccion;
package mundo is
type t_casilleros is array (t_posicion) of t_casillero;
type t_mundo is tagged record
casilleros : t_casilleros;
aspiradora : t_aspiradora;
end record;
procedure inicializar_mundo(m : in out t_mundo);
procedure ejecutar_iteracion(m : in out t_mundo);
end mundo;
|
with Generic_Queue;
pragma Elaborate_All (Generic_Queue);
package body Some_Package with SPARK_Mode is
type MyElement is new Float range 0.0 .. 10.0 with Default_Value => 0.0;
package Float_Buffer is new Generic_Queue(Index_Type => Unsigned_8,
Element_Type => MyElement);
use Float_Buffer;
Buf_Handle : Float_Buffer.Buffer_Tag;
procedure foo is
begin
Buf_Handle.push_back (1.2);
Buf_Handle.push_back (1.3);
end foo;
procedure bar is
begin
foo;
end bar;
end Some_Package;
|
pragma License (Unrestricted);
-- extended unit
with Interfaces.C.Pointers;
package Interfaces.C.WChar_Pointers is
new Pointers (
Index => size_t,
Element => wchar_t,
Element_Array => wchar_array,
Default_Terminator => wchar_t'Val (0));
-- The instance of Interfaces.C.Pointers for wchar_t.
pragma Pure (Interfaces.C.WChar_Pointers);
|
package body HTML_Table is
procedure Print(Items: Item_Array; Column_Heads: Header_Array) is
function Blanks(N: Natural) return String is
-- indention for better readable HTML
begin
if N=0 then
return "";
else
return " " & Blanks(N-1);
end if;
end Blanks;
procedure Print_Row(Row_Number: Positive) is
begin
Put(Blanks(4) & "<tr><td>" & Positive'Image(Row_Number) & "</td>");
for I in Items'Range(2) loop
Put("<td>" & To_String(Items(Row_Number, I)) & "</td>");
end loop;
Put_Line("</tr>");
end Print_Row;
procedure Print_Body is
begin
Put_Line(Blanks(2)&"<tbody align = ""right"">");
for I in Items'Range(1) loop
Print_Row(I);
end loop;
Put_Line(Blanks(2)&"</tbody>");
end Print_Body;
procedure Print_Header is
function To_Str(U: U_String) return String renames
Ada.Strings.Unbounded.To_String;
begin
Put_Line(Blanks(2) & "<thead align = ""right"">");
Put(Blanks(4) & "<tr><th></th>");
for I in Column_Heads'Range loop
Put("<td>" & To_Str(Column_Heads(I)) & "</td>");
end loop;
Put_Line("</tr>");
Put_Line(Blanks(2) & "</thead>");
end Print_Header;
begin
if Items'Length(2) /= Column_Heads'Length then
raise Constraint_Error with "number of headers /= number of columns";
end if;
Put_Line("<table>");
Print_Header;
Print_Body;
Put_Line("</table>");
end Print;
end HTML_Table;
|
with Ada.Text_IO;
use Ada.Text_IO;
procedure Specifier_Et_Tester is
-- La valeur absolue d'un nombre entier.
function Valeur_Absolue (N : in Integer) return Integer with
Post => Valeur_Absolue'Result >= 0
and (Valeur_Absolue'Result = N or Valeur_Absolue'Result = -N)
is
begin
if N >= 0 then
return N;
else
return - N;
end if;
end Valeur_Absolue;
-- Incrémenter un entier N. Les entiers étant bornés, il ne faut pas que
-- l'entier soit le dernier Integer'LAST. Après exécution de Incrémenter,
-- l'entier passé en paramètre a sa valeur augmentée de 1.
procedure Incrementer (N : in out Integer) with
Pre => N /= Integer'LAST,
Post => N = N'Old + 1 -- N incrémenté
-- Quand la post condition est fausse: SYSTEM.ASSERTIONS.ASSERT_FAILURE : failed postcondition
-- Post => N = N'Old * 2
is
begin
N := N + 1;
end Incrementer;
-- Calculer le quotient et le reste de deux nombres entiers, Dividende et
-- Diviseur. Les deux doivent être positif et Diviseur doit être non nul.
-- Quotient et Reste sont tels que Dividende = Quotient * Diviseur + Reste
-- avec Reste compris entre 0 et Diviseur - 1.
procedure Calculer_DivMod (Dividende, Diviseur : in Integer ; Quotient, Reste: out Integer) with
Pre => Dividende >= 0 and Diviseur > 0,
Post => Dividende = Quotient * Diviseur + Reste
and 0 <= Reste and Reste < Diviseur
is
Le_Quotient: Integer;
Le_Reste: Integer;
begin
-- Principe : Le reste étant initialisé avec le dividende, le quotient
-- est le nombre de fois que l'on peut lui retrancher Diviseur.
Le_Quotient := 0;
Le_Reste := Dividende;
while Le_Reste >= Diviseur loop --! Originalement c'était > seulement ce qui posait un problème.
-- Variant : Le_Reste
-- Invariant : Dividende = Le_Quotient * Diviseur + Le_Reste;
Le_Quotient := Le_Quotient + 1;
Le_Reste := Le_Reste - Diviseur;
end loop;
Quotient := Le_Quotient;
Reste := Le_Reste;
--! Quotient et Reste ne doivent être affectés qu'une seule fois car en out
--! Il est conseillé de le faire à la fin au cas où une exception se produirait
end Calculer_DivMod;
procedure Tester_Valeur_Absolue is
begin
pragma Assert (Valeur_Absolue (5) = 5); -- Cas entier positif
pragma Assert (Valeur_Absolue (-7) = 7); -- Cas entier négatif
pragma Assert (Valeur_Absolue (0) = 0); -- Cas entier nul
end Tester_Valeur_Absolue;
procedure Tester_Incrementer is
Un_Nombre: Integer;
begin
-- un premier test
Un_Nombre := 1;
Incrementer (Un_Nombre);
pragma Assert (Un_Nombre = 2);
-- un deuxième test
Un_Nombre := 5;
Incrementer (Un_Nombre);
pragma Assert (Un_Nombre = 6);
end Tester_Incrementer;
procedure Tester_Calculer_DivMod is
Q, R: Integer;
begin
-- Cas Dividende > Diviseur
Calculer_DivMod(13, 3, Q, R);
pragma Assert (Q = 4);
pragma Assert (R = 1);
-- Cas Dividende < Diviseur
Calculer_DivMod(7, 19, Q, R);
pragma Assert (Q = 0);
pragma Assert (R = 7);
-- Cas où la précondition est non verifiée
-- Donne l'exception 'SYSTEM.ASSERTIONS.ASSERT_FAILURE' : failed precondition
-- Calculer_DivMod(-9, 0, Q, R);
Calculer_DivMod(17, 17, Q, R);
end Tester_Calculer_DivMod;
begin
Tester_Valeur_Absolue;
Tester_Incrementer;
Tester_Calculer_DivMod;
Put_Line ("Fin");
end Specifier_Et_Tester;
|
-- Abstract :
--
-- A generalized LR parser.
--
-- In a child package of Parser.LR partly for historical reasons,
-- partly to allow McKenzie_Recover to be in a sibling package.
--
-- Copyright (C) 2002, 2003, 2009, 2010, 2013-2015, 2017 - 2019 Free Software Foundation, Inc.
--
-- This file is part of the WisiToken package.
--
-- The WisiToken package is free software; you can redistribute it
-- and/or modify it under terms of the GNU General Public License as
-- published by the Free Software Foundation; either version 3, or
-- (at your option) any later version. This library is distributed in
-- the hope that it will be useful, but WITHOUT ANY WARRANTY; without
-- even the implied warranty of MERCHAN- TABILITY or FITNESS FOR A
-- PARTICULAR PURPOSE.
--
-- As a special exception under Section 7 of GPL version 3, you are granted
-- additional permissions described in the GCC Runtime Library Exception,
-- version 3.1, as published by the Free Software Foundation.
pragma License (Modified_GPL);
with WisiToken.Parse.LR.Parser_Lists;
with WisiToken.Lexer;
with WisiToken.Parse;
with WisiToken.Syntax_Trees;
package WisiToken.Parse.LR.Parser is
Default_Max_Parallel : constant := 15;
type Language_Fixes_Access is access procedure
(Trace : in out WisiToken.Trace'Class;
Lexer : access constant WisiToken.Lexer.Instance'Class;
Parser_Label : in Natural;
Parse_Table : in WisiToken.Parse.LR.Parse_Table;
Terminals : in Base_Token_Arrays.Vector;
Tree : in Syntax_Trees.Tree;
Local_Config_Heap : in out Config_Heaps.Heap_Type;
Config : in Configuration);
-- Config encountered a parse table Error action, or failed a
-- semantic check; attempt to provide a language-specific fix,
-- enqueuing new configs on Local_Config_Heap.
--
-- For a failed semantic check, Config.Stack is in the pre-reduce
-- state, Config.Error_Token gives the nonterm token,
-- Config.Check_Token_Count the token count for the reduce. May be
-- called with Nonterm.Virtual = True or Tree.Valid_Indices (stack
-- top token_count items) false.
--
-- For an Error action, Config.Error_Token gives the terminal that
-- caused the error.
type Language_Matching_Begin_Tokens_Access is access procedure
(Tokens : in Token_ID_Array_1_3;
Config : in Configuration;
Matching_Tokens : out Token_ID_Arrays.Vector;
Forbid_Minimal_Complete : out Boolean);
-- Tokens (1) caused a parse error; Tokens (2 .. 3) are the following
-- tokens (Invalid_Token_ID if none). Set Matching_Tokens to a token
-- sequence that starts a production matching Tokens. If
-- Minimal_Complete would produce a bad solution at this error point,
-- set Forbid_Minimal_Complete True.
--
-- For example, if Tokens is a block end, return tokens that are the
-- corresponding block begin. If the error point is inside a
-- multi-token 'end' (ie 'end if;', or 'end <name>;'), set
-- Forbid_Minimal_Complete True.
type Language_String_ID_Set_Access is access function
(Descriptor : in WisiToken.Descriptor;
String_Literal_ID : in Token_ID)
return Token_ID_Set;
-- Return a Token_ID_Set containing String_Literal_ID and
-- nonterminals that can contain String_Literal_ID as part of an
-- expression. Used in placing a missing string quote.
type Post_Recover_Access is access procedure;
type Parser is new WisiToken.Parse.Base_Parser with record
Table : Parse_Table_Ptr;
Language_Fixes : Language_Fixes_Access;
Language_Matching_Begin_Tokens : Language_Matching_Begin_Tokens_Access;
Language_String_ID_Set : Language_String_ID_Set_Access;
String_Quote_Checked : Line_Number_Type := Invalid_Line_Number;
-- Max line checked for missing string quote.
Post_Recover : Post_Recover_Access;
-- Gather data for tests.
Shared_Tree : aliased Syntax_Trees.Base_Tree;
-- Each parser (normal and recover) has its own branched syntax tree,
-- all branched from this tree. Terminals are added to the tree when
-- they become the current token.
--
-- It is never the case that terminals are added to this shared tree
-- when there is more than one task active, so we don't need a
-- protected tree.
--
-- See WisiToken.LR.Parser_Lists Parser_State for more discussion of
-- Shared_Tree.
Parsers : aliased Parser_Lists.List;
Max_Parallel : SAL.Base_Peek_Type;
Terminate_Same_State : Boolean;
Enable_McKenzie_Recover : Boolean;
Recover_Log_File : Ada.Text_IO.File_Type;
end record;
overriding procedure Finalize (Object : in out LR.Parser.Parser);
-- Deep free Object.Table.
procedure New_Parser
(Parser : out LR.Parser.Parser;
Trace : not null access WisiToken.Trace'Class;
Lexer : in WisiToken.Lexer.Handle;
Table : in Parse_Table_Ptr;
Language_Fixes : in Language_Fixes_Access;
Language_Matching_Begin_Tokens : in Language_Matching_Begin_Tokens_Access;
Language_String_ID_Set : in Language_String_ID_Set_Access;
User_Data : in WisiToken.Syntax_Trees.User_Data_Access;
Max_Parallel : in SAL.Base_Peek_Type := Default_Max_Parallel;
Terminate_Same_State : in Boolean := True);
overriding procedure Parse (Shared_Parser : aliased in out LR.Parser.Parser);
-- Attempt a parse. Calls Parser.Lexer.Reset, runs lexer to end of
-- input setting Shared_Parser.Terminals, then parses tokens.
--
-- If an error is encountered, Parser.Lexer_Errors and
-- Parsers(*).Errors contain information about the errors. If a
-- recover strategy succeeds, no exception is raised. If recover does
-- not succeed, raises Syntax_Error.
--
-- For errors where no recovery is possible, raises Parse_Error with
-- an appropriate error message.
overriding function Tree (Shared_Parser : in Parser) return Syntax_Trees.Tree;
-- If there is one parser in Parsers, return its tree. Otherwise,
-- raise Parse_Error for an ambiguous parse.
overriding procedure Execute_Actions (Parser : in out LR.Parser.Parser);
-- Call User_Data.Delete_Token on any tokens deleted by error
-- recovery, then User_Data.Reduce and the grammar semantic actions
-- on all nonterms in the syntax tree.
overriding function Any_Errors (Parser : in LR.Parser.Parser) return Boolean;
-- Return True if any errors where encountered, recovered or not.
overriding procedure Put_Errors (Parser : in LR.Parser.Parser);
-- Put user-friendly error messages from the parse to
-- Ada.Text_IO.Current_Error.
end WisiToken.Parse.LR.Parser;
|
-- Cycle computations
-- A variant to the integer division, where the number of cycles and the phase
-- within the cycle are computed and returned by single function.
-- In these functions, the remainder (the phase) is always non-negative.
-- Decompose_cycle is the standard operation;
-- Decompose_cycle_ceiled is appropriate when the phase is authorised to be
-- equal to the divisor.
-- First variant for integer types,
-- second variant for fixed types.
----------------------------------------------------------------------------
-- Copyright Miletus 2015
-- 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:
-- 1. The above copyright notice and this permission notice shall be included
-- in all copies or substantial portions of the Software.
-- 2. Changes with respect to any former version shall be documented.
--
-- The software is provided "as is", without warranty of any kind,
-- express of implied, including but not limited to the warranties of
-- merchantability, fitness for a particular purpose and noninfringement.
-- In no event shall the authors of 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.
-- Inquiries: www.calendriermilesien.org
-------------------------------------------------------------------------------
package Cycle_computations is
generic type Num is range <>;
package Integer_cycle_computations is
subtype Positive_num is Num range 1..Num'Last;
type Cycle_coordinates is record
Cycle : Integer;
Phase : Num;
end record;
function Decompose_cycle
(Dividend : Num;
Divisor : Positive_num)
return Cycle_coordinates;
-- Dividend = Cycle * Divisor + Phase, 0 <= Phase < Divisor
function Decompose_cycle_ceiled
(Dividend : Num;
Divisor : Positive_num;
Ceiling : Positive)
return Cycle_coordinates;
-- 0 <= Dividend <= Ceiling * Divisor
-- Dividend = Cycle * Divisor + Phase, 0 <= Phase <= Divisor,
-- Phase = Divisor only for last value of Dividend, Cycle < Ceiling.
end Integer_cycle_computations;
generic type Fixed_num is delta <>;
package Fixed_Cycle_Computations is
subtype Positive_num is Fixed_num range Fixed_num'Delta..Fixed_num'Last;
type Cycle_coordinates is record
Cycle : Integer;
Phase : Fixed_num;
end record;
function Decompose_cycle
(Dividend : Fixed_num;
Divisor : Positive_num)
return Cycle_coordinates;
-- Dividend = Cycle * Divisor + Phase, 0 <= Phase < Divisor
function Decompose_cycle_ceiled
(Dividend : Fixed_num;
Divisor : Positive_num;
Ceiling : Positive)
return Cycle_coordinates;
-- 0 <= Dividend <= Ceiling * Divisor
-- Dividend = Cycle * Divisor + Phase, 0 <= Phase <= Divisor,
-- Phase = Divisor only for last value of Dividend, Cycle < Ceiling.
end Fixed_cycle_computations;
end Cycle_computations;
|
-- { dg-do compile }
-- { dg-options "-O" }
package body Opt17 is
function Func return S is
V : String (1 .. 6);
begin
V (1 .. 3) := "ABC";
return V (1 .. 5);
end;
end Opt17;
|
with Ada.Text_IO; use Ada.Text_IO;
with Libadalang.Analysis; use Libadalang.Analysis;
with Libadalang.Common; use Libadalang.Common;
with Rejuvenation; use Rejuvenation;
with Rejuvenation.Factory; use Rejuvenation.Factory;
with Rejuvenation.Simple_Factory; use Rejuvenation.Simple_Factory;
package body Examples.Factory is
procedure Demo_Parse_Full_Text;
procedure Demo_Parse_Partial_Text;
procedure Demo_Parse_File_Outside_Project_Context (File_Name : String);
procedure Demo_Parse_File_Inside_Project_Context
(Project_Name : String; File_Name : String);
procedure Demo (Project_Name : String; File_Name : String) is
begin
Put_Line ("=== Examples of Factory =======");
New_Line;
Put_Line ("--- Example of parsing full text -------");
New_Line;
Demo_Parse_Full_Text;
New_Line;
Put_Line ("--- Example of parsing partial text -------");
New_Line;
Demo_Parse_Partial_Text;
New_Line;
Put_Line ("--- Example of parsing file outside project context -------");
New_Line;
Demo_Parse_File_Outside_Project_Context (File_Name);
New_Line;
Put_Line ("--- Example of parsing file inside project context -------");
New_Line;
Demo_Parse_File_Inside_Project_Context (Project_Name, File_Name);
New_Line;
end Demo;
procedure Demo_Parse_Full_Text is
Unit : constant Analysis_Unit :=
Analyze_Fragment ("procedure Test is begin New_Line; end;");
begin
Unit.Print; -- Show the node's internal structure
end Demo_Parse_Full_Text;
procedure Demo_Parse_Partial_Text is
Unit : constant Analysis_Unit := Analyze_Fragment ("x := 4;", Stmt_Rule);
begin
Unit.Print; -- Show the node's internal structure
end Demo_Parse_Partial_Text;
procedure Demo_Parse_File_Outside_Project_Context (File_Name : String) is
Unit : constant Analysis_Unit := Open_File (File_Name);
begin
Unit.Print; -- Show the node's internal structure
end Demo_Parse_File_Outside_Project_Context;
procedure Demo_Parse_File_Inside_Project_Context
(Project_Name : String; File_Name : String)
is
Context : constant Project_Context := Open_Project (Project_Name);
Unit : constant Analysis_Unit := Open_File (File_Name, Context);
begin
Unit.Print; -- Show the node's internal structure
end Demo_Parse_File_Inside_Project_Context;
end Examples.Factory;
|
-- This package has been generated automatically by GNATtest.
-- Do not edit any part of it, see GNATtest documentation for more details.
-- begin read only
with Gnattest_Generated;
package Ships.Movement.Test_Data.Tests is
type Test is new GNATtest_Generated.GNATtest_Standard.Ships.Movement
.Test_Data
.Test with
null record;
procedure Test_MoveShip_143def_3bb6cb(Gnattest_T: in out Test);
-- ships-movement.ads:36:4:MoveShip:Test_MoveShip
procedure Test_DockShip_bfbe82_875e5b(Gnattest_T: in out Test);
-- ships-movement.ads:52:4:DockShip:Test_DockShip
procedure Test_ChangeShipSpeed_a103ef_17b968(Gnattest_T: in out Test);
-- ships-movement.ads:65:4:ChangeShipSpeed:Test_ChangeShipSpeed
procedure Test_RealSpeed_da7fcb_f7fd56(Gnattest_T: in out Test);
-- ships-movement.ads:79:4:RealSpeed:Test_RealSpeed
procedure Test_CountFuelNeeded_db602d_18e85d(Gnattest_T: in out Test);
-- ships-movement.ads:90:4:CountFuelNeeded:Test_CountFuelNeeded
procedure Test_WaitInPlace_a6040e_d787da(Gnattest_T: in out Test);
-- ships-movement.ads:100:4:WaitInPlace:Test_WaitInPlace
end Ships.Movement.Test_Data.Tests;
-- end read only
|
-----------------------------------------------------------------------
-- jason-testsuite -- Testsuite for jason
-- Copyright (C) 2016 Stephane.Carrez
-- Written by Stephane.Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Tests;
with Jason.Applications;
with Jason.Projects.Tests;
with Jason.Tickets.Tests;
package body Jason.Testsuite is
Tests : aliased Util.Tests.Test_Suite;
function Suite return Util.Tests.Access_Test_Suite is
begin
Jason.Projects.Tests.Add_Tests (Tests'Access);
Jason.Tickets.Tests.Add_Tests (Tests'Access);
return Tests'Access;
end Suite;
procedure Initialize (Props : in Util.Properties.Manager) is
App : constant Jason.Applications.Application_Access := Jason.Applications.Create;
begin
-- Jason.Applications.Initialize (App);
-- ASF.Server.Tests.Set_Context (App.all'Access);
AWA.Tests.Initialize (App.all'Access, Props, True);
end Initialize;
end Jason.Testsuite;
|
---------------------------------------------------------------------------------
-- 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.
---------------------------------------------------------------------------------
with Interfaces.C; use Interfaces.C;
with GL;
use type GL.GLfloat;
use type GL.GLbitfield;
with SDL.Types; use SDL.Types;
with SDL.Keysym; use SDL.Keysym;
with SDL.Video; use SDL.Video;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
package Example is
procedure PrintUsage;
function Initialise return Boolean;
procedure Uninitialise;
procedure Update(Ticks : in Integer);
procedure Draw;
function GetTitle return String;
function GetWidth return Integer;
function GetHeight return Integer;
function GetBitsPerPixel return Integer;
procedure SetLastTickCount(Ticks : in Integer);
procedure SetSurface(Surface : in SDL.Video.Surface_Ptr);
function GetSurface return SDL.Video.Surface_Ptr;
procedure SetKey(Key : in SDL.Keysym.Key; Down : in Boolean);
procedure SetActive(Active : in Boolean);
function IsActive return Boolean;
procedure SetQuit(Quit : in Boolean);
function Quit return Boolean;
private
type KeysArray is array(SDL.Keysym.K_FIRST .. SDL.Keysym.K_LAST) of Boolean;
Title : String := "NeHe Base Code in Ada/SDL";
Width : Integer := 640;
Height : Integer := 480;
BitsPerPixel : Integer := 16;
IsFullScreen : Boolean := False;
Keys : KeysArray := (others => False);
IsVisible : Boolean := False;
LastTickCount : Integer := 0;
ScreenSurface : SDL.Video.Surface_Ptr := null;
AppActive : Boolean := True;
AppQuit : Boolean := False;
XSpeed : GL.GLfloat := 0.0;
YSpeed : GL.GLfloat := 0.0;
Zoom : GL.GLfloat := -6.0;
end Example;
|
with System;
package Unc_Memops is
pragma Elaborate_Body;
type size_t is mod 2 ** Standard'Address_Size;
subtype addr_t is System.Address;
function Alloc (Size : size_t) return addr_t;
procedure Free (Ptr : addr_t);
function Realloc (Ptr : addr_t; Size : size_t) return addr_t;
procedure Expect_Symetry (Status : Boolean);
-- Whether we expect "free"s to match "alloc" return values in
-- reverse order, like alloc->X, alloc->Y should be followed by
-- free Y, free X.
private
-- Uncomment the exports below to really exercise the alternate versions.
-- This only works when using an installed version of the tools which
-- grabs the runtime library objects from an archive, hence doesn't force
-- the inclusion of s-memory.o.
-- pragma Export (C, Alloc, "__gnat_malloc");
-- pragma Export (C, Free, "__gnat_free");
-- pragma Export (C, Realloc, "__gnat_realloc");
end;
|
------------------------------------------------------------------------------
-- --
-- P G A D A . T H I N --
-- --
-- S p e c --
-- --
-- Copyright (c) coreland 2009 --
-- Copyright (c) Samuel Tardieu 2000 --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of Samuel Tardieu 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 SAMUEL TARDIEU 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 SAMUEL --
-- TARDIEU 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 Interfaces.C.Strings;
with Interfaces.C;
package PGAda.Thin is
pragma Preelaborate;
package C renames Interfaces.C;
package CS renames Interfaces.C.Strings;
type Conn_Status_t is (CONNECTION_OK, CONNECTION_BAD);
for Conn_Status_t'Size use C.int'Size;
pragma Convention (C, Conn_Status_t);
type Exec_Status_t is
(PGRES_EMPTY_QUERY,
PGRES_COMMAND_OK,
PGRES_TUPLES_OK,
PGRES_COPY_OUT,
PGRES_COPY_IN,
PGRES_BAD_RESPONSE,
PGRES_NONFATAL_ERROR,
PGRES_FATAL_ERROR);
for Exec_Status_t'Size use C.int'Size;
pragma Convention (C, Exec_Status_t);
type PG_Conn is null record;
type PG_Conn_Access_t is access PG_Conn;
pragma Convention (C, PG_Conn_Access_t);
type PG_Result is null record;
type PG_Result_Access_t is access PG_Result;
pragma Convention (C, PG_Result_Access_t);
type Oid is new C.unsigned;
type Error_Field is
(PG_DIAG_SQLSTATE,
PG_DIAG_MESSAGE_DETAIL,
PG_DIAG_SOURCE_FILE,
PG_DIAG_MESSAGE_HINT,
PG_DIAG_SOURCE_LINE,
PG_DIAG_MESSAGE_PRIMARY,
PG_DIAG_STATEMENT_POSITION,
PG_DIAG_SOURCE_FUNCTION,
PG_DIAG_SEVERITY,
PG_DIAG_CONTEXT,
PG_DIAG_INTERNAL_POSITION,
PG_DIAG_INTERNAL_QUERY);
for Error_Field use
(PG_DIAG_SQLSTATE => 67,
PG_DIAG_MESSAGE_DETAIL => 68,
PG_DIAG_SOURCE_FILE => 70,
PG_DIAG_MESSAGE_HINT => 72,
PG_DIAG_SOURCE_LINE => 76,
PG_DIAG_MESSAGE_PRIMARY => 77,
PG_DIAG_STATEMENT_POSITION => 80,
PG_DIAG_SOURCE_FUNCTION => 82,
PG_DIAG_SEVERITY => 83,
PG_DIAG_CONTEXT => 87,
PG_DIAG_INTERNAL_POSITION => 112,
PG_DIAG_INTERNAL_QUERY => 113);
for Error_Field'Size use C.int'Size;
function PQ_Set_Db_Login
(PG_Host : CS.chars_ptr;
PG_Port : CS.chars_ptr;
PG_Options : CS.chars_ptr;
PG_TTY : CS.chars_ptr;
Db_Name : CS.chars_ptr;
Login : CS.chars_ptr;
Password : CS.chars_ptr) return PG_Conn_Access_t;
pragma Import (C, PQ_Set_Db_Login, "PQsetdbLogin");
function PQ_Db (Conn : PG_Conn_Access_t) return CS.chars_ptr;
pragma Import (C, PQ_Db, "PQdb");
function PQ_Host (Conn : PG_Conn_Access_t) return CS.chars_ptr;
pragma Import (C, PQ_Host, "PQhost");
function PQ_Port (Conn : PG_Conn_Access_t) return CS.chars_ptr;
pragma Import (C, PQ_Port, "PQport");
function PQ_Options (Conn : PG_Conn_Access_t) return CS.chars_ptr;
pragma Import (C, PQ_Options, "PQoptions");
function PQ_Status (Conn : PG_Conn_Access_t) return Conn_Status_t;
pragma Import (C, PQ_Status, "PQstatus");
function PQ_Error_Message (Conn : PG_Conn_Access_t) return CS.chars_ptr;
pragma Import (C, PQ_Error_Message, "PQerrorMessage");
procedure PQ_Finish (Conn : in PG_Conn_Access_t);
pragma Import (C, PQ_Finish, "PQfinish");
procedure PQ_Reset (Conn : in PG_Conn_Access_t);
pragma Import (C, PQ_Reset, "PQreset");
function PQ_Exec
(Conn : PG_Conn_Access_t;
Query : CS.chars_ptr) return PG_Result_Access_t;
pragma Import (C, PQ_Exec, "PQexec");
function PQ_Result_Status (Res : PG_Result_Access_t) return Exec_Status_t;
pragma Import (C, PQ_Result_Status, "PQresultStatus");
function PQ_N_Tuples (Res : PG_Result_Access_t) return C.int;
pragma Import (C, PQ_N_Tuples, "PQntuples");
function PQ_N_Fields (Res : PG_Result_Access_t) return C.int;
pragma Import (C, PQ_N_Fields, "PQnfields");
function PQ_F_Name
(Res : PG_Result_Access_t;
Field_Index : C.int) return CS.chars_ptr;
pragma Import (C, PQ_F_Name, "PQfname");
function PQ_F_Number
(Res : PG_Result_Access_t;
Field_Index : CS.chars_ptr) return C.int;
pragma Import (C, PQ_F_Number, "PQfnumber");
function PQ_F_Type
(Res : PG_Result_Access_t;
Field_Index : C.int) return Oid;
pragma Import (C, PQ_F_Type, "PQftype");
function PQ_Get_Value
(Res : PG_Result_Access_t;
Tup_Num : C.int;
Field_Num : C.int) return CS.chars_ptr;
pragma Import (C, PQ_Get_Value, "PQgetvalue");
function PQ_Get_Length
(Res : PG_Result_Access_t;
Tup_Num : C.int;
Field_Num : C.int) return C.int;
pragma Import (C, PQ_Get_Length, "PQgetlength");
function PQ_Get_Is_Null
(Res : PG_Result_Access_t;
Tup_Num : C.int;
Field_Num : C.int) return C.int;
pragma Import (C, PQ_Get_Is_Null, "PQgetisnull");
function PQ_Cmd_Tuples (Res : PG_Result_Access_t) return CS.chars_ptr;
pragma Import (C, PQ_Cmd_Tuples, "PQcmdTuples");
function PQ_Cmd_Status (Res : PG_Result_Access_t) return CS.chars_ptr;
pragma Import (C, PQ_Cmd_Status, "PQcmdStatus");
function PQ_Oid_Status (Res : PG_Result_Access_t) return CS.chars_ptr;
pragma Import (C, PQ_Oid_Status, "PQoidStatus");
procedure PQ_Clear (Res : in PG_Result_Access_t);
pragma Import (C, PQ_Clear, "PQclear");
function PQ_Result_Error_Field
(Res : PG_Result_Access_t;
Field : Error_Field) return CS.chars_ptr;
pragma Import (C, PQ_Result_Error_Field, "PQresultErrorField");
end PGAda.Thin;
|
with
gel_demo_Server,
gel_demo_Client;
procedure launch_GEL_fused
--
-- Launches the fused version.
--
is
begin
gel_demo_Server.item.start;
gel_demo_Client.item.start;
end launch_GEL_fused;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUNTIME COMPONENTS --
-- --
-- G N A T . I O _ A U X --
-- --
-- B o d y --
-- --
-- $Revision$
-- --
-- Copyright (C) 1995-2000 Ada Core Technologies, 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 is maintained by Ada Core Technologies Inc (http://www.gnat.com). --
-- --
------------------------------------------------------------------------------
with Interfaces.C_Streams; use Interfaces.C_Streams;
package body GNAT.IO_Aux is
Buflen : constant := 2000;
-- Buffer length. Works for any non-zero value, larger values take
-- more stack space, smaller values require more recursion.
-----------------
-- File_Exists --
-----------------
function File_Exists (Name : String) return Boolean
is
Namestr : aliased String (1 .. Name'Length + 1);
-- Name as given with ASCII.NUL appended
begin
Namestr (1 .. Name'Length) := Name;
Namestr (Name'Length + 1) := ASCII.NUL;
return file_exists (Namestr'Address) /= 0;
end File_Exists;
--------------
-- Get_Line --
--------------
-- Current_Input case
function Get_Line return String is
Buffer : String (1 .. Buflen);
-- Buffer to read in chunks of remaining line. Will work with any
-- size buffer. We choose a length so that most of the time no
-- recursion will be required.
Last : Natural;
begin
Ada.Text_IO.Get_Line (Buffer, Last);
-- If the buffer is not full, then we are all done
if Last < Buffer'Last then
return Buffer (1 .. Last);
-- Otherwise, we still have characters left on the line. Note that
-- as specified by (RM A.10.7(19)) the end of line is not skipped
-- in this case, even if we are right at it now.
else
return Buffer & GNAT.IO_Aux.Get_Line;
end if;
end Get_Line;
-- Case of reading from a specified file. Note that we could certainly
-- share code between these two versions, but these are very short
-- routines, and we may as well aim for maximum speed, cutting out an
-- intermediate call (calls returning string may be somewhat slow)
function Get_Line (File : Ada.Text_IO.File_Type) return String is
Buffer : String (1 .. Buflen);
Last : Natural;
begin
Ada.Text_IO.Get_Line (File, Buffer, Last);
if Last < Buffer'Last then
return Buffer (1 .. Last);
else
return Buffer & Get_Line (File);
end if;
end Get_Line;
end GNAT.IO_Aux;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- S Y S T E M . D I M . M K S . O T H E R _ P R E F I X E S --
-- --
-- S p e c --
-- --
-- Copyright (C) 2011-2012, 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. --
-- --
------------------------------------------------------------------------------
-- Package that defines some other prefixes for the MKS base unit system.
-- These prefixes have been defined in a child package in order to avoid too
-- many constant declarations in System.Dim_Mks.
package System.Dim.Mks.Other_Prefixes is
-- SI prefixes for Meter
pragma Warnings (Off);
-- Turn off the all the dimension warnings
ym : constant Length := 1.0E-24; -- yocto
zm : constant Length := 1.0E-21; -- zepto
am : constant Length := 1.0E-18; -- atto
fm : constant Length := 1.0E-15; -- femto
pm : constant Length := 1.0E-12; -- pico
nm : constant Length := 1.0E-09; -- nano
Gm : constant Length := 1.0E+09; -- giga
Tm : constant Length := 1.0E+12; -- tera
Pem : constant Length := 1.0E+15; -- peta
Em : constant Length := 1.0E+18; -- exa
Zem : constant Length := 1.0E+21; -- zetta
Yom : constant Length := 1.0E+24; -- yotta
-- SI prefixes for Kilogram
yg : constant Mass := 1.0E-27; -- yocto
zg : constant Mass := 1.0E-24; -- zepto
ag : constant Mass := 1.0E-21; -- atto
fg : constant Mass := 1.0E-18; -- femto
pg : constant Mass := 1.0E-15; -- pico
ng : constant Mass := 1.0E-12; -- nano
Gg : constant Mass := 1.0E+06; -- giga
Tg : constant Mass := 1.0E+09; -- tera
Peg : constant Mass := 1.0E+13; -- peta
Eg : constant Mass := 1.0E+15; -- exa
Zeg : constant Mass := 1.0E+18; -- zetta
Yog : constant Mass := 1.0E+21; -- yotta
-- SI prefixes for Second
ys : constant Time := 1.0E-24; -- yocto
zs : constant Time := 1.0E-21; -- zepto
as : constant Time := 1.0E-18; -- atto
fs : constant Time := 1.0E-15; -- femto
ps : constant Time := 1.0E-12; -- pico
ns : constant Time := 1.0E-09; -- nano
Gs : constant Time := 1.0E+09; -- giga
Ts : constant Time := 1.0E+12; -- tera
Pes : constant Time := 1.0E+15; -- peta
Es : constant Time := 1.0E+18; -- exa
Zes : constant Time := 1.0E+21; -- zetta
Yos : constant Time := 1.0E+24; -- yotta
-- SI prefixes for Ampere
yA : constant Electric_Current := 1.0E-24; -- yocto
zA : constant Electric_Current := 1.0E-21; -- zepto
aA : constant Electric_Current := 1.0E-18; -- atto
fA : constant Electric_Current := 1.0E-15; -- femto
nA : constant Electric_Current := 1.0E-09; -- nano
uA : constant Electric_Current := 1.0E-06; -- micro (u)
GA : constant Electric_Current := 1.0E+09; -- giga
TA : constant Electric_Current := 1.0E+12; -- tera
PeA : constant Electric_Current := 1.0E+15; -- peta
EA : constant Electric_Current := 1.0E+18; -- exa
ZeA : constant Electric_Current := 1.0E+21; -- zetta
YoA : constant Electric_Current := 1.0E+24; -- yotta
-- SI prefixes for Kelvin
yK : constant Thermodynamic_Temperature := 1.0E-24; -- yocto
zK : constant Thermodynamic_Temperature := 1.0E-21; -- zepto
aK : constant Thermodynamic_Temperature := 1.0E-18; -- atto
fK : constant Thermodynamic_Temperature := 1.0E-15; -- femto
pK : constant Thermodynamic_Temperature := 1.0E-12; -- pico
nK : constant Thermodynamic_Temperature := 1.0E-09; -- nano
uK : constant Thermodynamic_Temperature := 1.0E-06; -- micro (u)
mK : constant Thermodynamic_Temperature := 1.0E-03; -- milli
cK : constant Thermodynamic_Temperature := 1.0E-02; -- centi
dK : constant Thermodynamic_Temperature := 1.0E-01; -- deci
daK : constant Thermodynamic_Temperature := 1.0E+01; -- deka
hK : constant Thermodynamic_Temperature := 1.0E+02; -- hecto
kK : constant Thermodynamic_Temperature := 1.0E+03; -- kilo
MeK : constant Thermodynamic_Temperature := 1.0E+06; -- mega
GK : constant Thermodynamic_Temperature := 1.0E+09; -- giga
TK : constant Thermodynamic_Temperature := 1.0E+12; -- tera
PeK : constant Thermodynamic_Temperature := 1.0E+15; -- peta
EK : constant Thermodynamic_Temperature := 1.0E+18; -- exa
ZeK : constant Thermodynamic_Temperature := 1.0E+21; -- zetta
YoK : constant Thermodynamic_Temperature := 1.0E+24; -- yotta
-- SI prefixes for Mole
ymol : constant Amount_Of_Substance := 1.0E-24; -- yocto
zmol : constant Amount_Of_Substance := 1.0E-21; -- zepto
amol : constant Amount_Of_Substance := 1.0E-18; -- atto
fmol : constant Amount_Of_Substance := 1.0E-15; -- femto
pmol : constant Amount_Of_Substance := 1.0E-12; -- pico
nmol : constant Amount_Of_Substance := 1.0E-09; -- nano
umol : constant Amount_Of_Substance := 1.0E-06; -- micro (u)
mmol : constant Amount_Of_Substance := 1.0E-03; -- milli
cmol : constant Amount_Of_Substance := 1.0E-02; -- centi
dmol : constant Amount_Of_Substance := 1.0E-01; -- deci
damol : constant Amount_Of_Substance := 1.0E+01; -- deka
hmol : constant Amount_Of_Substance := 1.0E+02; -- hecto
kmol : constant Amount_Of_Substance := 1.0E+03; -- kilo
Memol : constant Amount_Of_Substance := 1.0E+06; -- mega
Gmol : constant Amount_Of_Substance := 1.0E+09; -- giga
Tmol : constant Amount_Of_Substance := 1.0E+12; -- tera
Pemol : constant Amount_Of_Substance := 1.0E+15; -- peta
Emol : constant Amount_Of_Substance := 1.0E+18; -- exa
Zemol : constant Amount_Of_Substance := 1.0E+21; -- zetta
Yomol : constant Amount_Of_Substance := 1.0E+24; -- yotta
-- SI prefixes for Candela
ycd : constant Luminous_Intensity := 1.0E-24; -- yocto
zcd : constant Luminous_Intensity := 1.0E-21; -- zepto
acd : constant Luminous_Intensity := 1.0E-18; -- atto
fcd : constant Luminous_Intensity := 1.0E-15; -- femto
pcd : constant Luminous_Intensity := 1.0E-12; -- pico
ncd : constant Luminous_Intensity := 1.0E-09; -- nano
ucd : constant Luminous_Intensity := 1.0E-06; -- micro (u)
mcd : constant Luminous_Intensity := 1.0E-03; -- milli
ccd : constant Luminous_Intensity := 1.0E-02; -- centi
dcd : constant Luminous_Intensity := 1.0E-01; -- deci
dacd : constant Luminous_Intensity := 1.0E+01; -- deka
hcd : constant Luminous_Intensity := 1.0E+02; -- hecto
kcd : constant Luminous_Intensity := 1.0E+03; -- kilo
Mecd : constant Luminous_Intensity := 1.0E+06; -- mega
Gcd : constant Luminous_Intensity := 1.0E+09; -- giga
Tcd : constant Luminous_Intensity := 1.0E+12; -- tera
Pecd : constant Luminous_Intensity := 1.0E+15; -- peta
Ecd : constant Luminous_Intensity := 1.0E+18; -- exa
Zecd : constant Luminous_Intensity := 1.0E+21; -- zetta
Yocd : constant Luminous_Intensity := 1.0E+24; -- yotta
pragma Warnings (On);
end System.Dim.Mks.Other_Prefixes;
|
pragma License (Unrestricted);
package Ada.Containers is
pragma Pure;
type Hash_Type is mod 2 ** 32; -- implementation-defined
-- extended
-- Shift_Left, Shift_Right, Shift_Right_Arithmetic, Rotate_Left,
-- and Rotate_Right.
-- These subprograms are convenience to make hash functions.
pragma Provide_Shift_Operators (Hash_Type);
-- modified
-- Count_Type is essentially same as Natural.
-- type Count_Type is range 0 .. implementation-defined;
subtype Count_Type is Natural;
Capacity_Error : exception;
end Ada.Containers;
|
package body semaphore is
protected body Counting_Semaphore is
entry Secure when Current_Count > 0 is
begin
Current_Count := Current_Count - 1;
end;
procedure Release is
begin
Current_Count := Current_Count + 1;
end;
function Count return Integer is
begin
return Current_Count;
end;
end Counting_Semaphore;
end semaphore;
|
with
gel.remote.World;
package gel_demo_Services
--
-- Provides RCI services.
--
is
pragma remote_call_Interface;
function World return gel.remote.World.view;
end gel_demo_Services;
|
-- Lumen.Events.Animate -- Event loop with frame-animation callback
--
-- Chip Richards, NiEstu, Phoenix AZ, Spring 2010
-- This code is covered by the ISC License:
--
-- Copyright © 2010, NiEstu
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- The software is provided "as is" and the author disclaims all warranties
-- with regard to this software including all implied warranties of
-- merchantability and fitness. In no event shall the author be liable for any
-- special, direct, indirect, or consequential damages or any damages
-- whatsoever resulting from loss of use, data or profits, whether in an
-- action of contract, negligence or other tortious action, arising out of or
-- in connection with the use or performance of this software.
with Lumen.Window; use Lumen.Window;
package Lumen.Events.Animate is
---------------------------------------------------------------------------
-- Count of frames displayed from Animate
type Frame_Count is new Long_Integer range 0 .. Long_Integer'Last;
-- Means "display frames as fast as you can"
Flat_Out : constant Frame_Count := 0;
---------------------------------------------------------------------------
-- An animate-frame callback procedure
type Animate_Callback is access procedure (Frame_Delta : in Duration);
No_Callback : constant Animate_Callback := null;
---------------------------------------------------------------------------
-- Procedure to change FPS after window creation
procedure Set_FPS (Win : in Window_Handle;
FPS : in Frame_Count);
-- Type of frames-per-second count to fetch. "Overall" means since the app
-- started; "Since_Prior" means since the last time you called FPS.
type FPS_Type is (FPS_Overall, FPS_Since_Prior);
-- Function to fetch FPS (and reset rolling average if necessary)
function FPS (Win : Window_Handle;
Since : FPS_Type := FPS_Since_Prior)
return Float;
---------------------------------------------------------------------------
type Event_Frame is
access function
(Frame_Delta : in Duration)
return Boolean;
procedure Run (Win : in Window_Handle;
FPS : in Frame_Count;
Frame : in Event_Frame);
end Lumen.Events.Animate;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2019, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with MicroBit.Console; use MicroBit.Console;
with MicroBit.Display; use MicroBit.Display;
with MicroBit.IOs; use MicroBit.IOs;
with MicroBit.Servos; use MicroBit.Servos;
with MicroBit.Buttons; use MicroBit.Buttons;
with MicroBit.Time; use MicroBit.Time;
with NeoPixel; use NeoPixel;
with HMI; use HMI;
procedure Main is
type Side is (Left, Right);
-----------
-- Input --
-----------
-- P15 right sensor
-- P16 left sensor
type Optical_Sensor is record
Pin : Pin_Id;
-- Sensor pin (digital input, True when on light background)
LED_State : Integer;
LED_Color : LED_Values;
-- Index and color for LED pixel reflecting sensor state
State : Boolean;
-- Current state
end record;
Sensors : array (Side) of Optical_Sensor :=
(Left => (16, 4, Purple, False), Right => (15, 0, Orange, False));
------------
-- Output --
------------
-- P0 NeoPixel strip
-- P1 right servo
-- P2 left servo
type Motor is record
Pin : Servo_Pin_Id;
-- Servo pin (PWM output, see MicroBit.Servos)
LED_Running : Integer;
-- Index for LED pixel reflecting motor state:
-- Green = running at nominal speed
-- Blue = running at reduced speed (Slow)
-- off = stopped
Slow : Boolean;
-- Set True when motor must run at reduced speed
-- to compensate drift.
end record;
Motors : array (Side) of Motor :=
(Left => (Pin => 2,
LED_Running => 3,
Slow => False),
Right => (Pin => 1,
LED_Running => 1,
Slow => False));
function Set_Point
(Motor_Side : Side; Slow : Boolean) return Servo_Set_Point
-- Compute the servo set point for the given motor
-- (left motor runs counter-clockwise, right motor runs clockwise).
is
(90 + (if Motor_Side = Left then 1 else -1) * (if Slow then 10 else 90));
Code : Character := ' ';
-- Character to be displayed on LED array
Discard : Boolean;
Motor_Color : LED_Values;
Run : Boolean := True;
begin
Put_Line ("Start");
Discard := MicroBit.Buttons.Subscribe (Button_CB'Access);
loop
-- Check sensors
for Side in Sensors'Range loop
Sensors (Side).State := Set (Sensors (Side).Pin);
Set_Color
(Strip, Sensors (Side).LED_State,
(if Sensors (Side).State then Sensors (Side).LED_Color else Black));
end loop;
-- Determine action based on sensor readings
-- On track: black strip is centered between sensors, steam ahead!
Run := True;
if Sensors (Left).State and Sensors (Right).State then
Motors (Left).Slow := False;
Motors (Right).Slow := False;
Code := '|';
-- Left sensor goes dark: we are too far right,
-- slow left motor to move left.
elsif Sensors (Right).State then
Motors (Right).Slow := False;
Motors (Left).Slow := True;
Code := '>';
-- Right sensor goes dark: we are too far left,
-- slow right motor to move right.
elsif Sensors (Left).State then
Motors (Right).Slow := True;
Motors (Left).Slow := False;
Code := '<';
-- Both sensors dark: stop
else
Code := '-';
Run := False;
end if;
if not Motors_Enable then
Code := '0';
end if;
Clear;
Display (Code);
-- Drive servos based on steering decision
Set_Color (Strip, 2, (if Motors_Enable then Green else Red));
for M in Motors'Range loop
if Run then
Motor_Color := (if Motors (M).Slow then Blue else Green);
else
Motor_Color := Red;
end if;
if Motors_Enable and Run then
Set_Color (Strip, Motors (M).LED_Running, Motor_Color);
Go (Motors (M).Pin, Set_Point (M, Motors (M).Slow));
else
Set_Color (Strip, Motors (M).LED_Running, Black);
Stop (Motors (M).Pin);
end if;
end loop;
Show (Strip, Kitronik_Write'Access);
Delay_Ms (10);
end loop;
end Main;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- A D A . T E X T _ I O . F I X E D _ I O --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-2019, 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. --
-- --
------------------------------------------------------------------------------
-- Fixed point I/O
-- ---------------
-- The following documents implementation details of the fixed point
-- input/output routines in the GNAT run time. The first part describes
-- general properties of fixed point types as defined by the Ada 95 standard,
-- including the Information Systems Annex.
-- Subsequently these are reduced to implementation constraints and the impact
-- of these constraints on a few possible approaches to I/O are given.
-- Based on this analysis, a specific implementation is selected for use in
-- the GNAT run time. Finally, the chosen algorithm is analyzed numerically in
-- order to provide user-level documentation on limits for range and precision
-- of fixed point types as well as accuracy of input/output conversions.
-- -------------------------------------------
-- - General Properties of Fixed Point Types -
-- -------------------------------------------
-- Operations on fixed point values, other than input and output, are not
-- important for the purposes of this document. Only the set of values that a
-- fixed point type can represent and the input and output operations are
-- significant.
-- Values
-- ------
-- Set set of values of a fixed point type comprise the integral
-- multiples of a number called the small of the type. The small can
-- either be a power of ten, a power of two or (if the implementation
-- allows) an arbitrary strictly positive real value.
-- Implementations need to support fixed-point types with a precision
-- of at least 24 bits, and (in order to comply with the Information
-- Systems Annex) decimal types need to support at least digits 18.
-- For the rest, however, no requirements exist for the minimal small
-- and range that need to be supported.
-- Operations
-- ----------
-- 'Image and 'Wide_Image (see RM 3.5(34))
-- These attributes return a decimal real literal best approximating
-- the value (rounded away from zero if halfway between) with a
-- single leading character that is either a minus sign or a space,
-- one or more digits before the decimal point (with no redundant
-- leading zeros), a decimal point, and N digits after the decimal
-- point. For a subtype S, the value of N is S'Aft, the smallest
-- positive integer such that (10**N)*S'Delta is greater or equal to
-- one, see RM 3.5.10(5).
-- For an arbitrary small, this means large number arithmetic needs
-- to be performed.
-- Put (see RM A.10.9(22-26))
-- The requirements for Put add no extra constraints over the image
-- attributes, although it would be nice to be able to output more
-- than S'Aft digits after the decimal point for values of subtype S.
-- 'Value and 'Wide_Value attribute (RM 3.5(40-55))
-- Since the input can be given in any base in the range 2..16,
-- accurate conversion to a fixed point number may require
-- arbitrary precision arithmetic if there is no limit on the
-- magnitude of the small of the fixed point type.
-- Get (see RM A.10.9(12-21))
-- The requirements for Get are identical to those of the Value
-- attribute.
-- ------------------------------
-- - Implementation Constraints -
-- ------------------------------
-- The requirements listed above for the input/output operations lead to
-- significant complexity, if no constraints are put on supported smalls.
-- Implementation Strategies
-- -------------------------
-- * Float arithmetic
-- * Arbitrary-precision integer arithmetic
-- * Fixed-precision integer arithmetic
-- Although it seems convenient to convert fixed point numbers to floating-
-- point and then print them, this leads to a number of restrictions.
-- The first one is precision. The widest floating-point type generally
-- available has 53 bits of mantissa. This means that Fine_Delta cannot
-- be less than 2.0**(-53).
-- In GNAT, Fine_Delta is 2.0**(-63), and Duration for example is a
-- 64-bit type. It would still be possible to use multi-precision
-- floating-point to perform calculations using longer mantissas,
-- but this is a much harder approach.
-- The base conversions needed for input and output of (non-decimal)
-- fixed point types can be seen as pairs of integer multiplications
-- and divisions.
-- Arbitrary-precision integer arithmetic would be suitable for the job
-- at hand, but has the draw-back that it is very heavy implementation-wise.
-- Especially in embedded systems, where fixed point types are often used,
-- it may not be desirable to require large amounts of storage and time
-- for fixed I/O operations.
-- Fixed-precision integer arithmetic has the advantage of simplicity and
-- speed. For the most common fixed point types this would be a perfect
-- solution. The downside however may be a too limited set of acceptable
-- fixed point types.
-- Extra Precision
-- ---------------
-- Using a scaled divide which truncates and returns a remainder R,
-- another E trailing digits can be calculated by computing the value
-- (R * (10.0**E)) / Z using another scaled divide. This procedure
-- can be repeated to compute an arbitrary number of digits in linear
-- time and storage. The last scaled divide should be rounded, with
-- a possible carry propagating to the more significant digits, to
-- ensure correct rounding of the unit in the last place.
-- An extension of this technique is to limit the value of Q to 9 decimal
-- digits, since 32-bit integers can be much more efficient than 64-bit
-- integers to output.
with Interfaces; use Interfaces;
with System.Arith_64; use System.Arith_64;
with System.Img_Real; use System.Img_Real;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO.Float_Aux;
with Ada.Text_IO.Generic_Aux;
package body Ada.Text_IO.Fixed_IO is
-- Note: we still use the floating-point I/O routines for input of
-- ordinary fixed-point and output using exponent format. This will
-- result in inaccuracies for fixed point types with a small that is
-- not a power of two, and for types that require more precision than
-- is available in Long_Long_Float.
package Aux renames Ada.Text_IO.Float_Aux;
Extra_Layout_Space : constant Field := 5 + Num'Fore;
-- Extra space that may be needed for output of sign, decimal point,
-- exponent indication and mandatory decimals after and before the
-- decimal point. A string with length
-- Fore + Aft + Exp + Extra_Layout_Space
-- is always long enough for formatting any fixed point number
-- Implementation of Put routines
-- The following section describes a specific implementation choice for
-- performing base conversions needed for output of values of a fixed
-- point type T with small T'Small. The goal is to be able to output
-- all values of types with a precision of 64 bits and a delta of at
-- least 2.0**(-63), as these are current GNAT limitations already.
-- The chosen algorithm uses fixed precision integer arithmetic for
-- reasons of simplicity and efficiency. It is important to understand
-- in what ways the most simple and accurate approach to fixed point I/O
-- is limiting, before considering more complicated schemes.
-- Without loss of generality assume T has a range (-2.0**63) * T'Small
-- .. (2.0**63 - 1) * T'Small, and is output with Aft digits after the
-- decimal point and T'Fore - 1 before. If T'Small is integer, or
-- 1.0 / T'Small is integer, let S = T'Small and E = 0. For other T'Small,
-- let S and E be integers such that S / 10**E best approximates T'Small
-- and S is in the range 10**17 .. 10**18 - 1. The extra decimal scaling
-- factor 10**E can be trivially handled during final output, by adjusting
-- the decimal point or exponent.
-- Convert a value X * S of type T to a 64-bit integer value Q equal
-- to 10.0**D * (X * S) rounded to the nearest integer.
-- This conversion is a scaled integer divide of the form
-- Q := (X * Y) / Z,
-- where all variables are 64-bit signed integers using 2's complement,
-- and both the multiplication and division are done using full
-- intermediate precision. The final decimal value to be output is
-- Q * 10**(E-D)
-- This value can be written to the output file or to the result string
-- according to the format described in RM A.3.10. The details of this
-- operation are omitted here.
-- A 64-bit value can contain all integers with 18 decimal digits, but
-- not all with 19 decimal digits. If the total number of requested output
-- digits (Fore - 1) + Aft is greater than 18, for purposes of the
-- conversion Aft is adjusted to 18 - (Fore - 1). In that case, or
-- when Fore > 19, trailing zeros can complete the output after writing
-- the first 18 significant digits, or the technique described in the
-- next section can be used.
-- The final expression for D is
-- D := Integer'Max (-18, Integer'Min (Aft, 18 - (Fore - 1)));
-- For Y and Z the following expressions can be derived:
-- Q / (10.0**D) = X * S
-- Q = X * S * (10.0**D) = (X * Y) / Z
-- S * 10.0**D = Y / Z;
-- If S is an integer greater than or equal to one, then Fore must be at
-- least 20 in order to print T'First, which is at most -2.0**63.
-- This means D < 0, so use
-- (1) Y = -S and Z = -10**(-D)
-- If 1.0 / S is an integer greater than one, use
-- (2) Y = -10**D and Z = -(1.0 / S), for D >= 0
-- or
-- (3) Y = 1 and Z = (1.0 / S) * 10**(-D), for D < 0
-- Negative values are used for nominator Y and denominator Z, so that S
-- can have a maximum value of 2.0**63 and a minimum of 2.0**(-63).
-- For Z in -1 .. -9, Fore will still be 20, and D will be negative, as
-- (-2.0**63) / -9 is greater than 10**18. In these cases there is room
-- in the denominator for the extra decimal scaling required, so case (3)
-- will not overflow.
pragma Assert (System.Fine_Delta >= 2.0**(-63));
pragma Assert (Num'Small in 2.0**(-63) .. 2.0**63);
pragma Assert (Num'Fore <= 37);
-- These assertions need to be relaxed to allow for a Small of
-- 2.0**(-64) at least, since there is an ACATS test for this ???
Max_Digits : constant := 18;
-- Maximum number of decimal digits that can be represented in a
-- 64-bit signed number, see above
-- The constants E0 .. E5 implement a binary search for the appropriate
-- power of ten to scale the small so that it has one digit before the
-- decimal point.
subtype Int is Integer;
E0 : constant Int := -(20 * Boolean'Pos (Num'Small >= 1.0E1));
E1 : constant Int := E0 + 10 * Boolean'Pos (Num'Small * 10.0**E0 < 1.0E-10);
E2 : constant Int := E1 + 5 * Boolean'Pos (Num'Small * 10.0**E1 < 1.0E-5);
E3 : constant Int := E2 + 3 * Boolean'Pos (Num'Small * 10.0**E2 < 1.0E-3);
E4 : constant Int := E3 + 2 * Boolean'Pos (Num'Small * 10.0**E3 < 1.0E-1);
E5 : constant Int := E4 + 1 * Boolean'Pos (Num'Small * 10.0**E4 < 1.0E-0);
Scale : constant Integer := E5;
pragma Assert (Num'Small * 10.0**Scale >= 1.0
and then Num'Small * 10.0**Scale < 10.0);
Exact : constant Boolean :=
Float'Floor (Num'Small) = Float'Ceiling (Num'Small)
or else Float'Floor (1.0 / Num'Small) = Float'Ceiling (1.0 / Num'Small)
or else Num'Small >= 10.0**Max_Digits;
-- True iff a numerator and denominator can be calculated such that
-- their ratio exactly represents the small of Num.
procedure Put
(To : out String;
Last : out Natural;
Item : Num;
Fore : Integer;
Aft : Field;
Exp : Field);
-- Actual output function, used internally by all other Put routines.
-- The formal Fore is an Integer, not a Field, because the routine is
-- also called from the version of Put that performs I/O to a string,
-- where the starting position depends on the size of the String, and
-- bears no relation to the bounds of Field.
---------
-- Get --
---------
procedure Get
(File : File_Type;
Item : out Num;
Width : Field := 0)
is
pragma Unsuppress (Range_Check);
begin
Aux.Get (File, Long_Long_Float (Item), Width);
exception
when Constraint_Error => raise Data_Error;
end Get;
procedure Get
(Item : out Num;
Width : Field := 0)
is
pragma Unsuppress (Range_Check);
begin
Aux.Get (Current_In, Long_Long_Float (Item), Width);
exception
when Constraint_Error => raise Data_Error;
end Get;
procedure Get
(From : String;
Item : out Num;
Last : out Positive)
is
pragma Unsuppress (Range_Check);
begin
Aux.Gets (From, Long_Long_Float (Item), Last);
exception
when Constraint_Error => raise Data_Error;
end Get;
---------
-- Put --
---------
procedure Put
(File : File_Type;
Item : Num;
Fore : Field := Default_Fore;
Aft : Field := Default_Aft;
Exp : Field := Default_Exp)
is
S : String (1 .. Fore + Aft + Exp + Extra_Layout_Space);
Last : Natural;
begin
Put (S, Last, Item, Fore, Aft, Exp);
Generic_Aux.Put_Item (File, S (1 .. Last));
end Put;
procedure Put
(Item : Num;
Fore : Field := Default_Fore;
Aft : Field := Default_Aft;
Exp : Field := Default_Exp)
is
S : String (1 .. Fore + Aft + Exp + Extra_Layout_Space);
Last : Natural;
begin
Put (S, Last, Item, Fore, Aft, Exp);
Generic_Aux.Put_Item (Text_IO.Current_Out, S (1 .. Last));
end Put;
procedure Put
(To : out String;
Item : Num;
Aft : Field := Default_Aft;
Exp : Field := Default_Exp)
is
Fore : constant Integer :=
To'Length
- 1 -- Decimal point
- Field'Max (1, Aft) -- Decimal part
- Boolean'Pos (Exp /= 0) -- Exponent indicator
- Exp; -- Exponent
Last : Natural;
begin
if Fore - Boolean'Pos (Item < 0.0) < 1 then
raise Layout_Error;
end if;
Put (To, Last, Item, Fore, Aft, Exp);
if Last /= To'Last then
raise Layout_Error;
end if;
end Put;
procedure Put
(To : out String;
Last : out Natural;
Item : Num;
Fore : Integer;
Aft : Field;
Exp : Field)
is
subtype Digit is Int64 range 0 .. 9;
X : constant Int64 := Int64'Integer_Value (Item);
A : constant Field := Field'Max (Aft, 1);
Neg : constant Boolean := (Item < 0.0);
Pos : Integer := 0; -- Next digit X has value X * 10.0**Pos;
procedure Put_Character (C : Character);
pragma Inline (Put_Character);
-- Add C to the output string To, updating Last
procedure Put_Digit (X : Digit);
-- Add digit X to the output string (going from left to right), updating
-- Last and Pos, and inserting the sign, leading zeros or a decimal
-- point when necessary. After outputting the first digit, Pos must not
-- be changed outside Put_Digit anymore.
procedure Put_Int64 (X : Int64; Scale : Integer);
-- Output the decimal number abs X * 10**Scale
procedure Put_Scaled
(X, Y, Z : Int64;
A : Field;
E : Integer);
-- Output the decimal number (X * Y / Z) * 10**E, producing A digits
-- after the decimal point and rounding the final digit. The value
-- X * Y / Z is computed with full precision, but must be in the
-- range of Int64.
-------------------
-- Put_Character --
-------------------
procedure Put_Character (C : Character) is
begin
Last := Last + 1;
-- Never put a character outside of string To. Exception Layout_Error
-- will be raised later if Last is greater than To'Last.
if Last <= To'Last then
To (Last) := C;
end if;
end Put_Character;
---------------
-- Put_Digit --
---------------
procedure Put_Digit (X : Digit) is
Digs : constant array (Digit) of Character := "0123456789";
begin
if Last = To'First - 1 then
if X /= 0 or else Pos <= 0 then
-- Before outputting first digit, include leading space,
-- possible minus sign and, if the first digit is fractional,
-- decimal seperator and leading zeros.
-- The Fore part has Pos + 1 + Boolean'Pos (Neg) characters,
-- if Pos >= 0 and otherwise has a single zero digit plus minus
-- sign if negative. Add leading space if necessary.
for J in Integer'Max (0, Pos) + 2 + Boolean'Pos (Neg) .. Fore
loop
Put_Character (' ');
end loop;
-- Output minus sign, if number is negative
if Neg then
Put_Character ('-');
end if;
-- If starting with fractional digit, output leading zeros
if Pos < 0 then
Put_Character ('0');
Put_Character ('.');
for J in Pos .. -2 loop
Put_Character ('0');
end loop;
end if;
Put_Character (Digs (X));
end if;
else
-- This is not the first digit to be output, so the only
-- special handling is that for the decimal point
if Pos = -1 then
Put_Character ('.');
end if;
Put_Character (Digs (X));
end if;
Pos := Pos - 1;
end Put_Digit;
---------------
-- Put_Int64 --
---------------
procedure Put_Int64 (X : Int64; Scale : Integer) is
begin
if X = 0 then
return;
end if;
if X not in -9 .. 9 then
Put_Int64 (X / 10, Scale + 1);
end if;
-- Use Put_Digit to advance Pos. This fixes a case where the second
-- or later Scaled_Divide would omit leading zeroes, resulting in
-- too few digits produced and a Layout_Error as result.
while Pos > Scale loop
Put_Digit (0);
end loop;
-- If and only if more than one digit is output before the decimal
-- point, pos will be unequal to scale when outputting the first
-- digit.
pragma Assert (Pos = Scale or else Last = To'First - 1);
Pos := Scale;
Put_Digit (abs (X rem 10));
end Put_Int64;
----------------
-- Put_Scaled --
----------------
procedure Put_Scaled
(X, Y, Z : Int64;
A : Field;
E : Integer)
is
pragma Assert (E >= -Max_Digits);
AA : constant Field := E + A;
N : constant Natural := (AA + Max_Digits - 1) / Max_Digits + 1;
Q : array (0 .. N - 1) of Int64 := (others => 0);
-- Each element of Q has Max_Digits decimal digits, except the
-- last, which has eAA rem Max_Digits. Only Q (Q'First) may have an
-- absolute value equal to or larger than 10**Max_Digits. Only the
-- absolute value of the elements is not significant, not the sign.
XX : Int64 := X;
YY : Int64 := Y;
begin
for J in Q'Range loop
exit when XX = 0;
if J > 0 then
YY := 10**(Integer'Min (Max_Digits, AA - (J - 1) * Max_Digits));
end if;
Scaled_Divide (XX, YY, Z, Q (J), R => XX, Round => False);
end loop;
if -E > A then
pragma Assert (N = 1);
Discard_Extra_Digits : declare
Factor : constant Int64 := 10**(-E - A);
begin
-- The scaling factors were such that the first division
-- produced more digits than requested. So divide away extra
-- digits and compute new remainder for later rounding.
if abs (Q (0) rem Factor) >= Factor / 2 then
Q (0) := abs (Q (0) / Factor) + 1;
else
Q (0) := Q (0) / Factor;
end if;
XX := 0;
end Discard_Extra_Digits;
end if;
-- At this point XX is a remainder and we need to determine if the
-- quotient in Q must be rounded away from zero.
-- As XX is less than the divisor, it is safe to take its absolute
-- without chance of overflow. The check to see if XX is at least
-- half the absolute value of the divisor must be done carefully to
-- avoid overflow or lose precision.
XX := abs XX;
if XX >= 2**62
or else (Z < 0 and then (-XX) * 2 <= Z)
or else (Z >= 0 and then XX * 2 >= Z)
then
-- OK, rounding is necessary. As the sign is not significant,
-- take advantage of the fact that an extra negative value will
-- always be available when propagating the carry.
Q (Q'Last) := -abs Q (Q'Last) - 1;
Propagate_Carry :
for J in reverse 1 .. Q'Last loop
if Q (J) = YY or else Q (J) = -YY then
Q (J) := 0;
Q (J - 1) := -abs Q (J - 1) - 1;
else
exit Propagate_Carry;
end if;
end loop Propagate_Carry;
end if;
for J in Q'First .. Q'Last - 1 loop
Put_Int64 (Q (J), E - J * Max_Digits);
end loop;
Put_Int64 (Q (Q'Last), -A);
end Put_Scaled;
-- Start of processing for Put
begin
Last := To'First - 1;
if Exp /= 0 then
-- With the Exp format, it is not known how many output digits to
-- generate, as leading zeros must be ignored. Computing too many
-- digits and then truncating the output will not give the closest
-- output, it is necessary to round at the correct digit.
-- The general approach is as follows: as long as no digits have
-- been generated, compute the Aft next digits (without rounding).
-- Once a non-zero digit is generated, determine the exact number
-- of digits remaining and compute them with rounding.
-- Since a large number of iterations might be necessary in case
-- of Aft = 1, the following optimization would be desirable.
-- Count the number Z of leading zero bits in the integer
-- representation of X, and start with producing Aft + Z * 1000 /
-- 3322 digits in the first scaled division.
-- However, the floating-point routines are still used now ???
System.Img_Real.Set_Image_Real (Long_Long_Float (Item), To, Last,
Fore, Aft, Exp);
return;
end if;
if Exact then
declare
D : constant Integer := Integer'Min (A, Max_Digits
- (Num'Fore - 1));
Y : constant Int64 := Int64'Min (Int64 (-Num'Small), -1)
* 10**Integer'Max (0, D);
Z : constant Int64 := Int64'Min (Int64 (-(1.0 / Num'Small)), -1)
* 10**Integer'Max (0, -D);
begin
Put_Scaled (X, Y, Z, A, -D);
end;
else -- not Exact
declare
E : constant Integer := Max_Digits - 1 + Scale;
D : constant Integer := Scale - 1;
Y : constant Int64 := Int64 (-Num'Small * 10.0**E);
Z : constant Int64 := -10**Max_Digits;
begin
Put_Scaled (X, Y, Z, A, -D);
end;
end if;
-- If only zero digits encountered, unit digit has not been output yet
if Last < To'First then
Pos := 0;
elsif Last > To'Last then
raise Layout_Error; -- Not enough room in the output variable
end if;
-- Always output digits up to the first one after the decimal point
while Pos >= -A loop
Put_Digit (0);
end loop;
end Put;
end Ada.Text_IO.Fixed_IO;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2017, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
package body SSD1306 is
procedure Write_Command (This : SSD1306_Screen;
Cmd : UInt8);
procedure Write_Data (This : SSD1306_Screen;
Data : UInt8_Array);
-------------------
-- Write_Command --
-------------------
procedure Write_Command (This : SSD1306_Screen;
Cmd : UInt8)
is
Status : I2C_Status;
begin
This.Port.Master_Transmit (Addr => SSD1306_I2C_Addr,
Data => (1 => 0, 2 => (Cmd)),
Status => Status);
if Status /= Ok then
-- No error handling...
raise Program_Error;
end if;
end Write_Command;
----------------
-- Write_Data --
----------------
procedure Write_Data (This : SSD1306_Screen;
Data : UInt8_Array)
is
Status : I2C_Status;
begin
This.Port.Master_Transmit (Addr => SSD1306_I2C_Addr,
Data => Data,
Status => Status);
if Status /= Ok then
-- No error handling...
raise Program_Error;
end if;
end Write_Data;
----------------
-- Initialize --
----------------
procedure Initialize (This : in out SSD1306_Screen;
External_VCC : Boolean)
is
begin
if This.Width * This.Height /= (This.Buffer_Size_In_Byte * 8) then
raise Program_Error with "Invalid screen parameters";
end if;
This.RST.Clear;
This.Time.Delay_Milliseconds (100);
This.RST.Set;
This.Time.Delay_Milliseconds (100);
Write_Command (This, DISPLAY_OFF);
Write_Command (This, SET_DISPLAY_CLOCK_DIV);
Write_Command (This, 16#80#);
Write_Command (This, SET_MULTIPLEX);
Write_Command (This, UInt8 (This.Height - 1));
Write_Command (This, SET_DISPLAY_OFFSET);
Write_Command (This, 16#00#);
Write_Command (This, SET_START_LINE or 0);
Write_Command (This, CHARGE_PUMP);
Write_Command (This, (if External_VCC then 16#10# else 16#14#));
Write_Command (This, MEMORY_MODE);
Write_Command (This, 16#00#);
Write_Command (This, SEGREMAP or 1);
Write_Command (This, COM_SCAN_DEC);
Write_Command (This, SET_COMPINS);
if This.Height > 32 then
Write_Command (This, 16#12#);
else
Write_Command (This, 16#02#);
end if;
Write_Command (This, SET_CONTRAST);
Write_Command (This, 16#AF#);
Write_Command (This, SET_PRECHARGE);
Write_Command (This, (if External_VCC then 16#22# else 16#F1#));
Write_Command (This, SET_VCOM_DETECT);
Write_Command (This, 16#40#);
Write_Command (This, DISPLAY_ALL_ON_RESUME);
Write_Command (This, NORMAL_DISPLAY);
Write_Command (This, DEACTIVATE_SCROLL);
This.Device_Initialized := True;
end Initialize;
-----------------
-- Initialized --
-----------------
overriding
function Initialized (This : SSD1306_Screen) return Boolean is
(This.Device_Initialized);
-------------
-- Turn_On --
-------------
procedure Turn_On (This : SSD1306_Screen) is
begin
Write_Command (This, DISPLAY_ON);
end Turn_On;
--------------
-- Turn_Off --
--------------
procedure Turn_Off (This : SSD1306_Screen) is
begin
Write_Command (This, DISPLAY_OFF);
end Turn_Off;
--------------------------
-- Display_Inversion_On --
--------------------------
procedure Display_Inversion_On (This : SSD1306_Screen) is
begin
Write_Command (This, INVERT_DISPLAY);
end Display_Inversion_On;
---------------------------
-- Display_Inversion_Off --
---------------------------
procedure Display_Inversion_Off (This : SSD1306_Screen) is
begin
Write_Command (This, NORMAL_DISPLAY);
end Display_Inversion_Off;
----------------------
-- Write_Raw_Pixels --
----------------------
procedure Write_Raw_Pixels (This : SSD1306_Screen;
Data : HAL.UInt8_Array)
is
begin
Write_Command (This, COLUMN_ADDR);
Write_Command (This, 0); -- from
Write_Command (This, UInt8 (This.Width - 1)); -- to
Write_Command (This, PAGE_ADDR);
Write_Command (This, 0); -- from
Write_Command (This, UInt8 (This.Height / 8) - 1); -- to
Write_Data (This, (1 => 16#40#) & Data);
end Write_Raw_Pixels;
--------------------
-- Get_Max_Layers --
--------------------
overriding
function Max_Layers
(This : SSD1306_Screen) return Positive is (1);
------------------
-- Is_Supported --
------------------
overriding
function Supported
(This : SSD1306_Screen;
Mode : FB_Color_Mode) return Boolean is
(Mode = HAL.Bitmap.RGB_565);
---------------------
-- Set_Orientation --
---------------------
overriding
procedure Set_Orientation
(This : in out SSD1306_Screen;
Orientation : Display_Orientation)
is
begin
null;
end Set_Orientation;
--------------
-- Set_Mode --
--------------
overriding
procedure Set_Mode
(This : in out SSD1306_Screen;
Mode : Wait_Mode)
is
begin
null;
end Set_Mode;
---------------
-- Get_Width --
---------------
overriding
function Width
(This : SSD1306_Screen) return Positive is (This.Width);
----------------
-- Get_Height --
----------------
overriding
function Height
(This : SSD1306_Screen) return Positive is (This.Height);
----------------
-- Is_Swapped --
----------------
overriding
function Swapped
(This : SSD1306_Screen) return Boolean is (False);
--------------------
-- Set_Background --
--------------------
overriding
procedure Set_Background
(This : SSD1306_Screen; R, G, B : UInt8)
is
begin
-- Does it make sense when there's no alpha channel...
raise Program_Error;
end Set_Background;
----------------------
-- Initialize_Layer --
----------------------
overriding
procedure Initialize_Layer
(This : in out SSD1306_Screen;
Layer : Positive;
Mode : FB_Color_Mode;
X : Natural := 0;
Y : Natural := 0;
Width : Positive := Positive'Last;
Height : Positive := Positive'Last)
is
pragma Unreferenced (X, Y, Width, Height);
begin
if Layer /= 1 or else Mode /= M_1 then
raise Program_Error;
end if;
This.Memory_Layer.Actual_Width := This.Width;
This.Memory_Layer.Actual_Height := This.Height;
This.Memory_Layer.Addr := This.Memory_Layer.Data'Address;
This.Memory_Layer.Actual_Color_Mode := Mode;
This.Layer_Initialized := True;
end Initialize_Layer;
-----------------
-- Initialized --
-----------------
overriding
function Initialized
(This : SSD1306_Screen;
Layer : Positive) return Boolean
is
begin
return Layer = 1 and then This.Layer_Initialized;
end Initialized;
------------------
-- Update_Layer --
------------------
overriding
procedure Update_Layer
(This : in out SSD1306_Screen;
Layer : Positive;
Copy_Back : Boolean := False)
is
pragma Unreferenced (Copy_Back);
begin
if Layer /= 1 then
raise Program_Error;
end if;
This.Write_Raw_Pixels (This.Memory_Layer.Data);
end Update_Layer;
-------------------
-- Update_Layers --
-------------------
overriding
procedure Update_Layers
(This : in out SSD1306_Screen)
is
begin
This.Update_Layer (1);
end Update_Layers;
--------------------
-- Get_Color_Mode --
--------------------
overriding
function Color_Mode
(This : SSD1306_Screen;
Layer : Positive) return FB_Color_Mode
is
pragma Unreferenced (This);
begin
if Layer /= 1 then
raise Program_Error;
end if;
return M_1;
end Color_Mode;
-----------------------
-- Get_Hidden_Buffer --
-----------------------
overriding
function Hidden_Buffer
(This : in out SSD1306_Screen;
Layer : Positive) return not null HAL.Bitmap.Any_Bitmap_Buffer
is
begin
if Layer /= 1 then
raise Program_Error;
end if;
return This.Memory_Layer'Unchecked_Access;
end Hidden_Buffer;
--------------------
-- Get_Pixel_Size --
--------------------
overriding
function Pixel_Size
(This : SSD1306_Screen;
Layer : Positive) return Positive is (1);
---------------
-- Set_Pixel --
---------------
overriding
procedure Set_Pixel
(Buffer : in out SSD1306_Bitmap_Buffer;
Pt : Point)
is
X : constant Natural := Buffer.Width - 1 - Pt.X;
Y : constant Natural := Buffer.Height - 1 - Pt.Y;
Index : constant Natural := X + (Y / 8) * Buffer.Actual_Width;
Byte : UInt8 renames Buffer.Data (Buffer.Data'First + Index);
begin
if Buffer.Native_Source = 0 then
Byte := Byte and not (Shift_Left (1, Y mod 8));
else
Byte := Byte or Shift_Left (1, Y mod 8);
end if;
end Set_Pixel;
---------------
-- Set_Pixel --
---------------
overriding
procedure Set_Pixel
(Buffer : in out SSD1306_Bitmap_Buffer;
Pt : Point;
Color : Bitmap_Color)
is
begin
Buffer.Set_Pixel (Pt, (if Color = Black then 0 else 1));
end Set_Pixel;
---------------
-- Set_Pixel --
---------------
overriding
procedure Set_Pixel
(Buffer : in out SSD1306_Bitmap_Buffer;
Pt : Point;
Raw : UInt32)
is
begin
Buffer.Native_Source := Raw;
Buffer.Set_Pixel (Pt);
end Set_Pixel;
-----------
-- Pixel --
-----------
overriding
function Pixel
(Buffer : SSD1306_Bitmap_Buffer;
Pt : Point)
return Bitmap_Color
is
begin
return (if Buffer.Pixel (Pt) = 0 then Black else White);
end Pixel;
-----------
-- Pixel --
-----------
overriding
function Pixel
(Buffer : SSD1306_Bitmap_Buffer;
Pt : Point)
return UInt32
is
X : constant Natural := Buffer.Width - 1 - Pt.X;
Y : constant Natural := Buffer.Height - 1 - Pt.Y;
Index : constant Natural := X + (Y / 8) * Buffer.Actual_Width;
Byte : UInt8 renames Buffer.Data (Buffer.Data'First + Index);
begin
if (Byte and (Shift_Left (1, Y mod 8))) /= 0 then
return 1;
else
return 0;
end if;
end Pixel;
----------
-- Fill --
----------
overriding
procedure Fill
(Buffer : in out SSD1306_Bitmap_Buffer)
is
Val : constant UInt8 := (if Buffer.Native_Source /= 0 then 16#FF# else 0);
begin
Buffer.Data := (others => Val);
end Fill;
end SSD1306;
|
generic
type Data is private;
package Bin_Trees is
type Tree_Type is private;
function Empty(Tree: Tree_Type) return Boolean;
function Left (Tree: Tree_Type) return Tree_Type;
function Right(Tree: Tree_Type) return Tree_Type;
function Item (Tree: Tree_Type) return Data;
function Empty return Tree_Type;
procedure Destroy_Tree(N: in out Tree_Type);
function Tree(Value: Data) return Tree_Type;
function Tree(Value: Data; Left, Right : Tree_Type) return Tree_Type;
private
type Node;
type Tree_Type is access Node;
type Node is record
Left, Right: Tree_Type := null;
Item: Data;
end record;
end Bin_Trees;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with Ada.Text_IO;
with JohnnyText;
with Signals;
with Unix;
package body Display is
package JT renames JohnnyText;
package SIG renames Signals;
package TIO renames Ada.Text_IO;
----------------------
-- launch_monitor --
----------------------
function launch_monitor (num_builders : builders) return Boolean is
begin
if not Start_Curses_Mode then
TIO.Put_Line ("Failed to enter curses modes");
return False;
end if;
if not TIC.Has_Colors or else not establish_colors then
Return_To_Text_Mode;
TIO.Put_Line ("The TERM environment variable value (" &
Unix.env_variable_value ("TERM") &
") does not support colors.");
TIO.Put_Line ("Falling back to text mode.");
return False;
end if;
begin
TIC.Set_Echo_Mode (False);
TIC.Set_Raw_Mode (True);
TIC.Set_Cbreak_Mode (True);
TIC.Set_Cursor_Visibility (Visibility => cursor_vis);
exception
when TIC.Curses_Exception =>
Return_To_Text_Mode;
return False;
end;
builders_used := Integer (num_builders);
if not launch_summary_zone or else
not launch_builders_zone or else
not launch_actions_zone
then
terminate_monitor;
return False;
end if;
draw_static_summary_zone;
draw_static_builders_zone;
Refresh_Zone (summary);
Refresh_Zone (builder);
return True;
end launch_monitor;
-------------------------
-- terminate_monitor --
-------------------------
procedure terminate_monitor
is
ok : Boolean := True;
begin
-- zone_window can't be used because Delete will modify Win variable
begin
TIC.Delete (Win => zone_summary);
TIC.Delete (Win => zone_builders);
TIC.Delete (Win => zone_actions);
exception
when TIC.Curses_Exception => ok := False;
end;
if ok then
Return_To_Text_Mode;
end if;
end terminate_monitor;
-----------------------------------
-- set_full_redraw_next_update --
-----------------------------------
procedure set_full_redraw_next_update is
begin
draw_static_summary_zone;
draw_static_builders_zone;
for zone in zones'Range loop
begin
TIC.Redraw (Win => zone_window (zone));
exception
when TIC.Curses_Exception => null;
end;
end loop;
end set_full_redraw_next_update;
---------------------------
-- launch_summary_zone --
---------------------------
function launch_summary_zone return Boolean is
begin
zone_summary := TIC.Create (Number_Of_Lines => 2,
Number_Of_Columns => app_width,
First_Line_Position => 0,
First_Column_Position => 0);
return True;
exception
when TIC.Curses_Exception => return False;
end launch_summary_zone;
--------------------------------
-- draw_static_summary_zone --
--------------------------------
procedure draw_static_summary_zone
is
line1 : constant appline :=
custom_message (message => " Total Built Ignored " &
" Load 0.00 Pkg/hour ",
attribute => bright,
pen_color => c_sumlabel);
line2 : constant appline :=
custom_message (message => " Left Failed Skipped " &
" Swap 0.0% Impulse 00:00:00 ",
attribute => bright,
pen_color => c_sumlabel);
begin
Scrawl (summary, line1, 0);
Scrawl (summary, line2, 1);
end draw_static_summary_zone;
----------------------------
-- launch_builders_zone --
----------------------------
function launch_builders_zone return Boolean
is
hghtint : constant Integer := 4 + builders_used;
height : constant TIC.Line_Position := TIC.Line_Position (hghtint);
begin
zone_builders := TIC.Create (Number_Of_Lines => height,
Number_Of_Columns => app_width,
First_Line_Position => 2,
First_Column_Position => 0);
return True;
exception
when TIC.Curses_Exception => return False;
end launch_builders_zone;
---------------------------------
-- draw_static_builders_zone --
---------------------------------
procedure draw_static_builders_zone
is
hghtint : constant Integer := 4 + builders_used;
height : constant TIC.Line_Position := TIC.Line_Position (hghtint);
lastrow : constant TIC.Line_Position := inc (height, -1);
dmsg : constant String (appline'Range) := (others => '=');
dashes : constant appline := custom_message (message => dmsg,
attribute => bright,
pen_color => c_dashes);
headtxt : constant appline :=
custom_message (message => " ID Duration Build Phase Origin " &
" Lines ",
attribute => normal,
pen_color => c_tableheader);
begin
Scrawl (builder, dashes, 0);
Scrawl (builder, dashes, 2);
Scrawl (builder, dashes, lastrow);
if SIG.graceful_shutdown_requested then
Scrawl (builder, shutdown_message, 1);
else
Scrawl (builder, headtxt, 1);
end if;
for z in 3 .. inc (lastrow, -1) loop
Scrawl (builder, blank_line, z);
end loop;
end draw_static_builders_zone;
---------------------------
-- launch_actions_zone --
---------------------------
function launch_actions_zone return Boolean
is
consumed : constant Integer := builders_used + 4 + 2;
viewpos : constant TIC.Line_Position := TIC.Line_Position (consumed);
difference : Integer := 0 - consumed;
use type TIC.Line_Position;
begin
historyheight := inc (TIC.Lines, difference);
-- Make sure history window lines range from 10 to 50
if historyheight < 10 then
historyheight := 10;
elsif historyheight > TIC.Line_Position (cyclic_range'Last) then
historyheight := TIC.Line_Position (cyclic_range'Last);
end if;
zone_actions := TIC.Create (Number_Of_Lines => historyheight,
Number_Of_Columns => app_width,
First_Line_Position => viewpos,
First_Column_Position => 0);
return True;
exception
when TIC.Curses_Exception => return False;
end launch_actions_zone;
-----------
-- inc --
-----------
function inc (X : TIC.Line_Position; by : Integer) return TIC.Line_Position
is
use type TIC.Line_Position;
begin
return X + TIC.Line_Position (by);
end inc;
-----------------
-- summarize --
-----------------
procedure summarize (data : summary_rec)
is
function pad (S : String; amount : Positive := 5) return String;
procedure colorado (S : String; color : TIC.Color_Pair;
col : TIC.Column_Position;
row : TIC.Line_Position;
dim : Boolean := False);
remaining : constant Integer := data.Initially - data.Built -
data.Failed - data.Ignored - data.Skipped;
function pad (S : String; amount : Positive := 5) return String
is
result : String (1 .. amount) := (others => ' ');
slen : constant Natural := S'Length;
begin
if slen <= amount then
result (1 .. slen) := S;
else
result := S (S'First .. S'First + amount - 1);
end if;
return result;
end pad;
procedure colorado (S : String; color : TIC.Color_Pair;
col : TIC.Column_Position;
row : TIC.Line_Position;
dim : Boolean := False)
is
info : TIC.Attributed_String := custom_message (message => S,
attribute => emphasis (dim),
pen_color => color);
begin
Scrawl (summary, info, row, col);
end colorado;
L1F1 : constant String := pad (JT.int2str (data.Initially));
L1F2 : constant String := pad (JT.int2str (data.Built));
L1F3 : constant String := pad (JT.int2str (data.Ignored));
L1F4 : fivelong;
L1F5 : constant String := pad (JT.int2str (data.pkg_hour), 4);
L2F1 : constant String := pad (JT.int2str (remaining));
L2F2 : constant String := pad (JT.int2str (data.Failed));
L2F3 : constant String := pad (JT.int2str (data.Skipped));
L2F4 : fivelong;
L2F5 : constant String := pad (JT.int2str (data.impulse), 4);
begin
if data.swap = 100.0 then
L2F4 := " 100%";
elsif data.swap > 100.0 then
L2F4 := " n/a";
else
L2F4 := fmtpc (data.swap, True);
end if;
if data.load >= 100.0 then
L1F4 := pad (JT.int2str (Integer (data.load)));
else
L1F4 := fmtload (data.load);
end if;
colorado (L1F1, c_standard, 7, 0);
colorado (L1F2, c_success, 21, 0);
colorado (L1F3, c_ignored, 36, 0);
colorado (L1F4, c_standard, 48, 0, True);
colorado (L1F5, c_standard, 64, 0, True);
colorado (L2F1, c_standard, 7, 1);
colorado (L2F2, c_failure, 21, 1);
colorado (L2F3, c_skipped, 36, 1);
colorado (L2F4, c_standard, 48, 1, True);
colorado (L2F5, c_standard, 64, 1, True);
colorado (data.elapsed, c_elapsed, 70, 1);
Refresh_Zone (summary);
end summarize;
-----------------------
-- update_builder --
-----------------------
procedure update_builder (BR : builder_rec)
is
procedure colorado (S : String; color : TIC.Color_Pair;
col : TIC.Column_Position;
row : TIC.Line_Position;
dim : Boolean := False);
procedure print_id;
row : TIC.Line_Position := inc (TIC.Line_Position (BR.id), 2);
procedure print_id
is
info : TIC.Attributed_String := custom_message (message => BR.slavid,
attribute => c_slave (BR.id).attribute,
pen_color => c_slave (BR.id).palette);
begin
Scrawl (builder, info, row, 1);
end print_id;
procedure colorado (S : String; color : TIC.Color_Pair;
col : TIC.Column_Position;
row : TIC.Line_Position;
dim : Boolean := False)
is
info : TIC.Attributed_String := custom_message (message => S,
attribute => emphasis (dim),
pen_color => color);
begin
Scrawl (builder, info, row, col);
end colorado;
begin
if SIG.graceful_shutdown_requested then
Scrawl (builder, shutdown_message, 1);
end if;
print_id;
colorado (BR.Elapsed, c_standard, 5, row, True);
colorado (BR.phase, c_bldphase, 15, row, True);
colorado (BR.origin, c_origin, 32, row, False);
colorado (BR.LLines, c_standard, 71, row, True);
end update_builder;
------------------------------
-- refresh_builder_window --
------------------------------
procedure refresh_builder_window is
begin
Refresh_Zone (builder);
end refresh_builder_window;
----------------------
-- insert_history --
----------------------
procedure insert_history (HR : history_rec) is
begin
if history_arrow = cyclic_range'Last then
history_arrow := cyclic_range'First;
else
history_arrow := history_arrow + 1;
end if;
history (history_arrow) := HR;
end insert_history;
------------------------------
-- refresh_history_window --
------------------------------
procedure refresh_history_window
is
procedure clear_row (row : TIC.Line_Position);
procedure colorado (S : String; color : TIC.Color_Pair;
col : TIC.Column_Position;
row : TIC.Line_Position;
dim : Boolean := False);
function col_action (status : String) return TIC.Color_Pair;
procedure print_id (id : builders; sid : String; row : TIC.Line_Position;
status : String);
procedure clear_row (row : TIC.Line_Position) is
begin
Scrawl (action, blank_line, row);
end clear_row;
procedure colorado (S : String; color : TIC.Color_Pair;
col : TIC.Column_Position;
row : TIC.Line_Position;
dim : Boolean := False)
is
info : TIC.Attributed_String := custom_message (message => S,
attribute => emphasis (dim),
pen_color => color);
begin
Scrawl (action, info, row, col);
end colorado;
function col_action (status : String) return TIC.Color_Pair is
begin
if status = "shutdown" then
return c_shutdown;
elsif status = "success " then
return c_success;
elsif status = "failure " then
return c_failure;
elsif status = "skipped " then
return c_skipped;
elsif status = "ignored " then
return c_ignored;
else
return c_standard;
end if;
end col_action;
procedure print_id (id : builders; sid : String; row : TIC.Line_Position;
status : String)
is
bracket : TIC.Attributed_String := custom_message (message => "[--]",
attribute => normal,
pen_color => c_standard);
bindex : Positive := 2;
begin
if status /= "skipped " and then status /= "ignored "
then
for index in sid'Range loop
bracket (bindex) := (Attr => c_slave (id).attribute,
Color => c_slave (id).palette,
Ch => sid (index));
bindex := bindex + 1;
end loop;
end if;
Scrawl (action, bracket, row, 10);
end print_id;
arrow : cyclic_range := history_arrow;
maxrow : Natural;
row : TIC.Line_Position;
begin
-- historyheight guaranteed to be no bigger than cyclic_range
maxrow := Integer (historyheight) - 1;
for rowindex in 0 .. maxrow loop
row := TIC.Line_Position (rowindex);
if history (arrow).established then
colorado (history (arrow).run_elapsed, c_standard, 1, row, True);
print_id (id => history (arrow).id,
sid => history (arrow).slavid,
row => row,
status => history (arrow).action);
colorado (history (arrow).action,
col_action (history (arrow).action), 15, row);
colorado (history (arrow).origin, c_origin, 24, row);
colorado (history (arrow).pkg_elapsed, c_standard, 70, row, True);
else
clear_row (row);
end if;
if arrow = cyclic_range'First then
arrow := cyclic_range'Last;
else
arrow := arrow - 1;
end if;
end loop;
Refresh_Zone (action);
end refresh_history_window;
------------------------
-- establish_colors --
------------------------
function establish_colors return Boolean is
begin
TIC.Start_Color;
begin
TIC.Init_Pair (TIC.Color_Pair (1), TIC.White, TIC.Black);
TIC.Init_Pair (TIC.Color_Pair (2), TIC.Green, TIC.Black);
TIC.Init_Pair (TIC.Color_Pair (3), TIC.Red, TIC.Black);
TIC.Init_Pair (TIC.Color_Pair (4), TIC.Yellow, TIC.Black);
TIC.Init_Pair (TIC.Color_Pair (5), TIC.Black, TIC.Black);
TIC.Init_Pair (TIC.Color_Pair (6), TIC.Cyan, TIC.Black);
TIC.Init_Pair (TIC.Color_Pair (7), TIC.Blue, TIC.Black);
TIC.Init_Pair (TIC.Color_Pair (8), TIC.Magenta, TIC.Black);
TIC.Init_Pair (TIC.Color_Pair (9), TIC.Blue, TIC.White);
exception
when TIC.Curses_Exception => return False;
end;
c_standard := TIC.Color_Pair (1);
c_success := TIC.Color_Pair (2);
c_failure := TIC.Color_Pair (3);
c_ignored := TIC.Color_Pair (4);
c_skipped := TIC.Color_Pair (5);
c_sumlabel := TIC.Color_Pair (6);
c_dashes := TIC.Color_Pair (7);
c_elapsed := TIC.Color_Pair (4);
c_tableheader := TIC.Color_Pair (1);
c_origin := TIC.Color_Pair (6);
c_bldphase := TIC.Color_Pair (4);
c_shutdown := TIC.Color_Pair (1);
c_advisory := TIC.Color_Pair (4);
c_slave (1).palette := TIC.Color_Pair (1); -- white / Black
c_slave (1).attribute := bright;
c_slave (2).palette := TIC.Color_Pair (2); -- light green / Black
c_slave (2).attribute := bright;
c_slave (3).palette := TIC.Color_Pair (4); -- yellow / Black
c_slave (3).attribute := bright;
c_slave (4).palette := TIC.Color_Pair (8); -- light magenta / Black
c_slave (4).attribute := bright;
c_slave (5).palette := TIC.Color_Pair (3); -- light red / Black
c_slave (5).attribute := bright;
c_slave (6).palette := TIC.Color_Pair (7); -- light blue / Black
c_slave (6).attribute := bright;
c_slave (7).palette := TIC.Color_Pair (6); -- light cyan / Black
c_slave (7).attribute := bright;
c_slave (8).palette := TIC.Color_Pair (5); -- dark grey / Black
c_slave (8).attribute := bright;
c_slave (9).palette := TIC.Color_Pair (1); -- light grey / Black
c_slave (9).attribute := normal;
c_slave (10).palette := TIC.Color_Pair (2); -- light green / Black
c_slave (10).attribute := normal;
c_slave (11).palette := TIC.Color_Pair (4); -- brown / Black
c_slave (11).attribute := normal;
c_slave (12).palette := TIC.Color_Pair (8); -- dark magenta / Black
c_slave (12).attribute := normal;
c_slave (13).palette := TIC.Color_Pair (3); -- dark red / Black
c_slave (13).attribute := normal;
c_slave (14).palette := TIC.Color_Pair (7); -- dark blue / Black
c_slave (14).attribute := normal;
c_slave (15).palette := TIC.Color_Pair (6); -- dark cyan / Black
c_slave (15).attribute := normal;
c_slave (16).palette := TIC.Color_Pair (9); -- white / dark blue
c_slave (16).attribute := normal;
for bld in builders (17) .. builders (32) loop
c_slave (bld) := c_slave (bld - 16);
c_slave (bld).attribute.Under_Line := True;
end loop;
for bld in builders (33) .. builders (64) loop
c_slave (bld) := c_slave (bld - 32);
end loop;
return True;
end establish_colors;
------------------------------------------------------------------------
-- zone_window
------------------------------------------------------------------------
function zone_window (zone : zones) return TIC.Window is
begin
case zone is
when builder => return zone_builders;
when summary => return zone_summary;
when action => return zone_actions;
end case;
end zone_window;
------------------------------------------------------------------------
-- Scrawl
------------------------------------------------------------------------
procedure Scrawl (zone : zones;
information : TIC.Attributed_String;
at_line : TIC.Line_Position;
at_column : TIC.Column_Position := 0) is
begin
TIC.Add (Win => zone_window (zone),
Line => at_line,
Column => at_column,
Str => information,
Len => information'Length);
exception
when TIC.Curses_Exception => null;
end Scrawl;
------------------------------------------------------------------------
-- Return_To_Text_Mode
------------------------------------------------------------------------
procedure Return_To_Text_Mode is
begin
TIC.End_Windows;
exception
when TIC.Curses_Exception => null;
end Return_To_Text_Mode;
------------------------------------------------------------------------
-- Refresh_Zone
------------------------------------------------------------------------
procedure Refresh_Zone (zone : zones) is
begin
TIC.Refresh (Win => zone_window (zone));
exception
when TIC.Curses_Exception => null;
end Refresh_Zone;
------------------------------------------------------------------------
-- Start_Curses_Mode
------------------------------------------------------------------------
function Start_Curses_Mode return Boolean is
begin
TIC.Init_Screen;
return True;
exception
when TIC.Curses_Exception => return False;
end Start_Curses_Mode;
------------------------------------------------------------------------
-- blank_line
------------------------------------------------------------------------
function blank_line return appline
is
space : TIC.Attributed_Character := (Attr => TIC.Normal_Video,
Color => c_standard,
Ch => ' ');
product : appline := (others => space);
begin
return product;
end blank_line;
------------------------------------------------------------------------
-- custom_message
------------------------------------------------------------------------
function custom_message (message : String;
attribute : TIC.Character_Attribute_Set;
pen_color : TIC.Color_Pair) return TIC.Attributed_String
is
product : TIC.Attributed_String (1 .. message'Length);
pindex : Positive := 1;
begin
for index in message'Range loop
product (pindex) := (Attr => attribute,
Color => pen_color,
Ch => message (index));
pindex := pindex + 1;
end loop;
return product;
end custom_message;
------------------------------------------------------------------------
-- shutdown_message
------------------------------------------------------------------------
function shutdown_message return appline
is
data : constant String := " Graceful shutdown in progress, " &
"so no new tasks will be started. ";
product : appline := custom_message (message => data,
attribute => bright,
pen_color => c_advisory);
begin
return product;
end shutdown_message;
------------------------------------------------------------------------
-- emphasis
------------------------------------------------------------------------
function emphasis (dimmed : Boolean) return TIC.Character_Attribute_Set is
begin
if dimmed then
return normal;
else
return bright;
end if;
end emphasis;
------------------------------------------------------------------------
-- fmtpc
------------------------------------------------------------------------
function fmtpc (f : Float; percent : Boolean) return fivelong
is
type loadtype is delta 0.01 digits 4;
result : fivelong := (others => ' ');
raw1 : constant loadtype := loadtype (f);
raw2 : constant String := raw1'Img;
raw3 : constant String := raw2 (2 .. raw2'Last);
rlen : constant Natural := raw3'Length;
start : constant Natural := 6 - rlen;
begin
result (start .. 5) := raw3;
if percent then
result (5) := '%';
end if;
return result;
end fmtpc;
------------------------------------------------------------------------
-- fmtload
------------------------------------------------------------------------
function fmtload (f : Float) return fivelong
is
type loadtype is delta 0.01 digits 4;
result : fivelong := (others => ' ');
begin
if f < 100.0 then
return fmtpc (f, False);
elsif f < 1000.0 then
declare
type loadtype is delta 0.1 digits 4;
raw1 : constant loadtype := loadtype (f);
begin
return JT.trim (raw1'Img);
end;
elsif f < 10000.0 then
declare
raw1 : constant Integer := Integer (f);
begin
-- preceded by space, 1000.0 .. 9999.99, should be 5 chars
return raw1'Img;
end;
elsif f < 100000.0 then
declare
raw1 : constant Integer := Integer (f);
begin
-- 100000.0 .. 99999.9
return JT.trim (raw1'Img);
end;
else
return "100k+";
end if;
exception
when others =>
return "ERROR";
end fmtload;
end Display;
|
with Ada.Strings.Fixed;
package Latex_Writer.Picture is
subtype Latex_Slope is Integer range -6 .. 6;
type Picture_Length is delta 0.01 range -10_000.0 .. 10_000.0;
function "*" (X : Integer; Y : Picture_Length) return Picture_Length
is (Picture_Length (X) * Y);
function Pos (X, Y : Picture_Length) return String;
function Put (X, Y : Picture_Length; What : String) return String
is ("\put" & Pos (X, Y) & "{" & What & "}");
function Line (Slope_X, Slope_Y : Latex_Slope; Length : Picture_Length) return String;
function Arrow (Slope_X, Slope_Y : Latex_Slope; Length : Picture_Length) return String;
function Hline (X, Y : Picture_Length; Length : Picture_Length) return String
is (Put (X, Y, Line (1, 0, Length)));
function Hline (Length : Picture_Length) return String
is (Line (1, 0, Length));
type Vertical_Direction is (Up, Down);
function VLine (X, Y : Picture_Length;
Length : Picture_Length;
Direction : Vertical_Direction := Up) return String
is (Put (X, Y, Line (Slope_X => 0,
Slope_Y => (case Direction is
when Up => 1,
when Down => -1),
Length => Length)));
function VLine (Length : Picture_Length;
Direction : Vertical_Direction := Up) return String
is (Line (Slope_X => 0,
Slope_Y => (case Direction is
when Up => 1,
when Down => -1),
Length => Length));
function Text (X, Y : Picture_Length; Content : String) return String;
procedure Within_Picture
(Output : File_Access;
Width : Picture_Length;
Heigth : Picture_Length;
Callback : access procedure (Output : File_Access));
private
function Chop (X : String) return String
is (Ada.Strings.Fixed.Trim (X, Ada.Strings.Both));
function Image (X : Integer) return String
is (Chop (Integer'Image (X)));
function Image (X : Picture_Length) return String
is (Chop (Picture_Length'Image (X)));
function Pos (X, Y : Picture_Length) return String
is ("(" & Image (X) & "," & Image (Y) & ")");
function Slope (X, Y : Latex_Slope) return String
is ("(" & Image (X) & "," & Image (Y) & ")");
function Line (Slope_X, Slope_Y : Latex_Slope; Length : Picture_Length) return String
is ("\line" & Slope (Slope_X, Slope_Y) & "{" & Chop (Picture_Length'Image (Length)) & "}");
function Arrow (Slope_X, Slope_Y : Latex_Slope; Length : Picture_Length) return String
is ("\vector" & Slope (Slope_X, Slope_Y) & "{" & Chop (Picture_Length'Image (Length)) & "}");
function Text (X, Y : Picture_Length; Content : String) return String
is (Put (X, Y, "{" & Content & "}"));
end Latex_Writer.Picture;
|
-----------------------------------------------------------------------
-- ADO Postgresql Database -- Postgresql Database connections
-- Copyright (C) 2018, 2019 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.Task_Identification;
with Interfaces.C.Strings;
with Util.Log;
with Util.Log.Loggers;
with Util.Processes.Tools;
with ADO.Statements.Postgresql;
with ADO.Schemas.Postgresql;
with ADO.Sessions;
with ADO.C;
package body ADO.Connections.Postgresql is
use ADO.Statements.Postgresql;
use Interfaces.C;
use type PQ.PGconn_Access;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Postgresql");
Driver_Name : aliased constant String := "postgresql";
Driver : aliased Postgresql_Driver;
-- ------------------------------
-- Get the database driver which manages this connection.
-- ------------------------------
overriding
function Get_Driver (Database : in Database_Connection)
return ADO.Connections.Driver_Access is
pragma Unreferenced (Database);
begin
return Driver'Access;
end Get_Driver;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Query => Query);
end Create_Statement;
-- ------------------------------
-- Create a delete statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an insert statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an update statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Database_Connection) is
begin
Database.Execute ("BEGIN");
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Database_Connection) is
begin
Database.Execute ("COMMIT");
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Database_Connection) is
begin
Database.Execute ("ROLLBACK");
end Rollback;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is
begin
ADO.Schemas.Postgresql.Load_Schema (Database, Schema,
Ada.Strings.Unbounded.To_String (Database.Name));
end Load_Schema;
-- ------------------------------
-- Execute a simple SQL statement
-- ------------------------------
procedure Execute (Database : in out Database_Connection;
SQL : in Query_String) is
SQL_Stat : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL);
Result : PQ.PGresult_Access;
begin
Log.Debug ("Execute SQL: {0}", SQL);
if Database.Server = PQ.Null_PGconn then
Log.Error ("Database connection is not open");
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
Result := PQ.PQexec (Database.Server, ADO.C.To_C (SQL_Stat));
Log.Debug ("Query result: {0}", PQ.ExecStatusType'Image (PQ.PQresultStatus (Result)));
PQ.PQclear (Result);
end Execute;
-- ------------------------------
-- Closes the database connection
-- ------------------------------
overriding
procedure Close (Database : in out Database_Connection) is
begin
if Database.Server /= PQ.Null_PGconn then
Log.Info ("Closing connection {0}/{1}", Database.Name, Database.Ident);
PQ.PQfinish (Database.Server);
Database.Server := PQ.Null_PGconn;
end if;
end Close;
-- ------------------------------
-- Releases the Postgresql connection if it is open
-- ------------------------------
overriding
procedure Finalize (Database : in out Database_Connection) is
begin
Log.Debug ("Release connection {0}/{1}", Database.Name, Database.Ident);
Database.Close;
end Finalize;
-- ------------------------------
-- Initialize the database connection manager.
--
-- Postgresql://localhost:3306/db
--
-- ------------------------------
procedure Create_Connection (D : in out Postgresql_Driver;
Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
use type PQ.ConnStatusType;
URI : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Get_URI);
Connection : PQ.PGconn_Access;
begin
Log.Info ("Task {0} connecting to {1}:{2}",
Ada.Task_Identification.Image (Ada.Task_Identification.Current_Task),
Config.Get_Server, Config.Get_Database);
if Config.Get_Property ("password") = "" then
Log.Debug ("Postgresql connection with user={0}", Config.Get_Property ("user"));
else
Log.Debug ("Postgresql connection with user={0} password=XXXXXXXX",
Config.Get_Property ("user"));
end if;
Connection := PQ.PQconnectdb (ADO.C.To_C (URI));
if Connection = PQ.Null_PGconn then
declare
Message : constant String := "memory allocation error";
begin
Log.Error ("Cannot connect to '{0}': {1}", Config.Get_Log_URI, Message);
raise ADO.Configs.Connection_Error with
"Cannot connect to Postgresql server: " & Message;
end;
end if;
if PQ.PQstatus (Connection) /= PQ.CONNECTION_OK then
declare
Message : constant String := Strings.Value (PQ.PQerrorMessage (Connection));
begin
Log.Error ("Cannot connect to '{0}': {1}", Config.Get_Log_URI, Message);
raise ADO.Configs.Connection_Error with
"Cannot connect to Postgresql server: " & Message;
end;
end if;
D.Id := D.Id + 1;
declare
Ident : constant String := Util.Strings.Image (D.Id);
Database : constant Database_Connection_Access := new Database_Connection;
begin
Database.Ident (1 .. Ident'Length) := Ident;
Database.Server := Connection;
Database.Name := To_Unbounded_String (Config.Get_Database);
Result := Ref.Create (Database.all'Access);
end;
end Create_Connection;
-- ------------------------------
-- Create the database and initialize it with the schema SQL file.
-- The `Admin` parameter describes the database connection with administrator access.
-- The `Config` parameter describes the target database connection.
-- ------------------------------
overriding
procedure Create_Database (D : in out Postgresql_Driver;
Admin : in Configs.Configuration'Class;
Config : in Configs.Configuration'Class;
Schema_Path : in String;
Messages : out Util.Strings.Vectors.Vector) is
pragma Unreferenced (D, Admin);
Status : Integer;
Command : constant String :=
"psql -q '" & Config.Get_URI & "' --file=" & Schema_Path;
begin
Util.Processes.Tools.Execute (Command, Messages, Status);
if Status = 0 then
Log.Info ("Database schema created successfully.");
elsif Status = 255 then
Log.Error ("Command not found: {0}", Command);
else
Log.Error ("Command {0} failed with exit code {1}", Command,
Util.Strings.Image (Status));
end if;
end Create_Database;
-- ------------------------------
-- Initialize the Postgresql driver.
-- ------------------------------
procedure Initialize is
use type Util.Strings.Name_Access;
begin
Log.Debug ("Initializing Postgresql driver");
if Driver.Name = null then
Driver.Name := Driver_Name'Access;
Register (Driver'Access);
end if;
end Initialize;
-- ------------------------------
-- Deletes the Postgresql driver.
-- ------------------------------
overriding
procedure Finalize (D : in out Postgresql_Driver) is
pragma Unreferenced (D);
begin
Log.Debug ("Deleting the Postgresql driver");
end Finalize;
end ADO.Connections.Postgresql;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2018 onox <denkpadje@gmail.com>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Real_Time;
with Ada.Text_IO;
with GL.Barriers;
with GL.Compute;
with GL.Types.Compute;
with Orka.Contexts.AWT;
with Orka.Debug;
with Orka.Rendering.Buffers;
with Orka.Rendering.Programs.Modules;
with Orka.Rendering.Programs.Uniforms;
with Orka.Resources.Locations.Directories;
with Orka.Types;
procedure Orka_10_Compute is
Context : constant Orka.Contexts.Context'Class := Orka.Contexts.AWT.Create_Context
(Version => (4, 2), Flags => (Debug => True, others => False));
----------------------------------------------------------------------
use Ada.Text_IO;
use type GL.Types.Int;
use GL.Types;
Numbers : constant Int_Array
:= (10, 1, 8, -1, 0, -2, 3, 5, -2, -3, 2, 7, 0, 11, 0, 2);
begin
Orka.Debug.Set_Log_Messages (Enable => True);
declare
use Orka.Rendering.Buffers;
use Orka.Rendering.Programs;
use Orka.Resources;
Location_Shaders : constant Locations.Location_Ptr
:= Locations.Directories.Create_Location ("data/shaders");
Program_1 : Program := Create_Program (Modules.Create_Module
(Location_Shaders, CS => "test-10-module-1.comp"));
Uniform_1 : constant Uniforms.Uniform := Program_1.Uniform ("maxNumbers");
Max_Work_Groups, Local_Size : Size;
begin
Program_1.Use_Program;
-- Print some limits about compute shaders
Put_Line ("Maximum shared size:" &
Size'Image (GL.Compute.Max_Compute_Shared_Memory_Size));
Put_Line ("Maximum invocations:" &
Size'Image (GL.Compute.Max_Compute_Work_Group_Invocations));
declare
R : GL.Types.Compute.Dimension_Size_Array;
use all type Orka.Index_Homogeneous;
begin
R := GL.Compute.Max_Compute_Work_Group_Count;
Put_Line ("Maximum count:" & R (X)'Image & R (Y)'Image & R (Z)'Image);
Max_Work_Groups := R (X);
R := GL.Compute.Max_Compute_Work_Group_Size;
Put_Line ("Maximum size: " & R (X)'Image & R (Y)'Image & R (Z)'Image);
R := Program_1.Compute_Work_Group_Size;
Put_Line ("Local size: " & R (X)'Image & R (Y)'Image & R (Z)'Image);
Local_Size := R (X);
end;
declare
use all type Orka.Types.Element_Type;
use type Ada.Real_Time.Time;
Factor : constant Size := (Max_Work_Groups * Local_Size) / Numbers'Length;
Buffer_1 : constant Buffer := Create_Buffer
(Flags => (Dynamic_Storage => True, others => False),
Kind => Int_Type,
Length => Numbers'Length * Natural (Factor));
A, B : Ada.Real_Time.Time;
procedure Memory_Barrier is
begin
GL.Barriers.Memory_Barrier ((Shader_Storage | Buffer_Update => True, others => False));
end Memory_Barrier;
begin
Put_Line ("Factor:" & Factor'Image);
-- Upload numbers to SSBO
for Index in 0 .. Factor - 1 loop
Buffer_1.Set_Data (Data => Numbers, Offset => Numbers'Length * Natural (Index));
end loop;
Buffer_1.Bind (Shader_Storage, 0);
A := Ada.Real_Time.Clock;
declare
Count : constant Size := Size (Buffer_1.Length);
Ceiling : Size := Count + (Count rem Local_Size);
Groups : Size := Ceiling / Local_Size;
begin
Put_Line ("Numbers:" & Count'Image);
Put_Line ("Groups: " & Groups'Image);
pragma Assert (Groups <= Max_Work_Groups);
-- The uniform is used to set how many numbers need to be
-- summed. If a work group has more threads than there are
-- numbers to be summed (happens in the last iteration),
-- then these threads will use the number 0 in the shader.
Uniform_1.Set_UInt (UInt (Count));
while Groups > 0 loop
-- Add an SSBO barrier for the next iteration
-- and then dispatch the compute shader
Memory_Barrier;
GL.Compute.Dispatch_Compute (X => UInt (Groups));
Uniform_1.Set_UInt (UInt (Groups));
Ceiling := Groups + (Groups rem Local_Size);
Groups := Ceiling / Local_Size;
end loop;
-- Perform last iteration. Work groups in X dimension needs
-- to be at least one.
Memory_Barrier;
GL.Compute.Dispatch_Compute (X => UInt (Size'Max (1, Groups)));
end;
Memory_Barrier;
declare
Output : Int_Array (1 .. 2) := (others => 0);
begin
Buffer_1.Get_Data (Output);
Put_Line ("Expected Sum:" & Size'Image (Factor * 41));
Put_Line ("Computed sum:" & Output (Output'First)'Image);
-- Print the number of shader invocations that execute in
-- lockstep. This requires the extension ARB_shader_ballot
-- in the shader.
Put_Line ("Sub-group size:" & Output (Output'Last)'Image);
end;
B := Ada.Real_Time.Clock;
Put_Line (Duration'Image (1e3 * Ada.Real_Time.To_Duration (B - A)) & " ms");
end;
end;
end Orka_10_Compute;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2017 onox <denkpadje@gmail.com>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
private with Orka.Rendering.Buffers.Pointers;
package Orka.Rendering.Buffers.Mapped is
pragma Preelaborate;
type IO_Mode is (Read, Write);
type Mapped_Buffer
(Kind : Orka.Types.Element_Type;
Mode : IO_Mode) is abstract new Bindable_Buffer with private;
overriding
function Length (Object : Mapped_Buffer) return Natural;
-- Number of elements in the buffer
-----------------------------------------------------------------------------
overriding
procedure Bind
(Object : Mapped_Buffer;
Target : Indexed_Buffer_Target;
Index : Natural);
-- Bind the buffer object to the binding point at the given index of
-- the target
overriding
procedure Bind (Object : Mapped_Buffer; Target : Buffer_Target);
-- Bind the buffer object to the target
-----------------------------------------------------------------------------
procedure Write_Data
(Object : Mapped_Buffer;
Data : UByte_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length;
procedure Write_Data
(Object : Mapped_Buffer;
Data : UShort_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length;
procedure Write_Data
(Object : Mapped_Buffer;
Data : UInt_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length;
procedure Write_Data
(Object : Mapped_Buffer;
Data : Byte_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length;
procedure Write_Data
(Object : Mapped_Buffer;
Data : Short_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length;
procedure Write_Data
(Object : Mapped_Buffer;
Data : Int_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length;
procedure Write_Data
(Object : Mapped_Buffer;
Data : Half_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length;
procedure Write_Data
(Object : Mapped_Buffer;
Data : Single_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length;
procedure Write_Data
(Object : Mapped_Buffer;
Data : Double_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length;
-----------------------------------------------------------------------------
procedure Write_Data
(Object : Mapped_Buffer;
Data : Orka.Types.Singles.Vector4_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length;
procedure Write_Data
(Object : Mapped_Buffer;
Data : Orka.Types.Singles.Matrix4_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length;
procedure Write_Data
(Object : Mapped_Buffer;
Data : Orka.Types.Doubles.Vector4_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length;
procedure Write_Data
(Object : Mapped_Buffer;
Data : Orka.Types.Doubles.Matrix4_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length;
procedure Write_Data
(Object : Mapped_Buffer;
Data : Indirect.Arrays_Indirect_Command_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length;
procedure Write_Data
(Object : Mapped_Buffer;
Data : Indirect.Elements_Indirect_Command_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length;
procedure Write_Data
(Object : Mapped_Buffer;
Data : Indirect.Dispatch_Indirect_Command_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length;
-----------------------------------------------------------------------------
procedure Write_Data
(Object : Mapped_Buffer;
Value : Orka.Types.Singles.Vector4;
Offset : Natural)
with Pre => Object.Mode = Write and Offset < Object.Length;
procedure Write_Data
(Object : Mapped_Buffer;
Value : Orka.Types.Singles.Matrix4;
Offset : Natural)
with Pre => Object.Mode = Write and Offset < Object.Length;
procedure Write_Data
(Object : Mapped_Buffer;
Value : Orka.Types.Doubles.Vector4;
Offset : Natural)
with Pre => Object.Mode = Write and Offset < Object.Length;
procedure Write_Data
(Object : Mapped_Buffer;
Value : Orka.Types.Doubles.Matrix4;
Offset : Natural)
with Pre => Object.Mode = Write and Offset < Object.Length;
procedure Write_Data
(Object : Mapped_Buffer;
Value : Indirect.Arrays_Indirect_Command;
Offset : Natural)
with Pre => Object.Mode = Write and Offset < Object.Length;
procedure Write_Data
(Object : Mapped_Buffer;
Value : Indirect.Elements_Indirect_Command;
Offset : Natural)
with Pre => Object.Mode = Write and Offset < Object.Length;
procedure Write_Data
(Object : Mapped_Buffer;
Value : Indirect.Dispatch_Indirect_Command;
Offset : Natural)
with Pre => Object.Mode = Write and Offset < Object.Length;
-----------------------------------------------------------------------------
procedure Read_Data
(Object : Mapped_Buffer;
Data : out UByte_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Read and Offset + Data'Length <= Object.Length;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out UShort_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Read and Offset + Data'Length <= Object.Length;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out UInt_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Read and Offset + Data'Length <= Object.Length;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Byte_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Read and Offset + Data'Length <= Object.Length;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Short_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Read and Offset + Data'Length <= Object.Length;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Int_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Read and Offset + Data'Length <= Object.Length;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Half_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Read and Offset + Data'Length <= Object.Length;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Single_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Read and Offset + Data'Length <= Object.Length;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Double_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Read and Offset + Data'Length <= Object.Length;
-----------------------------------------------------------------------------
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Orka.Types.Singles.Vector4_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Read and Offset + Data'Length <= Object.Length;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Orka.Types.Singles.Matrix4_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Read and Offset + Data'Length <= Object.Length;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Orka.Types.Doubles.Vector4_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Read and Offset + Data'Length <= Object.Length;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Orka.Types.Doubles.Matrix4_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Read and Offset + Data'Length <= Object.Length;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Indirect.Arrays_Indirect_Command_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Read and Offset + Data'Length <= Object.Length;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Indirect.Elements_Indirect_Command_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Read and Offset + Data'Length <= Object.Length;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Indirect.Dispatch_Indirect_Command_Array;
Offset : Natural := 0)
with Pre => Object.Mode = Read and Offset + Data'Length <= Object.Length;
private
use Orka.Types;
type Mapped_Buffer
(Kind : Orka.Types.Element_Type; Mode : IO_Mode)
is new Bindable_Buffer with record
Buffer : Buffers.Buffer (Kind);
Offset : Natural;
-- Offset in number of elements to the start of the buffer
--
-- Initially zero and incremented by Length whenever the index is
-- advanced if the buffer is mapped persistent.
case Kind is
-- Numeric types
when UByte_Type =>
Pointer_UByte : Pointers.UByte.Pointer;
when UShort_Type =>
Pointer_UShort : Pointers.UShort.Pointer;
when UInt_Type =>
Pointer_UInt : Pointers.UInt.Pointer;
when Byte_Type =>
Pointer_Byte : Pointers.Byte.Pointer;
when Short_Type =>
Pointer_Short : Pointers.Short.Pointer;
when Int_Type =>
Pointer_Int : Pointers.Int.Pointer;
when Half_Type =>
Pointer_Half : Pointers.Half.Pointer;
when Single_Type =>
Pointer_Single : Pointers.Single.Pointer;
when Double_Type =>
Pointer_Double : Pointers.Double.Pointer;
-- Composite types
when Single_Vector_Type =>
Pointer_SV : Pointers.Single_Vector4.Pointer;
when Double_Vector_Type =>
Pointer_DV : Pointers.Double_Vector4.Pointer;
when Single_Matrix_Type =>
Pointer_SM : Pointers.Single_Matrix4.Pointer;
when Double_Matrix_Type =>
Pointer_DM : Pointers.Double_Matrix4.Pointer;
when Arrays_Command_Type =>
Pointer_AC : Pointers.Arrays_Command.Pointer;
when Elements_Command_Type =>
Pointer_EC : Pointers.Elements_Command.Pointer;
when Dispatch_Command_Type =>
Pointer_DC : Pointers.Dispatch_Command.Pointer;
end case;
end record;
procedure Map
(Object : in out Mapped_Buffer;
Length : Size;
Flags : GL.Objects.Buffers.Access_Bits);
end Orka.Rendering.Buffers.Mapped;
|
package Max2 with SPARK_Mode is
type Vector is array (Integer range <>) of Positive;
function FindMax2 (V : Vector) return Integer
with
Pre => V'First < Integer'Last and V'Length > 0,
Post => FindMax2'Result >= 0 and
(FindMax2'Result = 0 or
(for some I in V'Range => FindMax2'Result = V(I))) and
(if FindMax2'Result /=0 then
(for some I in V'Range => V(I) > FindMax2'Result)) and
(if FindMax2'Result = 0 then
(for all I in V'Range =>
(for all J in V'Range => V(I) = V(J)))
else
(for all I in V'Range =>
(if V(I) > FindMax2'Result then
(for all J in V'Range => V(J) <= V(I)))));
end Max2;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- E X P _ A T A G --
-- --
-- S p e c --
-- --
-- Copyright (C) 2006-2020, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING3. If not, go to --
-- http://www.gnu.org/licenses for a complete copy of the license. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package contains routines involved in the frontend expansion of
-- subprograms of package Ada.Tags
with Types; use Types;
with Uintp; use Uintp;
package Exp_Atag is
-- Note: In all the subprograms of this package formal 'Loc' is the source
-- location used in constructing the corresponding nodes.
procedure Build_Common_Dispatching_Select_Statements
(Typ : Entity_Id;
Stmts : List_Id);
-- Ada 2005 (AI-345): Build statements that are common to the expansion of
-- timed, asynchronous, and conditional select and append them to Stmts.
-- Typ is the tagged type used for dispatching calls.
function Build_Get_Access_Level
(Loc : Source_Ptr;
Tag_Node : Node_Id) return Node_Id;
-- Build code that retrieves the accessibility level of the tagged type.
--
-- Generates: TSD (Tag).Access_Level
function Build_Get_Alignment
(Loc : Source_Ptr;
Tag_Node : Node_Id) return Node_Id;
-- Build code that retrieves the alignment of the tagged type.
-- Generates: TSD (Tag).Alignment
procedure Build_Get_Predefined_Prim_Op_Address
(Loc : Source_Ptr;
Position : Uint;
Tag_Node : in out Node_Id;
New_Node : out Node_Id);
-- Given a pointer to a dispatch table (T) and a position in the DT, build
-- code that gets the address of the predefined virtual function stored in
-- it (used for dispatching calls). Tag_Node is relocated.
--
-- Generates: Predefined_DT (Tag).D (Position);
procedure Build_Get_Prim_Op_Address
(Loc : Source_Ptr;
Typ : Entity_Id;
Position : Uint;
Tag_Node : in out Node_Id;
New_Node : out Node_Id);
-- Build code that retrieves the address of the virtual function stored in
-- a given position of the dispatch table (used for dispatching calls).
-- Tag_Node is relocated.
--
-- Generates: To_Tag (Tag).D (Position);
function Build_Get_Transportable
(Loc : Source_Ptr;
Tag_Node : Node_Id) return Node_Id;
-- Build code that retrieves the value of the Transportable flag for
-- the given Tag.
--
-- Generates: TSD (Tag).Transportable;
function Build_Inherit_CPP_Prims (Typ : Entity_Id) return List_Id;
-- Build code that copies from Typ's parent the dispatch table slots of
-- inherited primitives and updates slots of overridden primitives. The
-- generated code handles primary and secondary dispatch tables of Typ.
function Build_Inherit_Predefined_Prims
(Loc : Source_Ptr;
Old_Tag_Node : Node_Id;
New_Tag_Node : Node_Id;
Num_Predef_Prims : Nat) return Node_Id;
-- Build code that inherits the predefined primitives of the parent.
--
-- Generates: Predefined_DT (New_T).D (All_Predefined_Prims) :=
-- Predefined_DT (Old_T).D (All_Predefined_Prims);
--
-- Required to build non-library level dispatch tables. Also required
-- when compiling without static dispatch tables support.
function Build_Inherit_Prims
(Loc : Source_Ptr;
Typ : Entity_Id;
Old_Tag_Node : Node_Id;
New_Tag_Node : Node_Id;
Num_Prims : Nat) return Node_Id;
-- Build code that inherits Num_Prims user-defined primitives from the
-- dispatch table of the parent type of tagged type Typ. It is used to
-- copy the dispatch table of the parent in the following cases:
-- a) case of derivations of CPP_Class types
-- b) tagged types whose dispatch table is not statically allocated
--
-- Generates:
-- New_Tag.Prims_Ptr (1 .. Num_Prims) :=
-- Old_Tag.Prims_Ptr (1 .. Num_Prims);
function Build_Offset_To_Top
(Loc : Source_Ptr;
This_Node : Node_Id) return Node_Id;
-- Build code that references the Offset_To_Top component of the primary
-- or secondary dispatch table associated with This_Node. This subprogram
-- provides a subset of the functionality provided by the function
-- Offset_To_Top of package Ada.Tags, and is only called by the frontend
-- when such routine is not available in a configurable runtime.
--
-- Generates:
-- Offset_To_Top_Ptr
-- (Address!(Tag_Ptr!(This).all) - Offset_To_Top_Offset).all
function Build_Set_Predefined_Prim_Op_Address
(Loc : Source_Ptr;
Tag_Node : Node_Id;
Position : Uint;
Address_Node : Node_Id) return Node_Id;
-- Build code that saves the address of a virtual function in a given
-- Position of the portion of the dispatch table associated with the
-- predefined primitives of Tag. Called from Exp_Disp.Fill_DT_Entry
-- and Exp_Disp.Fill_Secondary_DT_Entry. It is used for:
-- 1) Filling the dispatch table of CPP_Class types.
-- 2) Late overriding (see Check_Dispatching_Operation).
--
-- Generates: Predefined_DT (Tag).D (Position) := Value
function Build_Set_Prim_Op_Address
(Loc : Source_Ptr;
Typ : Entity_Id;
Tag_Node : Node_Id;
Position : Uint;
Address_Node : Node_Id) return Node_Id;
-- Build code that saves the address of a virtual function in a given
-- Position of the dispatch table associated with the Tag. Called from
-- Exp_Disp.Fill_DT_Entry and Exp_Disp.Fill_Secondary_DT_Entry. Used for:
-- 1) Filling the dispatch table of CPP_Class types.
-- 2) Late overriding (see Check_Dispatching_Operation).
--
-- Generates: Tag.D (Position) := Value
function Build_Set_Size_Function
(Loc : Source_Ptr;
Tag_Node : Node_Id;
Size_Func : Entity_Id) return Node_Id;
-- Build code that saves in the TSD the address of the function
-- calculating _size of the object.
function Build_Set_Static_Offset_To_Top
(Loc : Source_Ptr;
Iface_Tag : Node_Id;
Offset_Value : Node_Id) return Node_Id;
-- Build code that initialize the Offset_To_Top component of the
-- secondary dispatch table referenced by Iface_Tag.
--
-- Generates:
-- Offset_To_Top_Ptr
-- (Address!(Tag_Ptr!(This).all) - Offset_To_Top_Offset).all
-- := Offset_Value
end Exp_Atag;
|
pragma License (Unrestricted);
-- extended unit
generic
type Index_Type is range <>;
type Element_Type is private;
type Array_Type is array (Index_Type range <>) of Element_Type;
-- diff (Array_Access)
-- diff (Free)
package Ada.Containers.Generic_Array_Types is
-- Ada.Containers.Vectors-like utilities for array types.
pragma Preelaborate;
subtype Extended_Index is
Index_Type'Base range
Index_Type'Base'Pred (Index_Type'First) ..
Index_Type'Last;
function Length (Container : Array_Type) return Count_Type;
-- diff (Set_Length)
--
--
-- diff (Clear)
--
procedure Assign (Target : in out Array_Type; Source : Array_Type);
procedure Move (
Target : in out Array_Type;
Source : in out Array_Type);
-- diff (Insert)
--
--
--
-- diff (Insert)
--
--
--
-- diff (Insert)
--
--
--
--
-- diff (Insert)
--
--
--
-- diff (Prepend)
--
--
-- diff (Prepend)
--
--
-- diff (Prepend)
--
--
--
-- diff (Prepend)
--
--
-- diff (Append)
--
--
-- diff (Append)
--
--
-- diff (Append)
--
--
--
-- diff (Append)
--
--
-- diff (Delete)
--
--
--
-- diff (Delete_First)
--
--
-- diff (Delete_Last)
--
--
procedure Swap (Container : in out Array_Type; I, J : Index_Type);
function First_Index (Container : Array_Type) return Index_Type;
function Last_Index (Container : Array_Type) return Extended_Index;
generic
with procedure Swap (
Container : in out Array_Type;
I, J : Index_Type) is Generic_Array_Types.Swap;
package Generic_Reversing is
procedure Reverse_Elements (Container : in out Array_Type);
procedure Reverse_Rotate_Elements (
Container : in out Array_Type;
Before : Extended_Index);
procedure Juggling_Rotate_Elements (
Container : in out Array_Type;
Before : Extended_Index);
procedure Rotate_Elements (
Container : in out Array_Type;
Before : Extended_Index)
renames Juggling_Rotate_Elements;
end Generic_Reversing;
generic
with function "<" (Left, Right : Element_Type) return Boolean is <>;
with procedure Swap (
Container : in out Array_Type;
I, J : Index_Type) is Generic_Array_Types.Swap;
package Generic_Sorting is
function Is_Sorted (Container : Array_Type) return Boolean;
procedure Insertion_Sort (Container : in out Array_Type);
procedure Merge_Sort (Container : in out Array_Type);
procedure Sort (Container : in out Array_Type)
renames Merge_Sort;
-- diff (Merge)
--
--
end Generic_Sorting;
end Ada.Containers.Generic_Array_Types;
|
package Plop is
type A is interface;
function Img (This : A) return String is abstract;
type B is new A with null record;
function Img (This : B) return String is ("B");
type C is new A with null record;
function Img (This : C) return String is ("C");
procedure Print (This : A'Class);
end Plop;
|
--------------------------------------------------------------------------------
-- Copyright (c) 2013, Felix Krause <contact@flyx.org>
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--------------------------------------------------------------------------------
with Ada.Text_IO;
with Interfaces.C.Strings;
with CL.API;
with CL.Enumerations;
with CL.Helpers;
package body CL.Programs is
-----------------------------------------------------------------------------
-- Helpers
-----------------------------------------------------------------------------
procedure Build_Callback_Dispatcher (Subject : System.Address;
Callback : Build_Callback);
pragma Convention (C, Build_Callback_Dispatcher);
procedure Build_Callback_Dispatcher (Subject : System.Address;
Callback : Build_Callback) is
begin
Callback (Program'(Ada.Finalization.Controlled with Location => Subject));
end Build_Callback_Dispatcher;
function String_Info is
new Helpers.Get_Parameters (Return_Element_T => Character,
Return_T => String,
Parameter_T => Enumerations.Program_Info,
C_Getter => API.Get_Program_Info);
function String_Build_Info is
new Helpers.Get_Parameters2 (Return_Element_T => Character,
Return_T => String,
Parameter_T => Enumerations.Program_Build_Info,
C_Getter => API.Get_Program_Build_Info);
-----------------------------------------------------------------------------
-- Implementations
-----------------------------------------------------------------------------
package body Constructors is
function Create_From_Source (Context : Contexts.Context'Class;
Source : String) return Program is
C_String : aliased IFC.Strings.chars_ptr
:= IFC.Strings.New_String (Source);
String_Size : aliased Size := Source'Length;
Ret_Program : System.Address;
Error : aliased Enumerations.Error_Code;
begin
Ret_Program
:= API.Create_Program_With_Source (CL_Object (Context).Location,
1, C_String'Access,
String_Size'Access,
Error'Unchecked_Access);
IFC.Strings.Free (C_String);
Helpers.Error_Handler (Error);
return Program'(Ada.Finalization.Controlled with Location => Ret_Program);
end Create_From_Source;
function Create_From_Source (Context : Contexts.Context'Class;
Sources : String_List)
return Program is
C_Strings : array (Sources.First_Index .. Sources.Last_Index)
of aliased IFC.Strings.chars_ptr;
Size_List : array (C_Strings'Range) of aliased Size;
Ret_Program : System.Address;
Error : aliased Enumerations.Error_Code;
begin
for Index in C_Strings'Range loop
C_Strings (Index) := IFC.Strings.New_String (Sources.Element (Index));
Size_List (Index) := Size (IFC.Strings.Strlen (C_Strings (Index)));
end loop;
Ret_Program
:= API.Create_Program_With_Source (CL_Object (Context).Location,
UInt (Size_List'Length),
C_Strings (C_Strings'First)'Access,
Size_List (Size_List'First)'Access,
Error'Unchecked_Access);
for Index in C_Strings'Range loop
IFC.Strings.Free (C_Strings (Index));
end loop;
Helpers.Error_Handler (Error);
return Program'(Ada.Finalization.Controlled with Location => Ret_Program);
end Create_From_Source;
function Create_From_Files (Context : Contexts.Context'Class;
Sources : String_List)
return Program is
C_Strings : array (Sources.First_Index .. Sources.Last_Index)
of aliased IFC.Strings.chars_ptr;
Size_List : array (C_Strings'Range) of aliased Size;
Ret_Program : System.Address;
Error : aliased Enumerations.Error_Code;
begin
for Index in C_Strings'Range loop
declare
File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Open (File, Ada.Text_IO.In_File, Sources.Element (Index));
C_Strings (Index) := IFC.Strings.New_String
(Helpers.Read_File (File));
Ada.Text_IO.Close (File);
end;
Size_List (Index) := Size (IFC.Strings.Strlen (C_Strings (Index)));
end loop;
Ret_Program
:= API.Create_Program_With_Source (CL_Object (Context).Location,
UInt (Size_List'Length),
C_Strings (C_Strings'First)'Access,
Size_List (Size_List'First)'Access,
Error'Unchecked_Access);
for Index in C_Strings'Range loop
IFC.Strings.Free (C_Strings (Index));
end loop;
Helpers.Error_Handler (Error);
return Program'(Ada.Finalization.Controlled with Location => Ret_Program);
end Create_From_Files;
function Create_From_Binary (Context : Contexts.Context'Class;
Devices : Platforms.Device_List;
Binaries : Binary_List;
Success : access Bool_List)
return Program is
Binary_Pointers : array (Binaries'Range) of aliased System.Address;
Size_List : array (Binaries'Range) of aliased Size;
Status : array (Binaries'Range) of aliased Int;
Ret_Program : System.Address;
Error : aliased Enumerations.Error_Code;
begin
for Index in Binaries'Range loop
Binary_Pointers (Index) := Binaries (Index) (Binaries (Index)'First)'Address;
Size_List (Index) := Binaries (Index)'Length;
end loop;
Ret_Program
:= API.Create_Program_With_Binary (CL_Object (Context).Location,
UInt (Devices'Length),
Devices (Devices'First)'Address,
Size_List (Size_List'First)'Unchecked_Access,
Binary_Pointers (Binary_Pointers'First)'Access,
Status (Status'First)'Access,
Error'Unchecked_Access);
if Success /= null then
for Index in Success.all'Range loop
Success.all (Index) := (Status (Index) = 1);
end loop;
else
Helpers.Error_Handler (Error);
end if;
return Program'(Ada.Finalization.Controlled with Location => Ret_Program);
end Create_From_Binary;
end Constructors;
overriding procedure Adjust (Object : in out Program) is
use type System.Address;
begin
if Object.Location /= System.Null_Address then
Helpers.Error_Handler (API.Retain_Program (Object.Location));
end if;
end Adjust;
overriding procedure Finalize (Object : in out Program) is
use type System.Address;
begin
if Object.Location /= System.Null_Address then
Helpers.Error_Handler (API.Release_Program (Object.Location));
end if;
end Finalize;
procedure Build (Source : Program;
Devices : Platforms.Device_List;
Options : String;
Callback : Build_Callback) is
function Raw_Device_List is
new Helpers.Raw_List (Platforms.Device, Platforms.Device_List);
Error : Enumerations.Error_Code;
Raw_List : Address_List := Raw_Device_List (Devices);
begin
if Callback /= null then
Error := API.Build_Program (Source.Location, UInt (Raw_List'Length),
Raw_List (1)'Address,
IFC.Strings.New_String (Options),
Build_Callback_Dispatcher'Access,
Callback);
else
Error := API.Build_Program (Source.Location, UInt (Raw_List'Length),
Raw_List (1)'Address,
IFC.Strings.New_String (Options),
null, null);
end if;
Helpers.Error_Handler (Error);
end Build;
function Reference_Count (Source : Program) return UInt is
function Getter is
new Helpers.Get_Parameter (Return_T => UInt,
Parameter_T => Enumerations.Program_Info,
C_Getter => API.Get_Program_Info);
begin
return Getter (Source, Enumerations.Reference_Count);
end Reference_Count;
function Context (Source : Program) return Contexts.Context is
function Getter is
new Helpers.Get_Parameter (Return_T => System.Address,
Parameter_T => Enumerations.Program_Info,
C_Getter => API.Get_Program_Info);
function New_Context_Reference is
new Helpers.New_Reference (Object_T => Contexts.Context);
begin
return New_Context_Reference (Getter (Source, Enumerations.Context));
end Context;
function Devices (Source : Program) return Platforms.Device_List is
function Getter is
new Helpers.Get_Parameters (Return_Element_T => System.Address,
Return_T => Address_List,
Parameter_T => Enumerations.Program_Info,
C_Getter => API.Get_Program_Info);
Raw_List : constant Address_List := Getter (Source, Enumerations.Devices);
Ret_List : Platforms.Device_List (Raw_List'Range);
begin
for Index in Raw_List'Range loop
Ret_List (Index) := Platforms.Device'(Ada.Finalization.Controlled with
Location => Raw_List (Index));
end loop;
return Ret_List;
end Devices;
function Source (Source : Program) return String is
begin
return String_Info (Source, Enumerations.Source_String);
end Source;
function Binaries (Source : Program) return Binary_List is
Empty_List : Binary_List (1..0);
begin
-- not implemented, chrhrhr
raise CL.Invalid_Operation;
return Empty_List;
end Binaries;
function Status (Source : Program;
Device : Platforms.Device) return Build_Status is
function Getter is
new Helpers.Get_Parameter2 (Return_T => Build_Status,
Parameter_T => Enumerations.Program_Build_Info,
C_Getter => API.Get_Program_Build_Info);
begin
return Getter (Source, Device, Enumerations.Status);
end Status;
function Build_Options (Source : Program;
Device : Platforms.Device) return String is
begin
return String_Build_Info (Source, Device, Enumerations.Options);
end Build_Options;
function Build_Log (Source : Program;
Device : Platforms.Device) return String is
begin
return String_Build_Info (Source, Device, Enumerations.Log);
end Build_Log;
procedure Unload_Compiler is
begin
Helpers.Error_Handler (API.Unload_Compiler);
end Unload_Compiler;
end CL.Programs;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Web Framework --
-- --
-- Tools Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2015, 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$
------------------------------------------------------------------------------
with League.String_Vectors;
with Asis.Declarations;
with Asis.Definitions;
with Asis.Elements;
with Asis.Expressions;
with Properties.Tools;
with Properties.Expressions.Identifiers;
package body Properties.Expressions.Record_Aggregate is
----------
-- Code --
----------
function Code
(Engine : access Engines.Contexts.Context;
Element : Asis.Expression;
Name : Engines.Text_Property)
return League.Strings.Universal_String
is
use type League.Strings.Universal_String;
use type Asis.Declaration_List;
procedure Append
(Names : League.Strings.Universal_String;
Code : League.Strings.Universal_String);
procedure Mark_Done (Name : League.Strings.Universal_String);
function Get_Name
(Index : Positive) return League.Strings.Universal_String;
function Get_Type_Name return League.Strings.Universal_String;
Tipe : constant Asis.Element :=
Asis.Expressions.Corresponding_Expression_Type_Definition (Element);
Parts : constant Asis.Declaration_List :=
Tools.Corresponding_Type_Discriminants (Tipe) &
Tools.Corresponding_Type_Components (Tipe);
Done : array (Parts'Range) of Boolean := (others => False);
Last : Natural := 0;
Result : League.Strings.Universal_String;
------------
-- Append --
------------
procedure Append
(Names : League.Strings.Universal_String;
Code : League.Strings.Universal_String)
is
Text : League.Strings.Universal_String;
List : constant League.String_Vectors.Universal_String_Vector :=
Names.Split (',');
begin
if List.Length = 0 then -- positional association
Last := Last + 1;
Done (Last) := True;
Text := Get_Name (Last);
Result.Append (Text);
Result.Append (":");
Result.Append (Code);
else
for J in 1 .. List.Length loop
Mark_Done (List.Element (J));
Result.Append (List.Element (J));
Result.Append (":");
Result.Append (Code);
end loop;
end if;
end Append;
--------------
-- Get_Name --
--------------
function Get_Name
(Index : Positive) return League.Strings.Universal_String
is
Names : constant Asis.Defining_Name_List :=
Asis.Declarations.Names (Parts (Index));
begin
pragma Assert (Names'Length = 1);
return Engine.Text.Get_Property (Names (Names'First), Code.Name);
end Get_Name;
-------------------
-- Get_Type_Name --
-------------------
function Get_Type_Name return League.Strings.Universal_String is
use type Asis.Definition_Kinds;
use type Asis.Expression_Kinds;
Result : League.Strings.Universal_String;
Name : League.Strings.Universal_String;
X : Asis.Element := Tipe;
Decl : Asis.Declaration;
begin
-- Unwind all subtype declarations
while Asis.Elements.Definition_Kind (X)
= Asis.A_Subtype_Indication
loop
X := Asis.Definitions.Subtype_Mark (X);
if Asis.Elements.Expression_Kind (X)
= Asis.A_Selected_Component
then
X := Asis.Expressions.Selector (X);
end if;
X := Asis.Expressions.Corresponding_Name_Declaration (X);
X := Asis.Declarations.Type_Declaration_View (X);
end loop;
if Asis.Elements.Definition_Kind (X) = Asis.A_Type_Definition then
Decl := Asis.Elements.Enclosing_Element (X);
Result := Properties.Expressions.Identifiers.Name_Prefix
(Engine => Engine,
Name => Element,
Decl => Asis.Elements.Enclosing_Element (X));
Name := Engine.Text.Get_Property
(Asis.Declarations.Names (Decl) (1), Code.Name);
Result.Append (Name);
end if;
return Result;
end Get_Type_Name;
---------------
-- Mark_Done --
---------------
procedure Mark_Done (Name : League.Strings.Universal_String) is
Text : League.Strings.Universal_String;
begin
for J in Parts'Range loop
if not Done (J) then
Text := Get_Name (J);
if Text = Name then
Done (J) := True;
return;
end if;
end if;
end loop;
end Mark_Done;
Names : League.Strings.Universal_String;
Text : League.Strings.Universal_String;
List : constant Asis.Association_List :=
Asis.Expressions.Record_Component_Associations (Element);
Tipe_Name : constant League.Strings.Universal_String := Get_Type_Name;
begin
if not Tipe_Name.Is_Empty then
Result.Append (Tipe_Name);
Result.Append ("._cast(");
end if;
Result.Append ("{");
for J in List'Range loop
Names := Engine.Text.Get_Property (List (J), Engines.Associations);
if Names /= League.Strings.To_Universal_String ("others") then
Text := Engine.Text.Get_Property (List (J), Name);
if not Text.Is_Empty then
-- Box <> expression returns empty Code. We ignore such assoc.
if J /= List'First then
Result.Append (",");
end if;
Append (Names, Text);
end if;
end if;
end loop;
for J in Parts'Range loop
if not Done (J) then
Text := Get_Name (J);
Result.Append (",");
Result.Append (Text);
Result.Append (":");
Text := Engine.Text.Get_Property (Parts (J), Engines.Initialize);
Result.Append (Text);
end if;
end loop;
Result.Append ("}");
if not Tipe_Name.Is_Empty then
Result.Append (")");
end if;
return Result;
end Code;
----------------------------
-- Typed_Array_Initialize --
----------------------------
function Typed_Array_Initialize
(Engine : access Engines.Contexts.Context;
Element : Asis.Expression;
Name : Engines.Text_Property) return League.Strings.Universal_String
is
Result : League.Strings.Universal_String;
Down : League.Strings.Universal_String;
Item : Asis.Expression;
List : constant Asis.Association_List :=
Asis.Expressions.Record_Component_Associations (Element);
begin
Result.Append ("_result._TA_allign(4);");
for J in List'Range loop
pragma Assert (Asis.Expressions.Record_Component_Choices
(List (J))'Length = 0,
"Named associations in Typed_Array aggregate"
& " are not supported");
Item := Asis.Expressions.Component_Expression (List (J));
Down := Engine.Text.Get_Property (Item, Name);
Result.Append (Down);
end loop;
return Result;
end Typed_Array_Initialize;
end Properties.Expressions.Record_Aggregate;
|
--
-- Copyright (C) 2015-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 Interfaces;
package HW is
type Bit is mod 2 ** 1;
subtype Byte is Interfaces.Unsigned_8;
subtype Word8 is Byte;
function Shift_Left (Value : Word8; Amount : Natural) return Word8
renames Interfaces.Shift_Left;
function Shift_Right (Value : Word8; Amount : Natural) return Word8
renames Interfaces.Shift_Right;
subtype Word16 is Interfaces.Unsigned_16;
function Shift_Left (Value : Word16; Amount : Natural) return Word16
renames Interfaces.Shift_Left;
function Shift_Right (Value : Word16; Amount : Natural) return Word16
renames Interfaces.Shift_Right;
subtype Word32 is Interfaces.Unsigned_32;
function Shift_Left (Value : Word32; Amount : Natural) return Word32
renames Interfaces.Shift_Left;
function Shift_Right (Value : Word32; Amount : Natural) return Word32
renames Interfaces.Shift_Right;
subtype Word64 is Interfaces.Unsigned_64;
function Shift_Left (Value : Word64; Amount : Natural) return Word64
renames Interfaces.Shift_Left;
function Shift_Right (Value : Word64; Amount : Natural) return Word64
renames Interfaces.Shift_Right;
subtype Int8 is Interfaces.Integer_8;
subtype Int16 is Interfaces.Integer_16;
subtype Int32 is Interfaces.Integer_32;
subtype Int64 is Interfaces.Integer_64;
subtype Pos8 is Interfaces.Integer_8 range 1 .. Interfaces.Integer_8'Last;
subtype Pos16 is Interfaces.Integer_16 range 1 .. Interfaces.Integer_16'Last;
subtype Pos32 is Interfaces.Integer_32 range 1 .. Interfaces.Integer_32'Last;
subtype Pos64 is Interfaces.Integer_64 range 1 .. Interfaces.Integer_64'Last;
use type Pos8;
function Div_Round_Up (N, M : Pos8) return Pos8 is ((N + (M - 1)) / M)
with
Pre => N <= Pos8'Last - (M - 1);
function Div_Round_Closest (N, M : Pos8) return Int8 is ((N + M / 2) / M)
with
Pre => N <= Pos8'Last - M / 2;
use type Pos16;
function Div_Round_Up (N, M : Pos16) return Pos16 is ((N + (M - 1)) / M)
with
Pre => N <= Pos16'Last - (M - 1);
function Div_Round_Closest (N, M : Pos16) return Int16 is ((N + M / 2) / M)
with
Pre => N <= Pos16'Last - M / 2;
use type Pos32;
function Div_Round_Up (N, M : Pos32) return Pos32 is ((N + (M - 1)) / M)
with
Pre => N <= Pos32'Last - (M - 1);
function Div_Round_Closest (N, M : Pos32) return Int32 is ((N + M / 2) / M)
with
Pre => N <= Pos32'Last - M / 2;
use type Pos64;
function Div_Round_Up (N, M : Pos64) return Pos64 is ((N + (M - 1)) / M)
with
Pre => N <= Pos64'Last - (M - 1);
function Div_Round_Closest (N, M : Pos64) return Int64 is ((N + M / 2) / M)
with
Pre => N <= Pos64'Last - M / 2;
subtype Buffer_Range is Natural range 0 .. Natural'Last - 1;
type Buffer is array (Buffer_Range range <>) of Byte;
end HW;
|
with Ada.Real_Time; use Ada.Real_Time;
with STM_Board; use STM_Board;
with Startup;
with Last_Chance_Handler; pragma Unreferenced (Last_Chance_Handler);
-- The "last chance handler" is the user-defined routine that is called when
-- an exception is propagated. We need it in the executable, therefore it
-- must be somewhere in the closure of the context clauses.
procedure Main is
begin
-- Start-up GPIOs, ADCs, Timer and PWM
Startup.Initialize;
Startup.Start_Inverter;
-- Enter steady state
loop
Set_Toggle (Green_LED);
delay until Clock + Seconds (3); -- arbitrary
end loop;
end Main;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- P R J . U T I L --
-- --
-- B o d y --
-- --
-- Copyright (C) 2001-2006, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with GNAT.Case_Util; use GNAT.Case_Util;
with Namet; use Namet;
with Osint; use Osint;
with Output; use Output;
with Prj.Com;
with Snames; use Snames;
package body Prj.Util is
procedure Free is new Ada.Unchecked_Deallocation
(Text_File_Data, Text_File);
-----------
-- Close --
-----------
procedure Close (File : in out Text_File) is
begin
if File = null then
Prj.Com.Fail ("Close attempted on an invalid Text_File");
end if;
-- Close file, no need to test status, since this is a file that we
-- read, and the file was read successfully before we closed it.
Close (File.FD);
Free (File);
end Close;
-----------------
-- End_Of_File --
-----------------
function End_Of_File (File : Text_File) return Boolean is
begin
if File = null then
Prj.Com.Fail ("End_Of_File attempted on an invalid Text_File");
end if;
return File.End_Of_File_Reached;
end End_Of_File;
-------------------
-- Executable_Of --
-------------------
function Executable_Of
(Project : Project_Id;
In_Tree : Project_Tree_Ref;
Main : Name_Id;
Index : Int;
Ada_Main : Boolean := True) return Name_Id
is
pragma Assert (Project /= No_Project);
The_Packages : constant Package_Id :=
In_Tree.Projects.Table (Project).Decl.Packages;
Builder_Package : constant Prj.Package_Id :=
Prj.Util.Value_Of
(Name => Name_Builder,
In_Packages => The_Packages,
In_Tree => In_Tree);
Executable : Variable_Value :=
Prj.Util.Value_Of
(Name => Main,
Index => Index,
Attribute_Or_Array_Name => Name_Executable,
In_Package => Builder_Package,
In_Tree => In_Tree);
Executable_Suffix : constant Variable_Value :=
Prj.Util.Value_Of
(Name => Main,
Index => 0,
Attribute_Or_Array_Name =>
Name_Executable_Suffix,
In_Package => Builder_Package,
In_Tree => In_Tree);
Body_Append : constant String := Get_Name_String
(In_Tree.Projects.Table
(Project).
Naming.Ada_Body_Suffix);
Spec_Append : constant String := Get_Name_String
(In_Tree.Projects.Table
(Project).
Naming.Ada_Spec_Suffix);
begin
if Builder_Package /= No_Package then
if Executable = Nil_Variable_Value and Ada_Main then
Get_Name_String (Main);
-- Try as index the name minus the implementation suffix or minus
-- the specification suffix.
declare
Name : constant String (1 .. Name_Len) :=
Name_Buffer (1 .. Name_Len);
Last : Positive := Name_Len;
Naming : constant Naming_Data :=
In_Tree.Projects.Table (Project).Naming;
Spec_Suffix : constant String :=
Get_Name_String (Naming.Ada_Spec_Suffix);
Body_Suffix : constant String :=
Get_Name_String (Naming.Ada_Body_Suffix);
Truncated : Boolean := False;
begin
if Last > Body_Suffix'Length
and then Name (Last - Body_Suffix'Length + 1 .. Last) =
Body_Suffix
then
Truncated := True;
Last := Last - Body_Suffix'Length;
end if;
if not Truncated
and then Last > Spec_Suffix'Length
and then Name (Last - Spec_Suffix'Length + 1 .. Last) =
Spec_Suffix
then
Truncated := True;
Last := Last - Spec_Suffix'Length;
end if;
if Truncated then
Name_Len := Last;
Name_Buffer (1 .. Name_Len) := Name (1 .. Last);
Executable :=
Prj.Util.Value_Of
(Name => Name_Find,
Index => 0,
Attribute_Or_Array_Name => Name_Executable,
In_Package => Builder_Package,
In_Tree => In_Tree);
end if;
end;
end if;
-- If we have found an Executable attribute, return its value,
-- possibly suffixed by the executable suffix.
if Executable /= Nil_Variable_Value
and then Executable.Value /= Empty_Name
then
declare
Exec_Suffix : String_Access := Get_Executable_Suffix;
Result : Name_Id := Executable.Value;
begin
if Exec_Suffix'Length /= 0 then
Get_Name_String (Executable.Value);
Canonical_Case_File_Name (Name_Buffer (1 .. Name_Len));
-- If the Executable does not end with the executable
-- suffix, add it.
if Name_Len <= Exec_Suffix'Length
or else
Name_Buffer
(Name_Len - Exec_Suffix'Length + 1 .. Name_Len) /=
Exec_Suffix.all
then
-- Get the original Executable to keep the correct
-- case for systems where file names are case
-- insensitive (Windows).
Get_Name_String (Executable.Value);
Name_Buffer
(Name_Len + 1 .. Name_Len + Exec_Suffix'Length) :=
Exec_Suffix.all;
Name_Len := Name_Len + Exec_Suffix'Length;
Result := Name_Find;
end if;
Free (Exec_Suffix);
end if;
return Result;
end;
end if;
end if;
Get_Name_String (Main);
-- If there is a body suffix or a spec suffix, remove this suffix,
-- otherwise remove any suffix ('.' followed by other characters), if
-- there is one.
if Ada_Main and then Name_Len > Body_Append'Length
and then Name_Buffer (Name_Len - Body_Append'Length + 1 .. Name_Len) =
Body_Append
then
-- Found the body termination, remove it
Name_Len := Name_Len - Body_Append'Length;
elsif Ada_Main and then Name_Len > Spec_Append'Length
and then Name_Buffer (Name_Len - Spec_Append'Length + 1 .. Name_Len) =
Spec_Append
then
-- Found the spec termination, remove it
Name_Len := Name_Len - Spec_Append'Length;
else
-- Remove any suffix, if there is one
Get_Name_String (Strip_Suffix (Main));
end if;
if Executable_Suffix /= Nil_Variable_Value
and then not Executable_Suffix.Default
then
-- If attribute Executable_Suffix is specified, add this suffix
declare
Suffix : constant String :=
Get_Name_String (Executable_Suffix.Value);
begin
Name_Buffer (Name_Len + 1 .. Name_Len + Suffix'Length) := Suffix;
Name_Len := Name_Len + Suffix'Length;
return Name_Find;
end;
else
-- Otherwise, add the standard suffix for the platform, if any
return Executable_Name (Name_Find);
end if;
end Executable_Of;
--------------
-- Get_Line --
--------------
procedure Get_Line
(File : Text_File;
Line : out String;
Last : out Natural)
is
C : Character;
procedure Advance;
-------------
-- Advance --
-------------
procedure Advance is
begin
if File.Cursor = File.Buffer_Len then
File.Buffer_Len :=
Read
(FD => File.FD,
A => File.Buffer'Address,
N => File.Buffer'Length);
if File.Buffer_Len = 0 then
File.End_Of_File_Reached := True;
return;
else
File.Cursor := 1;
end if;
else
File.Cursor := File.Cursor + 1;
end if;
end Advance;
-- Start of processing for Get_Line
begin
if File = null then
Prj.Com.Fail ("Get_Line attempted on an invalid Text_File");
end if;
Last := Line'First - 1;
if not File.End_Of_File_Reached then
loop
C := File.Buffer (File.Cursor);
exit when C = ASCII.CR or else C = ASCII.LF;
Last := Last + 1;
Line (Last) := C;
Advance;
if File.End_Of_File_Reached then
return;
end if;
exit when Last = Line'Last;
end loop;
if C = ASCII.CR or else C = ASCII.LF then
Advance;
if File.End_Of_File_Reached then
return;
end if;
end if;
if C = ASCII.CR
and then File.Buffer (File.Cursor) = ASCII.LF
then
Advance;
end if;
end if;
end Get_Line;
--------------
-- Is_Valid --
--------------
function Is_Valid (File : Text_File) return Boolean is
begin
return File /= null;
end Is_Valid;
----------
-- Open --
----------
procedure Open (File : out Text_File; Name : String) is
FD : File_Descriptor;
File_Name : String (1 .. Name'Length + 1);
begin
File_Name (1 .. Name'Length) := Name;
File_Name (File_Name'Last) := ASCII.NUL;
FD := Open_Read (Name => File_Name'Address,
Fmode => GNAT.OS_Lib.Text);
if FD = Invalid_FD then
File := null;
else
File := new Text_File_Data;
File.FD := FD;
File.Buffer_Len :=
Read (FD => FD,
A => File.Buffer'Address,
N => File.Buffer'Length);
if File.Buffer_Len = 0 then
File.End_Of_File_Reached := True;
else
File.Cursor := 1;
end if;
end if;
end Open;
--------------
-- Value_Of --
--------------
function Value_Of
(Variable : Variable_Value;
Default : String) return String
is
begin
if Variable.Kind /= Single
or else Variable.Default
or else Variable.Value = No_Name
then
return Default;
else
return Get_Name_String (Variable.Value);
end if;
end Value_Of;
function Value_Of
(Index : Name_Id;
In_Array : Array_Element_Id;
In_Tree : Project_Tree_Ref) return Name_Id
is
Current : Array_Element_Id := In_Array;
Element : Array_Element;
Real_Index : Name_Id := Index;
begin
if Current = No_Array_Element then
return No_Name;
end if;
Element := In_Tree.Array_Elements.Table (Current);
if not Element.Index_Case_Sensitive then
Get_Name_String (Index);
To_Lower (Name_Buffer (1 .. Name_Len));
Real_Index := Name_Find;
end if;
while Current /= No_Array_Element loop
Element := In_Tree.Array_Elements.Table (Current);
if Real_Index = Element.Index then
exit when Element.Value.Kind /= Single;
exit when Element.Value.Value = Empty_String;
return Element.Value.Value;
else
Current := Element.Next;
end if;
end loop;
return No_Name;
end Value_Of;
function Value_Of
(Index : Name_Id;
Src_Index : Int := 0;
In_Array : Array_Element_Id;
In_Tree : Project_Tree_Ref) return Variable_Value
is
Current : Array_Element_Id := In_Array;
Element : Array_Element;
Real_Index : Name_Id := Index;
begin
if Current = No_Array_Element then
return Nil_Variable_Value;
end if;
Element := In_Tree.Array_Elements.Table (Current);
if not Element.Index_Case_Sensitive then
Get_Name_String (Index);
To_Lower (Name_Buffer (1 .. Name_Len));
Real_Index := Name_Find;
end if;
while Current /= No_Array_Element loop
Element := In_Tree.Array_Elements.Table (Current);
if Real_Index = Element.Index and then
Src_Index = Element.Src_Index
then
return Element.Value;
else
Current := Element.Next;
end if;
end loop;
return Nil_Variable_Value;
end Value_Of;
function Value_Of
(Name : Name_Id;
Index : Int := 0;
Attribute_Or_Array_Name : Name_Id;
In_Package : Package_Id;
In_Tree : Project_Tree_Ref) return Variable_Value
is
The_Array : Array_Element_Id;
The_Attribute : Variable_Value := Nil_Variable_Value;
begin
if In_Package /= No_Package then
-- First, look if there is an array element that fits
The_Array :=
Value_Of
(Name => Attribute_Or_Array_Name,
In_Arrays => In_Tree.Packages.Table (In_Package).Decl.Arrays,
In_Tree => In_Tree);
The_Attribute :=
Value_Of
(Index => Name,
Src_Index => Index,
In_Array => The_Array,
In_Tree => In_Tree);
-- If there is no array element, look for a variable
if The_Attribute = Nil_Variable_Value then
The_Attribute :=
Value_Of
(Variable_Name => Attribute_Or_Array_Name,
In_Variables => In_Tree.Packages.Table
(In_Package).Decl.Attributes,
In_Tree => In_Tree);
end if;
end if;
return The_Attribute;
end Value_Of;
function Value_Of
(Index : Name_Id;
In_Array : Name_Id;
In_Arrays : Array_Id;
In_Tree : Project_Tree_Ref) return Name_Id
is
Current : Array_Id := In_Arrays;
The_Array : Array_Data;
begin
while Current /= No_Array loop
The_Array := In_Tree.Arrays.Table (Current);
if The_Array.Name = In_Array then
return Value_Of
(Index, In_Array => The_Array.Value, In_Tree => In_Tree);
else
Current := The_Array.Next;
end if;
end loop;
return No_Name;
end Value_Of;
function Value_Of
(Name : Name_Id;
In_Arrays : Array_Id;
In_Tree : Project_Tree_Ref) return Array_Element_Id
is
Current : Array_Id := In_Arrays;
The_Array : Array_Data;
begin
while Current /= No_Array loop
The_Array := In_Tree.Arrays.Table (Current);
if The_Array.Name = Name then
return The_Array.Value;
else
Current := The_Array.Next;
end if;
end loop;
return No_Array_Element;
end Value_Of;
function Value_Of
(Name : Name_Id;
In_Packages : Package_Id;
In_Tree : Project_Tree_Ref) return Package_Id
is
Current : Package_Id := In_Packages;
The_Package : Package_Element;
begin
while Current /= No_Package loop
The_Package := In_Tree.Packages.Table (Current);
exit when The_Package.Name /= No_Name
and then The_Package.Name = Name;
Current := The_Package.Next;
end loop;
return Current;
end Value_Of;
function Value_Of
(Variable_Name : Name_Id;
In_Variables : Variable_Id;
In_Tree : Project_Tree_Ref) return Variable_Value
is
Current : Variable_Id := In_Variables;
The_Variable : Variable;
begin
while Current /= No_Variable loop
The_Variable :=
In_Tree.Variable_Elements.Table (Current);
if Variable_Name = The_Variable.Name then
return The_Variable.Value;
else
Current := The_Variable.Next;
end if;
end loop;
return Nil_Variable_Value;
end Value_Of;
---------------
-- Write_Str --
---------------
procedure Write_Str
(S : String;
Max_Length : Positive;
Separator : Character)
is
First : Positive := S'First;
Last : Natural := S'Last;
begin
-- Nothing to do for empty strings
if S'Length > 0 then
-- Start on a new line if current line is already longer than
-- Max_Length.
if Positive (Column) >= Max_Length then
Write_Eol;
end if;
-- If length of remainder is longer than Max_Length, we need to
-- cut the remainder in several lines.
while Positive (Column) + S'Last - First > Max_Length loop
-- Try the maximum length possible
Last := First + Max_Length - Positive (Column);
-- Look for last Separator in the line
while Last >= First and then S (Last) /= Separator loop
Last := Last - 1;
end loop;
-- If we do not find a separator, we output the maximum length
-- possible.
if Last < First then
Last := First + Max_Length - Positive (Column);
end if;
Write_Line (S (First .. Last));
-- Set the beginning of the new remainder
First := Last + 1;
end loop;
-- What is left goes to the buffer, without EOL
Write_Str (S (First .. S'Last));
end if;
end Write_Str;
end Prj.Util;
|
with Ada.Exceptions;
with System.Address_To_Named_Access_Conversions;
with System.Runtime_Context;
with System.Shared_Locking;
package body System.Storage_Pools.Subpools is
pragma Suppress (All_Checks);
use type Finalization_Masters.Finalization_Master_Ptr;
use type Finalization_Masters.Finalize_Address_Ptr;
use type Storage_Barriers.Flag;
package FM_Node_Ptr_Conv is
new Address_To_Named_Access_Conversions (
Finalization_Masters.FM_Node,
Finalization_Masters.FM_Node_Ptr);
-- hooks for smart linking, making code of subpool as removable
procedure Setup_Allocation (
Pool : in out Root_Storage_Pool'Class;
Context_Subpool : Subpool_Handle;
Context_Master : Finalization_Masters.Finalization_Master_Ptr;
Fin_Address : Finalization_Masters.Finalize_Address_Ptr;
Subpool : out Subpool_Handle;
Master : out Finalization_Masters.Finalization_Master_Ptr);
procedure Setup_Allocation (
Pool : in out Root_Storage_Pool'Class;
Context_Subpool : Subpool_Handle;
Context_Master : Finalization_Masters.Finalization_Master_Ptr;
Fin_Address : Finalization_Masters.Finalize_Address_Ptr;
Subpool : out Subpool_Handle;
Master : out Finalization_Masters.Finalization_Master_Ptr)
is
pragma Unreferenced (Pool);
pragma Unreferenced (Fin_Address);
pragma Assert (Context_Subpool = null);
begin
Subpool := null;
Master := Context_Master;
end Setup_Allocation;
procedure Setup_Allocation_With_Subpools (
Pool : in out Root_Storage_Pool'Class;
Context_Subpool : Subpool_Handle;
Context_Master : Finalization_Masters.Finalization_Master_Ptr;
Fin_Address : Finalization_Masters.Finalize_Address_Ptr;
Subpool : out Subpool_Handle;
Master : out Finalization_Masters.Finalization_Master_Ptr);
procedure Setup_Allocation_With_Subpools (
Pool : in out Root_Storage_Pool'Class;
Context_Subpool : Subpool_Handle;
Context_Master : Finalization_Masters.Finalization_Master_Ptr;
Fin_Address : Finalization_Masters.Finalize_Address_Ptr;
Subpool : out Subpool_Handle;
Master : out Finalization_Masters.Finalization_Master_Ptr) is
begin
if Pool in Root_Storage_Pool_With_Subpools'Class then
if Context_Subpool = null then
Subpool := Default_Subpool_For_Pool (
Root_Storage_Pool_With_Subpools'Class (Pool));
else
Subpool := Context_Subpool;
end if;
if Subpool.Owner /=
Root_Storage_Pool_With_Subpools'Class (Pool)'Unchecked_Access
then
raise Program_Error;
end if;
if Fin_Address /= null then
Master := Subpool.Master'Access;
end if;
else
Setup_Allocation (
Pool,
Context_Subpool,
Context_Master,
Fin_Address,
Subpool,
Master);
end if;
end Setup_Allocation_With_Subpools;
type Setup_Allocation_Handler is access procedure (
Pool : in out Root_Storage_Pool'Class;
Context_Subpool : Subpool_Handle;
Context_Master : Finalization_Masters.Finalization_Master_Ptr;
Fin_Address : Finalization_Masters.Finalize_Address_Ptr;
Subpool : out Subpool_Handle;
Master : out Finalization_Masters.Finalization_Master_Ptr);
pragma Favor_Top_Level (Setup_Allocation_Handler);
Setup_Allocation_Hook : not null Setup_Allocation_Handler :=
Setup_Allocation'Access;
-- subpools and theirs owner
procedure Attach (
Owner : not null Root_Storage_Pool_With_Subpools_Access;
Item : not null Subpool_Handle);
procedure Detach (Item : not null Subpool_Handle);
procedure Finalize_Subpool (Subpool : not null Subpool_Handle);
procedure Attach (
Owner : not null Root_Storage_Pool_With_Subpools_Access;
Item : not null Subpool_Handle) is
begin
pragma Assert (Item.Owner = null);
Shared_Locking.Enter;
Item.Owner := Owner;
Item.Previous := Owner.Last;
if Item.Previous /= null then
Item.Previous.Next := Item;
end if;
Item.Next := null;
Owner.Last := Item;
Shared_Locking.Leave;
end Attach;
procedure Detach (Item : not null Subpool_Handle) is
begin
pragma Assert (Item.Owner /= null);
Shared_Locking.Enter;
if Item.Previous /= null then
Item.Previous.Next := Item.Next;
end if;
if Item.Next /= null then
Item.Next.Previous := Item.Previous;
else
Item.Owner.Last := Item.Previous;
end if;
Item.Owner := null;
Shared_Locking.Leave;
end Detach;
procedure Finalize_Subpool (Subpool : not null Subpool_Handle) is
begin
if Subpool.Owner /= null then
Finalization_Masters.Finalize (Subpool.Master);
Detach (Subpool);
end if;
end Finalize_Subpool;
-- implementation
function Pool_Of_Subpool (
Subpool : not null Subpool_Handle)
return access Root_Storage_Pool_With_Subpools'Class is
begin
return Subpool.Owner;
end Pool_Of_Subpool;
procedure Set_Pool_Of_Subpool (
Subpool : not null Subpool_Handle;
To : in out Root_Storage_Pool_With_Subpools'Class) is
begin
if Subpool.Owner /= null
or else Storage_Barriers.atomic_load (
To.Finalization_Started'Access) /= 0
then
raise Program_Error;
else
Attach (To'Unrestricted_Access, Subpool);
end if;
end Set_Pool_Of_Subpool;
function Default_Subpool_For_Pool (
Pool : in out Root_Storage_Pool_With_Subpools)
return not null Subpool_Handle is
begin
-- RM 13.11.4(35/3)
-- The pool implementor should override Default_Subpool_For_Pool
-- if the pool is to support a default subpool for the pool.
raise Program_Error;
return Default_Subpool_For_Pool (Pool);
end Default_Subpool_For_Pool;
overriding procedure Allocate (
Pool : in out Root_Storage_Pool_With_Subpools;
Storage_Address : out Address;
Size_In_Storage_Elements : Storage_Elements.Storage_Count;
Alignment : Storage_Elements.Storage_Count) is
begin
Allocate_From_Subpool (
Root_Storage_Pool_With_Subpools'Class (Pool),
Storage_Address,
Size_In_Storage_Elements,
Alignment,
Default_Subpool_For_Pool (
Root_Storage_Pool_With_Subpools'Class (Pool)));
end Allocate;
procedure Unchecked_Deallocate_Subpool (Subpool : in out Subpool_Handle) is
begin
-- (s-spsufi.adb)
if Subpool /= null then
if Subpool.Owner = null then
raise Program_Error;
else
declare
Pool : constant access Root_Storage_Pool_With_Subpools'Class :=
Pool_Of_Subpool (Subpool); -- save it before finalize
begin
Finalize_Subpool (Subpool);
Deallocate_Subpool (Pool.all, Subpool);
end;
Subpool := null;
end if;
end if;
end Unchecked_Deallocate_Subpool;
overriding procedure Initialize (
Object : in out Root_Storage_Pool_With_Subpools) is
begin
Storage_Barriers.atomic_clear (Object.Finalization_Started'Access);
Setup_Allocation_Hook := Setup_Allocation_With_Subpools'Access;
end Initialize;
overriding procedure Finalize (
Object : in out Root_Storage_Pool_With_Subpools) is
begin
if not Storage_Barriers.atomic_test_and_set (
Object.Finalization_Started'Access)
then
declare
X : Ada.Exceptions.Exception_Occurrence;
Raised : Boolean := False;
begin
while Object.Last /= null loop
begin
Finalize_Subpool (Object.Last);
exception
when E : others =>
if not Raised then
Raised := True;
Ada.Exceptions.Save_Occurrence (X, E);
end if;
end;
end loop;
if Raised then
Ada.Exceptions.Reraise_Nonnull_Occurrence (X);
end if;
end;
end if;
end Finalize;
procedure Allocate_Any_Controlled (
Pool : in out Root_Storage_Pool'Class;
Context_Subpool : Subpool_Handle;
Context_Master : Finalization_Masters.Finalization_Master_Ptr;
Fin_Address : Finalization_Masters.Finalize_Address_Ptr;
Addr : out Address;
Storage_Size : Storage_Elements.Storage_Count;
Alignment : Storage_Elements.Storage_Count;
Is_Controlled : Boolean;
On_Subpool : Boolean)
is
Overlaid_Allocation : Address := Null_Address;
Subpool : Subpool_Handle := null;
Master : Finalization_Masters.Finalization_Master_Ptr := null;
Actual_Storage_Address : Address;
Actual_Size : Storage_Elements.Storage_Count;
Header_And_Padding : Storage_Elements.Storage_Offset;
begin
Setup_Allocation_Hook (
Pool,
Context_Subpool,
Context_Master,
Fin_Address,
Subpool,
Master);
pragma Assert (On_Subpool <= (Subpool /= null));
if Is_Controlled then
if Master = null
or else Finalization_Masters.Finalization_Started (Master.all)
or else Fin_Address = null
then
raise Program_Error;
else
Header_And_Padding := Header_Size_With_Padding (Alignment);
Actual_Size := Storage_Size + Header_And_Padding;
declare
TLS : constant
not null Runtime_Context.Task_Local_Storage_Access :=
Runtime_Context.Get_Task_Local_Storage;
begin
Overlaid_Allocation := TLS.Overlaid_Allocation;
end;
end if;
else
Actual_Size := Storage_Size;
end if;
-- allocation
if Subpool /= null then
Allocate_From_Subpool (
Root_Storage_Pool_With_Subpools'Class (Pool),
Actual_Storage_Address,
Actual_Size,
Alignment,
Subpool);
else
Allocate (Pool, Actual_Storage_Address, Actual_Size, Alignment);
end if;
-- fix address
if Is_Controlled
and then Actual_Storage_Address /=
Overlaid_Allocation -- for System.Storage_Pools.Overlaps
then
Shared_Locking.Enter;
declare
N_Ptr : constant Finalization_Masters.FM_Node_Ptr :=
FM_Node_Ptr_Conv.To_Pointer (
Actual_Storage_Address
+ Header_And_Padding
- Finalization_Masters.Header_Size);
begin
Finalization_Masters.Attach_Unprotected (
N_Ptr,
Finalization_Masters.Objects_Unprotected (
Master.all,
Fin_Address));
end;
Addr := Actual_Storage_Address + Header_And_Padding;
Finalization_Masters.Set_Finalize_Address_Unprotected (
Master.all,
Fin_Address);
Shared_Locking.Leave;
else
Addr := Actual_Storage_Address;
end if;
end Allocate_Any_Controlled;
procedure Deallocate_Any_Controlled (
Pool : in out Root_Storage_Pool'Class;
Addr : Address;
Storage_Size : Storage_Elements.Storage_Count;
Alignment : Storage_Elements.Storage_Count;
Is_Controlled : Boolean)
is
Actual_Storage_Address : Address;
Actual_Size : Storage_Elements.Storage_Count;
begin
-- fix address
if Is_Controlled
and then Addr /=
Runtime_Context.Get_Task_Local_Storage.Overlaid_Allocation
-- for System.Storage_Pools.Overlaps
then
Shared_Locking.Enter;
declare
Header_And_Padding : constant Storage_Elements.Storage_Offset :=
Header_Size_With_Padding (Alignment);
N_Ptr : constant Finalization_Masters.FM_Node_Ptr :=
FM_Node_Ptr_Conv.To_Pointer (
Addr - Finalization_Masters.Header_Size);
begin
Finalization_Masters.Detach_Unprotected (N_Ptr);
Actual_Storage_Address := Addr - Header_And_Padding;
Actual_Size := Storage_Size + Header_And_Padding;
end;
Shared_Locking.Leave;
else
Actual_Storage_Address := Addr;
Actual_Size := Storage_Size;
end if;
-- deallocation
Deallocate (Pool, Actual_Storage_Address, Actual_Size, Alignment);
end Deallocate_Any_Controlled;
function Header_Size_With_Padding (
Alignment : Storage_Elements.Storage_Count)
return Storage_Elements.Storage_Count is
begin
return Finalization_Masters.Header_Size
+ (-Finalization_Masters.Header_Size) mod Alignment;
end Header_Size_With_Padding;
end System.Storage_Pools.Subpools;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2020 onox <denkpadje@gmail.com>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Numerics.Generic_Elementary_Functions;
with GL.Barriers;
with GL.Compute;
with GL.Toggles;
with Orka.Rendering.Drawing;
with Orka.Rendering.Programs.Modules;
with Orka.Rendering.Textures;
package body Orka.Rendering.Effects.Filters is
package EF is new Ada.Numerics.Generic_Elementary_Functions (GL.Types.Double);
use type GL.Types.Double;
function Gaussian_Kernel (Radius : GL.Types.Size) return GL.Types.Single_Array is
Sigma : constant GL.Types.Double :=
((GL.Types.Double (Radius) - 1.0) * 0.5 - 1.0) * 0.3 + 0.8;
Denominator : constant GL.Types.Double :=
EF.Sqrt (2.0 * Ada.Numerics.Pi * Sigma ** 2);
Kernel : GL.Types.Double_Array (0 .. Radius);
Sum : GL.Types.Double := 0.0;
begin
for Index in Kernel'Range loop
Kernel (Index) := EF.Exp (-GL.Types.Double (Index**2) / (2.0 * Sigma ** 2))
/ Denominator;
Sum := Sum + Kernel (Index) * (if Index > 0 then 2.0 else 1.0);
-- Kernel array only stores the positive side of the curve, but
-- we need to compute the area of the whole curve for normalization
end loop;
-- Normalize the weights to prevent the image from becoming darker
for Index in Kernel'Range loop
Kernel (Index) := Kernel (Index) / Sum;
end loop;
declare
-- Use bilinear texture filtering hardware [1].
--
-- Weight (t1, t2) = Weight (t1) + Weight (t2)
--
-- offset (t1) * weight (t1) + offset (t2) * weight (t2)
-- Offset (t1, t2) = -----------------------------------------------------
-- weight (t1, t2)
--
-- [1] http://rastergrid.com/blog/2010/09/efficient-gaussian-blur-with-linear-sampling/
Weights : GL.Types.Single_Array (0 .. Radius / 2);
Offsets : GL.Types.Single_Array (0 .. Radius / 2);
use type GL.Types.Single_Array;
use GL.Types;
begin
Weights (Weights'First) := Single (Kernel (Weights'First));
Offsets (Offsets'First) := 0.0;
-- Weights
for Index in Weights'First + 1 .. Weights'Last loop
declare
T1 : constant Size := Index * 2 - 1;
T2 : constant Size := Index * 2;
begin
Weights (Index) := Single (Kernel (T1) + Kernel (T2));
end;
end loop;
-- Offsets
for Index in Offsets'First + 1 .. Offsets'Last loop
declare
T1 : constant Size := Index * 2 - 1;
T2 : constant Size := Index * 2;
W12 : constant Single := Weights (Index);
begin
if W12 > 0.0 then
Offsets (Index) := Single
((Double (T1) * Kernel (T1) + Double (T2) * Kernel (T2)) / Double (W12));
else
Offsets (Index) := 0.0;
end if;
end;
end loop;
return Offsets & Weights;
end;
end Gaussian_Kernel;
function Create_Filter
(Location : Resources.Locations.Location_Ptr;
Subject : GL.Objects.Textures.Texture;
Kernel : GL.Types.Single_Array) return Separable_Filter
is
use all type LE.Texture_Kind;
pragma Assert (Subject.Kind = LE.Texture_Rectangle);
use Rendering.Buffers;
use Rendering.Framebuffers;
use Rendering.Programs;
Width : constant GL.Types.Size := Subject.Width (0);
Height : constant GL.Types.Size := Subject.Height (0);
begin
return Result : Separable_Filter :=
(Buffer_Weights => Create_Buffer ((others => False), Kernel),
Program_Blur => Create_Program (Modules.Module_Array'
(Modules.Create_Module (Location, VS => "oversized-triangle.vert"),
Modules.Create_Module (Location, FS => "effects/blur.frag"))),
Framebuffer_H => Create_Framebuffer (Width, Height),
Framebuffer_V => Create_Framebuffer (Width, Height),
Texture_H => Subject,
others => <>)
do
Result.Uniform_Horizontal := Result.Program_Blur.Uniform ("horizontal");
Result.Texture_V.Allocate_Storage (Subject);
Result.Framebuffer_H.Attach (Result.Texture_H);
Result.Framebuffer_V.Attach (Result.Texture_V);
end return;
end Create_Filter;
procedure Render (Object : in out Separable_Filter; Passes : Positive := 1) is
use all type Orka.Rendering.Buffers.Indexed_Buffer_Target;
begin
GL.Toggles.Disable (GL.Toggles.Depth_Test);
Object.Program_Blur.Use_Program;
Object.Buffer_Weights.Bind (Shader_Storage, 0);
for Pass in 1 .. Passes loop
-- Horizontal pass: Texture_H => Texture_V
Object.Uniform_Horizontal.Set_Boolean (True);
Orka.Rendering.Textures.Bind (Object.Texture_H, Orka.Rendering.Textures.Texture, 0);
Object.Framebuffer_V.Use_Framebuffer;
Orka.Rendering.Drawing.Draw (GL.Types.Triangles, 0, 3);
-- Vertical pass: Texture_V => Texture_H
Object.Uniform_Horizontal.Set_Boolean (False);
Orka.Rendering.Textures.Bind (Object.Texture_V, Orka.Rendering.Textures.Texture, 0);
Object.Framebuffer_H.Use_Framebuffer;
Orka.Rendering.Drawing.Draw (GL.Types.Triangles, 0, 3);
end loop;
GL.Toggles.Enable (GL.Toggles.Depth_Test);
end Render;
-----------------------------------------------------------------------------
function Create_Filter
(Location : Resources.Locations.Location_Ptr;
Subject : GL.Objects.Textures.Texture;
Radius : GL.Types.Size) return Moving_Average_Filter
is
use all type LE.Texture_Kind;
pragma Assert (Subject.Kind = LE.Texture_Rectangle);
use Rendering.Programs;
use type GL.Types.Single;
Width : constant GL.Types.Size := Subject.Width (0);
Height : constant GL.Types.Size := Subject.Height (0);
begin
return Result : Moving_Average_Filter :=
(Program_Blur => Create_Program
(Modules.Create_Module (Location, CS => "effects/moving-average-blur.comp")),
Texture_H => Subject,
others => <>)
do
Result.Uniform_Horizontal := Result.Program_Blur.Uniform ("horizontal");
Result.Program_Blur.Uniform ("radius").Set_Int (Radius);
Result.Texture_V.Allocate_Storage (Subject);
declare
Work_Group_Size : constant GL.Types.Single :=
GL.Types.Single (Result.Program_Blur.Compute_Work_Group_Size (X));
begin
Result.Columns := GL.Types.UInt
(GL.Types.Single'Ceiling (GL.Types.Single (Width) / Work_Group_Size));
Result.Rows := GL.Types.UInt
(GL.Types.Single'Ceiling (GL.Types.Single (Height) / Work_Group_Size));
end;
end return;
end Create_Filter;
procedure Render (Object : in out Moving_Average_Filter; Passes : Positive := 2) is
begin
Object.Program_Blur.Use_Program;
for Pass in 1 .. Passes loop
-- Horizontal pass: Texture_H => Texture_V
Object.Uniform_Horizontal.Set_Boolean (True);
Orka.Rendering.Textures.Bind (Object.Texture_H, Orka.Rendering.Textures.Texture, 0);
Orka.Rendering.Textures.Bind (Object.Texture_V, Orka.Rendering.Textures.Image, 1);
GL.Compute.Dispatch_Compute (X => Object.Rows);
GL.Barriers.Memory_Barrier
((Shader_Image_Access | Texture_Fetch => True, others => False));
-- Vertical pass: Texture_V => Texture_H
Object.Uniform_Horizontal.Set_Boolean (False);
Orka.Rendering.Textures.Bind (Object.Texture_V, Orka.Rendering.Textures.Texture, 0);
Orka.Rendering.Textures.Bind (Object.Texture_H, Orka.Rendering.Textures.Image, 1);
GL.Compute.Dispatch_Compute (X => Object.Columns);
GL.Barriers.Memory_Barrier
((Shader_Image_Access | Texture_Fetch => True, others => False));
end loop;
end Render;
end Orka.Rendering.Effects.Filters;
|
-----------------------------------------------------------------------
-- ADO Parameters -- Parameters for queries
-- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Calendar;
with Ada.Containers.Indefinite_Vectors;
with ADO.Utils;
with ADO.Drivers.Dialects;
-- Defines a list of parameters for an SQL statement.
--
package ADO.Parameters is
use Ada.Strings.Unbounded;
type Token is new String;
type Parameter_Type is (T_NULL, T_STRING, T_TOKEN, T_LIST, T_DATE, T_LONG_INTEGER,
T_INTEGER, T_BOOLEAN, T_BLOB);
type Parameter (T : Parameter_Type;
Len : Natural;
Value_Len : Natural) is record
Position : Natural := 0;
Name : String (1 .. Len);
case T is
when T_NULL =>
null;
when T_LONG_INTEGER =>
Long_Num : Long_Long_Integer := 0;
when T_INTEGER =>
Num : Integer;
when T_BOOLEAN =>
Bool : Boolean;
when T_DATE =>
Time : Ada.Calendar.Time;
when T_BLOB =>
Data : ADO.Blob_Ref;
when others =>
Str : String (1 .. Value_Len);
end case;
end record;
type Abstract_List is abstract new Ada.Finalization.Controlled with private;
type Abstract_List_Access is access all Abstract_List'Class;
-- Set the SQL dialect description object.
procedure Set_Dialect (Params : in out Abstract_List;
D : in ADO.Drivers.Dialects.Dialect_Access);
-- Get the SQL dialect description object.
function Get_Dialect (From : in Abstract_List) return ADO.Drivers.Dialects.Dialect_Access;
-- Add the parameter in the list.
procedure Add_Parameter (Params : in out Abstract_List;
Param : in Parameter) is abstract;
-- Set the parameters from another parameter list.
procedure Set_Parameters (Parameters : in out Abstract_List;
From : in Abstract_List'Class) is abstract;
-- Return the number of parameters in the list.
function Length (Params : in Abstract_List) return Natural is abstract;
-- Return the parameter at the given position
function Element (Params : in Abstract_List;
Position : in Natural) return Parameter is abstract;
-- Execute the <b>Process</b> procedure with the given parameter as argument.
procedure Query_Element (Params : in Abstract_List;
Position : in Natural;
Process : not null access
procedure (Element : in Parameter)) is abstract;
-- Clear the list of parameters.
procedure Clear (Parameters : in out Abstract_List) is abstract;
-- Operations to bind a parameter
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Boolean);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Long_Long_Integer);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Identifier);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Integer);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in ADO.Entity_Type);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in String);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Unbounded_String);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Ada.Calendar.Time);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in Token);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in ADO.Blob_Ref);
procedure Bind_Param (Params : in out Abstract_List;
Name : in String;
Value : in ADO.Utils.Identifier_Vector);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Boolean);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Long_Long_Integer);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Identifier);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Integer);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Entity_Type);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in String);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Unbounded_String);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in Ada.Calendar.Time);
procedure Bind_Param (Params : in out Abstract_List;
Position : in Natural;
Value : in ADO.Blob_Ref);
procedure Bind_Null_Param (Params : in out Abstract_List;
Position : in Natural);
procedure Bind_Null_Param (Params : in out Abstract_List;
Name : in String);
procedure Add_Param (Params : in out Abstract_List;
Value : in Boolean);
procedure Add_Param (Params : in out Abstract_List;
Value : in Long_Long_Integer);
procedure Add_Param (Params : in out Abstract_List;
Value : in Identifier);
procedure Add_Param (Params : in out Abstract_List;
Value : in Integer);
procedure Add_Param (Params : in out Abstract_List;
Value : in String);
procedure Add_Param (Params : in out Abstract_List;
Value : in Unbounded_String);
procedure Add_Param (Params : in out Abstract_List;
Value : in Ada.Calendar.Time);
-- Add a null parameter.
procedure Add_Null_Param (Params : in out Abstract_List);
-- Expand the SQL string with the query parameters. The following parameters syntax
-- are recognized and replaced:
-- <ul>
-- <li>? is replaced according to the current parameter index. The index is incremented
-- after each occurrence of ? character.
-- <li>:nnn is replaced by the parameter at index <b>nnn</b>.
-- <li>:name is replaced by the parameter with the name <b>name</b>
-- </ul>
-- Parameter strings are escaped. When a parameter is not found, an empty string is used.
-- Returns the expanded SQL string.
function Expand (Params : in Abstract_List'Class;
SQL : in String) return String;
-- ------------------------------
-- List of parameters
-- ------------------------------
-- The <b>List</b> is an implementation of the parameter list.
type List is new Abstract_List with private;
procedure Add_Parameter (Params : in out List;
Param : in Parameter);
procedure Set_Parameters (Params : in out List;
From : in Abstract_List'Class);
-- Return the number of parameters in the list.
function Length (Params : in List) return Natural;
-- Return the parameter at the given position
function Element (Params : in List;
Position : in Natural) return Parameter;
-- Execute the <b>Process</b> procedure with the given parameter as argument.
procedure Query_Element (Params : in List;
Position : in Natural;
Process : not null access procedure (Element : in Parameter));
-- Clear the list of parameters.
procedure Clear (Params : in out List);
private
package Parameter_Vectors is
new Ada.Containers.Indefinite_Vectors (Index_Type => Positive,
Element_Type => Parameter);
type Abstract_List is abstract new Ada.Finalization.Controlled with record
Dialect : ADO.Drivers.Dialects.Dialect_Access := null;
end record;
type List is new Abstract_List with record
Params : Parameter_Vectors.Vector;
end record;
end ADO.Parameters;
|
-----------------------------------------------------------------------
-- security-oauth -- OAuth Security
-- Copyright (C) 2012, 2013 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.Numerics.Discrete_Random;
with Interfaces;
with Ada.Streams;
with Util.Log.Loggers;
with Util.Strings;
with Util.Http.Clients;
with Util.Properties.JSON;
with Util.Encoders.Base64;
with Util.Encoders.HMAC.SHA1;
-- The <b>Security.OAuth.Clients</b> package implements the client OAuth 2.0 authorization.
--
-- Note: OAuth 1.0 could be implemented but since it's being deprecated it's not worth doing it.
package body Security.OAuth.Clients is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.Clients");
-- ------------------------------
-- Access Token
-- ------------------------------
package Id_Random is new Ada.Numerics.Discrete_Random (Interfaces.Unsigned_32);
protected type Random is
procedure Generate (Into : out Ada.Streams.Stream_Element_Array);
private
-- Random number generator used for ID generation.
Random : Id_Random.Generator;
end Random;
protected body Random is
procedure Generate (Into : out Ada.Streams.Stream_Element_Array) is
use Ada.Streams;
use Interfaces;
Size : constant Ada.Streams.Stream_Element_Offset := Into'Last / 4;
begin
-- Generate the random sequence.
for I in 0 .. Size loop
declare
Value : constant Unsigned_32 := Id_Random.Random (Random);
begin
Into (4 * I) := Stream_Element (Value and 16#0FF#);
Into (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#);
Into (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#);
Into (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#);
end;
end loop;
end Generate;
end Random;
Random_Generator : Random;
-- ------------------------------
-- Generate a random nonce with at last the number of random bits.
-- The number of bits is rounded up to a multiple of 32.
-- The random bits are then converted to base64url in the returned string.
-- ------------------------------
function Create_Nonce (Bits : in Positive := 256) return String is
use type Ada.Streams.Stream_Element_Offset;
Rand_Count : constant Ada.Streams.Stream_Element_Offset
:= Ada.Streams.Stream_Element_Offset (4 * ((Bits + 31) / 32));
Rand : Ada.Streams.Stream_Element_Array (0 .. Rand_Count - 1);
Buffer : Ada.Streams.Stream_Element_Array (0 .. Rand_Count * 3);
Encoder : Util.Encoders.Base64.Encoder;
Last : Ada.Streams.Stream_Element_Offset;
Encoded : Ada.Streams.Stream_Element_Offset;
begin
-- Generate the random sequence.
Random_Generator.Generate (Rand);
-- Encode the random stream in base64url and save it into the result string.
Encoder.Set_URL_Mode (True);
Encoder.Transform (Data => Rand, Into => Buffer,
Last => Last, Encoded => Encoded);
declare
Result : String (1 .. Natural (Encoded + 1));
begin
for I in 0 .. Encoded loop
Result (Natural (I + 1)) := Character'Val (Buffer (I));
end loop;
return Result;
end;
end Create_Nonce;
-- ------------------------------
-- Get the principal name. This is the OAuth access token.
-- ------------------------------
function Get_Name (From : in Access_Token) return String is
begin
return From.Access_Id;
end Get_Name;
-- ------------------------------
-- Get the id_token that was returned by the authentication process.
-- ------------------------------
function Get_Id_Token (From : in OpenID_Token) return String is
begin
return From.Id_Token;
end Get_Id_Token;
-- ------------------------------
-- Get the application identifier.
-- ------------------------------
function Get_Application_Identifier (App : in Application) return String is
begin
return Ada.Strings.Unbounded.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
use Ada.Strings.Unbounded;
begin
App.Client_Id := To_Unbounded_String (Client);
App.Protect := App.Client_Id & App.Callback;
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 := Ada.Strings.Unbounded.To_Unbounded_String (Secret);
App.Key := App.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
use Ada.Strings.Unbounded;
begin
App.Callback := To_Unbounded_String (URI);
App.Protect := App.Client_Id & App.Callback;
end Set_Application_Callback;
-- ------------------------------
-- Set the OAuth authorization server URI that the application must use
-- to exchange the OAuth code into an access token.
-- ------------------------------
procedure Set_Provider_URI (App : in out Application;
URI : in String) is
begin
App.Request_URI := Ada.Strings.Unbounded.To_Unbounded_String (URI);
end Set_Provider_URI;
-- ------------------------------
-- Build a unique opaque value used to prevent cross-site request forgery.
-- The <b>Nonce</b> parameters is an optional but recommended unique value
-- used only once. The state value will be returned back by the OAuth provider.
-- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters.
-- ------------------------------
function Get_State (App : in Application;
Nonce : in String) return String is
use Ada.Strings.Unbounded;
Data : constant String := Nonce & To_String (App.Protect);
Hmac : String := Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => To_String (App.Key),
Data => Data,
URL => True);
begin
-- Avoid the '=' at end of HMAC since it could be replaced by %C20 which is annoying...
Hmac (Hmac'Last) := '.';
return Hmac;
end Get_State;
-- ------------------------------
-- Get the authenticate parameters to build the URI to redirect the user to
-- the OAuth authorization form.
-- ------------------------------
function Get_Auth_Params (App : in Application;
State : in String;
Scope : in String := "") return String is
begin
return Security.OAuth.Client_Id
& "=" & Ada.Strings.Unbounded.To_String (App.Client_Id)
& "&"
& Security.OAuth.Redirect_Uri
& "=" & Ada.Strings.Unbounded.To_String (App.Callback)
& "&"
& Security.OAuth.Scope
& "=" & Scope
& "&"
& Security.OAuth.State
& "=" & State;
end Get_Auth_Params;
-- ------------------------------
-- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b>
-- operation with the given client and redirect URL.
-- ------------------------------
function Is_Valid_State (App : in Application;
Nonce : in String;
State : in String) return Boolean is
Hmac : constant String := Application'Class (App).Get_State (Nonce);
begin
return Hmac = State;
end Is_Valid_State;
-- ------------------------------
-- Exchange the OAuth code into an access token.
-- ------------------------------
function Request_Access_Token (App : in Application;
Code : in String) return Access_Token_Access is
Client : Util.Http.Clients.Client;
Response : Util.Http.Clients.Response;
Data : constant String
:= Security.OAuth.Grant_Type & "=authorization_code"
& "&"
& Security.OAuth.Code & "=" & Code
& "&"
& Security.OAuth.Redirect_Uri & "=" & Ada.Strings.Unbounded.To_String (App.Callback)
& "&"
& Security.OAuth.Client_Id & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id)
& "&"
& Security.OAuth.Client_Secret & "=" & Ada.Strings.Unbounded.To_String (App.Secret);
URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI);
begin
Log.Info ("Getting access token from {0}", URI);
Client.Post (URL => URI,
Data => Data,
Reply => Response);
if Response.Get_Status /= Util.Http.SC_OK then
Log.Warn ("Cannot get access token from {0}: status is {1} Body {2}",
URI, Natural'Image (Response.Get_Status), Response.Get_Body);
return null;
end if;
-- Decode the response.
declare
Content : constant String := Response.Get_Body;
Content_Type : constant String := Response.Get_Header ("Content-Type");
Pos : Natural := Util.Strings.Index (Content_Type, ';');
Last : Natural;
Expires : Natural;
begin
if Pos = 0 then
Pos := Content_Type'Last;
else
Pos := Pos - 1;
end if;
Log.Debug ("Content type: {0}", Content_Type);
Log.Debug ("Data: {0}", Content);
-- Facebook sends the access token as a 'text/plain' content.
if Content_Type (Content_Type'First .. Pos) = "text/plain" then
Pos := Util.Strings.Index (Content, '=');
if Pos = 0 then
Log.Error ("Invalid access token response: '{0}'", Content);
return null;
end if;
if Content (Content'First .. Pos) /= "access_token=" then
Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content);
return null;
end if;
Last := Util.Strings.Index (Content, '&', Pos + 1);
if Last = 0 then
Log.Error ("Invalid 'access_token' parameter: '{0}'", Content);
return null;
end if;
if Content (Last .. Last + 8) /= "&expires=" then
Log.Error ("Invalid 'expires' parameter: '{0}'", Content);
return null;
end if;
Expires := Natural'Value (Content (Last + 9 .. Content'Last));
return Application'Class (App).Create_Access_Token (Content (Pos + 1 .. Last - 1),
"", "",
Expires);
elsif Content_Type (Content_Type'First .. Pos) = "application/json" then
declare
P : Util.Properties.Manager;
begin
Util.Properties.JSON.Parse_JSON (P, Content);
Expires := Natural'Value (P.Get ("expires_in"));
return Application'Class (App).Create_Access_Token (P.Get ("access_token"),
P.Get ("refresh_token", ""),
P.Get ("id_token", ""),
Expires);
end;
else
Log.Error ("Content type {0} not supported for access token response", Content_Type);
Log.Error ("Response: {0}", Content);
return null;
end if;
end;
end Request_Access_Token;
-- ------------------------------
-- Create the access token
-- ------------------------------
function Create_Access_Token (App : in Application;
Token : in String;
Refresh : in String;
Id_Token : in String;
Expires : in Natural) return Access_Token_Access is
pragma Unreferenced (App, Expires);
begin
if Id_Token'Length > 0 then
declare
Result : constant OpenID_Token_Access
:= new OpenID_Token '(Len => Token'Length,
Id_Len => Id_Token'Length,
Refresh_Len => Refresh'Length,
Access_Id => Token,
Id_Token => Id_Token,
Refresh_Token => Refresh);
begin
return Result.all'Access;
end;
else
return new Access_Token '(Len => Token'Length,
Access_Id => Token);
end if;
end Create_Access_Token;
end Security.OAuth.Clients;
|
-- { dg-do compile }
pragma Restrictions (No_Allocators);
procedure Test_BIP_No_Alloc is
type LR (B : Boolean) is limited record
X : Integer;
end record;
function FLR return LR is
begin
-- A return statement in a function with a limited and unconstrained
-- result subtype can result in expansion of an allocator for the
-- secondary stack, but that should not result in a violation of the
-- restriction No_Allocators.
return (B => False, X => 123);
end FLR;
Obj : LR := FLR;
begin
null;
end Test_BIP_No_Alloc;
|
package Corr_Discr is
type Base (T1 : Boolean := True; T2 : Boolean := False)
is null record;
for Base use record
T1 at 0 range 0 .. 0;
T2 at 0 range 1 .. 1;
end record;
type Deriv (D : Boolean := False) is new Base (T1 => True, T2 => D);
end Corr_Discr;
|
-- SPDX-FileCopyrightText: 2019 Max Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-------------------------------------------------------------
with Program.Elements.Representation_Clauses;
with Program.Lexical_Elements;
with Program.Elements.Expressions;
with Program.Elements.Component_Clauses;
package Program.Elements.Record_Representation_Clauses is
pragma Pure (Program.Elements.Record_Representation_Clauses);
type Record_Representation_Clause is
limited interface
and Program.Elements.Representation_Clauses.Representation_Clause;
type Record_Representation_Clause_Access is
access all Record_Representation_Clause'Class with Storage_Size => 0;
not overriding function Name
(Self : Record_Representation_Clause)
return not null Program.Elements.Expressions.Expression_Access
is abstract;
not overriding function Mod_Clause_Expression
(Self : Record_Representation_Clause)
return Program.Elements.Expressions.Expression_Access is abstract;
not overriding function Component_Clauses
(Self : Record_Representation_Clause)
return not null Program.Elements.Component_Clauses
.Component_Clause_Vector_Access is abstract;
type Record_Representation_Clause_Text is limited interface;
type Record_Representation_Clause_Text_Access is
access all Record_Representation_Clause_Text'Class with Storage_Size => 0;
not overriding function To_Record_Representation_Clause_Text
(Self : in out Record_Representation_Clause)
return Record_Representation_Clause_Text_Access is abstract;
not overriding function For_Token
(Self : Record_Representation_Clause_Text)
return not null Program.Lexical_Elements.Lexical_Element_Access
is abstract;
not overriding function Use_Token
(Self : Record_Representation_Clause_Text)
return not null Program.Lexical_Elements.Lexical_Element_Access
is abstract;
not overriding function Record_Token
(Self : Record_Representation_Clause_Text)
return not null Program.Lexical_Elements.Lexical_Element_Access
is abstract;
not overriding function At_Token
(Self : Record_Representation_Clause_Text)
return Program.Lexical_Elements.Lexical_Element_Access is abstract;
not overriding function Mod_Token
(Self : Record_Representation_Clause_Text)
return Program.Lexical_Elements.Lexical_Element_Access is abstract;
not overriding function Mod_Semicolon_Token
(Self : Record_Representation_Clause_Text)
return Program.Lexical_Elements.Lexical_Element_Access is abstract;
not overriding function Semicolon_Token
(Self : Record_Representation_Clause_Text)
return not null Program.Lexical_Elements.Lexical_Element_Access
is abstract;
end Program.Elements.Record_Representation_Clauses;
|
with scanner.DFA; use scanner.DFA;
with Ada.Characters.Wide_Wide_Latin_1;
with Ada.Wide_Wide_Text_IO;
package scanner.IO is
User_Input_File : Ada.Wide_Wide_Text_IO.File_Type;
User_Output_File : Ada.Wide_Wide_Text_IO.File_Type;
Null_In_Input : exception;
Aflex_Internal_Error : exception;
Unexpected_Last_Match : exception;
Pushback_Overflow : exception;
Aflex_Scanner_Jammed : exception;
type EOB_Action_Type is
(EOB_ACT_RESTART_SCAN,
EOB_ACT_END_OF_FILE,
EOB_ACT_LAST_MATCH);
YY_END_OF_BUFFER_CHAR : constant Wide_Wide_Character :=
Ada.Characters.Wide_Wide_Latin_1.NUL;
yy_n_chars : integer; -- number of characters read into yy_ch_buf
-- true when we've seen an EOF for the current input file
yy_eof_has_been_seen : boolean;
procedure YY_Input
(Buf : out Unbounded_Character_Array;
Result : out Integer;
Max_Size : Integer);
function YY_Get_Next_Buffer return EOB_Action_Type;
procedure YYUnput (c : Wide_Wide_Character; YY_BP: in out Integer);
procedure Unput (c : Wide_Wide_Character);
function Input return Wide_Wide_Character;
procedure Output (c : Wide_Wide_Character);
function YYWrap return Boolean;
procedure Open_Input (FName : String);
procedure Close_Input;
procedure Create_Output (FName : String := "");
procedure Close_Output;
end scanner.IO;
|
--
-- This library is free software; you can redistribute it and/or modify
-- it under the terms of the GNU Library General Public License as
-- published by the Free Software Foundation; either version 3 of the
-- License; or (at your option) any later version.
-- Copyright (C) 2002 Leonid Dulman
with gener_builtin;
package builtin is new gener_builtin (varing_max => 255);
|
with Libadalang.Analysis; use Libadalang.Analysis;
with Rejuvenation.Navigation; use Rejuvenation.Navigation;
package Rewriters_Context_Utils is
function Combine_Contexts (C1, C2 : Ada_Node) return Ada_Node
with Pre =>
Is_Reflexive_Ancestor (C1, C2)
or else Is_Reflexive_Ancestor (C2, C1),
Post =>
Is_Reflexive_Ancestor (Combine_Contexts'Result, C1)
and then Is_Reflexive_Ancestor (Combine_Contexts'Result, C2);
end Rewriters_Context_Utils;
|
-------------------------------------------------------------------------------
-- Copyright (c) 2019, Daniel King
-- 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.
-- * The name of the copyright holder may not 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 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 Keccak.Util; use Keccak.Util;
package body Keccak.Generic_Parallel_CSHAKE
is
---------------------------
-- Process_Full_Blocks --
---------------------------
procedure Process_Full_Blocks
(Ctx : in out Context;
Block : in out Types.Byte_Array;
Input : in Types.Byte_Array;
Block_Offset : in out Natural)
with Global => null,
Pre => (Block_Offset < Block'Length
and Block'First = 0
and Block'Length = Rate / 8
and State_Of (Ctx) = Updating),
Post => (Block_Offset < Block'Length
and State_Of (Ctx) = Updating);
---------------------------
-- Process_Full_Blocks --
---------------------------
procedure Process_Full_Blocks
(Ctx : in out Context;
Block : in out Types.Byte_Array;
Input : in Types.Byte_Array;
Block_Offset : in out Natural)
is
use type XOF.States;
Block_Length : constant Natural := Block'Length - Block_Offset;
Input_Remaining : Natural := Input'Length;
Input_Offset : Natural := 0;
Length : Natural;
Num_Full_Blocks : Natural;
Pos : Types.Index_Number;
begin
if Block_Offset > 0 then
-- Merge first bytes of Input with the last bytes currently in
-- the block.
if Input_Remaining < Block_Length then
-- Not enough for a full block.
Block (Block_Offset .. Block_Offset + Input_Remaining - 1) :=
Input (Input'First .. Input'First + Input_Remaining - 1);
Input_Offset := Input'Length;
Block_Offset := Block_Offset + Input_Remaining;
Input_Remaining := 0;
else
-- We have enough for a full block
Block (Block_Offset .. Block'Last) :=
Input (Input'First .. Input'First + Block_Length - 1);
XOF.Update_All (Ctx.XOF_Ctx, Block);
Input_Offset := Input_Offset + Block_Length;
Input_Remaining := Input_Remaining - Block_Length;
Block_Offset := 0;
end if;
end if;
pragma Assert_And_Cut
(Input_Offset + Input_Remaining = Input'Length
and Block_Offset < Block'Length
and Block'Length = Rate / 8
and State_Of (Ctx) = Updating
and XOF.State_Of (Ctx.XOF_Ctx) = XOF.Updating
and (if Input_Remaining > 0 then Block_Offset = 0));
-- Now process as many full blocks from Input as we can.
Num_Full_Blocks := Input_Remaining / Block'Length;
if Num_Full_Blocks > 0 then
Pos := Input'First + Input_Offset;
Length := Num_Full_Blocks * Block'Length;
XOF.Update_All (Ctx.XOF_Ctx, Input (Pos .. Pos + Length - 1));
Input_Offset := Input_Offset + Length;
Input_Remaining := Input_Remaining - Length;
end if;
pragma Assert_And_Cut
(Input_Offset + Input_Remaining = Input'Length
and Block_Offset < Block'Length
and Block'Length = Rate / 8
and State_Of (Ctx) = Updating
and (if Input_Remaining > 0 then Block_Offset = 0)
and Input_Remaining < Block'Length);
-- Store any leftover bytes in the block
if Input_Remaining > 0 then
Pos := Input'First + Input_Offset;
Block (0 .. Input_Remaining - 1) := Input (Pos .. Input'Last);
Block_Offset := Input_Remaining;
end if;
end Process_Full_Blocks;
------------
-- Init --
------------
procedure Init (Ctx : out Context;
Customization : in String;
Function_Name : in String)
is
Rate_Bytes : constant Positive := Rate / 8;
Block : Types.Byte_Array (0 .. Rate_Bytes - 1) := (others => 0);
Block_Offset : Natural;
begin
XOF.Init (Ctx.XOF_Ctx);
-- We need to make sure that the data length for each call to
-- XOF.Update_Separate is a multiple of the rate in order to keep the XOF
-- in the "Updating" state. This requires packing the encoded
-- rate, customization string, and function name into a block which is
-- the length of the rate.
--
-- +------+---------------+---------------+
-- | rate | Function_Name | Customization |
-- +------+---------------+---------------+
-- |<-------------->|
-- Rate
Block_Offset := 0;
Process_Full_Blocks
(Ctx => Ctx,
Block => Block,
Input => Left_Encode_NIST (Rate_Bytes),
Block_Offset => Block_Offset);
Process_Full_Blocks
(Ctx => Ctx,
Block => Block,
Input => Left_Encode_NIST_Bit_Length (Function_Name'Length),
Block_Offset => Block_Offset);
Process_Full_Blocks
(Ctx => Ctx,
Block => Block,
Input => To_Byte_Array (Function_Name),
Block_Offset => Block_Offset);
Process_Full_Blocks
(Ctx => Ctx,
Block => Block,
Input => Left_Encode_NIST_Bit_Length (Customization'Length),
Block_Offset => Block_Offset);
Process_Full_Blocks
(Ctx => Ctx,
Block => Block,
Input => To_Byte_Array (Customization),
Block_Offset => Block_Offset);
if Block_Offset > 0 then
-- Need to add padding zeroes to leftover data
Block (Block_Offset .. Block'Last) := (others => 0);
XOF.Update_All (Ctx.XOF_Ctx, Block);
end if;
end Init;
-----------------------
-- Update_Separate --
-----------------------
procedure Update_Separate (Ctx : in out Context;
Data : in Types.Byte_Array)
is
begin
XOF.Update_Separate (Ctx.XOF_Ctx, Data);
end Update_Separate;
-----------------------
-- Extract_Separate --
-----------------------
procedure Extract_Separate (Ctx : in out Context;
Data : out Types.Byte_Array)
is
begin
XOF.Extract_Separate (Ctx.XOF_Ctx, Data);
end Extract_Separate;
end Keccak.Generic_Parallel_CSHAKE;
|
-- Abstract :
--
-- see spec
--
-- Copyright (C) 2014 - 2019 All Rights Reserved.
--
-- The WisiToken package is free software; you can redistribute it
-- and/or modify it under terms of the GNU General Public License as
-- published by the Free Software Foundation; either version 3, or
-- (at your option) any later version. This library is distributed in
-- the hope that it will be useful, but WITHOUT ANY WARRANTY; without
-- even the implied warranty of MERCHAN- TABILITY or FITNESS FOR A
-- PARTICULAR PURPOSE.
--
-- As a special exception under Section 7 of GPL version 3, you are granted
-- additional permissions described in the GCC Runtime Library Exception,
-- version 3.1, as published by the Free Software Foundation.
pragma License (Modified_GPL);
package body WisiToken.Parse.LR.Parser_Lists is
function Parser_Stack_Image
(Stack : in Parser_Stacks.Stack;
Descriptor : in WisiToken.Descriptor;
Tree : in Syntax_Trees.Tree;
Depth : in SAL.Base_Peek_Type := 0)
return String
is
use all type SAL.Base_Peek_Type;
use Ada.Strings.Unbounded;
Last : constant SAL.Base_Peek_Type :=
(if Depth = 0
then Stack.Depth
else SAL.Base_Peek_Type'Min (Depth, Stack.Depth));
Result : Unbounded_String := +"(";
begin
for I in 1 .. Last loop
declare
use all type WisiToken.Syntax_Trees.Node_Index;
Item : Parser_Stack_Item renames Stack.Peek (I);
begin
Result := Result &
((if Item.State = Unknown_State then " " else Trimmed_Image (Item.State)) & " :" &
(if I = Stack.Depth
then ""
else
(if Item.Token = Syntax_Trees.Invalid_Node_Index -- From recover fast-forward
then ""
else Tree.Image (Item.Token, Descriptor) & ", ")));
end;
end loop;
return To_String (Result & ")");
end Parser_Stack_Image;
function New_List (Shared_Tree : in Syntax_Trees.Base_Tree_Access) return List
is
First_Parser_Label : constant := 0;
Parser : Parser_State := (Label => First_Parser_Label, others => <>);
begin
Parser.Tree.Initialize (Shared_Tree, Flush => True);
return Result : List
do
Result.Parser_Label := First_Parser_Label;
Result.Elements.Append (Parser);
end return;
end New_List;
function Last_Label (List : in Parser_Lists.List) return Natural
is begin
return List.Parser_Label;
end Last_Label;
function Count (List : in Parser_Lists.List) return SAL.Base_Peek_Type
is begin
return List.Elements.Length;
end Count;
function First (List : aliased in out Parser_Lists.List'Class) return Cursor
is begin
return (Elements => List.Elements'Access, Ptr => List.Elements.First);
end First;
procedure Next (Cursor : in out Parser_Lists.Cursor)
is begin
Parser_State_Lists.Next (Cursor.Ptr);
end Next;
function Is_Done (Cursor : in Parser_Lists.Cursor) return Boolean
is
use Parser_State_Lists;
begin
return Cursor.Ptr = No_Element;
end Is_Done;
function Active_Parser_Count (Cursor : in Parser_Lists.Cursor) return SAL.Base_Peek_Type
is begin
return Cursor.Elements.Length;
end Active_Parser_Count;
function Label (Cursor : in Parser_Lists.Cursor) return Natural
is begin
return Parser_State_Lists.Constant_Reference (Cursor.Ptr).Label;
end Label;
function Total_Recover_Cost (Cursor : in Parser_Lists.Cursor) return Integer
is
Result : Integer := 0;
begin
for Error of Parser_State_Lists.Constant_Reference (Cursor.Ptr).Errors loop
Result := Error.Recover.Cost;
end loop;
return Result;
end Total_Recover_Cost;
function Max_Recover_Ops_Length (Cursor : in Parser_Lists.Cursor) return Ada.Containers.Count_Type
is
use Ada.Containers;
Result : Count_Type := 0;
Errors : Parse_Error_Lists.List renames Parser_State_Lists.Constant_Reference (Cursor.Ptr).Errors;
begin
for Error of Errors loop
if Error.Recover.Ops.Length > Result then
Result := Error.Recover.Ops.Length;
end if;
end loop;
return Result;
end Max_Recover_Ops_Length;
function Min_Recover_Cost (Cursor : in Parser_Lists.Cursor) return Integer
is
Result : Integer := Integer'Last;
Errors : Parse_Error_Lists.List renames Parser_State_Lists.Constant_Reference (Cursor.Ptr).Errors;
begin
for Error of Errors loop
if Error.Recover.Cost < Result then
Result := Error.Recover.Cost;
end if;
end loop;
return Result;
end Min_Recover_Cost;
procedure Set_Verb (Cursor : in Parser_Lists.Cursor; Verb : in All_Parse_Action_Verbs)
is begin
Parser_State_Lists.Reference (Cursor.Ptr).Verb := Verb;
end Set_Verb;
function Verb (Cursor : in Parser_Lists.Cursor) return All_Parse_Action_Verbs
is begin
return Parser_State_Lists.Constant_Reference (Cursor.Ptr).Verb;
end Verb;
procedure Terminate_Parser
(Parsers : in out List;
Current : in out Cursor'Class;
Message : in String;
Trace : in out WisiToken.Trace'Class;
Terminals : in Base_Token_Arrays.Vector)
is
use all type SAL.Base_Peek_Type;
State : Parser_State renames Parser_State_Lists.Constant_Reference (Current.Ptr).Element.all;
begin
if Trace_Parse > Outline then
Trace.Put_Line
(Integer'Image (Current.Label) & ": terminate (" &
Trimmed_Image (Integer (Parsers.Count) - 1) & " active)" &
": " & Message & Image
(State.Tree.Min_Terminal_Index (State.Current_Token),
Terminals, Trace.Descriptor.all));
end if;
Current.Free;
if Parsers.Count = 1 then
Parsers.First.State_Ref.Tree.Flush;
end if;
end Terminate_Parser;
procedure Duplicate_State
(Parsers : in out List;
Current : in out Cursor'Class;
Trace : in out WisiToken.Trace'Class;
Terminals : in Base_Token_Arrays.Vector)
is
use all type SAL.Base_Peek_Type;
use all type Ada.Containers.Count_Type;
function Compare
(Stack_1 : in Parser_Stacks.Stack;
Tree_1 : in Syntax_Trees.Tree;
Stack_2 : in Parser_Stacks.Stack;
Tree_2 : in Syntax_Trees.Tree)
return Boolean
is
begin
if Stack_1.Depth /= Stack_2.Depth then
return False;
else
for I in reverse 1 .. Stack_1.Depth - 1 loop
-- Assume they differ near the top; no point in comparing bottom
-- item. The syntax trees will differ even if the tokens on the stack
-- are the same, so compare the tokens.
declare
Item_1 : Parser_Stack_Item renames Stack_1 (I);
Item_2 : Parser_Stack_Item renames Stack_2 (I);
begin
if Item_1.State /= Item_2.State then
return False;
else
if not Syntax_Trees.Same_Token (Tree_1, Item_1.Token, Tree_2, Item_2.Token) then
return False;
end if;
end if;
end;
end loop;
return True;
end if;
end Compare;
Other : Cursor := Parsers.First;
begin
loop
exit when Other.Is_Done;
declare
Other_Parser : Parser_State renames Other.State_Ref;
begin
if Other.Label /= Current.Label and then
Other.Verb /= Error and then
Compare
(Other_Parser.Stack, Other_Parser.Tree, Current.State_Ref.Stack, Current.State_Ref.Tree)
then
exit;
end if;
end;
Other.Next;
end loop;
if not Other.Is_Done then
-- Both have the same number of errors, otherwise one would have been
-- terminated earlier.
if Other.Total_Recover_Cost = Current.Total_Recover_Cost then
if Other.Max_Recover_Ops_Length = Current.Max_Recover_Ops_Length then
Parsers.Terminate_Parser (Other, "duplicate state: random", Trace, Terminals);
else
if Other.Max_Recover_Ops_Length > Current.Max_Recover_Ops_Length then
null;
else
Other := Cursor (Current);
Current.Next;
end if;
Parsers.Terminate_Parser (Other, "duplicate state: ops length", Trace, Terminals);
end if;
else
if Other.Total_Recover_Cost > Current.Total_Recover_Cost then
null;
else
Other := Cursor (Current);
Current.Next;
end if;
Parsers.Terminate_Parser (Other, "duplicate state: cost", Trace, Terminals);
end if;
end if;
end Duplicate_State;
function State_Ref (Position : in Cursor) return State_Reference
is begin
return (Element => Parser_State_Lists.Constant_Reference (Position.Ptr).Element);
end State_Ref;
function First_State_Ref (List : in Parser_Lists.List'Class) return State_Reference
is begin
return (Element => Parser_State_Lists.Constant_Reference (List.Elements.First).Element);
end First_State_Ref;
function First_Constant_State_Ref (List : in Parser_Lists.List'Class) return Constant_State_Reference
is begin
return (Element => Parser_State_Lists.Constant_Reference (List.Elements.First).Element);
end First_Constant_State_Ref;
procedure Put_Top_10 (Trace : in out WisiToken.Trace'Class; Cursor : in Parser_Lists.Cursor)
is
Parser_State : Parser_Lists.Parser_State renames Parser_State_Lists.Constant_Reference (Cursor.Ptr);
begin
Trace.Put (Natural'Image (Parser_State.Label) & " stack: ");
Trace.Put_Line (Image (Parser_State.Stack, Trace.Descriptor.all, Parser_State.Tree, Depth => 10));
end Put_Top_10;
procedure Prepend_Copy
(List : in out Parser_Lists.List;
Cursor : in Parser_Lists.Cursor'Class)
is
New_Item : Parser_State;
begin
List.Parser_Label := List.Parser_Label + 1;
declare
Item : Parser_State renames Parser_State_Lists.Reference (Cursor.Ptr).Element.all;
-- We can't do 'Prepend' in the scope of this 'renames';
-- that would be tampering with cursors.
begin
Item.Tree.Set_Flush_False;
-- We specify all items individually, rather copy Item and then
-- override a few, to avoid copying large items like Recover.
-- We copy Recover.Enqueue_Count .. Check_Count for unit tests.
New_Item :=
(Shared_Token => Item.Shared_Token,
Recover_Insert_Delete => Item.Recover_Insert_Delete,
Prev_Deleted => Item.Prev_Deleted,
Current_Token => Item.Current_Token,
Inc_Shared_Token => Item.Inc_Shared_Token,
Stack => Item.Stack,
Tree => Item.Tree,
Recover =>
(Enqueue_Count => Item.Recover.Enqueue_Count,
Config_Full_Count => Item.Recover.Config_Full_Count,
Check_Count => Item.Recover.Check_Count,
others => <>),
Resume_Active => Item.Resume_Active,
Resume_Token_Goal => Item.Resume_Token_Goal,
Conflict_During_Resume => Item.Conflict_During_Resume,
Zombie_Token_Count => 0,
Errors => Item.Errors,
Label => List.Parser_Label,
Verb => Item.Verb);
end;
List.Elements.Prepend (New_Item);
end Prepend_Copy;
procedure Free (Cursor : in out Parser_Lists.Cursor'Class)
is
Temp : Parser_State_Lists.Cursor := Cursor.Ptr;
begin
Parser_State_Lists.Next (Cursor.Ptr);
Parser_State_Lists.Delete (Cursor.Elements.all, Temp);
end Free;
----------
-- stuff for iterators
function To_Cursor (Ptr : in Parser_Node_Access) return Cursor
is begin
return (Ptr.Elements, Ptr.Ptr);
end To_Cursor;
function Constant_Reference
(Container : aliased in List'Class;
Position : in Parser_Node_Access)
return Constant_Reference_Type
is
pragma Unreferenced (Container);
begin
return (Element => Parser_State_Lists.Constant_Reference (Position.Ptr).Element);
end Constant_Reference;
function Reference
(Container : aliased in out List'Class;
Position : in Parser_Node_Access)
return State_Reference
is
pragma Unreferenced (Container);
begin
return (Element => Parser_State_Lists.Reference (Position.Ptr).Element);
end Reference;
function Persistent_State_Ref (Position : in Parser_Node_Access) return State_Access
is begin
return State_Access (Parser_State_Lists.Persistent_Ref (Position.Ptr));
end Persistent_State_Ref;
type List_Access is access all List;
type Iterator is new Iterator_Interfaces.Forward_Iterator with record
Container : List_Access;
end record;
overriding function First (Object : Iterator) return Parser_Node_Access;
overriding function Next
(Object : in Iterator;
Position : in Parser_Node_Access)
return Parser_Node_Access;
overriding function First (Object : Iterator) return Parser_Node_Access
is begin
return (Elements => Object.Container.Elements'Access, Ptr => Object.Container.Elements.First);
end First;
overriding function Next
(Object : in Iterator;
Position : in Parser_Node_Access)
return Parser_Node_Access
is
pragma Unreferenced (Object);
begin
return (Position.Elements, Parser_State_Lists.Next (Position.Ptr));
end Next;
function Iterate (Container : aliased in out List) return Iterator_Interfaces.Forward_Iterator'Class
is begin
return Iterator'(Container => Container'Access);
end Iterate;
function Has_Element (Iterator : in Parser_Node_Access) return Boolean
is begin
return Parser_State_Lists.Has_Element (Iterator.Ptr);
end Has_Element;
function Label (Iterator : in Parser_State) return Natural
is begin
return Iterator.Label;
end Label;
function Verb (Iterator : in Parser_State) return All_Parse_Action_Verbs
is begin
return Iterator.Verb;
end Verb;
procedure Set_Verb (Iterator : in out Parser_State; Verb : in All_Parse_Action_Verbs)
is begin
Iterator.Verb := Verb;
end Set_Verb;
end WisiToken.Parse.LR.Parser_Lists;
|
with
Glib,
glib.Error,
gtk.Builder,
gtk.Handlers;
package body aIDE.Editor.of_subprogram
is
use gtk.Builder,
Glib,
glib.Error;
function on_name_Entry_leave (the_Entry : access Gtk_Entry_Record'Class;
Self : in aIDE.Editor.of_subprogram.view) return Boolean
is
the_Text : constant String := the_Entry.Get_Text;
begin
Self.Subprogram.Name_is (the_Text);
return False;
end on_name_Entry_leave;
package Entry_return_Callbacks is new Gtk.Handlers.User_Return_Callback (Gtk_Entry_Record,
Boolean,
aIDE.Editor.of_subprogram.view);
function on_procedure_Label_clicked (the_Label : access Gtk_Label_Record'Class;
Self : in aIDE.Editor.of_subprogram.view) return Boolean
is
begin
return False;
end on_procedure_Label_clicked;
package Label_return_Callbacks is new Gtk.Handlers.User_Return_Callback (Gtk_Label_Record,
Boolean,
aIDE.Editor.of_subprogram.view);
package body Forge
is
function to_subprogram_Editor (the_Subprogram : in AdaM.Subprogram.view) return View
is
Self : constant Editor.of_subprogram.view := new Editor.of_subprogram.item;
the_Builder : Gtk_Builder;
Error : aliased GError;
Result : Guint;
pragma Unreferenced (Result);
begin
Gtk_New (the_Builder);
Result := the_Builder.Add_From_File ("glade/editor/subprogram_editor.glade", Error'Access);
if Error /= null then
Error_Free (Error);
end if;
Self.top_Box := gtk_Box (the_Builder.get_Object ("top_Box"));
Self.block_Alignment := gtk_Alignment (the_Builder.get_Object ("block_Alignment"));
Self.context_Alignment := gtk_Alignment (the_Builder.get_Object ("context_Alignment"));
Self.procedure_Label := gtk_Label (the_Builder.get_Object ("procedure_Label"));
Self.name_Entry := gtk_Entry (the_Builder.get_Object ("name_Entry"));
Entry_return_Callbacks.Connect (Self.name_Entry,
"focus-out-event",
on_name_Entry_leave'Access,
Self);
Label_return_Callbacks.Connect (Self.procedure_Label,
"button-release-event",
on_procedure_Label_clicked'Access,
Self);
Self.Subprogram := the_Subprogram;
Self.context_Editor := aIDE.Editor.of_context.Forge.to_context_Editor (Self.Subprogram.Context);
Self.context_Editor.top_Widget.Reparent (new_Parent => Self.context_Alignment);
Self.block_Editor := aIDE.Editor.of_block.Forge.to_block_Editor (Self.Subprogram.Block);
Self.block_Editor.top_Widget.Reparent (new_Parent => Self.block_Alignment);
Self.freshen;
return Self;
end to_subprogram_Editor;
end Forge;
overriding
procedure freshen (Self : in out Item)
is
use AdaM;
begin
Self.name_Entry.Set_Text (+Self.Subprogram.Name);
Self.context_Editor.Context_is (Self.Subprogram.Context);
Self. block_Editor.Target_is (Self.Subprogram.Block);
end freshen;
function Target (Self : in Item) return AdaM.Subprogram.view
is
begin
return Self.Subprogram;
end Target;
procedure Target_is (Self : in out Item; Now : in AdaM.Subprogram.view)
is
begin
Self.Subprogram := Now;
Self.freshen;
end Target_is;
overriding function top_Widget (Self : in Item) return gtk.Widget.Gtk_Widget
is
begin
return gtk.Widget.Gtk_Widget (Self.top_Box);
end top_Widget;
end aIDE.Editor.of_subprogram;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.