content stringlengths 23 1.05M |
|---|
with DOM.Core;
package XML_Utilities is
function Parse_String (Item : String) return DOM.Core.Document;
--
-- If node N has the given attribute, return its value otherwise raise
-- No_such_Attribute
--
function Expect_Attribute (N : DOM.Core.Node; Name : String) return String;
--
-- Return True if the node has the given attribute
--
function Has_Attribute (N : DOM.Core.Node; Name : String) return Boolean;
--
-- If node N has the given attribute, return its value otherwise return
-- the default value
--
function Get_Attribute (N : DOM.Core.Node;
Name : String;
Default : String := "")
return String;
No_Such_Attribute : exception;
end XML_Utilities;
|
-- part of AdaYaml, (c) 2017 Felix Krause
-- released under the terms of the MIT license, see the file "copying.txt"
with System;
with Yaml.C;
package Lexer.Source.C_Handler is
type Instance is new Source.Instance with private;
overriding procedure Read_Data (S : in out Instance; Buffer : out String;
Length : out Natural);
function As_Source (Data : System.Address; Handler : Yaml.C.Read_Handler)
return Pointer;
private
type Instance is new Source.Instance with record
Handler : Yaml.C.Read_Handler;
Data : System.Address;
end record;
end Lexer.Source.C_Handler;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S C N . N L I T --
-- --
-- B o d y --
-- --
-- $Revision$
-- --
-- Copyright (C) 1992-2001 Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
-- MA 02111-1307, USA. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Uintp; use Uintp;
with Urealp; use Urealp;
separate (Scn)
procedure Nlit is
C : Character;
-- Current source program character
Base_Char : Character;
-- Either # or : (character at start of based number)
Base : Int;
-- Value of base
UI_Base : Uint;
-- Value of base in Uint format
UI_Int_Value : Uint;
-- Value of integer scanned by Scan_Integer in Uint format
UI_Num_Value : Uint;
-- Value of integer in numeric value being scanned
Scale : Int;
-- Scale value for real literal
UI_Scale : Uint;
-- Scale in Uint format
Exponent_Is_Negative : Boolean;
-- Set true for negative exponent
Extended_Digit_Value : Int;
-- Extended digit value
Point_Scanned : Boolean;
-- Flag for decimal point scanned in numeric literal
-----------------------
-- Local Subprograms --
-----------------------
procedure Error_Digit_Expected;
-- Signal error of bad digit, Scan_Ptr points to the location at which
-- the digit was expected on input, and is unchanged on return.
procedure Scan_Integer;
-- Procedure to scan integer literal. On entry, Scan_Ptr points to a
-- digit, on exit Scan_Ptr points past the last character of the integer.
-- For each digit encountered, UI_Int_Value is multiplied by 10, and the
-- value of the digit added to the result. In addition, the value in
-- Scale is decremented by one for each actual digit scanned.
--------------------------
-- Error_Digit_Expected --
--------------------------
procedure Error_Digit_Expected is
begin
Error_Msg_S ("digit expected");
end Error_Digit_Expected;
-------------------
-- Scan_Integer --
-------------------
procedure Scan_Integer is
C : Character;
-- Next character scanned
begin
C := Source (Scan_Ptr);
-- Loop through digits (allowing underlines)
loop
Accumulate_Checksum (C);
UI_Int_Value :=
UI_Int_Value * 10 + (Character'Pos (C) - Character'Pos ('0'));
Scan_Ptr := Scan_Ptr + 1;
Scale := Scale - 1;
C := Source (Scan_Ptr);
if C = '_' then
Accumulate_Checksum ('_');
loop
Scan_Ptr := Scan_Ptr + 1;
C := Source (Scan_Ptr);
exit when C /= '_';
Error_No_Double_Underline;
end loop;
if C not in '0' .. '9' then
Error_Digit_Expected;
exit;
end if;
else
exit when C not in '0' .. '9';
end if;
end loop;
end Scan_Integer;
----------------------------------
-- Start of Processing for Nlit --
----------------------------------
begin
Base := 10;
UI_Base := Uint_10;
UI_Int_Value := Uint_0;
Scale := 0;
Scan_Integer;
Scale := 0;
Point_Scanned := False;
UI_Num_Value := UI_Int_Value;
-- Various possibilities now for continuing the literal are
-- period, E/e (for exponent), or :/# (for based literal).
Scale := 0;
C := Source (Scan_Ptr);
if C = '.' then
-- Scan out point, but do not scan past .. which is a range sequence,
-- and must not be eaten up scanning a numeric literal.
while C = '.' and then Source (Scan_Ptr + 1) /= '.' loop
Accumulate_Checksum ('.');
if Point_Scanned then
Error_Msg_S ("duplicate point ignored");
end if;
Point_Scanned := True;
Scan_Ptr := Scan_Ptr + 1;
C := Source (Scan_Ptr);
if C not in '0' .. '9' then
Error_Msg ("real literal cannot end with point", Scan_Ptr - 1);
else
Scan_Integer;
UI_Num_Value := UI_Int_Value;
end if;
end loop;
-- Based literal case. The base is the value we already scanned.
-- In the case of colon, we insist that the following character
-- is indeed an extended digit or a period. This catches a number
-- of common errors, as well as catching the well known tricky
-- bug otherwise arising from "x : integer range 1 .. 10:= 6;"
elsif C = '#'
or else (C = ':' and then
(Source (Scan_Ptr + 1) = '.'
or else
Source (Scan_Ptr + 1) in '0' .. '9'
or else
Source (Scan_Ptr + 1) in 'A' .. 'Z'
or else
Source (Scan_Ptr + 1) in 'a' .. 'z'))
then
Accumulate_Checksum (C);
Base_Char := C;
UI_Base := UI_Int_Value;
if UI_Base < 2 or else UI_Base > 16 then
Error_Msg_SC ("base not 2-16");
UI_Base := Uint_16;
end if;
Base := UI_To_Int (UI_Base);
Scan_Ptr := Scan_Ptr + 1;
-- Scan out extended integer [. integer]
C := Source (Scan_Ptr);
UI_Int_Value := Uint_0;
Scale := 0;
loop
if C in '0' .. '9' then
Accumulate_Checksum (C);
Extended_Digit_Value :=
Int'(Character'Pos (C)) - Int'(Character'Pos ('0'));
elsif C in 'A' .. 'F' then
Accumulate_Checksum (Character'Val (Character'Pos (C) + 32));
Extended_Digit_Value :=
Int'(Character'Pos (C)) - Int'(Character'Pos ('A')) + 10;
elsif C in 'a' .. 'f' then
Accumulate_Checksum (C);
Extended_Digit_Value :=
Int'(Character'Pos (C)) - Int'(Character'Pos ('a')) + 10;
else
Error_Msg_S ("extended digit expected");
exit;
end if;
if Extended_Digit_Value >= Base then
Error_Msg_S ("digit >= base");
end if;
UI_Int_Value := UI_Int_Value * UI_Base + Extended_Digit_Value;
Scale := Scale - 1;
Scan_Ptr := Scan_Ptr + 1;
C := Source (Scan_Ptr);
if C = '_' then
loop
Accumulate_Checksum ('_');
Scan_Ptr := Scan_Ptr + 1;
C := Source (Scan_Ptr);
exit when C /= '_';
Error_No_Double_Underline;
end loop;
elsif C = '.' then
Accumulate_Checksum ('.');
if Point_Scanned then
Error_Msg_S ("duplicate point ignored");
end if;
Scan_Ptr := Scan_Ptr + 1;
C := Source (Scan_Ptr);
Point_Scanned := True;
Scale := 0;
elsif C = Base_Char then
Accumulate_Checksum (C);
Scan_Ptr := Scan_Ptr + 1;
exit;
elsif C = '#' or else C = ':' then
Error_Msg_S ("based number delimiters must match");
Scan_Ptr := Scan_Ptr + 1;
exit;
elsif not Identifier_Char (C) then
if Base_Char = '#' then
Error_Msg_S ("missing '#");
else
Error_Msg_S ("missing ':");
end if;
exit;
end if;
end loop;
UI_Num_Value := UI_Int_Value;
end if;
-- Scan out exponent
if not Point_Scanned then
Scale := 0;
UI_Scale := Uint_0;
else
UI_Scale := UI_From_Int (Scale);
end if;
if Source (Scan_Ptr) = 'e' or else Source (Scan_Ptr) = 'E' then
Accumulate_Checksum ('e');
Scan_Ptr := Scan_Ptr + 1;
Exponent_Is_Negative := False;
if Source (Scan_Ptr) = '+' then
Accumulate_Checksum ('+');
Scan_Ptr := Scan_Ptr + 1;
elsif Source (Scan_Ptr) = '-' then
Accumulate_Checksum ('-');
if not Point_Scanned then
Error_Msg_S ("negative exponent not allowed for integer literal");
else
Exponent_Is_Negative := True;
end if;
Scan_Ptr := Scan_Ptr + 1;
end if;
UI_Int_Value := Uint_0;
if Source (Scan_Ptr) in '0' .. '9' then
Scan_Integer;
else
Error_Digit_Expected;
end if;
if Exponent_Is_Negative then
UI_Scale := UI_Scale - UI_Int_Value;
else
UI_Scale := UI_Scale + UI_Int_Value;
end if;
end if;
-- Case of real literal to be returned
if Point_Scanned then
Token := Tok_Real_Literal;
Token_Node := New_Node (N_Real_Literal, Token_Ptr);
Set_Realval (Token_Node,
UR_From_Components (
Num => UI_Num_Value,
Den => -UI_Scale,
Rbase => Base));
-- Case of integer literal to be returned
else
Token := Tok_Integer_Literal;
Token_Node := New_Node (N_Integer_Literal, Token_Ptr);
if UI_Scale = 0 then
Set_Intval (Token_Node, UI_Num_Value);
-- Avoid doing possibly expensive calculations in cases like
-- parsing 163E800_000# when semantics will not be done anyway.
-- This is especially useful when parsing garbled input.
elsif Operating_Mode /= Check_Syntax
and then (Errors_Detected = 0 or else Try_Semantics)
then
Set_Intval (Token_Node, UI_Num_Value * UI_Base ** UI_Scale);
else
Set_Intval (Token_Node, No_Uint);
end if;
end if;
return;
end Nlit;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2019 onox <denkpadje@gmail.com>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
package Orka.Inputs.Joysticks.Gamepads is
pragma Preelaborate;
type Button is
(Right_Pad_Down,
Right_Pad_Right,
Right_Pad_Left,
Right_Pad_Up,
Left_Shoulder,
Right_Shoulder,
Center_Left,
Center_Right,
Center_Logo,
Left_Stick,
Right_Stick,
Left_Pad_Up,
Left_Pad_Right,
Left_Pad_Down,
Left_Pad_Left);
type Axis is
(Left_Stick_X,
Left_Stick_Y,
Right_Stick_X,
Right_Stick_Y,
Left_Trigger,
Right_Trigger);
function Value (Index : Button_Index) return Button;
function Value (Index : Axis_Index) return Axis;
function Index (Value : Button) return Button_Index;
function Index (Value : Axis) return Axis_Index;
procedure Normalize_Axes (Axes : in out Axis_Positions);
end Orka.Inputs.Joysticks.Gamepads;
|
package body ACO.Utils.Generic_Event is
function Events_Waiting
(This : Queued_Event_Publisher)
return Natural
is
begin
return This.Queue.Count;
end Events_Waiting;
procedure Put
(This : in out Queued_Event_Publisher;
Data : in Item_Type)
is
Success : Boolean;
pragma Unreferenced (Success);
begin
This.Queue.Put (Data, Success);
end Put;
procedure Process
(This : in out Queued_Event_Publisher)
is
Data : Item_Type;
begin
while not This.Queue.Is_Empty loop
This.Queue.Get (Data);
PS.Pub (This).Update (Data);
end loop;
end Process;
end ACO.Utils.Generic_Event;
|
with vole_lex_dfa; use vole_lex_dfa;
package body vole_lex_dfa is
function YYText return string is
i : integer;
str_loc : integer := 1;
buffer : string(1..1024);
EMPTY_STRING : constant string := "";
begin
-- find end of buffer
i := yytext_ptr;
while ( yy_ch_buf(i) /= ASCII.NUL ) loop
buffer(str_loc ) := yy_ch_buf(i);
i := i + 1;
str_loc := str_loc + 1;
end loop;
-- return yy_ch_buf(yytext_ptr.. i - 1);
if (str_loc < 2) then
return EMPTY_STRING;
else
return buffer(1..str_loc-1);
end if;
end;
-- returns the length of the matched text
function YYLength return integer is
begin
return yy_cp - yy_bp;
end YYLength;
-- done after the current pattern has been matched and before the
-- corresponding action - sets up yytext
procedure YY_DO_BEFORE_ACTION is
begin
yytext_ptr := yy_bp;
yy_hold_char := yy_ch_buf(yy_cp);
yy_ch_buf(yy_cp) := ASCII.NUL;
yy_c_buf_p := yy_cp;
end YY_DO_BEFORE_ACTION;
end vole_lex_dfa;
|
-- ROUTER-to-REQ example
with Ada.Command_Line;
with Ada.Real_Time;
with Ada.Text_IO;
with GNAT.Formatted_String;
with ZMQ;
with ZHelper;
use type GNAT.Formatted_String.Formatted_String;
use type Ada.Real_Time.Time_Span;
procedure RTReq is
Nbr_Workers : constant := 10;
Work_Time_Span : constant := 5;
task type Worker_Task_Type is
entry Start;
end Worker_Task_Type;
task body Worker_Task_Type is
begin
accept Start;
declare
Context : ZMQ.Context_Type := ZMQ.New_Context;
Worker : ZMQ.Socket_Type'Class := Context.New_Socket (ZMQ.ZMQ_REQ);
Total : Natural := 0;
begin
ZHelper.Set_Id (Worker); -- Set a printable identity.
Worker.Connect ("tcp://localhost:5671");
Work_Loop :
loop
-- Tell the broker we're ready for work
Worker.Send ("Hi Boss");
-- Get workload from broker, until finished
declare
Workload : constant String := Worker.Recv;
begin
exit Work_Loop when Workload = "Fired!";
end;
-- Do some random work
delay Duration (ZHelper.Rand_Of (0.001, 0.5));
Total := Total + 1;
end loop Work_Loop;
Ada.Text_IO.Put_Line (-(+"Completed: %d tasks"&Total));
Worker.Close;
Context.Term;
end;
end Worker_Task_Type;
-- While this example runs in a single process, that is only to make
-- it easier to start and stop the example. Each thread has its own
-- context and conceptually acts as a separate process.
function Main return Ada.Command_Line.Exit_Status
is
Context : ZMQ.Context_Type := ZMQ.New_Context;
Broker : ZMQ.Socket_Type'Class := Context.New_Socket (ZMQ.ZMQ_ROUTER);
begin
Broker.Bind ("tcp://*:5671");
declare
Start_Time : constant Ada.Real_Time.Time := Ada.Real_Time.Clock;
Tasks : array (1 .. Nbr_Workers) of Worker_Task_Type;
Workers_Fired : Integer := 0;
begin
for T of Tasks loop
T.Start;
end loop;
-- Run for five seconds and then tell workers to end
Monitor_Loop :
loop
-- Next message gives us least recently used worker
declare
Identity : constant String := Broker.Recv;
Unused_Delimiter : constant String := Broker.Recv; -- Envelope delimiter
Unused_Response : constant String := Broker.Recv; -- Response from worker
begin
Broker.Send (Identity, Send_More => True);
Broker.Send ("", Send_More => True);
-- Encourage workers until it's time to fire them
if (Ada.Real_Time.Clock - Start_Time) < Ada.Real_Time.Seconds (Work_Time_Span) then
Broker.Send ("Work harder");
else
Broker.Send ("Fired!");
Workers_Fired := Workers_Fired + 1;
end if;
exit Monitor_Loop when Workers_Fired >= Nbr_Workers;
end;
end loop Monitor_Loop;
end;
Broker.Close;
Context.Term;
return 0;
end Main;
begin
Ada.Command_Line.Set_Exit_Status (Main);
end RTReq;
|
with Ada.Text_IO;
use Ada.Text_IO;
with Ada.Integer_Text_IO;
use Ada.Integer_Text_IO;
with Ada.Strings.Unbounded;
use Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Text_IO;
use Ada.Strings.Unbounded.Text_IO;
with Ada.Containers.Doubly_Linked_Lists;
with GNAT.Regpat;
use GNAT.Regpat;
procedure Main is
type Password_Type is
record
Min: Natural;
Max: Natural;
Letter: Character;
Password: Unbounded_String;
end record;
package Password_Lists is new Ada.Containers.Doubly_Linked_Lists(Password_Type);
function Parse_Line(Line: Unbounded_String) return Password_Type is
Re: constant Pattern_Matcher := Compile("(\d+)-(\d+)\s+(\w):\s+(\w+)\s*$");
Matches: Match_Array(0 .. 4);
Password: Password_Type;
S: String := To_String(Line);
begin
Match(Re, S, Matches);
Password.Min := Integer'Value(S(Matches(1).First .. Matches(1).Last));
Password.Max := Integer'Value(S(Matches(2).First .. Matches(2).Last));
Password.Letter := S(Matches(3).First);
Password.Password := To_Unbounded_String(S(Matches(4).First .. Matches(4).Last));
return Password;
end;
function Load_Database(Filename: String) return Password_Lists.List is
Database: Password_Lists.List;
Line: Unbounded_String;
Fp: File_Type;
begin
Open(Fp, In_File, Filename);
loop
exit when End_Of_File(Fp);
Line := Get_Line(Fp);
Database.Append(Parse_Line(Line));
end loop;
Close(Fp);
return Database;
end;
function Count_Letters(Input: Unbounded_String; Letter: Character) return Natural is
N: Natural := 0;
begin
for I in 1 .. Length(Input) loop
if Element(Input, I) = Letter then
N := N + 1;
end if;
end loop;
return N;
end;
function Password_Ok_1(Password: Password_Type) return Boolean is
N: Natural := Count_Letters(Password.Password, Password.Letter);
Ok: Boolean;
begin
if N < Password.Min then
Ok := False;
elsif N <= Password.Max then
Ok := True;
else
Ok := False;
end if;
return Ok;
end;
function Password_Ok_2(Password: Password_Type) return Boolean is
Ok: Boolean := False;
Num_Found: Natural := 0;
begin
if Element(Password.Password, Password.Min) = Password.Letter then
Num_Found := Num_Found + 1;
end if;
if Element(Password.Password, Password.Max) = Password.Letter then
Num_Found := Num_Found + 1;
end if;
if Num_Found = 1 then
return True;
else
return False;
end if;
end;
Database: Password_Lists.List;
Num_Passwords: Natural := 0;
Num_Valid_Passwords_1: Natural := 0;
Num_Valid_Passwords_2: Natural := 0;
begin
Put_Line("Advent of Code - Day 2");
Database := Load_Database("puzzle_input.txt");
for Password of Database loop
Num_Passwords := Num_Passwords + 1;
if Password_Ok_1(Password) then
Num_Valid_Passwords_1 := Num_Valid_Passwords_1 + 1;
end if;
if Password_Ok_2(Password) then
Num_Valid_Passwords_2 := Num_Valid_Passwords_2 + 1;
end if;
end loop;
Put("Total passwords: ");
Put(Num_Passwords);
New_Line;
Put("Valid passwords (1): ");
Put(Num_Valid_Passwords_1);
New_Line;
Put("Valid passwords (2): ");
Put(Num_Valid_Passwords_2);
New_Line;
end Main;
|
pragma Ada_2005;
pragma Style_Checks (Off);
with Interfaces.C; use Interfaces.C;
with Interfaces.C.Strings;
limited with CUPS.stdio_h;
with Interfaces.C_Streams;
with System;
with CUPS.cups_cups_h;
private package CUPS.cups_adminutil_h is
CUPS_SERVER_DEBUG_LOGGING : aliased constant String := "_debug_logging" & ASCII.NUL; -- cups/adminutil.h:42
CUPS_SERVER_REMOTE_ADMIN : aliased constant String := "_remote_admin" & ASCII.NUL; -- cups/adminutil.h:43
CUPS_SERVER_REMOTE_ANY : aliased constant String := "_remote_any" & ASCII.NUL; -- cups/adminutil.h:44
CUPS_SERVER_SHARE_PRINTERS : aliased constant String := "_share_printers" & ASCII.NUL; -- cups/adminutil.h:46
CUPS_SERVER_USER_CANCEL_ANY : aliased constant String := "_user_cancel_any" & ASCII.NUL; -- cups/adminutil.h:47
-- * "$Id: adminutil.h 10996 2013-05-29 11:51:34Z msweet $"
-- *
-- * Administration utility API definitions for CUPS.
-- *
-- * Copyright 2007-2012 by Apple Inc.
-- * Copyright 2001-2007 by Easy Software Products.
-- *
-- * These coded instructions, statements, and computer programs are the
-- * property of Apple Inc. and are protected by Federal copyright
-- * law. Distribution and use rights are outlined in the file "LICENSE.txt"
-- * which should have been included with this file. If this file is
-- * file is missing or damaged, see the license at "http://www.cups.org/".
-- *
-- * This file is subject to the Apple OS-Developed Software exception.
--
-- * Include necessary headers...
--
-- * C++ magic...
--
-- * Constants...
--
--# define CUPS_SERVER_REMOTE_PRINTERS "_remote_printers"
-- * Functions...
--
function cupsAdminExportSamba
(dest : Interfaces.C.Strings.chars_ptr;
ppd : Interfaces.C.Strings.chars_ptr;
samba_server : Interfaces.C.Strings.chars_ptr;
samba_user : Interfaces.C.Strings.chars_ptr;
samba_password : Interfaces.C.Strings.chars_ptr;
logfile : access Interfaces.C_Streams.FILEs) return int; -- cups/adminutil.h:54
pragma Import (C, cupsAdminExportSamba, "cupsAdminExportSamba");
function cupsAdminCreateWindowsPPD
(http : System.Address;
dest : Interfaces.C.Strings.chars_ptr;
buffer : Interfaces.C.Strings.chars_ptr;
bufsize : int) return Interfaces.C.Strings.chars_ptr; -- cups/adminutil.h:59
pragma Import (C, cupsAdminCreateWindowsPPD, "cupsAdminCreateWindowsPPD");
function cupsAdminGetServerSettings
(http : System.Address;
num_settings : access int;
settings : System.Address) return int; -- cups/adminutil.h:63
pragma Import (C, cupsAdminGetServerSettings, "cupsAdminGetServerSettings");
function cupsAdminSetServerSettings
(http : System.Address;
num_settings : int;
settings : access CUPS.cups_cups_h.cups_option_t) return int; -- cups/adminutil.h:67
pragma Import (C, cupsAdminSetServerSettings, "cupsAdminSetServerSettings");
-- * End of "$Id: adminutil.h 10996 2013-05-29 11:51:34Z msweet $".
--
end CUPS.cups_adminutil_h;
|
with Ada.Text_IO; use Ada.Text_IO;
package body Radar_Internals is
T : Natural := 0;
type Angle_Degrees_T is mod 360;
Antenna_Angle : Angle_Degrees_T := 120;
type Object_Type_T is (Sarah_Connor, Peon, John_Connor);
Active_Object_Type : Object_Type_T := Sarah_Connor;
Active_Object_Status : Object_Status_T := Out_Of_Range;
Active_Object_Distance : Object_Distance_Km_T := 9.0;
Current_Walk_Speed : Speed_Setting_T;
Has_E_T_A : Boolean := False;
Time_To_Arrival : Float := 0.0;
procedure Rotate_Antenna (Speed : Speed_Setting_T) is
begin
Antenna_Angle := Antenna_Angle + (case Speed is
when Slow => 7,
when Normal => 17,
when Fast => 59,
when Stopped => 0);
end Rotate_Antenna;
procedure Walk_And_Scan is
begin
Put_Line ("Scanning " & Object_Type_T'Image (Active_Object_Type));
Get_Closer (Slow);
if Active_Object_Status = Tracked then
if Active_Object_Type = John_Connor then
Active_Object_Status := Selected;
else
Active_Object_Status := Cleared;
end if;
end if;
end Walk_And_Scan;
procedure Next_Object is
begin
Active_Object_Distance := 9.0;
Active_Object_Status := Out_Of_Range;
if Active_Object_Type = Object_Type_T'Last then
Active_Object_Type := Object_Type_T'First;
else
Active_Object_Type := Object_Type_T'Val (Object_Type_T'Pos (Active_Object_Type) + 1);
end if;
end Next_Object;
procedure Get_Closer (Speed : Speed_Setting_T) is
begin
Current_Walk_Speed := Speed;
end Get_Closer;
function Get_Active_Object_Status return Object_Status_T is
begin
return Active_Object_Status;
end Get_Active_Object_Status;
function Get_Active_Object_Distance return Object_Distance_Km_T is
begin
return Active_Object_Distance;
end Get_Active_Object_Distance;
function Get_Running_Speed return Speed_Kph_T is
begin
return (case Current_Walk_Speed is
when Stopped => 0.0,
when Slow => 4.0,
when Normal => 8.0,
when Fast => 30.0);
end Get_Running_Speed;
procedure Update_E_T_A (E_T_A : Float) is
begin
Has_E_T_A := True;
Time_To_Arrival := E_T_A;
end Update_E_T_A;
procedure Update_No_E_T_A is
begin
Has_E_T_A := False;
end Update_No_E_T_A;
procedure Time_Step is
begin
Put ("T =" & Natural'Image(T)
& " Antenna" & Angle_Degrees_T'Image (Antenna_Angle)
& "deg."& ASCII.HT & "ETA");
if Has_E_T_A then
declare
E_T_A_H : Integer
:= Integer (Float'Floor (Time_To_Arrival / 3600.0));
E_T_A_M : Integer
:= Integer (Float'Floor (Time_To_Arrival / 60.0)) mod 60;
E_T_A_S : Integer
:= Integer (Float'Rounding (Time_To_Arrival)) mod 60;
begin
Put ( Integer'Image (E_T_A_H) & "h"
& Integer'Image (E_T_A_M) & "m"
& Integer'Image (E_T_A_S) & "s");
end;
if Time_To_Arrival <= 500.0 then
Active_Object_Distance := Object_Distance_Km_T'First;
else
Active_Object_Distance := Active_Object_Distance
- Object_Distance_Km_T'Min (Active_Object_Distance - Object_Distance_Km_T'First,
Active_Object_Distance * 500.0 / Time_To_Arrival);
end if;
else
Put (" none ");
end if;
if Active_Object_Distance < 5.0 and Active_Object_Status = Out_Of_Range then
Active_Object_Status := Tracked;
end if;
Put_Line (ASCII.HT & Object_Type_T'Image (Active_Object_Type)
& " is " & Object_Status_T'Image (Active_Object_Status));
T := T + 1;
end Time_Step;
end Radar_Internals;
|
package body agar.gui.types is
function widget_icon_widget (icon : widget_icon_access_t)
return agar.gui.widget.widget_access_t is
begin
return icon.widget'access;
end widget_icon_widget;
function window_widget (window : window_access_t)
return agar.gui.widget.widget_access_t is
begin
return window.widget'access;
end window_widget;
function widget_titlebar_widget (titlebar : widget_titlebar_access_t)
return agar.gui.widget.widget_access_t is
begin
return agar.gui.widget.box.widget (titlebar.box'access);
end widget_titlebar_widget;
end agar.gui.types;
|
-- Copyright 2016-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.Vectors; use Ada.Containers;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Game; use Game;
-- ****h* Events/Events
-- FUNCTION
-- Provide code to generate and update random events
-- SOURCE
package Events is
-- ****
-- ****t* Events/Events.Events_Types
-- FUNCTION
-- Types of events
-- SOURCE
type Events_Types is
(None, EnemyShip, AttackOnBase, Disease, DoublePrice, BaseRecovery,
FullDocks, EnemyPatrol, Trader, FriendlyShip) with
Default_Value => None;
-- ****
-- ****s* Events/Events.EventData
-- FUNCTION
-- Data structure for random events
-- PARAMETERS
-- SkyX - X coordinate on sky map
-- SkyY - Y coordinate on sky map
-- Time - Time to end of event
-- ItemIndex - Index of proto item which have bonus to price
-- ShipIndex - Index of proto ship which player meet
-- Data - Various data for event (for example index of enemy ship)
-- SOURCE
type EventData(EType: Events_Types := None) is record
SkyX: Map_X_Range;
SkyY: Map_Y_Range;
Time: Positive;
case EType is
when DoublePrice =>
ItemIndex: Unbounded_String;
when AttackOnBase | EnemyShip | EnemyPatrol | Trader | FriendlyShip =>
ShipIndex: Unbounded_String;
when others =>
Data: Natural := 0;
end case;
end record;
-- ****
-- ****t* Events/Events.Events_Container
-- FUNCTION
-- Used to store events data
-- SOURCE
package Events_Container is new Vectors(Positive, EventData);
-- ****
-- ****v* Events/Events.Events_List
-- FUNCTION
-- List of all events in the game
-- SOURCE
Events_List: Events_Container.Vector;
-- ****
-- ****v* Events/Events.Traders
-- FUNCTION
-- List of indexes of all friendly traders in the game
-- SOURCE
Traders: UnboundedString_Container.Vector;
-- ****
-- ****v* Events/Events.FriendlyShips
-- FUNCTION
-- List of indexes of all friendly ships in the game
-- SOURCE
FriendlyShips: UnboundedString_Container.Vector;
-- ****
-- ****f* Events/Events.CheckForEvent
-- FUNCTION
-- Check if event happen
-- RESULT
-- Return true if combat starts, otherwise false
-- SOURCE
function CheckForEvent return Boolean with
Test_Case => (Name => "Test_CheckForEvent", Mode => Robustness);
-- ****
-- ****f* Events/Events.UpdateEvents
-- FUNCTION
-- Update all events timers
-- PARAMETERS
-- Minutes - Amount of in-game minutes which passed
-- SOURCE
procedure UpdateEvents(Minutes: Positive) with
Test_Case => (Name => "Test_UpdateEvents", Mode => Robustness);
-- ****
-- ****f* Events/Events.DeleteEvent
-- FUNCTION
-- Delete selected event
-- PARAMETERS
-- EventIndex - Index of the event to delete
-- SOURCE
procedure DeleteEvent(EventIndex: Positive) with
Pre => EventIndex <= Events_List.Last_Index,
Test_Case => (Name => "Test_DeleteEvent", Mode => Nominal);
-- ****
-- ****f* Events/Events.GenerateTraders
-- FUNCTION
-- Create list of traders needed for trader event
-- SOURCE
procedure GenerateTraders with
Test_Case => (Name => "Test_GenerateTraders", Mode => Robustness);
-- ****
-- ****f* Events/Events.RecoverBase
-- FUNCTION
-- Recover abandoned base
-- PARAMETERS
-- BaseIndex - Index of the base where recovery happened
-- SOURCE
procedure RecoverBase(BaseIndex: Bases_Range) with
Test_Case => (Name => "Test_RecoverBase", Mode => Robustness);
-- ****
-- ****f* Events/Events.GenerateEnemies
-- FUNCTION
-- Create list of enemies ships
-- PARAMETERS
-- Enemies - List of enemies to generate
-- Owner - Index of faction which enemies list should contains.
-- Default all factions
-- WithTraders - Did list should contains enemy traders too. Default true
-- SOURCE
procedure GenerateEnemies
(Enemies: in out UnboundedString_Container.Vector;
Owner: Unbounded_String := To_Unbounded_String("Any");
WithTraders: Boolean := True) with
Pre => Owner /= Null_Unbounded_String,
Test_Case => (Name => "Test_GenerateEnemies", Mode => Nominal);
-- ****
end Events;
|
------------------------------------------------------------------------------
-- EMAIL: <darkestkhan@gmail.com> --
-- License: ISC License (see COPYING file) --
-- --
-- Copyright © 2015 darkestkhan --
------------------------------------------------------------------------------
-- 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.Characters.Handling;
with Ada.Containers.Hashed_Sets;
with Ada.Command_Line;
with Ada.Strings.Fixed;
with Ada.Strings.Hash;
package body CBAP is
---------------------------------------------------------------------------
function To_Lower (Item: in String) return String
renames Ada.Characters.Handling.To_Lower;
---------------------------------------------------------------------------
type Callback_Data is
record
Hash : Ada.Containers.Hash_Type;
Callback: Callbacks;
Arg_Type: Argument_Types := Value;
Case_Sensitive: Boolean := True;
end record;
function Hash (This: in Callback_Data) return Ada.Containers.Hash_Type
is
begin
return This.Hash;
end Hash;
overriding function "=" (Left, Right: in Callback_Data) return Boolean
is
use type Ada.Containers.Hash_Type;
begin
return Left.Hash = Right.Hash;
end "=";
procedure Null_Callback (Item: in String) is null;
Empty_Callback_Data: constant Callback_Data :=
Callback_Data'(0, Null_Callback'Access, Value, True);
package Callback_Sets is new
Ada.Containers.Hashed_Sets (Callback_Data, Hash, "=");
---------------------------------------------------------------------------
Callback_Set: Callback_Sets.Set := Callback_Sets.Empty_Set;
---------------------------------------------------------------------------
procedure Register
( Callback : in Callbacks;
Called_On : in String;
Argument_Type : in Argument_Types := Value;
Case_Sensitive: in Boolean := True
)
is
Var: Callback_Data :=
Callback_Data'(0, Callback, Argument_Type, Case_Sensitive);
begin
if Ada.Strings.Fixed.Index (Called_On, "=", Called_On'First) /= 0 then
raise Incorrect_Called_On with Called_On;
end if;
if Case_Sensitive then
Var.Hash := Ada.Strings.Hash (Called_On);
else
Var.Hash := Ada.Strings.Hash (To_Lower (Called_On));
end if;
Callback_Set.Insert (Var);
exception
when Constraint_Error => raise Constraint_Error with
"Following argument already has callback registered: " & Called_On;
end Register;
---------------------------------------------------------------------------
procedure Process_Arguments
is
---------------------------------------------------------------------------
package CLI renames Ada.Command_Line;
---------------------------------------------------------------------------
procedure Add_Inputs (From: in Natural)
is
begin
if not (From < CLI.Argument_Count) then
return;
end if;
for K in From + 1 .. CLI.Argument_Count loop
Input_Arguments.Append (CLI.Argument (K));
end loop;
end Add_Inputs;
---------------------------------------------------------------------------
function Extract_Name (Item: in String) return String
is
begin
return Item
(Item'First .. Ada.Strings.Fixed.Index (Item, "=", Item'First) - 1);
end Extract_Name;
---------------------------------------------------------------------------
function Extract_Value (Item: in String) return String
is
Pos: constant Natural := Ada.Strings.Fixed.Index (Item, "=", Item'First);
begin
if Pos = Item'Last then
return ""; -- in case: "variable="
else
return Item (Pos + 1 .. Item'Last);
end if;
end Extract_Value;
---------------------------------------------------------------------------
procedure Check_Callback (Item: in String)
is
Dummy_Callback : Callback_Data := Empty_Callback_Data;
Actual_Callback : Callback_Data := Empty_Callback_Data;
begin
Case_Check: -- loop over case sensitiviness
for Case_Sensitive in Boolean'Range loop
Arg_Type_Check: -- loop over argument type
for Arg_Type in Argument_Types'Range loop
if Arg_Type = Value then
if Case_Sensitive then
Dummy_Callback.Hash := Ada.Strings.Hash (Item);
else
Dummy_Callback.Hash := Ada.Strings.Hash (To_Lower (Item));
end if;
else -- For Variable we need to need to hash name ONLY
if Case_Sensitive then
Dummy_Callback.Hash := Ada.Strings.Hash (Extract_Name (Item));
else
Dummy_Callback.Hash := Ada.Strings.Hash
(Extract_Name (To_Lower (Item)));
end if;
end if;
if Callback_Set.Contains (Dummy_Callback) then
Actual_Callback :=
Callback_Sets.Element (Callback_Set.Find (Dummy_Callback));
if Actual_Callback.Case_Sensitive = Case_Sensitive and
Actual_Callback.Arg_Type = Arg_Type
then
if Arg_Type = Value then
Actual_Callback.Callback (Item);
return;
else -- Special circuitry for Variable type
declare
Pos: constant Natural :=
Ada.Strings.Fixed.Index (Item, "=", Item'First);
begin
if Pos = 0 then
Unknown_Arguments.Append (Item);
return;
else
Actual_Callback.Callback (Extract_Value (Item));
return;
end if;
end;
end if;
end if;
end if; -- Callback_Set.Contains
end loop Arg_Type_Check;
end loop Case_Check;
-- No callback associated with argument has been found.
Unknown_Arguments.Append (Item);
end Check_Callback;
---------------------------------------------------------------------------
begin
if CLI.Argument_Count = 0 then
return;
end if;
for K in 1 .. CLI.Argument_Count loop
declare
Arg: constant String := CLI.Argument (K);
begin
if Arg = "--" then
Add_Inputs (K);
return;
end if;
-- Strip leading hyphens
if Arg'Length > 2 and then Arg (Arg'First .. Arg'First + 1) = "--" then
Check_Callback (Arg (Arg'First + 2 .. Arg'Last));
elsif Arg'Length > 1 and then Arg (1 .. 1) = "-" then
Check_Callback (Arg (Arg'First + 1 .. Arg'Last));
else
Check_Callback (Arg);
end if;
end;
end loop;
end Process_Arguments;
---------------------------------------------------------------------------
end CBAP;
|
-- AoC 2020, Day 8
with VM; use VM;
with Ada.Text_IO;
with Ada.Containers.Ordered_Sets;
with Ada.Containers; use Ada.Containers;
package body Day is
package TIO renames Ada.Text_IO;
package PC_Sets is new Ada.Containers.Ordered_Sets (Element_Type => Instruction_Index);
use PC_Sets;
function acc_before_repeat(filename : in String) return Integer is
v : VM.VM := load_file(filename);
i : Instruction_Index := pc(v);
seen : PC_Sets.Set;
halt : Boolean;
begin
loop
if seen.contains(i) then
exit;
end if;
seen.insert(i);
halt := step(v);
i := pc(v);
end loop;
TIO.put_line("Halted?: " & Boolean'Image(halt));
return acc(v);
end acc_before_repeat;
function acc_after_terminate(filename : in String) return Integer is
v : VM.VM := load_file(filename);
max : constant Count_Type := instructions(v);
begin
for i in 0..max-1 loop
swap_nop_jmp(Instruction_Index(i), v);
-- backed this value down to find a reasonable cutoff
if eval(v, 250) then
return acc(v);
end if;
swap_nop_jmp(Instruction_Index(i), v);
reset(v);
end loop;
return -1;
end acc_after_terminate;
end Day;
|
-----------------------------------------------------------------------
-- AWA.Blogs.Models -- AWA.Blogs.Models
-----------------------------------------------------------------------
-- File generated by ada-gen DO NOT MODIFY
-- Template used: templates/model/package-spec.xhtml
-- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 1095
-----------------------------------------------------------------------
-- Copyright (C) 2020 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
pragma Warnings (Off);
with ADO.Sessions;
with ADO.Objects;
with ADO.Statements;
with ADO.SQL;
with ADO.Schemas;
with ADO.Queries;
with ADO.Queries.Loaders;
with Ada.Calendar;
with Ada.Containers.Vectors;
with Ada.Strings.Unbounded;
with Util.Beans.Objects;
with Util.Beans.Objects.Enums;
with Util.Beans.Basic.Lists;
with ADO.Audits;
with AWA.Comments.Models;
with AWA.Events;
with AWA.Images.Models;
with AWA.Storages.Models;
with AWA.Users.Models;
with AWA.Workspaces.Models;
with Util.Beans.Methods;
pragma Warnings (On);
package AWA.Blogs.Models is
pragma Style_Checks ("-mr");
type Format_Type is (FORMAT_DOTCLEAR, FORMAT_HTML, FORMAT_MARKDOWN, FORMAT_MEDIAWIKI, FORMAT_CREOLE);
for Format_Type use (FORMAT_DOTCLEAR => 0, FORMAT_HTML => 1, FORMAT_MARKDOWN => 2, FORMAT_MEDIAWIKI => 3, FORMAT_CREOLE => 4);
package Format_Type_Objects is
new Util.Beans.Objects.Enums (Format_Type);
type Nullable_Format_Type is record
Is_Null : Boolean := True;
Value : Format_Type;
end record;
type Post_Status_Type is (POST_DRAFT, POST_PUBLISHED, POST_SCHEDULED);
for Post_Status_Type use (POST_DRAFT => 0, POST_PUBLISHED => 1, POST_SCHEDULED => 2);
package Post_Status_Type_Objects is
new Util.Beans.Objects.Enums (Post_Status_Type);
type Nullable_Post_Status_Type is record
Is_Null : Boolean := True;
Value : Post_Status_Type;
end record;
type Blog_Ref is new ADO.Objects.Object_Ref with null record;
type Post_Ref is new ADO.Objects.Object_Ref with null record;
-- Create an object key for Blog.
function Blog_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key;
-- Create an object key for Blog from a string.
-- Raises Constraint_Error if the string cannot be converted into the object key.
function Blog_Key (Id : in String) return ADO.Objects.Object_Key;
Null_Blog : constant Blog_Ref;
function "=" (Left, Right : Blog_Ref'Class) return Boolean;
-- Set the blog identifier
procedure Set_Id (Object : in out Blog_Ref;
Value : in ADO.Identifier);
-- Get the blog identifier
function Get_Id (Object : in Blog_Ref)
return ADO.Identifier;
-- Set the blog name
procedure Set_Name (Object : in out Blog_Ref;
Value : in Ada.Strings.Unbounded.Unbounded_String);
procedure Set_Name (Object : in out Blog_Ref;
Value : in String);
-- Get the blog name
function Get_Name (Object : in Blog_Ref)
return Ada.Strings.Unbounded.Unbounded_String;
function Get_Name (Object : in Blog_Ref)
return String;
-- Get the version
function Get_Version (Object : in Blog_Ref)
return Integer;
-- Set the blog uuid
procedure Set_Uid (Object : in out Blog_Ref;
Value : in Ada.Strings.Unbounded.Unbounded_String);
procedure Set_Uid (Object : in out Blog_Ref;
Value : in String);
-- Get the blog uuid
function Get_Uid (Object : in Blog_Ref)
return Ada.Strings.Unbounded.Unbounded_String;
function Get_Uid (Object : in Blog_Ref)
return String;
-- Set the blog creation date
procedure Set_Create_Date (Object : in out Blog_Ref;
Value : in Ada.Calendar.Time);
-- Get the blog creation date
function Get_Create_Date (Object : in Blog_Ref)
return Ada.Calendar.Time;
-- Set the date when the blog was updated
procedure Set_Update_Date (Object : in out Blog_Ref;
Value : in Ada.Calendar.Time);
-- Get the date when the blog was updated
function Get_Update_Date (Object : in Blog_Ref)
return Ada.Calendar.Time;
-- Set The blog base URL.
procedure Set_Url (Object : in out Blog_Ref;
Value : in Ada.Strings.Unbounded.Unbounded_String);
procedure Set_Url (Object : in out Blog_Ref;
Value : in String);
-- Get The blog base URL.
function Get_Url (Object : in Blog_Ref)
return Ada.Strings.Unbounded.Unbounded_String;
function Get_Url (Object : in Blog_Ref)
return String;
-- Set the default post format.
procedure Set_Format (Object : in out Blog_Ref;
Value : in AWA.Blogs.Models.Format_Type);
-- Get the default post format.
function Get_Format (Object : in Blog_Ref)
return AWA.Blogs.Models.Format_Type;
-- Set the default image URL to be used
procedure Set_Default_Image_Url (Object : in out Blog_Ref;
Value : in Ada.Strings.Unbounded.Unbounded_String);
procedure Set_Default_Image_Url (Object : in out Blog_Ref;
Value : in String);
-- Get the default image URL to be used
function Get_Default_Image_Url (Object : in Blog_Ref)
return Ada.Strings.Unbounded.Unbounded_String;
function Get_Default_Image_Url (Object : in Blog_Ref)
return String;
-- Set the workspace that this blog belongs to
procedure Set_Workspace (Object : in out Blog_Ref;
Value : in AWA.Workspaces.Models.Workspace_Ref'Class);
-- Get the workspace that this blog belongs to
function Get_Workspace (Object : in Blog_Ref)
return AWA.Workspaces.Models.Workspace_Ref'Class;
-- Load the entity identified by 'Id'.
-- Raises the NOT_FOUND exception if it does not exist.
procedure Load (Object : in out Blog_Ref;
Session : in out ADO.Sessions.Session'Class;
Id : in ADO.Identifier);
-- Load the entity identified by 'Id'.
-- Returns True in <b>Found</b> if the object was found and False if it does not exist.
procedure Load (Object : in out Blog_Ref;
Session : in out ADO.Sessions.Session'Class;
Id : in ADO.Identifier;
Found : out Boolean);
-- Find and load the entity.
overriding
procedure Find (Object : in out Blog_Ref;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class;
Found : out Boolean);
-- Save the entity. If the entity does not have an identifier, an identifier is allocated
-- and it is inserted in the table. Otherwise, only data fields which have been changed
-- are updated.
overriding
procedure Save (Object : in out Blog_Ref;
Session : in out ADO.Sessions.Master_Session'Class);
-- Delete the entity.
overriding
procedure Delete (Object : in out Blog_Ref;
Session : in out ADO.Sessions.Master_Session'Class);
overriding
function Get_Value (From : in Blog_Ref;
Name : in String) return Util.Beans.Objects.Object;
-- Table definition
BLOG_TABLE : constant ADO.Schemas.Class_Mapping_Access;
-- Internal method to allocate the Object_Record instance
overriding
procedure Allocate (Object : in out Blog_Ref);
-- Copy of the object.
procedure Copy (Object : in Blog_Ref;
Into : in out Blog_Ref);
package Blog_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Blog_Ref,
"=" => "=");
subtype Blog_Vector is Blog_Vectors.Vector;
procedure List (Object : in out Blog_Vector;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class);
-- Create an object key for Post.
function Post_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key;
-- Create an object key for Post from a string.
-- Raises Constraint_Error if the string cannot be converted into the object key.
function Post_Key (Id : in String) return ADO.Objects.Object_Key;
Null_Post : constant Post_Ref;
function "=" (Left, Right : Post_Ref'Class) return Boolean;
-- Set the post identifier
procedure Set_Id (Object : in out Post_Ref;
Value : in ADO.Identifier);
-- Get the post identifier
function Get_Id (Object : in Post_Ref)
return ADO.Identifier;
-- Set the post title
procedure Set_Title (Object : in out Post_Ref;
Value : in Ada.Strings.Unbounded.Unbounded_String);
procedure Set_Title (Object : in out Post_Ref;
Value : in String);
-- Get the post title
function Get_Title (Object : in Post_Ref)
return Ada.Strings.Unbounded.Unbounded_String;
function Get_Title (Object : in Post_Ref)
return String;
-- Set the post text content
procedure Set_Text (Object : in out Post_Ref;
Value : in Ada.Strings.Unbounded.Unbounded_String);
procedure Set_Text (Object : in out Post_Ref;
Value : in String);
-- Get the post text content
function Get_Text (Object : in Post_Ref)
return Ada.Strings.Unbounded.Unbounded_String;
function Get_Text (Object : in Post_Ref)
return String;
-- Set the post creation date
procedure Set_Create_Date (Object : in out Post_Ref;
Value : in Ada.Calendar.Time);
-- Get the post creation date
function Get_Create_Date (Object : in Post_Ref)
return Ada.Calendar.Time;
-- Set the post URI
procedure Set_Uri (Object : in out Post_Ref;
Value : in Ada.Strings.Unbounded.Unbounded_String);
procedure Set_Uri (Object : in out Post_Ref;
Value : in String);
-- Get the post URI
function Get_Uri (Object : in Post_Ref)
return Ada.Strings.Unbounded.Unbounded_String;
function Get_Uri (Object : in Post_Ref)
return String;
--
function Get_Version (Object : in Post_Ref)
return Integer;
-- Set the post publication date
procedure Set_Publish_Date (Object : in out Post_Ref;
Value : in ADO.Nullable_Time);
-- Get the post publication date
function Get_Publish_Date (Object : in Post_Ref)
return ADO.Nullable_Time;
-- Set the post status
procedure Set_Status (Object : in out Post_Ref;
Value : in AWA.Blogs.Models.Post_Status_Type);
-- Get the post status
function Get_Status (Object : in Post_Ref)
return AWA.Blogs.Models.Post_Status_Type;
--
procedure Set_Allow_Comments (Object : in out Post_Ref;
Value : in Boolean);
--
function Get_Allow_Comments (Object : in Post_Ref)
return Boolean;
-- Set the number of times the post was read.
procedure Set_Read_Count (Object : in out Post_Ref;
Value : in Integer);
-- Get the number of times the post was read.
function Get_Read_Count (Object : in Post_Ref)
return Integer;
-- Set the post summary.
procedure Set_Summary (Object : in out Post_Ref;
Value : in Ada.Strings.Unbounded.Unbounded_String);
procedure Set_Summary (Object : in out Post_Ref;
Value : in String);
-- Get the post summary.
function Get_Summary (Object : in Post_Ref)
return Ada.Strings.Unbounded.Unbounded_String;
function Get_Summary (Object : in Post_Ref)
return String;
-- Set the blog post format.
procedure Set_Format (Object : in out Post_Ref;
Value : in AWA.Blogs.Models.Format_Type);
-- Get the blog post format.
function Get_Format (Object : in Post_Ref)
return AWA.Blogs.Models.Format_Type;
--
procedure Set_Author (Object : in out Post_Ref;
Value : in AWA.Users.Models.User_Ref'Class);
--
function Get_Author (Object : in Post_Ref)
return AWA.Users.Models.User_Ref'Class;
--
procedure Set_Blog (Object : in out Post_Ref;
Value : in AWA.Blogs.Models.Blog_Ref'Class);
--
function Get_Blog (Object : in Post_Ref)
return AWA.Blogs.Models.Blog_Ref'Class;
--
procedure Set_Image (Object : in out Post_Ref;
Value : in AWA.Images.Models.Image_Ref'Class);
--
function Get_Image (Object : in Post_Ref)
return AWA.Images.Models.Image_Ref'Class;
-- Load the entity identified by 'Id'.
-- Raises the NOT_FOUND exception if it does not exist.
procedure Load (Object : in out Post_Ref;
Session : in out ADO.Sessions.Session'Class;
Id : in ADO.Identifier);
-- Load the entity identified by 'Id'.
-- Returns True in <b>Found</b> if the object was found and False if it does not exist.
procedure Load (Object : in out Post_Ref;
Session : in out ADO.Sessions.Session'Class;
Id : in ADO.Identifier;
Found : out Boolean);
-- Find and load the entity.
overriding
procedure Find (Object : in out Post_Ref;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class;
Found : out Boolean);
-- Save the entity. If the entity does not have an identifier, an identifier is allocated
-- and it is inserted in the table. Otherwise, only data fields which have been changed
-- are updated.
overriding
procedure Save (Object : in out Post_Ref;
Session : in out ADO.Sessions.Master_Session'Class);
-- Delete the entity.
overriding
procedure Delete (Object : in out Post_Ref;
Session : in out ADO.Sessions.Master_Session'Class);
overriding
function Get_Value (From : in Post_Ref;
Name : in String) return Util.Beans.Objects.Object;
-- Table definition
POST_TABLE : constant ADO.Schemas.Class_Mapping_Access;
-- Internal method to allocate the Object_Record instance
overriding
procedure Allocate (Object : in out Post_Ref);
-- Copy of the object.
procedure Copy (Object : in Post_Ref;
Into : in out Post_Ref);
Query_Blog_Image_Get_Data : constant ADO.Queries.Query_Definition_Access;
Query_Blog_Image_Width_Get_Data : constant ADO.Queries.Query_Definition_Access;
Query_Blog_Image_Height_Get_Data : constant ADO.Queries.Query_Definition_Access;
Query_Blog_Tag_Cloud : constant ADO.Queries.Query_Definition_Access;
-- --------------------
-- The Admin_Post_Info describes a post in the administration interface.
-- --------------------
type Admin_Post_Info is
new Util.Beans.Basic.Bean with record
-- the post identifier.
Id : ADO.Identifier;
-- the post title.
Title : Ada.Strings.Unbounded.Unbounded_String;
-- the post uri.
Uri : Ada.Strings.Unbounded.Unbounded_String;
-- the post publish date.
Date : Ada.Calendar.Time;
-- the post status.
Status : AWA.Blogs.Models.Post_Status_Type;
-- the number of times the post was read.
Read_Count : Natural;
-- the user name.
Username : Ada.Strings.Unbounded.Unbounded_String;
-- the number of comments for this post.
Comment_Count : Natural;
end record;
-- Get the bean attribute identified by the name.
overriding
function Get_Value (From : in Admin_Post_Info;
Name : in String) return Util.Beans.Objects.Object;
-- Set the bean attribute identified by the name.
overriding
procedure Set_Value (Item : in out Admin_Post_Info;
Name : in String;
Value : in Util.Beans.Objects.Object);
package Admin_Post_Info_Beans is
new Util.Beans.Basic.Lists (Element_Type => Admin_Post_Info);
package Admin_Post_Info_Vectors renames Admin_Post_Info_Beans.Vectors;
subtype Admin_Post_Info_List_Bean is Admin_Post_Info_Beans.List_Bean;
type Admin_Post_Info_List_Bean_Access is access all Admin_Post_Info_List_Bean;
-- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>.
procedure List (Object : in out Admin_Post_Info_List_Bean'Class;
Session : in out ADO.Sessions.Session'Class;
Context : in out ADO.Queries.Context'Class);
subtype Admin_Post_Info_Vector is Admin_Post_Info_Vectors.Vector;
-- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>.
procedure List (Object : in out Admin_Post_Info_Vector;
Session : in out ADO.Sessions.Session'Class;
Context : in out ADO.Queries.Context'Class);
Query_Blog_Admin_Post_List : constant ADO.Queries.Query_Definition_Access;
Query_Blog_Admin_Post_List_Date : constant ADO.Queries.Query_Definition_Access;
-- --------------------
-- The list of blogs.
-- --------------------
type Blog_Info is
new Util.Beans.Basic.Bean with record
-- the blog identifier.
Id : ADO.Identifier;
-- the blog title.
Title : Ada.Strings.Unbounded.Unbounded_String;
-- the blog uuid.
Uid : Ada.Strings.Unbounded.Unbounded_String;
-- the blog creation date.
Create_Date : Ada.Calendar.Time;
-- the number of posts published.
Post_Count : Integer;
end record;
-- Get the bean attribute identified by the name.
overriding
function Get_Value (From : in Blog_Info;
Name : in String) return Util.Beans.Objects.Object;
-- Set the bean attribute identified by the name.
overriding
procedure Set_Value (Item : in out Blog_Info;
Name : in String;
Value : in Util.Beans.Objects.Object);
package Blog_Info_Beans is
new Util.Beans.Basic.Lists (Element_Type => Blog_Info);
package Blog_Info_Vectors renames Blog_Info_Beans.Vectors;
subtype Blog_Info_List_Bean is Blog_Info_Beans.List_Bean;
type Blog_Info_List_Bean_Access is access all Blog_Info_List_Bean;
-- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>.
procedure List (Object : in out Blog_Info_List_Bean'Class;
Session : in out ADO.Sessions.Session'Class;
Context : in out ADO.Queries.Context'Class);
subtype Blog_Info_Vector is Blog_Info_Vectors.Vector;
-- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>.
procedure List (Object : in out Blog_Info_Vector;
Session : in out ADO.Sessions.Session'Class;
Context : in out ADO.Queries.Context'Class);
Query_Blog_List : constant ADO.Queries.Query_Definition_Access;
-- --------------------
-- The comment information.
-- --------------------
type Comment_Info is
new Util.Beans.Basic.Bean with record
-- the comment identifier.
Id : ADO.Identifier;
-- the post identifier.
Post_Id : ADO.Identifier;
-- the post title.
Title : Ada.Strings.Unbounded.Unbounded_String;
-- the comment author's name.
Author : Ada.Strings.Unbounded.Unbounded_String;
-- the comment author's email.
Email : Ada.Strings.Unbounded.Unbounded_String;
-- the comment date.
Date : Ada.Calendar.Time;
-- the comment status.
Status : AWA.Comments.Models.Status_Type;
end record;
-- Get the bean attribute identified by the name.
overriding
function Get_Value (From : in Comment_Info;
Name : in String) return Util.Beans.Objects.Object;
-- Set the bean attribute identified by the name.
overriding
procedure Set_Value (Item : in out Comment_Info;
Name : in String;
Value : in Util.Beans.Objects.Object);
package Comment_Info_Beans is
new Util.Beans.Basic.Lists (Element_Type => Comment_Info);
package Comment_Info_Vectors renames Comment_Info_Beans.Vectors;
subtype Comment_Info_List_Bean is Comment_Info_Beans.List_Bean;
type Comment_Info_List_Bean_Access is access all Comment_Info_List_Bean;
-- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>.
procedure List (Object : in out Comment_Info_List_Bean'Class;
Session : in out ADO.Sessions.Session'Class;
Context : in out ADO.Queries.Context'Class);
subtype Comment_Info_Vector is Comment_Info_Vectors.Vector;
-- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>.
procedure List (Object : in out Comment_Info_Vector;
Session : in out ADO.Sessions.Session'Class;
Context : in out ADO.Queries.Context'Class);
Query_Comment_List : constant ADO.Queries.Query_Definition_Access;
-- --------------------
-- The information about an image used in a wiki page.
-- --------------------
type Image_Info is
new Util.Beans.Basic.Bean with record
-- the image folder identifier.
Folder_Id : ADO.Identifier;
-- the image file identifier.
Id : ADO.Identifier;
-- the file creation date.
Create_Date : Ada.Calendar.Time;
-- the file storage URI.
Uri : Ada.Strings.Unbounded.Unbounded_String;
-- the file storage URI.
Storage : AWA.Storages.Models.Storage_Type;
-- the file mime type.
Mime_Type : Ada.Strings.Unbounded.Unbounded_String;
-- the file size.
File_Size : Integer;
-- the image width.
Width : Integer;
-- the image height.
Height : Integer;
end record;
-- Get the bean attribute identified by the name.
overriding
function Get_Value (From : in Image_Info;
Name : in String) return Util.Beans.Objects.Object;
-- Set the bean attribute identified by the name.
overriding
procedure Set_Value (Item : in out Image_Info;
Name : in String;
Value : in Util.Beans.Objects.Object);
package Image_Info_Beans is
new Util.Beans.Basic.Lists (Element_Type => Image_Info);
package Image_Info_Vectors renames Image_Info_Beans.Vectors;
subtype Image_Info_List_Bean is Image_Info_Beans.List_Bean;
type Image_Info_List_Bean_Access is access all Image_Info_List_Bean;
-- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>.
procedure List (Object : in out Image_Info_List_Bean'Class;
Session : in out ADO.Sessions.Session'Class;
Context : in out ADO.Queries.Context'Class);
subtype Image_Info_Vector is Image_Info_Vectors.Vector;
-- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>.
procedure List (Object : in out Image_Info_Vector;
Session : in out ADO.Sessions.Session'Class;
Context : in out ADO.Queries.Context'Class);
Query_Blog_Image : constant ADO.Queries.Query_Definition_Access;
-- --------------------
-- The month statistics.
-- --------------------
type Month_Stat_Info is
new Util.Beans.Basic.Bean with record
-- the post identifier.
Year : Natural;
-- the post title.
Month : Natural;
-- the post uri.
Count : Natural;
end record;
-- Get the bean attribute identified by the name.
overriding
function Get_Value (From : in Month_Stat_Info;
Name : in String) return Util.Beans.Objects.Object;
-- Set the bean attribute identified by the name.
overriding
procedure Set_Value (Item : in out Month_Stat_Info;
Name : in String;
Value : in Util.Beans.Objects.Object);
package Month_Stat_Info_Beans is
new Util.Beans.Basic.Lists (Element_Type => Month_Stat_Info);
package Month_Stat_Info_Vectors renames Month_Stat_Info_Beans.Vectors;
subtype Month_Stat_Info_List_Bean is Month_Stat_Info_Beans.List_Bean;
type Month_Stat_Info_List_Bean_Access is access all Month_Stat_Info_List_Bean;
-- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>.
procedure List (Object : in out Month_Stat_Info_List_Bean'Class;
Session : in out ADO.Sessions.Session'Class;
Context : in out ADO.Queries.Context'Class);
subtype Month_Stat_Info_Vector is Month_Stat_Info_Vectors.Vector;
-- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>.
procedure List (Object : in out Month_Stat_Info_Vector;
Session : in out ADO.Sessions.Session'Class;
Context : in out ADO.Queries.Context'Class);
Query_Post_Publish_Stats : constant ADO.Queries.Query_Definition_Access;
Query_Post_Access_Stats : constant ADO.Queries.Query_Definition_Access;
-- --------------------
-- The Post_Info describes a post to be displayed in the blog page
-- --------------------
type Post_Info is
new Util.Beans.Basic.Bean with record
-- the post identifier.
Id : ADO.Identifier;
-- the post title.
Title : Ada.Strings.Unbounded.Unbounded_String;
-- the post uri.
Uri : Ada.Strings.Unbounded.Unbounded_String;
-- the post publish date.
Date : Ada.Calendar.Time;
-- the user name.
Username : Ada.Strings.Unbounded.Unbounded_String;
-- the post page format.
Format : AWA.Blogs.Models.Format_Type;
-- the post summary.
Summary : Ada.Strings.Unbounded.Unbounded_String;
-- the post text.
Text : Ada.Strings.Unbounded.Unbounded_String;
-- the post allows to add comments.
Allow_Comments : Boolean;
-- the number of comments for this post.
Comment_Count : Natural;
end record;
-- Get the bean attribute identified by the name.
overriding
function Get_Value (From : in Post_Info;
Name : in String) return Util.Beans.Objects.Object;
-- Set the bean attribute identified by the name.
overriding
procedure Set_Value (Item : in out Post_Info;
Name : in String;
Value : in Util.Beans.Objects.Object);
package Post_Info_Beans is
new Util.Beans.Basic.Lists (Element_Type => Post_Info);
package Post_Info_Vectors renames Post_Info_Beans.Vectors;
subtype Post_Info_List_Bean is Post_Info_Beans.List_Bean;
type Post_Info_List_Bean_Access is access all Post_Info_List_Bean;
-- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>.
procedure List (Object : in out Post_Info_List_Bean'Class;
Session : in out ADO.Sessions.Session'Class;
Context : in out ADO.Queries.Context'Class);
subtype Post_Info_Vector is Post_Info_Vectors.Vector;
-- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>.
procedure List (Object : in out Post_Info_Vector;
Session : in out ADO.Sessions.Session'Class;
Context : in out ADO.Queries.Context'Class);
Query_Blog_Post_List : constant ADO.Queries.Query_Definition_Access;
Query_Blog_Post_Tag_List : constant ADO.Queries.Query_Definition_Access;
-- --------------------
-- load the blog instance.
-- --------------------
type Blog_Bean is abstract new AWA.Blogs.Models.Blog_Ref
and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with null record;
-- This bean provides some methods that can be used in a Method_Expression.
overriding
function Get_Method_Bindings (From : in Blog_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access;
-- Set the bean attribute identified by the name.
overriding
procedure Set_Value (Item : in out Blog_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
procedure Create (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract;
procedure Create_Default (Bean : in out Blog_Bean;
Event : in AWA.Events.Module_Event'Class) is abstract;
procedure Load (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract;
-- --------------------
-- load the post for the administrator
-- --------------------
type Post_Bean is abstract new AWA.Blogs.Models.Post_Ref
and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with null record;
-- This bean provides some methods that can be used in a Method_Expression.
overriding
function Get_Method_Bindings (From : in Post_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access;
-- Set the bean attribute identified by the name.
overriding
procedure Set_Value (Item : in out Post_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
procedure Save (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract;
procedure Delete (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract;
procedure Load (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract;
procedure Load_Admin (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract;
procedure Setup (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract;
type Post_List_Bean is abstract limited
new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record
Tag : Ada.Strings.Unbounded.Unbounded_String;
Page : Integer;
Count : Integer;
Page_Size : Integer;
end record;
-- This bean provides some methods that can be used in a Method_Expression.
overriding
function Get_Method_Bindings (From : in Post_List_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access;
-- Get the bean attribute identified by the name.
overriding
function Get_Value (From : in Post_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the bean attribute identified by the name.
overriding
procedure Set_Value (Item : in out Post_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
procedure Load (Bean : in out Post_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract;
-- --------------------
-- Statistics about the blog or a post.
-- --------------------
type Stat_List_Bean is abstract limited
new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record
-- the blog identifier.
Blog_Id : ADO.Identifier;
-- the post identifier.
Post_Id : ADO.Identifier;
end record;
-- This bean provides some methods that can be used in a Method_Expression.
overriding
function Get_Method_Bindings (From : in Stat_List_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access;
-- Get the bean attribute identified by the name.
overriding
function Get_Value (From : in Stat_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the bean attribute identified by the name.
overriding
procedure Set_Value (Item : in out Stat_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
procedure Load (Bean : in out Stat_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract;
private
BLOG_NAME : aliased constant String := "awa_blog";
COL_0_1_NAME : aliased constant String := "id";
COL_1_1_NAME : aliased constant String := "name";
COL_2_1_NAME : aliased constant String := "version";
COL_3_1_NAME : aliased constant String := "uid";
COL_4_1_NAME : aliased constant String := "create_date";
COL_5_1_NAME : aliased constant String := "update_date";
COL_6_1_NAME : aliased constant String := "url";
COL_7_1_NAME : aliased constant String := "format";
COL_8_1_NAME : aliased constant String := "default_image_url";
COL_9_1_NAME : aliased constant String := "workspace_id";
BLOG_DEF : aliased constant ADO.Schemas.Class_Mapping :=
(Count => 10,
Table => BLOG_NAME'Access,
Members => (
1 => COL_0_1_NAME'Access,
2 => COL_1_1_NAME'Access,
3 => COL_2_1_NAME'Access,
4 => COL_3_1_NAME'Access,
5 => COL_4_1_NAME'Access,
6 => COL_5_1_NAME'Access,
7 => COL_6_1_NAME'Access,
8 => COL_7_1_NAME'Access,
9 => COL_8_1_NAME'Access,
10 => COL_9_1_NAME'Access)
);
BLOG_TABLE : constant ADO.Schemas.Class_Mapping_Access
:= BLOG_DEF'Access;
BLOG_AUDIT_DEF : aliased constant ADO.Audits.Auditable_Mapping :=
(Count => 5,
Of_Class => BLOG_DEF'Access,
Members => (
1 => 1,
2 => 3,
3 => 6,
4 => 7,
5 => 8)
);
BLOG_AUDIT_TABLE : constant ADO.Audits.Auditable_Mapping_Access
:= BLOG_AUDIT_DEF'Access;
Null_Blog : constant Blog_Ref
:= Blog_Ref'(ADO.Objects.Object_Ref with null record);
type Blog_Impl is
new ADO.Audits.Auditable_Object_Record (Key_Type => ADO.Objects.KEY_INTEGER,
Of_Class => BLOG_DEF'Access,
With_Audit => BLOG_AUDIT_DEF'Access)
with record
Name : Ada.Strings.Unbounded.Unbounded_String;
Version : Integer;
Uid : Ada.Strings.Unbounded.Unbounded_String;
Create_Date : Ada.Calendar.Time;
Update_Date : Ada.Calendar.Time;
Url : Ada.Strings.Unbounded.Unbounded_String;
Format : AWA.Blogs.Models.Format_Type;
Default_Image_Url : Ada.Strings.Unbounded.Unbounded_String;
Workspace : AWA.Workspaces.Models.Workspace_Ref;
end record;
type Blog_Access is access all Blog_Impl;
overriding
procedure Destroy (Object : access Blog_Impl);
overriding
procedure Find (Object : in out Blog_Impl;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class;
Found : out Boolean);
overriding
procedure Load (Object : in out Blog_Impl;
Session : in out ADO.Sessions.Session'Class);
procedure Load (Object : in out Blog_Impl;
Stmt : in out ADO.Statements.Query_Statement'Class;
Session : in out ADO.Sessions.Session'Class);
overriding
procedure Save (Object : in out Blog_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
procedure Create (Object : in out Blog_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
overriding
procedure Delete (Object : in out Blog_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
procedure Set_Field (Object : in out Blog_Ref'Class;
Impl : out Blog_Access);
POST_NAME : aliased constant String := "awa_post";
COL_0_2_NAME : aliased constant String := "id";
COL_1_2_NAME : aliased constant String := "title";
COL_2_2_NAME : aliased constant String := "text";
COL_3_2_NAME : aliased constant String := "create_date";
COL_4_2_NAME : aliased constant String := "uri";
COL_5_2_NAME : aliased constant String := "version";
COL_6_2_NAME : aliased constant String := "publish_date";
COL_7_2_NAME : aliased constant String := "status";
COL_8_2_NAME : aliased constant String := "allow_comments";
COL_9_2_NAME : aliased constant String := "read_count";
COL_10_2_NAME : aliased constant String := "summary";
COL_11_2_NAME : aliased constant String := "format";
COL_12_2_NAME : aliased constant String := "author_id";
COL_13_2_NAME : aliased constant String := "blog_id";
COL_14_2_NAME : aliased constant String := "image_id";
POST_DEF : aliased constant ADO.Schemas.Class_Mapping :=
(Count => 15,
Table => POST_NAME'Access,
Members => (
1 => COL_0_2_NAME'Access,
2 => COL_1_2_NAME'Access,
3 => COL_2_2_NAME'Access,
4 => COL_3_2_NAME'Access,
5 => COL_4_2_NAME'Access,
6 => COL_5_2_NAME'Access,
7 => COL_6_2_NAME'Access,
8 => COL_7_2_NAME'Access,
9 => COL_8_2_NAME'Access,
10 => COL_9_2_NAME'Access,
11 => COL_10_2_NAME'Access,
12 => COL_11_2_NAME'Access,
13 => COL_12_2_NAME'Access,
14 => COL_13_2_NAME'Access,
15 => COL_14_2_NAME'Access)
);
POST_TABLE : constant ADO.Schemas.Class_Mapping_Access
:= POST_DEF'Access;
POST_AUDIT_DEF : aliased constant ADO.Audits.Auditable_Mapping :=
(Count => 7,
Of_Class => POST_DEF'Access,
Members => (
1 => 1,
2 => 4,
3 => 6,
4 => 7,
5 => 8,
6 => 10,
7 => 11)
);
POST_AUDIT_TABLE : constant ADO.Audits.Auditable_Mapping_Access
:= POST_AUDIT_DEF'Access;
Null_Post : constant Post_Ref
:= Post_Ref'(ADO.Objects.Object_Ref with null record);
type Post_Impl is
new ADO.Audits.Auditable_Object_Record (Key_Type => ADO.Objects.KEY_INTEGER,
Of_Class => POST_DEF'Access,
With_Audit => POST_AUDIT_DEF'Access)
with record
Title : Ada.Strings.Unbounded.Unbounded_String;
Text : Ada.Strings.Unbounded.Unbounded_String;
Create_Date : Ada.Calendar.Time;
Uri : Ada.Strings.Unbounded.Unbounded_String;
Version : Integer;
Publish_Date : ADO.Nullable_Time;
Status : AWA.Blogs.Models.Post_Status_Type;
Allow_Comments : Boolean;
Read_Count : Integer;
Summary : Ada.Strings.Unbounded.Unbounded_String;
Format : AWA.Blogs.Models.Format_Type;
Author : AWA.Users.Models.User_Ref;
Blog : AWA.Blogs.Models.Blog_Ref;
Image : AWA.Images.Models.Image_Ref;
end record;
type Post_Access is access all Post_Impl;
overriding
procedure Destroy (Object : access Post_Impl);
overriding
procedure Find (Object : in out Post_Impl;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class;
Found : out Boolean);
overriding
procedure Load (Object : in out Post_Impl;
Session : in out ADO.Sessions.Session'Class);
procedure Load (Object : in out Post_Impl;
Stmt : in out ADO.Statements.Query_Statement'Class;
Session : in out ADO.Sessions.Session'Class);
overriding
procedure Save (Object : in out Post_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
procedure Create (Object : in out Post_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
overriding
procedure Delete (Object : in out Post_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
procedure Set_Field (Object : in out Post_Ref'Class;
Impl : out Post_Access);
package File_1 is
new ADO.Queries.Loaders.File (Path => "blog-images.xml",
Sha1 => "9B2B599473F75F92CB5AB5045675E4CCEF926543");
package Def_Blog_Image_Get_Data is
new ADO.Queries.Loaders.Query (Name => "blog-image-get-data",
File => File_1.File'Access);
Query_Blog_Image_Get_Data : constant ADO.Queries.Query_Definition_Access
:= Def_Blog_Image_Get_Data.Query'Access;
package Def_Blog_Image_Width_Get_Data is
new ADO.Queries.Loaders.Query (Name => "blog-image-width-get-data",
File => File_1.File'Access);
Query_Blog_Image_Width_Get_Data : constant ADO.Queries.Query_Definition_Access
:= Def_Blog_Image_Width_Get_Data.Query'Access;
package Def_Blog_Image_Height_Get_Data is
new ADO.Queries.Loaders.Query (Name => "blog-image-height-get-data",
File => File_1.File'Access);
Query_Blog_Image_Height_Get_Data : constant ADO.Queries.Query_Definition_Access
:= Def_Blog_Image_Height_Get_Data.Query'Access;
package File_2 is
new ADO.Queries.Loaders.File (Path => "blog-tags.xml",
Sha1 => "9B2B599473F75F92CB5AB5045675E4CCEF926543");
package Def_Blog_Tag_Cloud is
new ADO.Queries.Loaders.Query (Name => "blog-tag-cloud",
File => File_2.File'Access);
Query_Blog_Tag_Cloud : constant ADO.Queries.Query_Definition_Access
:= Def_Blog_Tag_Cloud.Query'Access;
package File_3 is
new ADO.Queries.Loaders.File (Path => "blog-admin-post-list.xml",
Sha1 => "05BD01CF2BA5242266B1259502A7B26EC7ACC26D");
package Def_Adminpostinfo_Blog_Admin_Post_List is
new ADO.Queries.Loaders.Query (Name => "blog-admin-post-list",
File => File_3.File'Access);
Query_Blog_Admin_Post_List : constant ADO.Queries.Query_Definition_Access
:= Def_Adminpostinfo_Blog_Admin_Post_List.Query'Access;
package Def_Adminpostinfo_Blog_Admin_Post_List_Date is
new ADO.Queries.Loaders.Query (Name => "blog-admin-post-list-date",
File => File_3.File'Access);
Query_Blog_Admin_Post_List_Date : constant ADO.Queries.Query_Definition_Access
:= Def_Adminpostinfo_Blog_Admin_Post_List_Date.Query'Access;
package File_4 is
new ADO.Queries.Loaders.File (Path => "blog-list.xml",
Sha1 => "BB41EBE10B232F150560185E9A955BDA9FB7F77F");
package Def_Bloginfo_Blog_List is
new ADO.Queries.Loaders.Query (Name => "blog-list",
File => File_4.File'Access);
Query_Blog_List : constant ADO.Queries.Query_Definition_Access
:= Def_Bloginfo_Blog_List.Query'Access;
package File_5 is
new ADO.Queries.Loaders.File (Path => "blog-comment-list.xml",
Sha1 => "44E136D659FBA9859F2F077995D82161C743CAF3");
package Def_Commentinfo_Comment_List is
new ADO.Queries.Loaders.Query (Name => "comment-list",
File => File_5.File'Access);
Query_Comment_List : constant ADO.Queries.Query_Definition_Access
:= Def_Commentinfo_Comment_List.Query'Access;
package File_6 is
new ADO.Queries.Loaders.File (Path => "blog-images-info.xml",
Sha1 => "D82CB845BBF166F3A4EC77BDDB3C5633D227B603");
package Def_Imageinfo_Blog_Image is
new ADO.Queries.Loaders.Query (Name => "blog-image",
File => File_6.File'Access);
Query_Blog_Image : constant ADO.Queries.Query_Definition_Access
:= Def_Imageinfo_Blog_Image.Query'Access;
package File_7 is
new ADO.Queries.Loaders.File (Path => "blog-stat.xml",
Sha1 => "933526108281E4E7755E68427D69738611F833F3");
package Def_Monthstatinfo_Post_Publish_Stats is
new ADO.Queries.Loaders.Query (Name => "post-publish-stats",
File => File_7.File'Access);
Query_Post_Publish_Stats : constant ADO.Queries.Query_Definition_Access
:= Def_Monthstatinfo_Post_Publish_Stats.Query'Access;
package Def_Monthstatinfo_Post_Access_Stats is
new ADO.Queries.Loaders.Query (Name => "post-access-stats",
File => File_7.File'Access);
Query_Post_Access_Stats : constant ADO.Queries.Query_Definition_Access
:= Def_Monthstatinfo_Post_Access_Stats.Query'Access;
package File_8 is
new ADO.Queries.Loaders.File (Path => "blog-post-list.xml",
Sha1 => "24E5EBFA169F82908DA31BF4FF4C7688FA714CC3");
package Def_Postinfo_Blog_Post_List is
new ADO.Queries.Loaders.Query (Name => "blog-post-list",
File => File_8.File'Access);
Query_Blog_Post_List : constant ADO.Queries.Query_Definition_Access
:= Def_Postinfo_Blog_Post_List.Query'Access;
package Def_Postinfo_Blog_Post_Tag_List is
new ADO.Queries.Loaders.Query (Name => "blog-post-tag-list",
File => File_8.File'Access);
Query_Blog_Post_Tag_List : constant ADO.Queries.Query_Definition_Access
:= Def_Postinfo_Blog_Post_Tag_List.Query'Access;
end AWA.Blogs.Models;
|
-- SPDX-FileCopyrightText: 2020 Max Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-------------------------------------------------------------
with Program.Error_Listeners;
package Errors is
type Error_Listener is new Program.Error_Listeners.Error_Listener
with null record;
overriding procedure No_Body_Text
(Self : access Error_Listener;
Name : Program.Text);
overriding procedure Circular_Dependency
(Self : access Error_Listener;
Name : Program.Text);
end Errors;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- S Y S T E M . T E X T _ I O --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-2020, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- Minimal version of Text_IO body for use on TMS570 family of MCUs, using
-- SCI1/LIN1
-- @design
-- This package is in charge of sending characters to the remote host
-- machine. The application output is sent through the UART, from which the
-- host machine extracts the application output.
--
-- The TMS570 runtime uses the SCI1/LIN1 module, configured for 115200 baud
-- rate, one stop bit, no parity.
with Interfaces; use Interfaces;
-- @design used for the 32-bit integers definition
with System.Board_Parameters; use System.Board_Parameters;
-- @design used to retrieve the system clock, used to calculate the prescaler
-- values to achieve the desired baud rate.
package body System.Text_IO is
SCI_BASE : constant := 16#FFF7_E400#;
-- SCI base address
SCIGCR0 : Unsigned_32;
for SCIGCR0'Address use SCI_BASE + 16#00#;
pragma Volatile (SCIGCR0);
pragma Import (Ada, SCIGCR0);
SCIGCR1 : Unsigned_32;
for SCIGCR1'Address use SCI_BASE + 16#04#;
pragma Volatile (SCIGCR1);
pragma Import (Ada, SCIGCR1);
SCIFLR : Unsigned_32;
for SCIFLR'Address use SCI_BASE + 16#1C#;
pragma Volatile (SCIFLR);
pragma Import (Ada, SCIFLR);
TX_READY : constant := 16#100#;
RX_READY : constant := 16#200#;
BRS : Unsigned_32;
for BRS'Address use SCI_BASE + 16#2C#;
pragma Volatile (BRS);
pragma Import (Ada, BRS);
SCIFORMAT : Unsigned_32;
for SCIFORMAT'Address use SCI_BASE + 16#28#;
pragma Volatile (SCIFORMAT);
pragma Import (Ada, SCIFORMAT);
SCIRD : Unsigned_32;
for SCIRD'Address use SCI_BASE + 16#34#;
pragma Volatile (SCIRD);
pragma Import (Ada, SCIRD);
SCITD : Unsigned_32;
for SCITD'Address use SCI_BASE + 16#38#;
pragma Volatile (SCITD);
pragma Import (Ada, SCITD);
SCIPIO0 : Unsigned_32;
for SCIPIO0'Address use SCI_BASE + 16#3C#;
pragma Volatile (SCIPIO0);
pragma Import (Ada, SCIPIO0);
SCIPIO8 : Unsigned_32;
for SCIPIO8'Address use SCI_BASE + 16#5C#;
pragma Volatile (SCIPIO8);
pragma Import (Ada, SCIPIO8);
---------
-- Get --
---------
function Get return Character is
begin
return Character'Val (SCIRD and 16#FF#);
end Get;
----------------
-- Initialize --
----------------
procedure Initialize is
begin
-- Do not reinitialize the SCI, if it is already initialized
if (SCIGCR0 and 1) = 0 then
-- Bring out of reset
SCIGCR0 := 1;
-- 8n1, enable RX and TX, async, idle-line mode, SWnRST, internal clk
-- NOTE: SPNU499A (Nov 2012) is incorrect on COMM MODE: Idle line
-- mode value is 0.
SCIGCR1 := 16#03_00_00_22#;
-- Baud rate. VCLK = RTI1CLK
declare
Baud : constant := 115200;
P : constant := VCLK_Frequency / (16 * Baud) - 1;
M : constant := (VCLK_Frequency / Baud) rem 16;
begin
BRS := P + M * 2**24;
end;
-- 8 bits
SCIFORMAT := 7;
-- Enable Tx and Rx pins, pull-up
SCIPIO0 := 2#110#;
SCIPIO8 := 2#110#;
-- Enable SCI
SCIGCR1 := SCIGCR1 or 16#80#;
end if;
Initialized := True;
end Initialize;
-----------------
-- Is_Tx_Ready --
-----------------
function Is_Tx_Ready return Boolean is
((SCIFLR and TX_READY) /= 0);
-----------------
-- Is_Rx_Ready --
-----------------
function Is_Rx_Ready return Boolean is
((SCIFLR and RX_READY) /= 0);
---------
-- Put --
---------
procedure Put (C : Character) is
begin
SCITD := Character'Pos (C);
end Put;
----------------------------
-- Use_Cr_Lf_For_New_Line --
----------------------------
function Use_Cr_Lf_For_New_Line return Boolean is
begin
return True;
end Use_Cr_Lf_For_New_Line;
end System.Text_IO;
|
--//////////////////////////////////////////////////////////
-- //
-- // SFML - Simple and Fast Multimedia Library
-- // Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-- //
-- // This software is provided 'as-is', without any express or implied warranty.
-- // In no event will the authors be held liable for any damages arising from the use of this software.
-- //
-- // Permission is granted to anyone to use this software for any purpose,
-- // including commercial applications, and to alter it and redistribute it freely,
-- // subject to the following restrictions:
-- //
-- // 1. The origin of this software must not be misrepresented;
-- // you must not claim that you wrote the original software.
-- // If you use this software in a product, an acknowledgment
-- // in the product documentation would be appreciated but is not required.
-- //
-- // 2. Altered source versions must be plainly marked as such,
-- // and must not be misrepresented as being the original software.
-- //
-- // 3. This notice may not be removed or altered from any source distribution.
-- //
--//////////////////////////////////////////////////////////
--//////////////////////////////////////////////////////////
--//////////////////////////////////////////////////////////
with Interfaces.C.Strings;
package body Sf.Network.Ftp is
use Interfaces.C.Strings;
package body ListingResponse is
--//////////////////////////////////////////////////////////
--/ Get the full message contained in the response
--/
--/ @param FtpListingResponse Ftp listing response
--/
--/ @return The response message
--/
--//////////////////////////////////////////////////////////
function GetMessage (FtpListingResponse : sfFtpListingResponse_Ptr) return String is
function Internal (FtpListingResponse : sfFtpListingResponse_Ptr) return chars_ptr;
pragma Import (C, Internal, "sfFtpListingResponse_getMessage");
Temp : chars_ptr := Internal (FtpListingResponse);
R : String := Value (Temp);
begin
Free (Temp);
return R;
end GetMessage;
--//////////////////////////////////////////////////////////
--/ @brief Return a directory/file name contained in a FTP listing response
--/
--/ @param ftpListingResponse Ftp listing response
--/ @param index Index of the name to get (in range [0 .. getCount])
--/
--/ @return The requested name
--/
--//////////////////////////////////////////////////////////
function GetName (FtpListingResponse : sfFtpListingResponse_Ptr; Index : sfSize_t) return String is
function Internal (FtpListingResponse : sfFtpListingResponse_Ptr; Index : sfSize_t) return chars_ptr;
pragma Import (C, Internal, "sfFtpListingResponse_getName");
Temp : chars_ptr := Internal (FtpListingResponse, Index);
R : String := Value (Temp);
begin
Free (Temp);
return R;
end GetName;
end ListingResponse;
package body DirectoryResponse is
--//////////////////////////////////////////////////////////
--/ Get the full message contained in the response
--/
--/ @param FtpDirectoryResponse Ftp directory response
--/
--/ @return The response message
--/
--//////////////////////////////////////////////////////////
function GetMessage (FtpDirectoryResponse : sfFtpDirectoryResponse_Ptr) return String is
function Internal (FtpDirectoryResponse : sfFtpDirectoryResponse_Ptr) return chars_ptr;
pragma Import (C, Internal, "sfFtpDirectoryResponse_getMessage");
Temp : chars_ptr := Internal (FtpDirectoryResponse);
R : String := Value (Temp);
begin
Free (Temp);
return R;
end GetMessage;
--//////////////////////////////////////////////////////////
--/ Get the directory returned in the response
--/
--/ @param FtpDirectoryResponse Ftp directory response
--/
--/ @return Directory name
--/
--//////////////////////////////////////////////////////////
function GetDirectory (FtpDirectoryResponse : sfFtpDirectoryResponse_Ptr) return String is
function Internal (FtpDirectoryResponse : sfFtpDirectoryResponse_Ptr) return chars_ptr;
pragma Import (C, Internal, "sfFtpDirectoryResponse_getDirectory");
Temp : chars_ptr := Internal (FtpDirectoryResponse);
R : String := Value (Temp);
begin
Free (Temp);
return R;
end GetDirectory;
end DirectoryResponse;
package body Response is
--//////////////////////////////////////////////////////////
--/ Get the full message contained in the response
--/
--/ @param FtpResponse Ftp response
--/
--/ @return The response message
--/
--//////////////////////////////////////////////////////////
function GetMessage (FtpResponse : sfFtpResponse_Ptr) return String is
function Internal (FtpResponse : sfFtpResponse_Ptr) return chars_ptr;
pragma Import (C, Internal, "sfFtpResponse_getMessage");
Temp : chars_ptr := Internal (FtpResponse);
R : String := Value (Temp);
begin
Free (Temp);
return R;
end GetMessage;
end Response;
function Login
(ftp : sfFtp_Ptr;
name : String;
password : String)
return sfFtpResponse_Ptr
is
function Internal
(Ftp : sfFtp_Ptr;
UserName : chars_ptr;
Password : chars_ptr)
return sfFtpResponse_Ptr;
pragma Import (C, Internal, "sfFtp_login");
Temp1 : chars_ptr := New_String (name);
Temp2 : chars_ptr := New_String (password);
R : sfFtpResponse_Ptr := Internal (Ftp, Temp1, Temp2);
begin
Free (Temp1);
Free (Temp2);
return R;
end Login;
--//////////////////////////////////////////////////////////
--/ Get the contents of the given directory
--/ (subdirectories and files)
--/
--/ @param Ftp Ftp instance
--/ @param Directory Directory to list ("" by default, the current one)
--/
--/ @return Server response to the request
--/
--//////////////////////////////////////////////////////////
function GetDirectoryListing (Ftp : sfFtp_Ptr; Directory : String) return sfFtpListingResponse_Ptr is
function Internal (Ftp : sfFtp_Ptr; Directory : chars_ptr) return sfFtpListingResponse_Ptr;
pragma Import (C, Internal, "sfFtp_getDirectoryListing");
Temp : chars_ptr := New_String (Directory);
R : sfFtpListingResponse_Ptr := Internal (Ftp, Temp);
begin
Free (Temp);
return R;
end GetDirectoryListing;
--//////////////////////////////////////////////////////////
--/ Change the current working directory
--/
--/ @param Ftp Ftp instance
--/ @param Directory New directory, relative to the current one
--/
--/ @return Server response to the request
--/
--//////////////////////////////////////////////////////////
function ChangeDirectory (Ftp : sfFtp_Ptr; Directory : String) return sfFtpResponse_Ptr is
function Internal (Ftp : sfFtp_Ptr; Directory : chars_ptr) return sfFtpResponse_Ptr;
pragma Import (C, Internal, "sfFtp_changeDirectory");
Temp : chars_ptr := New_String (Directory);
R : sfFtpResponse_Ptr := Internal (Ftp, Temp);
begin
Free (Temp);
return R;
end ChangeDirectory;
--//////////////////////////////////////////////////////////
--/ @brief Create a new directory
--/
--/ The new directory is created as a child of the current
--/ working directory.
--/
--/ @param ftp Ftp object
--/ @param name Name of the directory to create
--/
--/ @return Server response to the request
--/
--//////////////////////////////////////////////////////////
function CreateDirectory (Ftp : sfFtp_Ptr; Name : String) return sfFtpResponse_Ptr is
function Internal (Ftp : sfFtp_Ptr; Name : chars_ptr) return sfFtpResponse_Ptr;
pragma Import (C, Internal, "sfFtp_createDirectory");
Temp : chars_ptr := New_String (Name);
R : sfFtpResponse_Ptr := Internal (Ftp, Temp);
begin
Free (Temp);
return R;
end CreateDirectory;
--//////////////////////////////////////////////////////////
--/ Remove an existing directory
--/
--/ @param Ftp Ftp instance
--/ @param Name Name of the directory to remove
--/
--/ @return Server response to the request
--/
--//////////////////////////////////////////////////////////
function DeleteDirectory (Ftp : sfFtp_Ptr; Name : String) return sfFtpResponse_Ptr is
function Internal (Ftp : sfFtp_Ptr; Name : chars_ptr) return sfFtpResponse_Ptr;
pragma Import (C, Internal, "sfFtp_deleteDirectory");
Temp : chars_ptr := New_String (Name);
R : sfFtpResponse_Ptr := Internal (Ftp, Temp);
begin
Free (Temp);
return R;
end DeleteDirectory;
--//////////////////////////////////////////////////////////
--/ Rename a file
--/
--/ @param Ftp Ftp instance
--/ @param File File to rename
--/ @param NewName New name
--/
--/ @return Server response to the request
--/
--//////////////////////////////////////////////////////////
function RenameFile
(Ftp : sfFtp_Ptr;
File : String;
NewName : String)
return sfFtpResponse_Ptr
is
function Internal
(Ftp : sfFtp_Ptr;
File : chars_ptr;
NewName : chars_ptr)
return sfFtpResponse_Ptr;
pragma Import (C, Internal, "sfFtp_renameFile");
Temp1 : chars_ptr := New_String (File);
Temp2 : chars_ptr := New_String (NewName);
R : sfFtpResponse_Ptr := Internal (Ftp, Temp1, Temp2);
begin
Free (Temp1);
Free (Temp2);
return R;
end RenameFile;
--//////////////////////////////////////////////////////////
--/ Remove an existing file
--/
--/ @param Ftp Ftp instance
--/ @param Name File to remove
--/
--/ @return Server response to the request
--/
--//////////////////////////////////////////////////////////
function DeleteFile (Ftp : sfFtp_Ptr; Name : String) return sfFtpResponse_Ptr is
function Internal (Ftp : sfFtp_Ptr; Name : chars_ptr) return sfFtpResponse_Ptr;
pragma Import (C, Internal, "sfFtp_deleteFile");
Temp : chars_ptr := New_String (Name);
R : sfFtpResponse_Ptr := Internal (Ftp, Temp);
begin
Free (Temp);
return R;
end DeleteFile;
function download
(ftp : sfFtp_Ptr;
remoteFile : String;
localPath : String;
mode : sfFtpTransferMode) return sfFtpResponse_Ptr
is
function Internal
(ftp : sfFtp_Ptr;
remoteFile : chars_ptr;
localPath : chars_ptr;
mode : sfFtpTransferMode)
return sfFtpResponse_Ptr;
pragma Import (C, Internal, "sfFtp_download");
Temp1 : chars_ptr := New_String (remoteFile);
Temp2 : chars_ptr := New_String (localPath);
R : sfFtpResponse_Ptr := Internal (ftp, Temp1, Temp2, Mode);
begin
Free (Temp1);
Free (Temp2);
return R;
end Download;
function upload
(ftp : sfFtp_Ptr;
localFile : String;
remotePath : String;
mode : sfFtpTransferMode;
append : sfBool) return sfFtpResponse_Ptr
is
function Internal
(ftp : sfFtp_Ptr;
localFile : chars_ptr;
remotePath : chars_ptr;
mode : sfFtpTransferMode;
append : sfBool) return sfFtpResponse_Ptr;
pragma Import (C, Internal, "sfFtp_upload");
Temp1 : chars_ptr := New_String (LocalFile);
Temp2 : chars_ptr := New_String (remotePath);
R : sfFtpResponse_Ptr := Internal (Ftp, Temp1, Temp2, Mode, append);
begin
Free (Temp1);
Free (Temp2);
return R;
end Upload;
--//////////////////////////////////////////////////////////
--/ @brief Send a command to the FTP server
--/
--/ While the most often used commands are provided as
--/ specific functions, this function can be used to send
--/ any FTP command to the server. If the command requires
--/ one or more parameters, they can be specified in
--/ @a parameter. Otherwise you should pass NULL.
--/ If the server returns information, you can extract it
--/ from the response using sfResponse_getMessage().
--/
--/ @param ftp Ftp object
--/ @param command Command to send
--/ @param parameter Command parameter
--/
--/ @return Server response to the request
--/
--//////////////////////////////////////////////////////////
function sendCommand
(ftp : sfFtp_Ptr;
command : String;
parameter : String)
return sfFtpResponse_Ptr is
function Internal
(Ftp : sfFtp_Ptr;
command : chars_ptr;
parameter : chars_ptr)
return sfFtpResponse_Ptr;
pragma Import (C, Internal, "sfFtp_sendCommand");
Temp1 : chars_ptr := New_String (command);
Temp2 : chars_ptr := New_String (parameter);
R : sfFtpResponse_Ptr := Internal (Ftp, Temp1, Temp2);
begin
Free (Temp1);
Free (Temp2);
return R;
end sendCommand;
end Sf.Network.Ftp;
|
-----------------------------------------------------------------------
-- awa-tags -- Tags management
-- Copyright (C) 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.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <b>Tags</b> module allows to associate general purpose tags to any database entity.
-- It provides a JSF component that allows to insert easily a list of tags in a page and
-- in a form. An application can use the bean types defined in <tt>AWA.Tags.Beans</tt>
-- to define the tags and it will use the <tt>awa:tagList</tt> component to display them.
-- A tag cloud is also provided by the <tt>awa:tagCloud</tt> component.
--
-- == Model ==
-- The database model is generic and it uses the <tt>Entity_Type</tt> provided by
-- [http://ada-ado.googlecode.com ADO] to associate a tag to entities stored in different
-- tables. The <tt>Entity_Type</tt> identifies the database table and the stored identifier
-- in <tt>for_entity_id</tt> defines the entity in that table.
--
-- [http://ada-awa.googlecode.com/svn/wiki/awa_tags_model.png]
--
-- @include awa-tags-modules.ads
-- @include awa-tags-beans.ads
-- @include awa-tags-components.ads
--
-- == Queries ==
-- @include tag-queries.xml
package AWA.Tags is
pragma Pure;
end AWA.Tags;
|
-- Handle Foreign Command
--
-- This procedure supports the use of the VAX/VMS Foreign Command facility
-- in a way similar to that used by the VAX C runtime argc/argv mechanism.
--
-- The program is to be 'installed as a foreign command':
--
-- $ foo :== $disk:[directories]foo
--
-- after which the parameters to a command such as
--
-- $ foo -x bar
--
-- are obtainable.
--
-- In this case, Handle_Argument is called as:
--
-- Handle_Argument (Argument_count'First, "-x");
-- Handle_Argument (Argument_Count'First + 1, "bar");
--
-- As with VAX C,
-- (a) one level of quotes '"' is stripped.
-- (b) arguments not in quotes are converted to lower-case (so, if you
-- need upper-case, you _must_ quote the argument).
-- (c) only white space delimits arguments, so "-x" and -"x" are the same.
--
-- 2.9.92 sjw; orig
generic
type Argument_Count is range <>;
with procedure Handle_Argument (Count : Argument_Count; Argument : String);
procedure Handle_Foreign_Command;
|
with Ada.Containers.Array_Sorting;
with System.Long_Long_Integer_Types;
procedure Ada.Containers.Generic_Sort (First, Last : Index_Type'Base) is
subtype Word_Integer is System.Long_Long_Integer_Types.Word_Integer;
begin
if Index_Type'Pos (Index_Type'First) in
Long_Long_Integer (Word_Integer'First) ..
Long_Long_Integer (Word_Integer'Last)
and then Index_Type'Pos (Index_Type'Last) in
Long_Long_Integer (Word_Integer'First) ..
Long_Long_Integer (Word_Integer'Last)
then
declare
function LT (Left, Right : Word_Integer; Params : System.Address)
return Boolean;
function LT (Left, Right : Word_Integer; Params : System.Address)
return Boolean
is
pragma Unreferenced (Params);
Left_Index : constant Index_Type := Index_Type'Val (Left);
Right_Index : constant Index_Type := Index_Type'Val (Right);
begin
return Before (Left_Index, Right_Index);
end LT;
procedure Swap (
Left, Right : Word_Integer;
Params : System.Address);
procedure Swap (
Left, Right : Word_Integer;
Params : System.Address)
is
pragma Unreferenced (Params);
Left_Index : constant Index_Type := Index_Type'Val (Left);
Right_Index : constant Index_Type := Index_Type'Val (Right);
begin
Swap (Left_Index, Right_Index);
end Swap;
begin
Array_Sorting.In_Place_Merge_Sort (
Index_Type'Pos (First),
Index_Type'Pos (Last),
System.Null_Address,
LT => LT'Access,
Swap => Swap'Access);
end;
else
declare
type Context_Type is limited record
Offset : Long_Long_Integer;
end record;
pragma Suppress_Initialization (Context_Type);
function LT (Left, Right : Word_Integer; Params : System.Address)
return Boolean;
function LT (Left, Right : Word_Integer; Params : System.Address)
return Boolean
is
Context : Context_Type;
for Context'Address use Params;
Left_Index : constant Index_Type :=
Index_Type'Val (Long_Long_Integer (Left) + Context.Offset);
Right_Index : constant Index_Type :=
Index_Type'Val (Long_Long_Integer (Right) + Context.Offset);
begin
return Before (Left_Index, Right_Index);
end LT;
procedure Swap (
Left, Right : Word_Integer;
Params : System.Address);
procedure Swap (
Left, Right : Word_Integer;
Params : System.Address)
is
Context : Context_Type;
for Context'Address use Params;
Left_Index : constant Index_Type :=
Index_Type'Val (Long_Long_Integer (Left) + Context.Offset);
Right_Index : constant Index_Type :=
Index_Type'Val (Long_Long_Integer (Right) + Context.Offset);
begin
Swap (Left_Index, Right_Index);
end Swap;
Offset : constant Long_Long_Integer := Index_Type'Pos (First);
Context : aliased Context_Type := (Offset => Offset);
begin
Array_Sorting.In_Place_Merge_Sort (
0,
Word_Integer (Long_Long_Integer'(Index_Type'Pos (Last) - Offset)),
Context'Address,
LT => LT'Access,
Swap => Swap'Access);
end;
end if;
end Ada.Containers.Generic_Sort;
|
with Ada.Characters.Handling, Ada.Text_IO;
use Ada.Characters.Handling, Ada.Text_IO;
procedure Upper_Case_String is
S : constant String := "alphaBETA";
begin
Put_Line (To_Upper (S));
Put_Line (To_Lower (S));
end Upper_Case_String;
|
--
-- Copyright (C) 2016 secunet Security Networks AG
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
with HW.GFX.GMA.Registers;
package body HW.GFX.GMA.PLLs.DPLL is
-- NOTE: Order of DPLLs is twisted => always use named associations!
type Regs is array (Configurable_DPLLs) of Registers.Registers_Index;
DPLL_CTL : constant Regs := Regs'
(DPLL1 => Registers.LCPLL2_CTL,
DPLL2 => Registers.WRPLL_CTL_1,
DPLL3 => Registers.WRPLL_CTL_2);
DPLL_CTL_PLL_ENABLE : constant := 1 * 2 ** 31;
----------------------------------------------------------------------------
DPLL_CFGR1 : constant Regs := Regs'
(DPLL1 => Registers.DPLL1_CFGR1,
DPLL2 => Registers.DPLL2_CFGR1,
DPLL3 => Registers.DPLL3_CFGR1);
DPLL_CFGR1_FREQUENCY_ENABLE : constant := 1 * 2 ** 31;
DPLL_CFGR1_DCO_FRACTION_SHIFT : constant := 9;
DPLL_CFGR1_DCO_FRACTION_MASK : constant := 16#7fff# * 2 ** 9;
DPLL_CFGR1_DCO_INTEGER_MASK : constant := 16#01ff# * 2 ** 0;
DPLL_CFGR2 : constant Regs := Regs'
(DPLL1 => Registers.DPLL1_CFGR2,
DPLL2 => Registers.DPLL2_CFGR2,
DPLL3 => Registers.DPLL3_CFGR2);
DPLL_CFGR2_QDIV_RATIO_SHIFT : constant := 8;
DPLL_CFGR2_QDIV_RATIO_MASK : constant := 255 * 2 ** 8;
DPLL_CFGR2_QDIV_MODE : constant := 1 * 2 ** 7;
DPLL_CFGR2_KDIV_SHIFT : constant := 5;
DPLL_CFGR2_KDIV_MASK : constant := 3 * 2 ** 5;
DPLL_CFGR2_PDIV_SHIFT : constant := 2;
DPLL_CFGR2_PDIV_MASK : constant := 7 * 2 ** 2;
DPLL_CFGR2_CENTRAL_FREQ_MASK : constant := 3 * 2 ** 0;
DPLL_CFGR2_CENTRAL_FREQ_9600MHZ : constant := 0 * 2 ** 0;
DPLL_CFGR2_CENTRAL_FREQ_9000MHZ : constant := 1 * 2 ** 0;
DPLL_CFGR2_CENTRAL_FREQ_8400MHZ : constant := 3 * 2 ** 0;
----------------------------------------------------------------------------
HDMI_MODE : constant := 1 * 2 ** 5;
SSC : constant := 1 * 2 ** 4;
LINK_RATE_MASK : constant := 7 * 2 ** 1;
LINK_RATE_2700MHZ : constant := 0 * 2 ** 1;
LINK_RATE_1350MHZ : constant := 1 * 2 ** 1;
LINK_RATE_810MHZ : constant := 2 * 2 ** 1;
LINK_RATE_1620MHZ : constant := 3 * 2 ** 1;
LINK_RATE_1080MHZ : constant := 4 * 2 ** 1;
LINK_RATE_2160MHZ : constant := 5 * 2 ** 1;
OVERRIDE : constant := 1 * 2 ** 0;
LOCK : constant := 1 * 2 ** 0;
type Shifts is array (Configurable_DPLLs) of Natural;
DPLL_CTRL1_SHIFT : constant Shifts :=
(DPLL1 => 6, DPLL2 => 12, DPLL3 => 18);
DPLL_STATUS_SHIFT : constant Shifts :=
(DPLL1 => 8, DPLL2 => 16, DPLL3 => 24);
function LINK_RATE (Link_Rate : DP_Bandwidth) return Word32 is
begin
return (case Link_Rate is
when DP_Bandwidth_5_4 => LINK_RATE_2700MHZ,
when DP_Bandwidth_2_7 => LINK_RATE_1350MHZ,
when DP_Bandwidth_1_62 => LINK_RATE_810MHZ);
end LINK_RATE;
function DPLL_CTRL1_DPLLx
(Value : Word32;
PLL : Configurable_DPLLs)
return Word32 is
begin
return Shift_Left (Value, DPLL_CTRL1_SHIFT (PLL));
end DPLL_CTRL1_DPLLx;
function DPLL_STATUS_DPLLx_LOCK (PLL : Configurable_DPLLs) return Word32 is
begin
return Shift_Left (LOCK, DPLL_STATUS_SHIFT (PLL));
end DPLL_STATUS_DPLLx_LOCK;
----------------------------------------------------------------------------
subtype PDiv_Range is Pos64 range 1 .. 7;
subtype QDiv_Range is Pos64 range 1 .. 255;
subtype KDiv_Range is Pos64 range 1 .. 5;
type Central_Frequency is (CF_INVALID, CF_9600MHZ, CF_9000MHZ, CF_8400MHZ);
subtype Valid_Central_Freq is
Central_Frequency range CF_9600MHZ .. CF_8400MHZ;
type CF_Pos is array (Valid_Central_Freq) of Pos64;
CF_Pos64 : constant CF_Pos := CF_Pos'
(CF_9600MHZ => 9_600_000_000,
CF_9000MHZ => 9_000_000_000,
CF_8400MHZ => 8_400_000_000);
subtype DCO_Frequency is
Pos64 range 1 .. CF_Pos64 (CF_9600MHZ) + CF_Pos64 (CF_9600MHZ) / 100;
function DPLL_CFGR1_DCO_FRACTION (DCO_Freq : DCO_Frequency) return Word32
with
Pre => True
is
begin
return Shift_Left
(Word32 ((DCO_Freq * 2 ** 15) / 24_000_000) and 16#7fff#,
DPLL_CFGR1_DCO_FRACTION_SHIFT);
end DPLL_CFGR1_DCO_FRACTION;
function DPLL_CFGR1_DCO_INTEGER (DCO_Freq : DCO_Frequency) return Word32
with
Pre => True
is
begin
return Word32 (DCO_Freq / 24_000_000);
end DPLL_CFGR1_DCO_INTEGER;
function DPLL_CFGR2_PDIV (PDiv : PDiv_Range) return Word32 is
begin
return Shift_Left
((case PDiv is
when 1 => 0,
when 2 => 1,
when 3 => 2,
when 7 => 4,
when others => 4),
DPLL_CFGR2_PDIV_SHIFT);
end DPLL_CFGR2_PDIV;
function DPLL_CFGR2_QDIV (QDiv : QDiv_Range) return Word32 is
begin
return Shift_Left (Word32 (QDiv), DPLL_CFGR2_QDIV_RATIO_SHIFT) or
(if QDiv /= 1 then DPLL_CFGR2_QDIV_MODE else 0);
end DPLL_CFGR2_QDIV;
function DPLL_CFGR2_KDIV (KDiv : KDiv_Range) return Word32 is
begin
return Shift_Left
((case KDiv is
when 5 => 0,
when 2 => 1,
when 3 => 2,
when 1 => 3,
when others => 0),
DPLL_CFGR2_KDIV_SHIFT);
end DPLL_CFGR2_KDIV;
function DPLL_CFGR2_CENTRAL_FREQ (CF : Valid_Central_Freq) return Word32 is
begin
return (case CF is
when CF_9600MHZ => DPLL_CFGR2_CENTRAL_FREQ_9600MHZ,
when CF_9000MHZ => DPLL_CFGR2_CENTRAL_FREQ_9000MHZ,
when CF_8400MHZ => DPLL_CFGR2_CENTRAL_FREQ_8400MHZ);
end DPLL_CFGR2_CENTRAL_FREQ;
----------------------------------------------------------------------------
procedure Calculate_DPLL
(Dotclock : in Frequency_Type;
Central_Freq : out Central_Frequency;
DCO_Freq : out DCO_Frequency;
PDiv : out PDiv_Range;
QDiv : out QDiv_Range;
KDiv : out KDiv_Range)
with
Pre => True
is
Max_Pos_Deviation : constant := 1;
Max_Neg_Deviation : constant := 6;
subtype Div_Range is Pos64 range 1 .. 98;
subtype Candidate_Index is Positive range 1 .. 36;
type Candidate_Array is array (Candidate_Index) of Div_Range;
type Candidate_List is record
Divs : Candidate_Array;
Count : Candidate_Index;
end record;
type Parity_Type is (Even, Odd);
type Candidates_Type is array (Parity_Type) of Candidate_List;
Candidates : constant Candidates_Type := Candidates_Type'
(Even => Candidate_List'
(Divs => Candidate_Array'
(4, 6, 8, 10, 12, 14, 16, 18, 20, 24, 28, 30, 32, 36, 40, 42, 44,
48, 52, 54, 56, 60, 64, 66, 68, 70, 72, 76, 78, 80, 84, 88, 90,
92, 96, 98),
Count => 36),
Odd => Candidate_List'
(Divs => Candidate_Array'(3, 5, 7, 9, 15, 21, 35, others => 1),
Count => 7));
Temp_Freq,
Allowed_Deviation : Pos64;
Deviation : Int64;
Temp_Central : DCO_Frequency;
Min_Deviation : Int64 := Int64'Last;
Div : Div_Range := Div_Range'Last;
begin
Central_Freq := CF_INVALID;
DCO_Freq := 1;
PDiv := 1;
QDiv := 1;
KDiv := 1;
for Parity in Parity_Type loop
for CF in Valid_Central_Freq loop
Temp_Central := CF_Pos64 (CF);
for I in Candidate_Index range 1 .. Candidates (Parity).Count loop
Temp_Freq := Candidates (Parity).Divs (I) * 5 * Dotclock;
if Temp_Freq > Temp_Central then
Deviation := Temp_Freq - Temp_Central;
Allowed_Deviation := (Max_Pos_Deviation * Temp_Central) / 100;
else
Deviation := Temp_Central - Temp_Freq;
Allowed_Deviation := (Max_Neg_Deviation * Temp_Central) / 100;
end if;
if Deviation < Min_Deviation and
Deviation < Allowed_Deviation
then
Min_Deviation := Deviation;
Central_Freq := CF;
DCO_Freq := Temp_Freq;
Div := Candidates (Parity).Divs (I);
end if;
end loop;
end loop;
exit when Central_Freq /= CF_INVALID;
end loop;
if Central_Freq /= CF_INVALID then
if Div mod 2 = 0 then
pragma Assert (Div /= 1);
pragma Assert (Div > 1);
Div := Div / 2;
if Div = 1 or Div = 3 or Div = 5 then
-- 2, 6 and 10
PDiv := 2;
QDiv := 1;
KDiv := Div;
elsif Div mod 2 = 0 then
-- divisible by 4
PDiv := 2;
QDiv := Div / 2;
KDiv := 2;
elsif Div mod 3 = 0 then
-- divisible by 6
PDiv := 3;
QDiv := Div / 3;
KDiv := 2;
elsif Div mod 7 = 0 then
-- divisible by 14
PDiv := 7;
QDiv := Div / 7;
KDiv := 2;
end if;
elsif Div = 7 or Div = 21 or Div = 35 then
-- 7, 21 and 35
PDiv := 7;
QDiv := 1;
KDiv := Div / 7;
elsif Div = 3 or Div = 9 or Div = 15 then
-- 3, 9 and 15
PDiv := 3;
QDiv := 1;
KDiv := Div / 3;
elsif Div = 5 then
-- 5
PDiv := 5;
QDiv := 1;
KDiv := 1;
end if;
end if;
end Calculate_DPLL;
----------------------------------------------------------------------------
procedure On
(PLL : in Configurable_DPLLs;
Port_Cfg : in Port_Config;
Success : out Boolean)
is
Central_Freq : Central_Frequency;
DCO_Freq : DCO_Frequency;
PDiv : PDiv_Range;
QDiv : QDiv_Range;
KDiv : KDiv_Range;
begin
if Port_Cfg.Display = DP then
Registers.Unset_And_Set_Mask
(Register => Registers.DPLL_CTRL1,
Mask_Unset => DPLL_CTRL1_DPLLx (HDMI_MODE, PLL) or
DPLL_CTRL1_DPLLx (SSC, PLL) or
DPLL_CTRL1_DPLLx (LINK_RATE_MASK, PLL),
Mask_Set => DPLL_CTRL1_DPLLx (LINK_RATE
(Port_Cfg.DP.Bandwidth), PLL) or
DPLL_CTRL1_DPLLx (OVERRIDE, PLL));
Registers.Posting_Read (Registers.DPLL_CTRL1);
Success := True;
else
Calculate_DPLL
(Port_Cfg.Mode.Dotclock, Central_Freq, DCO_Freq, PDiv, QDiv, KDiv);
Success := Central_Freq /= CF_INVALID;
if Success then
Registers.Unset_And_Set_Mask
(Register => Registers.DPLL_CTRL1,
Mask_Unset => DPLL_CTRL1_DPLLx (SSC, PLL),
Mask_Set => DPLL_CTRL1_DPLLx (HDMI_MODE, PLL) or
DPLL_CTRL1_DPLLx (OVERRIDE, PLL));
Registers.Write
(Register => DPLL_CFGR1 (PLL),
Value => DPLL_CFGR1_FREQUENCY_ENABLE or
DPLL_CFGR1_DCO_FRACTION (DCO_Freq) or
DPLL_CFGR1_DCO_INTEGER (DCO_Freq));
Registers.Write
(Register => DPLL_CFGR2 (PLL),
Value => DPLL_CFGR2_QDIV (QDiv) or
DPLL_CFGR2_KDIV (KDiv) or
DPLL_CFGR2_PDIV (PDiv) or
DPLL_CFGR2_CENTRAL_FREQ (Central_Freq));
Registers.Posting_Read (Registers.DPLL_CTRL1);
Registers.Posting_Read (DPLL_CFGR1 (PLL));
Registers.Posting_Read (DPLL_CFGR2 (PLL));
end if;
end if;
if Success then
Registers.Write
(Register => DPLL_CTL (PLL),
Value => DPLL_CTL_PLL_ENABLE);
Registers.Wait_Set_Mask
(Register => Registers.DPLL_STATUS,
Mask => DPLL_STATUS_DPLLx_LOCK (PLL));
end if;
end On;
procedure Off (PLL : Configurable_DPLLs) is
begin
Registers.Unset_Mask (DPLL_CTL (PLL), DPLL_CTL_PLL_ENABLE);
end Off;
end HW.GFX.GMA.PLLs.DPLL;
|
------------------------------------------------------------------------------
-- --
-- GESTE --
-- --
-- Copyright (C) 2018 Fabien Chouteau --
-- --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with Interfaces; use Interfaces;
with GESTE.Maths_Types; use GESTE.Maths_Types;
package GESTE.Maths_Tables is
Sine_Table_Size : constant := 256;
Sine_Alpha : constant := Value (Sine_Table_Size) / (2 * 3.14159);
pragma Style_Checks (Off);
Sine_Table : constant array (Unsigned_32 range 0 .. Sine_Table_Size - 1) of Value :=
( 0.000, 0.025, 0.049, 0.074, 0.098, 0.122,
0.147, 0.171, 0.195, 0.219, 0.243, 0.267,
0.290, 0.314, 0.337, 0.360, 0.383, 0.405,
0.428, 0.450, 0.471, 0.493, 0.514, 0.535,
0.556, 0.576, 0.596, 0.615, 0.634, 0.653,
0.672, 0.690, 0.707, 0.724, 0.741, 0.757,
0.773, 0.788, 0.803, 0.818, 0.831, 0.845,
0.858, 0.870, 0.882, 0.893, 0.904, 0.914,
0.924, 0.933, 0.942, 0.950, 0.957, 0.964,
0.970, 0.976, 0.981, 0.985, 0.989, 0.992,
0.995, 0.997, 0.999, 1.000, 1.000, 1.000,
0.999, 0.997, 0.995, 0.992, 0.989, 0.985,
0.981, 0.976, 0.970, 0.964, 0.957, 0.950,
0.942, 0.933, 0.924, 0.914, 0.904, 0.893,
0.882, 0.870, 0.858, 0.845, 0.831, 0.818,
0.803, 0.788, 0.773, 0.757, 0.741, 0.724,
0.707, 0.690, 0.672, 0.653, 0.634, 0.615,
0.596, 0.576, 0.556, 0.535, 0.514, 0.493,
0.471, 0.450, 0.428, 0.405, 0.383, 0.360,
0.337, 0.314, 0.290, 0.267, 0.243, 0.219,
0.195, 0.171, 0.147, 0.122, 0.098, 0.074,
0.049, 0.025, 0.000,-0.025,-0.049,-0.074,
-0.098,-0.122,-0.147,-0.171,-0.195,-0.219,
-0.243,-0.267,-0.290,-0.314,-0.337,-0.360,
-0.383,-0.405,-0.428,-0.450,-0.471,-0.493,
-0.514,-0.535,-0.556,-0.576,-0.596,-0.615,
-0.634,-0.653,-0.672,-0.690,-0.707,-0.724,
-0.741,-0.757,-0.773,-0.788,-0.803,-0.818,
-0.831,-0.845,-0.858,-0.870,-0.882,-0.893,
-0.904,-0.914,-0.924,-0.933,-0.942,-0.950,
-0.957,-0.964,-0.970,-0.976,-0.981,-0.985,
-0.989,-0.992,-0.995,-0.997,-0.999,-1.000,
-1.000,-1.000,-0.999,-0.997,-0.995,-0.992,
-0.989,-0.985,-0.981,-0.976,-0.970,-0.964,
-0.957,-0.950,-0.942,-0.933,-0.924,-0.914,
-0.904,-0.893,-0.882,-0.870,-0.858,-0.845,
-0.831,-0.818,-0.803,-0.788,-0.773,-0.757,
-0.741,-0.724,-0.707,-0.690,-0.672,-0.653,
-0.634,-0.615,-0.596,-0.576,-0.556,-0.535,
-0.514,-0.493,-0.471,-0.450,-0.428,-0.405,
-0.383,-0.360,-0.337,-0.314,-0.290,-0.267,
-0.243,-0.219,-0.195,-0.171,-0.147,-0.122,
-0.098,-0.074,-0.049,-0.025);
pragma Style_Checks (On);
Cos_Table_Size : constant := 256;
Cos_Alpha : constant := Value (Cos_Table_Size) / (2 * 3.14159);
pragma Style_Checks (Off);
Cos_Table : constant array (Unsigned_32 range 0 .. Cos_Table_Size - 1) of Value :=
( 1.000, 1.000, 0.999, 0.997, 0.995, 0.992,
0.989, 0.985, 0.981, 0.976, 0.970, 0.964,
0.957, 0.950, 0.942, 0.933, 0.924, 0.914,
0.904, 0.893, 0.882, 0.870, 0.858, 0.845,
0.831, 0.818, 0.803, 0.788, 0.773, 0.757,
0.741, 0.724, 0.707, 0.690, 0.672, 0.653,
0.634, 0.615, 0.596, 0.576, 0.556, 0.535,
0.514, 0.493, 0.471, 0.450, 0.428, 0.405,
0.383, 0.360, 0.337, 0.314, 0.290, 0.267,
0.243, 0.219, 0.195, 0.171, 0.147, 0.122,
0.098, 0.074, 0.049, 0.025, 0.000,-0.025,
-0.049,-0.074,-0.098,-0.122,-0.147,-0.171,
-0.195,-0.219,-0.243,-0.267,-0.290,-0.314,
-0.337,-0.360,-0.383,-0.405,-0.428,-0.450,
-0.471,-0.493,-0.514,-0.535,-0.556,-0.576,
-0.596,-0.615,-0.634,-0.653,-0.672,-0.690,
-0.707,-0.724,-0.741,-0.757,-0.773,-0.788,
-0.803,-0.818,-0.831,-0.845,-0.858,-0.870,
-0.882,-0.893,-0.904,-0.914,-0.924,-0.933,
-0.942,-0.950,-0.957,-0.964,-0.970,-0.976,
-0.981,-0.985,-0.989,-0.992,-0.995,-0.997,
-0.999,-1.000,-1.000,-1.000,-0.999,-0.997,
-0.995,-0.992,-0.989,-0.985,-0.981,-0.976,
-0.970,-0.964,-0.957,-0.950,-0.942,-0.933,
-0.924,-0.914,-0.904,-0.893,-0.882,-0.870,
-0.858,-0.845,-0.831,-0.818,-0.803,-0.788,
-0.773,-0.757,-0.741,-0.724,-0.707,-0.690,
-0.672,-0.653,-0.634,-0.615,-0.596,-0.576,
-0.556,-0.535,-0.514,-0.493,-0.471,-0.450,
-0.428,-0.405,-0.383,-0.360,-0.337,-0.314,
-0.290,-0.267,-0.243,-0.219,-0.195,-0.171,
-0.147,-0.122,-0.098,-0.074,-0.049,-0.025,
-0.000, 0.025, 0.049, 0.074, 0.098, 0.122,
0.147, 0.171, 0.195, 0.219, 0.243, 0.267,
0.290, 0.314, 0.337, 0.360, 0.383, 0.405,
0.428, 0.450, 0.471, 0.493, 0.514, 0.535,
0.556, 0.576, 0.596, 0.615, 0.634, 0.653,
0.672, 0.690, 0.707, 0.724, 0.741, 0.757,
0.773, 0.788, 0.803, 0.818, 0.831, 0.845,
0.858, 0.870, 0.882, 0.893, 0.904, 0.914,
0.924, 0.933, 0.942, 0.950, 0.957, 0.964,
0.970, 0.976, 0.981, 0.985, 0.989, 0.992,
0.995, 0.997, 0.999, 1.000);
pragma Style_Checks (On);
end GESTE.Maths_Tables;
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT INTERFACE COMPONENTS --
-- --
-- A S I S . E L E M E N T S --
-- --
-- S p e c --
-- --
-- Copyright (C) 2006-2011, AdaCore --
-- --
-- This specification is adapted from the Ada Semantic Interface --
-- Specification Standard (ISO/IEC 15291) for use with GNAT. In accordance --
-- with the copyright of that document, you can freely copy and modify this --
-- specification, provided that if you redistribute a modified version, any --
-- changes that you have made are clearly indicated. --
-- --
-- This specification also contains suggestions and discussion items --
-- related to revising the ASIS Standard according to the changes proposed --
-- for the new revision of the Ada standard. The copyright notice above, --
-- and the license provisions that follow apply solely to these suggestions --
-- and discussion items that are separated by the corresponding comment --
-- sentinels --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 51 Franklin --
-- Street, Fifth Floor, Boston, MA 02110-1301, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by AdaCore --
-- (http://www.adacore.com). --
-- --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- 13 package Asis.Elements
-- Suggestions related to changing this specification to accept new Ada
-- features as defined in incoming revision of the Ada Standard (ISO 8652)
-- are marked by following comment sentinels:
--
-- --|A2005 start
-- ... the suggestion goes here ...
-- --|A2005 end
--
-- and the discussion items are marked by the comment sentinels of teh form:
--
-- --|D2005 start
-- ... the discussion item goes here ...
-- --|D2005 end
--
-- Suggestions related to changing this specification to accept new Ada
-- features as suggested by ARG for next revision of the Ada Standard
-- (ISO 8652) grouped in the end of the package specification.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
package Asis.Elements is
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Asis.Elements encapsulates a set of queries that operate on all elements
-- and some queries specific to A_Pragma elements.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- 13.1 function Unit_Declaration
------------------------------------------------------------------------------
-- Gateway queries between Compilation_Units and Elements.
------------------------------------------------------------------------------
function Unit_Declaration
(Compilation_Unit : Asis.Compilation_Unit)
return Asis.Declaration;
------------------------------------------------------------------------------
-- Compilation_Unit - Specifies the unit to query
--
-- Returns the element representing the declaration of the compilation_unit.
--
-- Returns a Nil_Element if the unit is A_Nonexistent_Declaration,
-- A_Nonexistent_Body, A_Configuration_Compilation, or An_Unknown_Unit.
--
-- All Unit_Kinds are appropriate except Not_A_Unit.
--
-- Returns Declaration_Kinds:
-- Not_A_Declaration
-- A_Function_Body_Declaration
-- A_Function_Declaration
-- A_Function_Instantiation
-- A_Generic_Function_Declaration
-- A_Generic_Package_Declaration
-- A_Generic_Procedure_Declaration
-- A_Package_Body_Declaration
-- A_Package_Declaration
-- A_Package_Instantiation
-- A_Procedure_Body_Declaration
-- A_Procedure_Declaration
-- A_Procedure_Instantiation
-- A_Task_Body_Declaration
-- A_Package_Renaming_Declaration
-- A_Procedure_Renaming_Declaration
-- A_Function_Renaming_Declaration
-- A_Generic_Package_Renaming_Declaration
-- A_Generic_Procedure_Renaming_Declaration
-- A_Generic_Function_Renaming_Declaration
-- A_Protected_Body_Declaration
--
------------------------------------------------------------------------------
-- 13.2 function Enclosing_Compilation_Unit
------------------------------------------------------------------------------
function Enclosing_Compilation_Unit
(Element : Asis.Element)
return Asis.Compilation_Unit;
------------------------------------------------------------------------------
-- Element - Specifies an Element whose Compilation_Unit is desired
--
-- Returns the Compilation_Unit that contains the given Element.
--
-- Raises ASIS_Inappropriate_Element if the Element is a Nil_Element.
--
------------------------------------------------------------------------------
-- 13.3 function Context_Clause_Elements
------------------------------------------------------------------------------
function Context_Clause_Elements
(Compilation_Unit : Asis.Compilation_Unit;
Include_Pragmas : Boolean := False)
return Asis.Context_Clause_List;
------------------------------------------------------------------------------
-- Compilation_Unit - Specifies the unit to query
-- Include_Pragmas - Specifies whether pragmas are to be returned
--
-- Returns a list of with clauses, use clauses, and pragmas that explicitly
-- appear in the context clause of the compilation unit, in their order of
-- appearance.
--
-- Returns a Nil_Element_List if the unit has A_Nonexistent_Declaration,
-- A_Nonexistent_Body, or An_Unknown_Unit Unit_Kind.
--
-- --|IR
-- All pragma Elaborate elements for this unit will appear in this list. Other
-- pragmas will appear in this list, or in the Compilation_Pragmas list, or
-- both.
-- --|IP
-- Implementors are encouraged to use this list to return all pragmas whose
-- full effect is determined by their exact textual position. Pragmas that
-- do not have placement dependencies may be returned in either list. Only
-- pragmas that appear in the unit's context clause are returned
-- by this query. All other pragmas, affecting the compilation of this
-- unit, are available from the Compilation_Pragmas query.
--
-- Ada predefined packages, such as package Standard, may or may not have
-- context-clause elements available for processing by applications. The
-- physical existence of a package Standard is implementation specific.
-- The same is true for other Ada predefined packages, such as Ada.Text_Io and
-- Ada.Direct_Io. The Origin query can be used to determine whether or not
-- a particular unit is an Ada Predefined unit.
--
-- --|IP
-- Results of this query may vary across ASIS implementations. Some
-- implementations normalize all multi-name with clauses and use clauses
-- into an equivalent sequence of single-name with clause and use clauses.
-- Similarly, an implementation may retain only a single reference to a name
-- that appeared more than once in the original context clause.
-- Some implementors will return only pragma
-- Elaborate elements in this list and return all other pragmas via the
-- Compilation_Pragmas query.
--
-- All Unit_Kinds are appropriate except Not_A_Unit.
--
-- Returns Element_Kinds:
-- A_Pragma
-- A_Clause
--
-- Returns Clause_Kinds:
-- A_With_Clause
-- A_Use_Package_Clause
--
------------------------------------------------------------------------------
-- 13.4 function Configuration_Pragmas
------------------------------------------------------------------------------
function Configuration_Pragmas
(The_Context : Asis.Context)
return Asis.Pragma_Element_List;
------------------------------------------------------------------------------
-- The_Context - Specifies the Context to query
--
-- Returns a list of pragmas that apply to all future compilation_unit
-- elements compiled into The_Context. Pragmas returned by this query should
-- have appeared in a compilation that had no compilation_unit elements.
-- To the extent that order is meaningful, the pragmas should be in
-- their order of appearance in the compilation. (The order is implementation
-- dependent, many pragmas have the same effect regardless of order.)
--
-- Returns a Nil_Element_List if there are no such configuration pragmas.
--
-- Returns Element_Kinds:
-- A_Pragma
--
------------------------------------------------------------------------------
-- 13.5 function Compilation_Pragmas
------------------------------------------------------------------------------
function Compilation_Pragmas
(Compilation_Unit : Asis.Compilation_Unit)
return Asis.Pragma_Element_List;
------------------------------------------------------------------------------
-- Compilation_Unit - Specifies the unit to query
--
-- Returns a list of pragmas that apply to the compilation of the unit.
-- To the extent that order is meaningful, the pragmas should be in
-- their order of appearance in the compilation. (The order is implementation
-- dependent, many pragmas have the same effect regardless of order.)
--
-- There are two sources for the pragmas that appear in this list:
--
-- - Program unit pragmas appearing at the place of a compilation_unit.
-- See Reference Manual 10.1.5(4).
--
-- - Configuration pragmas appearing before the first
-- compilation_unit of a compilation. See Reference Manual 10.1.5(8).
--
-- This query does not return Elaborate pragmas from the unit context
-- clause of the compilation unit; they do not apply to the compilation,
-- only to the unit.
--
-- Use the Context_Clause_Elements query to obtain a list of all pragmas
-- (including Elaborate pragmas) from the context clause of a compilation
-- unit.
--
-- Pragmas from this query may be duplicates of some or all of the
-- non-Elaborate pragmas available from the Context_Clause_Elements query.
-- Such duplication is simply the result of the textual position of the
-- pragma--globally effective pragmas may appear textually within the context
-- clause of a particular unit, and be returned as part of the Context_Clause
-- for that unit.
--
-- Ada predefined packages, such as package Standard, may or may not have
-- pragmas available for processing by applications. The physical
-- existence of a package Standard is implementation specific. The same
-- is true for other Ada predefined packages, such as Ada.Text_Io and
-- Ada.Direct_Io. The Origin query can be used to determine whether or
-- not a particular unit is an Ada Predefined unit.
--
-- Returns a Nil_Element_List if the compilation unit:
--
-- - has no such applicable pragmas.
--
-- - is an An_Unknown_Unit, A_Nonexistent_Declaration, or A_Nonexistent_Body.
--
-- All Unit_Kinds are appropriate except Not_A_Unit.
--
-- Returns Element_Kinds:
-- A_Pragma
--
------------------------------------------------------------------------------
-- Element_Kinds Hierarchy
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Element_Kinds Value Subordinate Kinds
------------------------------------------------------------------------------
--
-- Key: Read "->" as "can be further categorized by its"
--
-- A_Pragma -> Pragma_Kinds
--
-- A_Defining_Name -> Defining_Name_Kinds
-- -> Operator_Kinds
--
-- A_Declaration -> Declaration_Kinds
-- -> Declaration_Origin
-- -> Mode_Kinds
-- -> Subprogram_Default_Kinds
--
-- A_Definition -> Definition_Kinds
-- -> Trait_Kinds
-- -> Type_Kinds
-- -> Formal_Type_Kinds
-- -> Access_Type_Kinds
-- -> Root_Type_Kinds
-- -> Constraint_Kinds
-- -> Discrete_Range_Kinds
--
-- An_Expression -> Expression_Kinds
-- -> Operator_Kinds
-- -> Attribute_Kinds
--
-- An_Association -> Association_Kinds
--
-- A_Statement -> Statement_Kinds
--
-- A_Path -> Path_Kinds
--
-- A_Clause -> Clause_Kinds
-- -> Representation_Clause_Kinds
--
-- An_Exception_Handler
--
------------------------------------------------------------------------------
-- 13.6 function Element_Kind
------------------------------------------------------------------------------
function Element_Kind (Element : Asis.Element) return Asis.Element_Kinds;
------------------------------------------------------------------------------
-- Element - Specifies the element to query
--
-- Returns the Element_Kinds value of Element.
-- Returns Not_An_Element for a Nil_Element.
--
-- All element kinds are expected.
--
------------------------------------------------------------------------------
-- 13.7 function Pragma_Kind
------------------------------------------------------------------------------
function Pragma_Kind
(Pragma_Element : Asis.Pragma_Element)
return Asis.Pragma_Kinds;
------------------------------------------------------------------------------
-- Pragma_Element - Specifies the element to query
--
-- Returns the Pragma_Kinds value of Pragma_Element.
-- Returns Not_A_Pragma for any unexpected element such as a
-- Nil_Element, A_Statement, or A_Declaration.
--
-- Expected Element_Kinds:
-- A_Pragma
--
------------------------------------------------------------------------------
-- 13.8 function Defining_Name_Kind
------------------------------------------------------------------------------
function Defining_Name_Kind
(Defining_Name : Asis.Defining_Name)
return Asis.Defining_Name_Kinds;
------------------------------------------------------------------------------
-- Defining_Name - Specifies the element to query
--
-- Returns the Defining_Name_Kinds value of the Defining_Name.
--
-- Returns Not_A_Defining_Name for any unexpected element such as a
-- Nil_Element, A_Clause, or A_Statement.
--
-- Expected Element_Kinds:
-- A_Defining_Name
--
------------------------------------------------------------------------------
-- 13.9 function Declaration_Kind
------------------------------------------------------------------------------
function Declaration_Kind
(Declaration : Asis.Declaration)
return Asis.Declaration_Kinds;
------------------------------------------------------------------------------
-- Declaration - Specifies the element to query
--
-- Returns the Declaration_Kinds value of the Declaration.
--
-- Returns Not_A_Declaration for any unexpected element such as a
-- Nil_Element, A_Definition, or A_Statement.
--
-- Expected Element_Kinds:
-- A_Declaration
--
------------------------------------------------------------------------------
-- 13.10 function Trait_Kind
------------------------------------------------------------------------------
function Trait_Kind (Element : Asis.Element) return Asis.Trait_Kinds;
------------------------------------------------------------------------------
-- Element - Specifies the Element to query
--
-- Returns the Trait_Kinds value of the Element.
--
-- Returns Not_A_Trait for any unexpected element such as a
-- Nil_Element, A_Statement, or An_Expression.
--
-- Expected Declaration_Kinds:
-- A_Private_Type_Declaration
-- A_Private_Extension_Declaration
-- A_Variable_Declaration
-- A_Constant_Declaration
-- A_Deferred_Constant_Declaration
-- A_Discriminant_Specification
-- A_Loop_Parameter_Specification
-- --|A2012 start
-- A_Generalized_Iterator_Specification
-- An_Element_Iterator_Specification
-- --|A2012 end
-- A_Procedure_Declaration
-- A_Function_Declaration
-- A_Parameter_Specification
-- --|A2005 start
-- A_Return_Object_Declaration
-- An_Object_Renaming_Declaration
-- A_Formal_Object_Declaration
-- A_Formal_Procedure_Declaration
-- A_Formal_Function_Declaration
-- --|A2005 end
--
-- Expected Definition_Kinds:
-- A_Component_Definition
-- A_Private_Type_Definition
-- A_Tagged_Private_Type_Definition
-- A_Private_Extension_Definition
-- --|A2005 start
-- A_Subtype_Indication
-- An_Access_Definition
-- --|A2005 end
--
-- Expected Type_Kinds:
-- A_Derived_Type_Definition
-- A_Derived_Record_Extension_Definition
-- A_Record_Type_Definition
-- A_Tagged_Record_Type_Definition
-- --|A2005 start
-- An_Access_Type_Definition
-- --|A2005 end
--
-- Expected Formal_Type_Kinds:
-- A_Formal_Private_Type_Definition
-- A_Formal_Tagged_Private_Type_Definition
-- A_Formal_Derived_Type_Definition
--
-- --|A2005 start
-- Expected Clause_Kinds:
-- A_With_Clause
--
-- We need a note saying that An_Access_Definition_Trait is an obsolescent
-- value kept only because of upward compatibility reasons. Now an
-- access_definition that defines an anonymous access kind is represented as
-- a first-class citizen in the ASIS Element classification hierarchy
-- (An_Access_Definition value in Definition_Kinds and the subordinate
-- Access_Definition_Kinds type).
-- We have a problem here with A_Discriminant_Specification and
-- A_Parameter_Specification arguments. In Ada 95, the only possible value for
-- them was An_Access_Definition_Trait. Now we do not need this, because we
-- have An_Access_Definition as a new value in Definition_Kinds. But in
-- ASIS 2005 we have to define if the argument is of a new
-- A_Null_Exclusion_Trait Trait_Kinds value. A good thing is that the
-- situations when An_Access_Definition_Trait and A_Null_Exclusion_Trait
-- should be returned do not cross, so we can keep returning the
-- An_Access_Definition_Trait value even though it does not make very much
-- sense for Ada 2005.
--
-- Do we need a special note about this?
-- Another problem is an access definition of the form:
--
-- A : not null access function return not null T;
-- B : not null access function return T;
-- C : access function return not null T;
--
-- We have two null_exclusion syntax elements in the declaration of A, and
-- one null_exclusion syntax element in declarations of B and C, but - in
-- different places. How to make a difference between these cases? We can
-- hardly do this within the Trate_Kinds and with Trate_Kind query. I
-- would add a boolean query Is_Not_Null_Return to represent the presence of
-- null_exclusion in parameter_and_result_profile, and Trait_Kind should
-- reflect only the presence of null_exclusion in the syntax structure
-- of access_definition (this looks logical - an Access_Definition Element
-- represents exactly what is called access_definition in Ada 2005, and
-- we do not have a position in ASIS Elements classification to represent
-- as a whole parameter_and_result_profile or what follows the RETURN
-- keyword in function specification).
--
-- The ARG version of the ASIS 2005 definition says that Trait_Kinds and the
-- corresponding query Trait_Kind are obsolescent. And they are right, because
-- already for Ada 2005 Trait_Kinds cannot describe all the needed variations
-- in Element structure. The ARG definition suggests the following Boolean
-- queries as the replacement for Trait_Kind(s)
function Has_Abstract (Element : Asis.Element) return Boolean;
-- Element specifies the element to query.
--
-- Returns True if the reserved word abstract appears in Element, and False
-- otherwise. Returns False for any unexpected element, including
-- Nil_Element.
--
-- Element expects an element that has one of the following
-- Declaration_Kinds:
-- A_Formal_Procedure_Declaration
-- A_Formal_Function_Declaration
-- A_Function_Declaration
-- An_Ordinary_Type_Declaration
-- A_Private_Type_Declaration
-- A_Private_Extension_Declaration
-- A_Procedure_Declaration
-- or an element that has one of the following Definition_Kinds:
-- A_Private_Extension_Definition
-- A_Private_Type_Definition
-- A_Tagged_Private_Type_Definition
-- A_Type_Definition
-- or an element that has one of the following Formal_Type_Kinds:
-- A_Formal_Private_Type_Definition
-- A_Formal_Tagged_Private_Type_Definition
-- A_Formal_Derived_Type_Definition
--
-- Note: the specification above is taken "as is" from the ARG ASIS 2005
-- definition. But there is no sense to include in the list of
-- expedcted kinds (that is, to the list of kinds for that the query
-- can return True) A_Private_Type_Definition and
-- A_Formal_Private_Type_Definition, because only tagged (formal)
-- private types can be abstract.
function Has_Aliased (Element : Asis.Element) return Boolean;
-- Element specifies the Element to query.
--
-- Returns True if the reserved word aliased appears in Element, and False
-- otherwise. Returns False for any unexpected element, including
-- Nil_Element.
--
-- Element expects an element that has one of the following
-- Declaration_Kinds:
-- A_Constant_Declaration
-- A_Deferred_Constant_Declaration
-- A_Return_Object_Declaration
-- A_Variable_Declaration
-- A_Component_Declaration
-- A_Parameter_Specification -- 2012
-- or an element that has the following Definition_Kinds:
-- A_Component_Definition
--
-- NOTES: * A_Component_Declaration is added to the list of expected
-- Declaration_Kinds given in in ARG version of the ASIS 2005
-- definition.
--
-- * A_Parameter_Specification is added to the list of expected
-- kinds for Ada 2012
function Has_Limited (Element : Asis.Element) return Boolean;
-- Element specifies the Element to query.
--
-- Returns True if the reserved word limited appears in Element, and False
-- otherwise. Returns False for any unexpected element, including
-- Nil_Element.
--
-- Element expects an element that has the following Clause_Kinds:
-- A_With_Clause
-- or an element that has one of the following Declaration_Kinds:
-- An_Ordinary_Type_Declaration
-- A_Private_Type_Declaration
-- A_Private_Extension_Declaration
-- or an element that has one of the following Definition_Kinds:
-- A_Type_Definition
-- A_Private_Type_Definition
-- A_Tagged_Private_Type_Definition
-- A_Private_Extension_Definition
-- or an element that has one of the following Formal_Type_Kinds:
-- A_Formal_Private_Type_Definition
-- A_Formal_Tagged_Private_Type_Definition
-- A_Formal_Derived_Type_Definition
function Has_Private (Element : Asis.Element) return Boolean;
-- Element specifies the element to query.
--
-- Returns True if the reserved word private appears in Element, and False
-- otherwise. Returns False for any unexpected element, including
-- Nil_Element.
--
-- Element expects an element that has one of the following
-- Declaration_Kinds:
-- A_Private_Extension_Declaration
-- A_Private_Type_Declaration
-- or an element that has one of the following Definition_Kinds:
-- A_Private_Extension_Definition
-- A_Private_Type_Definition
-- A_Tagged_Private_Type_Definition
-- A_Type_Definition
-- or an element that has one of the following Formal_Type_Kinds:
-- A_Formal_Private_Type_Definition
-- A_Formal_Tagged_Private_Type_Definition
-- or an element that has the following Clause_Kinds:
-- A_With_Clause
function Has_Protected (Element : Asis.Element) return Boolean;
-- Element specifies the Element to query.
--
-- Returns True if the reserved word protected appears in Element, and
-- False otherwise. Returns False for any unexpected element, including
-- Nil_Element.
--
-- Element expects an element that has the following Definition_Kinds:
-- A_Protected_Definition
-- or an element that has the following Type_Kinds:
-- An_Interface_Type_Definition
-- or an element that has one of the following Declaration_Kinds:
-- A_Protected_Body_Declaration
-- A_Protected_Type_Declaration
-- A_Single_Protected_Declaration
--
-- NOTE: we have added
-- A_Protected_Body_Stub
-- to the list of expected kinds. Shoudl the list of expected kinds also
-- contain
-- An_Access_To_Protected_Procedure
-- An_Access_To_Protected_Function?
-- At the moment the query returns FALSE for these values.
function Has_Reverse (Element : Asis.Element) return Boolean;
-- Element specifies the Element to query.
--
-- Returns True if the reserved word reverse appears in Element, and False
-- otherwise. Returns False for any unexpected element, including
-- Nil_Element.
-- Element expects an element that has the following Declaration_Kinds:
-- A_Loop_Parameter_Specification
-- A_Generalized_Iterator_Specification
-- An_Element_Iterator_Specification
function Has_Synchronized (Element : Asis.Element) return Boolean;
-- Element specifies the Element to query.
--
-- Returns True if the reserved word synchronized appears in Element, and
-- False otherwise. Returns False for any unexpected element, including
-- Nil_Element.
--
-- Element expects an element that has the following Definition_Kinds:
-- A_Private_Extension_Definition
-- or an element that has the following Type_Kinds:
-- An_Interface_Type_Definition
--
-- NOTE: it looks like the following Formal_Type_Kinds value is missing
-- in the list of expected kinds:
--
-- A_Formal_Derived_Type_Definition
-- According to the syntax defined in 12.5.1 (3/2), it can contain
-- the reserved word 'synchronized'
function Has_Tagged (Element : Asis.Element) return Boolean;
-- Element specifies the Element to query.
--
-- Returns True if the reserved word tagged appears in Element, and False
-- otherwise. Returns False for any unexpected element, including
-- Nil_Element.
--
-- Element expects an element that has one of the following
-- Definition_Kinds:
-- A_Tagged_Private_Type_Definition
-- or an element that has the following Type_Kinds:
-- A_Tagged_Record_Type_Definition
-- or an element that has the following Formal_Type_Kinds:
-- A_Formal_Tagged_Private_Type_Definition
-- or an element that has the following Declaration_Kinds:
-- A_Tagged_Incomplete_Type_Declaration
-- A_Formal_Incomplete_Type_Declaration (Ada 2012)
--
-- NOTE: In the ARG ASIS, the definition of this query contains
-- A_Tagged_Incomplete_Type_Definition as expected Definition_Kinds
-- value. But the GNAT ASIS does not have
-- A_Tagged_Incomplete_Type_Definition, but it has
-- A_Tagged_Incomplete_Type_Declaration value in Declaration_Kinds
-- instead. The definition of the query is adjusted to follow GNAT
-- ASIS.
function Has_Task (Element : Asis.Element) return Boolean;
-- Element specifies the Element to query.
--
-- Returns True if the reserved word task appears in Element, and False
-- otherwise. Returns False for any unexpected element, including
-- Nil_Element.
--
-- Element expects an element that has the following Definition_Kinds:
-- A_Task_Definition
-- or an element that has the following Type_Kinds:
-- An_Interface_Type_Definition
-- or an element that has one of the following Declaration_Kinds:
-- A_Task_Type_Declaration
-- A_Single_Task_Declaration
-- A_Task_Body_Declaration
-- NOTE: we have added
-- A_Task_Body_Stub
-- to the list of expected kinds.
function Has_Null_Exclusion -- 3.2.2(3/2), 3.7(5/2), 3.10 (2/2,6/2),
-- 6.1(13/2,15/2), 8.5.1(2/2), 12.4(2/2)
(Element : Asis.Element)
return Boolean;
-- Element specifies the element to query.
--
-- Returns True if the argument element has a null_exclusion specifier, and
-- returns False otherwise (including for any unexpected element).
--
-- Element expects an element that has one of the following
-- Definition_Kinds:
-- A_Type_Definition
-- An_Access_Definition
-- A_Subtype_Indication
-- or Element expects an that has the following Type_Kinds:
-- An_Access_Type_Definition
-- or Element expects an that has one of the following Declaration_Kinds:
-- A_Discriminant_Specification
-- A_Parameter_Specification
-- A_Formal_Object_Declaration
-- An_Object_Renaming_Declaration
-- --|A2005 end
-- --|A2005 start
------------------------------------------------------------------------------
-- 13.?? function Is_Not_Null_Return
------------------------------------------------------------------------------
function Is_Not_Null_Return
(Element : Asis.Element)
return Boolean;
------------------------------------------------------------------------------
-- Element - Specifies the element to check
--
-- Checks if the argument element contains a parameter_and_result_profile
-- component and if this component has null_exclusion specifier
--
-- Returns False for any unexpected element as a Nil_Element, A_Statement or
-- A_Clause.
--
-- Expected Declaration_Kinds:
-- A_Function_Declaration
-- A_Function_Body_Declaration
-- A_Function_Renaming_Declaration
-- A_Function_Body_Stub
-- A_Generic_Function_Declaration
-- A_Formal_Function_Declaration
--
-- Expected Access_Type_Kinds: (not implemented in the compiler yet?)
-- An_Access_To_Function
-- An_Access_To_Protected_Function
--
-- Expected Access_Definition_Kinds: (not implemented in the compiler yet?)
-- An_Anonymous_Access_To_Function
-- An_Anonymous_Access_To_Protected_Function
-- --|A2005 end
-- --|A2005 start
------------------------------------------------------------------------------
-- 13.??? function Is_Prefix_Notation (implemented)
------------------------------------------------------------------------------
function Is_Prefix_Notation (Call : Asis.Element) return Boolean;
------------------------------------------------------------------------------
-- Call - Specifies the procedure or function call to query
--
-- Returns True if the argument is a procedure or a function call in the
-- prefix notation: Object_Name.Operation_Name (...). Returns False for any
-- unexpected argument
--
-- Expected Statement_Kinds:
-- A_Procedure_Call_Statement
--
-- Expected Expression_Kinds:
-- A_Function_Call
-- --|D2005 start
-- What is the right place for this query? Should it be here, should it be
-- in Asis.Statements (with the reference to it in Asis.Expressions or vise
-- versa, or do we need two separate queries - one for procedure calls, and
-- another for function calls
-- --|D2005 end
-- --|A2005 end
------------------------------------------------------------------------------
-- 13.11 function Declaration_Origin
------------------------------------------------------------------------------
function Declaration_Origin
(Declaration : Asis.Declaration)
return Asis.Declaration_Origins;
------------------------------------------------------------------------------
-- Declaration - Specifies the Declaration to query
--
-- Returns the Declaration_Origins value of the Declaration.
--
-- Returns Not_A_Declaration_Origin for any unexpected element such as a
-- Nil_Element, A_Definition, or A_Clause.
--
-- Expected Element_Kinds:
-- A_Declaration
--
------------------------------------------------------------------------------
-- 13.12 function Mode_Kind
------------------------------------------------------------------------------
function Mode_Kind
(Declaration : Asis.Declaration)
return Asis.Mode_Kinds;
------------------------------------------------------------------------------
-- Declaration - Specifies the element to query
--
-- Returns the Mode_Kinds value of the Declaration.
--
-- Returns A_Default_In_Mode for an access parameter.
--
-- Returns Not_A_Mode for any unexpected element such as a
-- Nil_Element, A_Definition, or A_Statement.
--
-- Expected Declaration_Kinds:
-- A_Parameter_Specification
-- A_Formal_Object_Declaration
--
------------------------------------------------------------------------------
-- 13.13 function Default_Kind
------------------------------------------------------------------------------
function Default_Kind
(Declaration : Asis.Generic_Formal_Parameter)
return Asis.Subprogram_Default_Kinds;
------------------------------------------------------------------------------
-- Declaration - Specifies the element to query
--
-- Returns the Subprogram_Default_Kinds value of the Declaration.
--
-- Returns Not_A_Declaration for any unexpected element such as a
-- Nil_Element, A_Definition, or A_Statement.
--
-- Expected Declaration_Kinds:
-- A_Formal_Function_Declaration
-- A_Formal_Procedure_Declaration
--
------------------------------------------------------------------------------
-- 13.14 function Definition_Kind
------------------------------------------------------------------------------
function Definition_Kind
(Definition : Asis.Definition)
return Asis.Definition_Kinds;
------------------------------------------------------------------------------
-- Definition - Specifies the Definition to query
--
-- Returns the Definition_Kinds value of the Definition.
--
-- Returns Not_A_Definition for any unexpected element such as a
-- Nil_Element, A_Statement, or A_Declaration.
--
-- Expected Element_Kinds:
-- A_Definition
--
------------------------------------------------------------------------------
-- 13.15 function Type_Kind
------------------------------------------------------------------------------
function Type_Kind
(Definition : Asis.Type_Definition)
return Asis.Type_Kinds;
------------------------------------------------------------------------------
-- Definition - Specifies the Type_Definition to query
--
-- Returns the Type_Kinds value of the Definition.
--
-- Returns Not_A_Type_Definition for any unexpected element such as a
-- Nil_Element, A_Statement, or A_Declaration.
--
-- Expected Definition_Kinds:
-- A_Type_Definition
--
------------------------------------------------------------------------------
-- --|A2005 start (implemented)
-- 13.#??? function Access_Definition_Kind
------------------------------------------------------------------------------
function Access_Definition_Kind
(Definition : Asis.Definition)
return Asis.Access_Definition_Kinds;
------------------------------------------------------------------------------
-- Definition - Specifies the Definition to query
--
-- Returns the Access_Definition_Kinds value of the Definition.
--
-- Returns Not_An_Access_Definition for any unexpected element such as a
-- Nil_Element, A_Statement, or A_Declaration.
--
-- Expected Definition_Kinds:
-- An_Access_Definition
--
-- --|A2005 end
------------------------------------------------------------------------------
-- 13.16 function Formal_Type_Kind
------------------------------------------------------------------------------
function Formal_Type_Kind
(Definition : Asis.Formal_Type_Definition)
return Asis.Formal_Type_Kinds;
------------------------------------------------------------------------------
-- Definition - Specifies the Formal_Type_Definition to query
--
-- Returns the Formal_Type_Kinds value of the Definition.
--
-- Returns Not_A_Formal_Type_Definition for any unexpected element such as a
-- Nil_Element, A_Statement, or A_Declaration.
--
-- Expected Definition_Kinds:
-- A_Formal_Type_Definition
--
------------------------------------------------------------------------------
-- 13.17 function Access_Type_Kind
------------------------------------------------------------------------------
function Access_Type_Kind
(Definition : Asis.Access_Type_Definition)
return Asis.Access_Type_Kinds;
------------------------------------------------------------------------------
-- Definition - Specifies the Access_Type_Definition to query
--
-- Returns the Access_Type_Kinds value of the Definition.
--
-- Returns Not_An_Access_Type_Definition for any unexpected element such as a
-- Nil_Element, A_Statement, or A_Declaration.
--
-- Expected Type_Kinds:
-- An_Access_Type_Definition
--
------------------------------------------------------------------------------
-- --|A2005 start (implemented)
-- 13.#??? function Interface_Kind
------------------------------------------------------------------------------
function Interface_Kind
(Definition : Asis.Definition)
return Asis.Interface_Kinds;
------------------------------------------------------------------------------
-- Definition - Specifies the Definition to query
--
-- Returns the Interface_Kinds value of the Definition.
--
-- Returns Not_An_Interface for any unexpected element such as a
-- Nil_Element, A_Statement, or A_Declaration.
--
-- Expected Definition_Kinds:
-- A_Type_Definition
-- A_Formal_Type_Definition
--
-- Expected Type_Kinds:
-- An_Interface_Type_Definition
--
-- Expected Formal_Type_Kinds:
-- A_Formal_Interface_Type_Definition
--
-- --|A2005 end
------------------------------------------------------------------------------
-- 13.18 function Root_Type_Kind
------------------------------------------------------------------------------
function Root_Type_Kind
(Definition : Asis.Root_Type_Definition)
return Asis.Root_Type_Kinds;
------------------------------------------------------------------------------
-- Definition - Specifies the Root_Type_Definition to query
--
-- Returns the Root_Type_Kinds value of the Definition.
--
-- Returns Not_A_Root_Type_Definition for any unexpected element such as a
-- Nil_Element, A_Statement, or A_Declaration.
--
-- Expected Type_Kinds:
-- A_Root_Type_Definition
--
------------------------------------------------------------------------------
-- 13.19 function Constraint_Kind
------------------------------------------------------------------------------
function Constraint_Kind
(Definition : Asis.Constraint)
return Asis.Constraint_Kinds;
------------------------------------------------------------------------------
-- Definition - Specifies the constraint to query
--
-- Returns the Constraint_Kinds value of the Definition.
--
-- Returns Not_A_Constraint for any unexpected element such as a
-- Nil_Element, A_Statement, or A_Declaration.
--
-- Expected Definition_Kinds:
-- A_Constraint
--
------------------------------------------------------------------------------
-- 13.20 function Discrete_Range_Kind
------------------------------------------------------------------------------
function Discrete_Range_Kind
(Definition : Asis.Discrete_Range)
return Asis.Discrete_Range_Kinds;
------------------------------------------------------------------------------
-- Definition - Specifies the discrete_range to query
--
-- Returns the Discrete_Range_Kinds value of the Definition.
--
-- Returns Not_A_Discrete_Range for any unexpected element such as a
-- Nil_Element, A_Statement, or A_Declaration.
--
-- Expected Definition_Kinds:
-- A_Discrete_Subtype_Definition
-- A_Discrete_Range
--
------------------------------------------------------------------------------
-- 13.21 function Expression_Kind
------------------------------------------------------------------------------
function Expression_Kind
(Expression : Asis.Expression)
return Asis.Expression_Kinds;
------------------------------------------------------------------------------
-- Expression - Specifies the Expression to query
--
-- Returns the Expression_Kinds value of the Expression.
--
-- Returns Not_An_Expression for any unexpected element such as a
-- Nil_Element, A_Statement, or A_Declaration.
--
-- Expected Element_Kinds:
-- An_Expression
--
------------------------------------------------------------------------------
-- 13.22 function Operator_Kind
------------------------------------------------------------------------------
function Operator_Kind
(Element : Asis.Element)
return Asis.Operator_Kinds;
------------------------------------------------------------------------------
-- Element - Specifies the Element to query
--
-- Returns the Operator_Kinds value of the A_Defining_Name or An_Expression
-- element.
--
-- Returns Not_An_Operator for any unexpected element such as a
-- Nil_Element, A_Statement, or A_Declaration.
--
-- Expected Defining_Name_Kinds:
-- A_Defining_Operator_Symbol
--
-- Expected Expression_Kinds:
-- An_Operator_Symbol
--
------------------------------------------------------------------------------
-- 13.23 function Attribute_Kind
------------------------------------------------------------------------------
function Attribute_Kind
(Expression : Asis.Expression)
return Asis.Attribute_Kinds;
------------------------------------------------------------------------------
-- Expression - Specifies the Expression to query
--
-- Returns the Attribute_Kinds value of the Expression.
--
-- Returns Not_An_Attribute for any unexpected element such as a
-- Nil_Element, A_Statement, or A_Declaration.
--
-- Expected Expression_Kinds:
-- An_Attribute_Reference
--
------------------------------------------------------------------------------
-- 13.24 function Association_Kind
------------------------------------------------------------------------------
function Association_Kind
(Association : Asis.Association)
return Asis.Association_Kinds;
------------------------------------------------------------------------------
-- Association - Specifies the Association to query
--
-- Returns the Association_Kinds value of the Association.
--
-- Returns Not_An_Association for any unexpected element such as a
-- Nil_Element, A_Statement, or A_Declaration.
--
-- Expected Element_Kinds:
-- An_Association
--
------------------------------------------------------------------------------
-- 13.25 function Statement_Kind
------------------------------------------------------------------------------
function Statement_Kind
(Statement : Asis.Statement)
return Asis.Statement_Kinds;
------------------------------------------------------------------------------
-- Statement - Specifies the element to query
--
-- Returns the Statement_Kinds value of the statement.
--
-- Returns Not_A_Statement for any unexpected element such as a
-- Nil_Element, A_Definition, or A_Declaration.
--
-- Expected Element_Kinds:
-- A_Statement
--
------------------------------------------------------------------------------
-- 13.26 function Path_Kind
------------------------------------------------------------------------------
function Path_Kind (Path : Asis.Path) return Asis.Path_Kinds;
------------------------------------------------------------------------------
-- Path - Specifies the Path to query
--
-- Returns the Path_Kinds value of the Path.
--
-- Returns Not_A_Path for any unexpected element such as a
-- Nil_Element, A_Statement, or A_Declaration.
--
-- Expected Element_Kinds:
-- A_Path
--
------------------------------------------------------------------------------
-- 13.27 function Clause_Kind
------------------------------------------------------------------------------
function Clause_Kind (Clause : Asis.Clause) return Asis.Clause_Kinds;
------------------------------------------------------------------------------
-- Clause - Specifies the element to query
--
-- Returns the Clause_Kinds value of the Clause.
--
-- Returns Not_A_Clause for any unexpected element such as a
-- Nil_Element, A_Definition, or A_Declaration.
--
-- Expected Element_Kinds:
-- A_Clause
--
------------------------------------------------------------------------------
-- 13.28 function Representation_Clause_Kind
------------------------------------------------------------------------------
function Representation_Clause_Kind
(Clause : Asis.Representation_Clause)
return Asis.Representation_Clause_Kinds;
------------------------------------------------------------------------------
-- Clause - Specifies the element to query
--
-- Returns the Representation_Clause_Kinds value of the Clause.
--
-- Returns Not_A_Representation_Clause for any unexpected element such as a
-- Nil_Element, A_Definition, or A_Declaration.
--
-- Expected Clause_Kinds:
-- A_Representation_Clause
--
------------------------------------------------------------------------------
-- 13.29 function Is_Nil
------------------------------------------------------------------------------
function Is_Nil (Right : Asis.Element) return Boolean;
------------------------------------------------------------------------------
-- Right - Specifies the element to check
--
-- Returns True if the program element is the Nil_Element.
--
------------------------------------------------------------------------------
-- 13.30 function Is_Nil
------------------------------------------------------------------------------
function Is_Nil (Right : Asis.Element_List) return Boolean;
------------------------------------------------------------------------------
-- Right - Specifies the element list to check
--
-- Returns True if the element list has a length of zero.
--
------------------------------------------------------------------------------
-- 13.31 function Is_Equal
------------------------------------------------------------------------------
function Is_Equal
(Left : Asis.Element;
Right : Asis.Element)
return Boolean;
------------------------------------------------------------------------------
-- Left - Specifies the left element to compare
-- Right - Specifies the right element to compare
--
-- Returns True if Left and Right represent the same physical element,
-- from the same physical compilation unit. The two elements may or
-- may not be from the same open ASIS Context variable.
--
-- Implies: Is_Equal (Enclosing_Compilation_Unit (Left),
-- Enclosing_Compilation_Unit (Right)) = True
--
------------------------------------------------------------------------------
-- 13.32 function Is_Identical
------------------------------------------------------------------------------
function Is_Identical
(Left : Asis.Element;
Right : Asis.Element)
return Boolean;
------------------------------------------------------------------------------
-- Left - Specifies the left element
-- Right - Specifies the right element
--
-- Returns True if Left and Right represent the same physical element,
-- from the same physical compilation unit, from the same open ASIS
-- Context variable.
--
-- Implies: Is_Identical (Enclosing_Compilation_Unit (Left),
-- Enclosing_Compilation_Unit (Right)) = True
--
------------------------------------------------------------------------------
-- 13.33 function Is_Part_Of_Implicit
------------------------------------------------------------------------------
function Is_Part_Of_Implicit (Element : Asis.Element) return Boolean;
------------------------------------------------------------------------------
-- Element - Specifies the element to query
--
-- Returns True for any Element that is, or that forms part of, any
-- implicitly declared or specified program Element structure.
--
-- Returns False for a Nil_Element, or any Element that correspond to text
-- which was specified explicitly (typed, entered, written).
--
-- Generic instance specifications and bodies, while implicit, are treated
-- as a special case. These elements will not normally test as
-- Is_Part_Of_Implicit. Rather, they are Is_Part_Of_Instance. They only test
-- as Is_Part_Of_Implicit if one of the following rules applies. This is
-- done so that it is possible to determine whether a declaration, which
-- happens to occur within an instance, is an implicit result of
-- another declaration which occurs explicitly within the generic template.
--
-- Implicit Elements are those that represent these portions of the Ada
-- language:
--
-- Reference Manual 4.5.(9) - All predefined operator declarations and
-- their component elements are
-- Is_Part_Of_Implicit
-- Reference Manual 3.4(16) - Implicit predefined operators of the derived
-- type.
-- Reference Manual 3.4(17-22) - Implicit inherited subprogram declarations
-- and their component elements are
-- Is_Part_Of_Implicit
--
-- Reference Manual 6.4(9) - Implicit actual parameter expressions
-- (defaults).
-- and 12.3(7) - The A_Parameter_Association that includes a
-- defaulted parameter value Is_Normalized and
-- also Is_Part_Of_Implicit. The
-- Formal_Parameter and the Actual_Parameter
-- values from such Associations are not
-- Is_Part_Of_Implicit unless they are from
-- default initializations for an inherited
-- subprogram declaration and have an
-- Enclosing_Element that is the parameter
-- specification of the subprogram declaration.
-- (Those elements are shared with (were created
-- by) the original subprogram declaration, or
-- they are naming expressions representing the
-- actual generic subprogram selected at the
-- place of an instantiation for A_Box_Default.)
-- - All A_Parameter_Association Kinds from a
-- Normalized list are Is_Part_Of_Implicit.
--
-- Reference Manual 6.6 (6) - Inequality operator declarations for limited
-- private types are Is_Part_Of_Implicit.
-- - Depending on the ASIS implementation, a "/="
-- appearing in the compilation may result in a
-- "NOT" and an "=" in the internal
-- representation. These two elements test as
-- Is_Part_Of_Implicit because they do not
-- represent text from the original compilation
-- text.
-- Reference Manual 12.3 (16) - implicit generic instance specifications and
-- bodies are not Is_Part_Of_Implicit; they are
-- Is_Part_Of_Instance and are only implicit if
-- some other rule makes them so
--
------------------------------------------------------------------------------
-- 13.34 function Is_Part_Of_Inherited
------------------------------------------------------------------------------
function Is_Part_Of_Inherited (Element : Asis.Element) return Boolean;
------------------------------------------------------------------------------
-- Element - Specifies the element to query
--
-- Returns True for any Element that is, or that forms part of, an
-- inherited primitive subprogram declaration.
--
-- Returns False for any other Element including a Nil_Element.
--
------------------------------------------------------------------------------
-- 13.35 function Is_Part_Of_Instance
------------------------------------------------------------------------------
function Is_Part_Of_Instance (Element : Asis.Element) return Boolean;
------------------------------------------------------------------------------
-- Element - Specifies the element to test
--
-- Returns True if the Element is part of an implicit generic specification
-- instance or an implicit generic body instance.
--
-- Returns False for explicit, inherited, and predefined Elements that are
-- not the result of a generic expansion.
--
-- Returns False for a Nil_Element.
--
-- Instantiations are not themselves Is_Part_Of_Instance unless they are
-- encountered while traversing a generic instance.
--
------------------------------------------------------------------------------
-- 13.36 function Enclosing_Element
------------------------------------------------------------------------------
function Enclosing_Element (Element : Asis.Element) return Asis.Element;
function Enclosing_Element
(Element : Asis.Element;
Expected_Enclosing_Element : Asis.Element)
return Asis.Element;
------------------------------------------------------------------------------
-- Element - Specifies the element to query
-- Expected_Enclosing_Element - Specifies an enclosing element expected to
-- contain the element
--
-- Returns the Element that immediately encloses the given element. This
-- query is intended to exactly reverse any single parent-to-child element
-- traversal. For any structural query that returns a subcomponent of an
-- element (or that returns a list of subcomponent elements), the original
-- element can be determined by passing the subcomponent element to this
-- query.
-- Note: Semantic queries (queries that test the meaning of a program rather
-- than its structure) return Elements that usually do not have the original
-- argument Element as their parent.
--
-- Returns a Nil_Element if:
--
-- - the element is the declaration part of a compilation unit
-- (Unit_Declaration).
--
-- - the element is with clause or use clause of a context clause
-- (Context_Clause_Elements).
--
-- - the element is a pragma for a compilation unit
-- (Compilation_Pragmas and Context_Clause_Elements).
--
-- Use Enclosing_Compilation_Unit to get the enclosing compilation unit for
-- any element value other than Nil_Element.
--
-- Raises ASIS_Inappropriate_Element if the Element is a Nil_Element.
--
-- Examples:
--
-- Given a A_Declaration/A_Full_Type_Declaration in the declarative region
-- of a block statement, returns the A_Statement/A_Block_Statement Element
-- that encloses the type declaration.
--
-- Given A_Statement, from the sequence of statements within a loop
-- statement, returns the enclosing A_Statement/A_Loop_Statement.
--
-- Given the An_Expression/An_Identifier selector from an expanded name,
-- returns the An_Expression/A_Selected_Component that represents the
-- combination of the prefix, the dot, and the selector.
--
-- --|AN Application Note:
-- --|AN
-- --|AN The optional Expected_Enclosing_Element parameter is used only to
-- --|AN optimize. This speed up is only present for ASIS implementations
-- --|AN where the underlying implementor's environment does not have "parent
-- --|AN pointers". For these implementations, this query is implemented as a
-- --|AN "search". The Enclosing_Compilation_Unit is searched for the argument
-- --|AN Element. The Expected_Enclosing_Element parameter provides a means of
-- --|AN shortening the search.
-- --|AN Note: If the argument Element is not a sub-element of the
-- --|AN Expected_Enclosing_Element parameter, or if the
-- --|AN Expected_Enclosing_Element is a Nil_Element, the result of the
-- --|AN call is a Nil_Element.
-- --|AN
-- --|AN Implementations that do not require the Expected_Enclosing_Element
-- --|AN parameter may ignore it. They are encouraged, but not required, to
-- --|AN test the Expected_Enclosing_Element parameter and to determine if it
-- --|AN is an invalid Element value (its associated Environment Context may
-- --|AN be closed)
-- --|AN
-- --|AN Portable applications should not use the Expected_Enclosing_Element
-- --|AN parameter since it can lead to unexpected differences when porting an
-- --|AN application between ASIS implementations where one implementation
-- --|AN uses the parameter and the other implementation does not. Passing a
-- --|AN "wrong" Expected_Enclosing_Element to an implementation that ignores
-- --|AN it, is harmless. Passing a "wrong" Expected_Enclosing_Element to an
-- --|AN implementation that may utilize it, can lead to an unexpected
-- --|AN Nil_Element result.
-- --
------------------------------------------------------------------------------
-- 13.37 function Pragmas
------------------------------------------------------------------------------
function Pragmas
(The_Element : Asis.Element)
return Asis.Pragma_Element_List;
------------------------------------------------------------------------------
-- The_Element - Specifies the element to query
--
-- Returns the list of pragmas, in their order of appearance, that appear
-- directly within the given The_Element. Returns only those pragmas that are
-- immediate component elements of the given The_Element. Pragmas embedded
-- within other component elements are not returned. For example, returns
-- the pragmas in a package specification, in the statement list of a loop,
-- or in a record component list.
--
-- This query returns exactly those pragmas that are returned by the
-- various queries, that accept these same argument kinds, and that
-- return Declaration_List and Statement_List, where the inclusion of
-- Pragmas is controlled by an Include_Pragmas parameter.
--
-- Returns a Nil_Element_List if there are no pragmas.
--
-- Appropriate Element_Kinds:
-- A_Path (pragmas from the statement list +
-- pragmas immediately preceding the
-- reserved word "when" of the first
-- alternative)
-- An_Exception_Handler (pragmas from the statement list +
-- pragmas immediately preceding the
-- reserved word "when" of the first
-- exception handler)
--
-- Appropriate Declaration_Kinds:
-- A_Procedure_Body_Declaration (pragmas from declarative region +
-- statements)
-- A_Function_Body_Declaration (pragmas from declarative region +
-- statements)
-- A_Package_Declaration (pragmas from visible + private
-- declarative regions)
-- A_Package_Body_Declaration (pragmas from declarative region +
-- statements)
-- A_Task_Body_Declaration (pragmas from declarative region +
-- statements)
-- A_Protected_Body_Declaration (pragmas from declarative region)
-- An_Entry_Body_Declaration (pragmas from declarative region +
-- statements)
-- A_Generic_Procedure_Declaration (pragmas from formal declarative
-- region)
-- A_Generic_Function_Declaration (pragmas from formal declarative
-- region)
-- A_Generic_Package_Declaration (pragmas from formal + visible +
-- private declarative regions)
--
-- Appropriate Definition_Kinds:
-- A_Record_Definition (pragmas from the component list)
-- A_Variant_Part (pragmas immediately preceding the
-- first reserved word "when" + between
-- variants)
-- A_Variant (pragmas from the component list)
-- A_Task_Definition (pragmas from visible + private
-- declarative regions)
-- A_Protected_Definition (pragmas from visible + private
-- declarative regions)
--
-- Appropriate Statement_Kinds:
-- A_Loop_Statement (pragmas from statement list)
-- A_While_Loop_Statement (pragmas from statement list)
-- A_For_Loop_Statement (pragmas from statement list)
-- A_Block_Statement (pragmas from declarative region +
-- statements)
-- An_Accept_Statement (pragmas from statement list +
--
-- Appropriate Representation_Clause_Kinds:
-- A_Record_Representation_Clause (pragmas from component
-- specifications)
--
-- Returns Element_Kinds:
-- A_Pragma
--
------------------------------------------------------------------------------
-- 13.38 function Corresponding_Pragmas
------------------------------------------------------------------------------
function Corresponding_Pragmas
(Element : Asis.Element)
return Asis.Pragma_Element_List;
------------------------------------------------------------------------------
-- Element - Specifies the element to query
--
-- Returns the list of pragmas semantically associated with the given element,
-- in their order of appearance, or, in any order that does not affect their
-- relative interpretations. These are pragmas that directly affect the
-- given element. For example, a pragma Pack affects the type it names.
--
-- Returns a Nil_Element_List if there are no semantically associated pragmas.
--
-- --|D2005 start
-- See the discussion for
-- Asis.Declarations.Corresponding_Representation_Clauses (15.17), we have
-- exactly the same problem for this query.
-- --|D2005 end
--
-- --|AN Application Note:
-- --|AN
-- --|AN If the argument is a inherited entry declaration from a derived task
-- --|AN type, all pragmas returned are elements taken from the original task
-- --|AN type's declarative item list. Their Enclosing_Element is the original
-- --|AN type definition and not the derived type definition.
-- --|AN
-- Appropriate Element_Kinds:
-- A_Declaration
-- A_Statement
-- --|D2005 start
-- How A_Statement can be an appropriate kind for this query???
-- --|D2005 end
--
-- Returns Element_Kinds:
-- A_Pragma
--
------------------------------------------------------------------------------
-- 13.39 function Pragma_Name_Image
------------------------------------------------------------------------------
function Pragma_Name_Image
(Pragma_Element : Asis.Pragma_Element)
return Program_Text;
------------------------------------------------------------------------------
-- Pragma_Element - Specifies the element to query
--
-- Returns the program text image of the simple name of the pragma.
--
-- The case of names returned by this query may vary between implementors.
-- Implementors are encouraged, but not required, to return names in the
-- same case as was used in the original compilation text.
--
-- Appropriate Element_Kinds:
-- A_Pragma
--
------------------------------------------------------------------------------
-- 13.40 function Pragma_Argument_Associations
------------------------------------------------------------------------------
function Pragma_Argument_Associations
(Pragma_Element : Asis.Pragma_Element)
return Asis.Association_List;
------------------------------------------------------------------------------
-- Pragma_Element - Specifies the element to query
--
-- Returns a list of the Pragma_Argument_Associations of the pragma, in their
-- order of appearance.
--
-- Appropriate Element_Kinds:
-- A_Pragma
--
-- Returns Element_Kinds:
-- A_Pragma_Argument_Association
--
------------------------------------------------------------------------------
-- 13.41 function Debug_Image
------------------------------------------------------------------------------
function Debug_Image (Element : Asis.Element) return Wide_String;
------------------------------------------------------------------------------
-- Element - Specifies the program element to convert
--
-- Returns a string value containing implementation-defined debug
-- information associated with the element.
--
-- The return value uses Asis.Text.Delimiter_Image to separate the lines
-- of multi-line results. The return value does not end with
-- Asis.Text.Delimiter_Image.
--
-- These values are intended for two purposes. They are suitable for
-- inclusion in problem reports sent to the ASIS implementor. They can
-- be presumed to contain information useful when debugging the implementation
-- itself. They are also suitable for use by the ASIS application when
-- printing simple application debugging messages during application
-- development. They are intended to be, to some worthwhile degree,
-- intelligible to the user.
--
------------------------------------------------------------------------------
-- 13.42 function Hash
------------------------------------------------------------------------------
function Hash (Element : Asis.Element) return Asis.ASIS_Integer;
-- The purpose of the hash function is to provide a convenient name for an
-- object of type Asis.Element in order to facilitate application defined I/O
-- and/or other application defined processing.
--
-- The hash function maps Asis.Element objects into N discrete classes
-- ("buckets") of objects. A good hash function is uniform across its range.
-- It is important to note that the distribution of objects in the
-- application's domain will affect the distribution of the hash function.
-- A good hash measured against one domain will not necessarily be good when
-- fed objects from a different set.
--
-- A continuous uniform hash can be divided by any N and provide a uniform
-- distribution of objects to each of the N discrete classes. A hash value is
-- not unique for each hashed Asis.Element. The application is responsible for
-- handling name collisions of the hashed value.
--
-- The hash function returns a hashed value of type ASIS_Integer. If desired,
-- a user could easily map ASIS_Integer'Range to any smaller range for the
-- hash based on application constraints (i.e., the application implementor
-- can tune the time-space tradeoffs by choosing a small table, implying
-- slower lookups within each "bucket", or a large table, implying faster
-- lookups within each "bucket").
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Processing of the Ada extensions that most likely will be included in --
-- Ada 2012 and that are already implemented in GNAT --
------------------------------------------------------------------------------
end Asis.Elements;
|
-- { dg-do compile }
-- { dg-options "-O -gnatp" }
package body Invariant_Index is
procedure Proc (S : String) is
N : constant Integer := S'Length;
begin
Name_Buffer (1 + N .. Name_Len + N) := Name_Buffer (1 .. Name_Len);
Name_Buffer (1 .. N) := S;
Name_Len := Name_Len + N;
end;
end Invariant_Index;
|
-- C55B06A.ADA
-- Grant of Unlimited Rights
--
-- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687,
-- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained
-- unlimited rights in the software and documentation contained herein.
-- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making
-- this public release, the Government intends to confer upon all
-- recipients unlimited rights equal to those held by the Government.
-- These rights include rights to use, duplicate, release or disclose the
-- released technical data and computer software in whole or in part, in
-- any manner and for any purpose whatsoever, and to have or permit others
-- to do so.
--
-- DISCLAIMER
--
-- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR
-- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED
-- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE
-- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE
-- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A
-- PARTICULAR PURPOSE OF SAID MATERIAL.
--*
-- CHECK THAT LOOPS MAY BE SPECIFIED FOR BOOLEAN, INTEGER,
-- CHARACTER, ENUMERATION, AND DERIVED TYPES, INCLUDING
-- TYPES DERIVED FROM DERIVED TYPES. DERIVED BOOLEAN IS NOT
-- TESTED IN THIS TEST.
-- DAT 3/26/81
-- JBG 9/29/82
-- SPS 3/11/83
-- JBG 10/5/83
-- PWN 01/31/95 REMOVED INCONSISTENCIES WITH ADA 9X.
WITH REPORT; USE REPORT;
PROCEDURE C55B06A IS
TYPE ENUM IS ('A', 'B', 'D', 'C', Z, X, D, A, C);
TYPE D1 IS NEW CHARACTER RANGE 'A' .. 'Z';
TYPE D2 IS NEW INTEGER;
TYPE D3 IS NEW ENUM;
TYPE D4 IS NEW D1;
TYPE D5 IS NEW D2;
TYPE D6 IS NEW D3;
ONE : INTEGER := IDENT_INT(1);
COUNT : INTEGER := 0;
OLDCOUNT : INTEGER := 0;
PROCEDURE Q IS
BEGIN
COUNT := COUNT + ONE;
END Q;
BEGIN
TEST ("C55B06A", "TEST LOOPS FOR ALL DISCRETE TYPES");
FOR I IN BOOLEAN LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(2) /= COUNT THEN
FAILED ("LOOP 1");
END IF;
OLDCOUNT := COUNT;
FOR I IN FALSE .. TRUE LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(2) /= COUNT THEN
FAILED ("LOOP 2");
END IF;
OLDCOUNT := COUNT;
FOR I IN BOOLEAN RANGE FALSE .. TRUE LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(2) /= COUNT THEN
FAILED ("LOOP 3");
END IF;
OLDCOUNT := COUNT;
FOR I IN INTEGER LOOP
Q;
EXIT WHEN I = INTEGER'FIRST + 2;
END LOOP;
IF OLDCOUNT + IDENT_INT(3) /= COUNT THEN
FAILED ("LOOP 4");
END IF;
OLDCOUNT := COUNT;
FOR I IN 3 .. IDENT_INT (5) LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(3) /= COUNT THEN
FAILED ("LOOP 5");
END IF;
OLDCOUNT := COUNT;
FOR I IN INTEGER RANGE -2 .. -1 LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(2) /= COUNT THEN
FAILED ("LOOP 6");
END IF;
OLDCOUNT := COUNT;
FOR I IN INTEGER RANGE INTEGER'FIRST .. INTEGER'FIRST + 1 LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(2) /= COUNT THEN
FAILED ("LOOP 7");
END IF;
OLDCOUNT := COUNT;
FOR I IN 'A' .. CHARACTER'('Z') LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(26) /= COUNT THEN
FAILED ("LOOP 9");
END IF;
OLDCOUNT := COUNT;
FOR I IN CHARACTER RANGE 'A' .. 'D' LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(4) /= COUNT THEN
FAILED ("LOOP 10");
END IF;
OLDCOUNT := COUNT;
FOR I IN ENUM LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(9) /= COUNT THEN
FAILED ("LOOP 11");
END IF;
OLDCOUNT := COUNT;
FOR I IN ENUM RANGE D .. C LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(3) /= COUNT THEN
FAILED ("LOOP 12");
END IF;
OLDCOUNT := COUNT;
FOR I IN 'A' .. ENUM'(Z) LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(5) /= COUNT THEN
FAILED ("LOOP 13");
END IF;
OLDCOUNT := COUNT;
FOR I IN D1 LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(26) /= COUNT THEN
FAILED ("LOOP 14");
END IF;
OLDCOUNT := COUNT;
FOR I IN D1 RANGE 'A' .. 'Z' LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(26) /= COUNT THEN
FAILED ("LOOP 15");
END IF;
OLDCOUNT := COUNT;
FOR I IN D1'('A') .. 'D' LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(4) /= COUNT THEN
FAILED ("LOOP 16");
END IF;
OLDCOUNT := COUNT;
FOR I IN D2 LOOP
Q;
IF I > D2'FIRST + 3 THEN
EXIT;
END IF;
END LOOP;
IF OLDCOUNT + IDENT_INT(5) /= COUNT THEN
FAILED ("LOOP 17");
END IF;
OLDCOUNT := COUNT;
FOR I IN D2 RANGE -100 .. -99 LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(2) /= COUNT THEN
FAILED ("LOOP 18");
END IF;
OLDCOUNT := COUNT;
FOR I IN D2'(1) .. 2 LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(2) /= COUNT THEN
FAILED ("LOOP 19");
END IF;
OLDCOUNT := COUNT;
FOR I IN D3 LOOP
IF I IN 'A' .. 'C' THEN
Q; -- 4
ELSE
Q; Q; -- 10
END IF;
END LOOP;
IF OLDCOUNT + IDENT_INT(14) /= COUNT THEN
FAILED ("LOOP 20");
END IF;
OLDCOUNT := COUNT;
FOR I IN D3 RANGE 'A' .. Z LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(5) /= COUNT THEN
FAILED ("LOOP 21");
END IF;
OLDCOUNT := COUNT;
FOR I IN 'A' .. D3'(Z) LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(5) /= COUNT THEN
FAILED ("LOOP 22");
END IF;
OLDCOUNT := COUNT;
FOR I IN D4 LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(26) /= COUNT THEN
FAILED ("LOOP 23");
END IF;
OLDCOUNT := COUNT;
FOR I IN D4'('A') .. 'Z' LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(26) /= COUNT THEN
FAILED ("LOOP 24");
END IF;
OLDCOUNT := COUNT;
FOR I IN D4 RANGE 'B' .. 'D' LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(3) /= COUNT THEN
FAILED ("LOOP 25");
END IF;
OLDCOUNT := COUNT;
FOR J IN D5 LOOP
Q; -- 4
EXIT WHEN J = D5(INTEGER'FIRST) + 3;
Q; -- 3
END LOOP;
IF OLDCOUNT + IDENT_INT(7) /= COUNT THEN
FAILED ("LOOP 26");
END IF;
OLDCOUNT := COUNT;
FOR J IN D5 RANGE -2 .. -1 LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(2) /= COUNT THEN
FAILED ("LOOP 27");
END IF;
OLDCOUNT := COUNT;
FOR J IN D5'(-10) .. D5'(-6) LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(5) /= COUNT THEN
FAILED ("LOOP 28");
END IF;
OLDCOUNT := COUNT;
FOR J IN D6 LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(9) /= COUNT THEN
FAILED ("LOOP 29");
END IF;
OLDCOUNT := COUNT;
FOR J IN D6 RANGE Z .. A LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(4) /= COUNT THEN
FAILED ("LOOP 30");
END IF;
OLDCOUNT := COUNT;
FOR J IN D6'('D') .. D LOOP
Q;
END LOOP;
IF OLDCOUNT + IDENT_INT(5) /= COUNT THEN
FAILED ("LOOP 31");
END IF;
OLDCOUNT := COUNT;
RESULT;
END C55B06A;
|
with Ada.Text_IO;
with Ada.Directories;
with Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Text_IO;
use Ada;
use Ada.Strings.Unbounded;
procedure file_exists is
File_Path : Unbounded_String;
Found_File : Boolean;
begin
Ada.Text_IO.Put("path: ");
Strings.Unbounded.Text_IO.Get_Line(File_Path);
Found_File := Directories.Exists(To_String(File_Path));
if Found_File then
Ada.Text_IO.Put_Line("file exists");
else
Ada.Text_IO.Put_Line("file does not exist");
end if;
end file_exists;
|
with Interfaces; use Interfaces;
generic
with procedure Write (Data : Unsigned_8);
with function Read return Unsigned_8;
package CBOR_Codec is
pragma Preelaborate;
type Major_Type is (Unsigned_Integer, Negative_Integer, Byte_String,
UTF8_String, Item_Array, Item_Map, Tag, Simple_Or_Float)
with Size => 3;
for Major_Type use (
Unsigned_Integer => 0,
Negative_Integer => 1,
Byte_String => 2,
UTF8_String => 3,
Item_Array => 4,
Item_Map => 5,
Tag => 6,
Simple_Or_Float => 7);
Date_Time_String_Tag : constant Natural := 0;
Epoch_Time_Tag : constant Natural := 1;
Positive_Bignum_Tag : constant Natural := 2;
Negative_Bignum_Tag : constant Natural := 3;
Decimal_Fraction_Tag : constant Natural := 4;
Bigfloat_Tag : constant Natural := 5;
Base64_URL_Expected_Tag : constant Natural := 21;
Base64_Expected_Tag : constant Natural := 22;
Base16_Expected_Tag : constant Natural := 23;
CBOR_Data_Tag : constant Natural := 24;
URI_String_Tag : constant Natural := 32;
Base64_URL_String_Tag : constant Natural := 33;
Base64_String_Tag : constant Natural := 34;
Regexp_Tag : constant Natural := 35;
MIME_Message_Tag : constant Natural := 36;
procedure Encode_Integer (Value : Integer);
procedure Encode_Byte_String (Value : String);
procedure Encode_UTF8_String (Value : String);
procedure Encode_Array (Count : Natural);
procedure Encode_Map (Count : Natural);
procedure Encode_Tag (Value : Natural);
procedure Encode_Null;
procedure Encode_False;
procedure Encode_True;
procedure Encode_Undefined;
procedure Encode_Simple_Value (Value : Integer);
procedure Encode_Float (Value : Short_Float);
procedure Encode_Float (Value : Float);
procedure Encode_Decimal_Fraction (Value : Integer; Mantissa : Integer);
function Decode_Integer (Value : out Integer) return Boolean;
function Decode_Byte_String (Size : out Natural) return Boolean;
function Decode_UTF8_String return Boolean;
function Decode_Array (Count : out Natural) return Boolean;
function Decode_Map return Boolean;
function Decode_Tag (Value : out Integer) return Boolean;
function Decode_Null return Boolean;
function Decode_Boolean return Boolean;
function Decode_Undefined return Boolean;
function Decode_Simple_Value return Boolean;
function Decode_Float return Boolean;
function Decode_Decimal_Fraction (Value : out Integer;
Mantissa : out Integer) return Boolean;
end CBOR_Codec;
|
-- Copyright (c) 2021 Devin Hill
-- zlib License -- see LICENSE for details.
with System.Allocation.Memory;
with System.Allocation.Arenas;
use System.Allocation.Arenas;
package GBA.Memory.Default_Heaps is
IWRAM_Heap_Start : constant Character
with Import, External_Name => "__iheap_start";
IWRAM_Heap : Heap_Arena
:= Create_Arena (IWRAM_Heap_Start'Address, Internal_WRAM_Address'Last);
EWRAM_Heap : Heap_Arena renames System.Allocation.Memory.Heap;
end GBA.Memory.Default_Heaps; |
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Localization, Internationalization, Globalization for Ada --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2011, 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 Ada.Containers.Generic_Array_Sort;
with Ada.Unchecked_Deallocation;
with League.Characters.Internals;
with Matreshka.Internals.Unicode;
with Matreshka.Internals.Unicode.Ucd.Core;
package body Matreshka.Internals.Code_Point_Sets is
function Max_Result_Last (Left, Right : Shared_Code_Point_Set)
return Second_Stage_Array_Index;
pragma Inline (Max_Result_Last);
generic
with function Operator
(Left, Right : Boolean_Second_Stage) return Boolean_Second_Stage;
function Apply_Binary_Operator
(Left, Right : Shared_Code_Point_Set)
return Shared_Code_Point_Set;
---------------------------
-- Apply_Binary_Operator --
---------------------------
function Apply_Binary_Operator
(Left, Right : Shared_Code_Point_Set)
return Shared_Code_Point_Set
is
use type First_Stage_Index;
Last : Second_Stage_Array_Index := 0;
First_Stage : First_Stage_Map;
Has_All_On : Boolean := False;
Has_All_Off : Boolean := False;
All_On_Index : Second_Stage_Array_Index;
All_Off_Index : Second_Stage_Array_Index;
Is_All_On : Boolean;
Is_All_Off : Boolean;
Second_Stages : Second_Stage_Array
(0 .. Max_Result_Last (Left, Right));
Set : array (Left.Second_Stages'Range, Right.Second_Stages'Range)
of Boolean := (others => (others => False));
Map : array (Left.Second_Stages'Range, Right.Second_Stages'Range)
of Second_Stage_Array_Index;
begin
for J in First_Stage'Range loop
if not Set (Left.First_Stage (J), Right.First_Stage (J)) then
Set (Left.First_Stage (J), Right.First_Stage (J)) := True;
Second_Stages (Last) := Operator
(Left.Second_Stages (Left.First_Stage (J)),
Right.Second_Stages (Right.First_Stage (J)));
Is_All_On := Second_Stages (Last) = All_On;
Is_All_Off := Second_Stages (Last) = All_Off;
if Is_All_On then
if not Has_All_On then
Has_All_On := True;
All_On_Index := Last;
Last := Last + 1;
end if;
Map (Left.First_Stage (J), Right.First_Stage (J)) :=
All_On_Index;
elsif Is_All_Off then
if not Has_All_Off then
Has_All_Off := True;
All_Off_Index := Last;
Last := Last + 1;
end if;
Map (Left.First_Stage (J), Right.First_Stage (J)) :=
All_Off_Index;
else
Map (Left.First_Stage (J), Right.First_Stage (J)) := Last;
Last := Last + 1;
end if;
end if;
First_Stage (J) := Map (Left.First_Stage (J), Right.First_Stage (J));
end loop;
Last := Last - 1;
return
(Last => Last,
Counter => <>,
First_Stage => First_Stage,
Second_Stages => Second_Stages (0 .. Last));
end Apply_Binary_Operator;
function Apply_And is new Apply_Binary_Operator ("and");
function Apply_Or is new Apply_Binary_Operator ("or");
function Apply_Xor is new Apply_Binary_Operator ("xor");
function Minus
(Left, Right : Boolean_Second_Stage)
return Boolean_Second_Stage;
function Apply_Minus is new Apply_Binary_Operator (Minus);
---------
-- "+" --
---------
function "+"
(Right : Shared_Code_Point_Set)
return Shared_Code_Point_Set is
begin
return (Last => Right.Last,
Counter => <>,
First_Stage => Right.First_Stage,
Second_Stages => Right.Second_Stages);
end "+";
---------
-- "-" --
---------
function "-"
(Left, Right : Shared_Code_Point_Set)
return Shared_Code_Point_Set renames Apply_Minus;
---------
-- "=" --
---------
function "=" (Left, Right : Shared_Code_Point_Set) return Boolean is
SF : constant First_Stage_Index := First_Stage_Index
(Internals.Unicode.Surrogate_First / Second_Stage_Index'Modulus);
SL : constant First_Stage_Index := First_Stage_Index
(Internals.Unicode.Surrogate_Last / Second_Stage_Index'Modulus);
begin
for J in Left.First_Stage'Range loop
if Left.Second_Stages (Left.First_Stage (J)) /=
Right.Second_Stages (Right.First_Stage (J))
and then J not in SF .. SL
then
return False;
end if;
end loop;
return True;
end "=";
-----------
-- "and" --
-----------
function "and"
(Left, Right : Shared_Code_Point_Set)
return Shared_Code_Point_Set renames Apply_And;
-----------
-- "not" --
-----------
function "not"
(Right : Shared_Code_Point_Set)
return Shared_Code_Point_Set is
begin
return Result : Shared_Code_Point_Set :=
(Last => Right.Last,
Counter => <>,
First_Stage => Right.First_Stage,
Second_Stages => <>)
do
for J in Right.Second_Stages'Range loop
Result.Second_Stages (J) := not Right.Second_Stages (J);
end loop;
end return;
end "not";
----------
-- "or" --
----------
function "or"
(Left, Right : Shared_Code_Point_Set)
return Shared_Code_Point_Set renames Apply_Or;
-----------
-- "xor" --
-----------
function "xor"
(Left, Right : Shared_Code_Point_Set)
return Shared_Code_Point_Set renames Apply_Xor;
-----------------
-- Dereference --
-----------------
procedure Dereference (Self : in out Shared_Code_Point_Set_Access) is
procedure Free is
new Ada.Unchecked_Deallocation
(Shared_Code_Point_Set, Shared_Code_Point_Set_Access);
pragma Assert (Self /= null);
pragma Suppress (Access_Check);
begin
if Self /= Shared_Empty'Access
and then Matreshka.Atomics.Counters.Decrement (Self.Counter)
then
Free (Self);
end if;
Self := null;
end Dereference;
---------
-- Has --
---------
function Has
(Set : Shared_Code_Point_Set;
Element : League.Characters.Universal_Character)
return Boolean
is
use Matreshka.Internals.Unicode;
First : First_Stage_Index;
Second : Second_Stage_Index;
Code : constant Code_Unit_32 :=
League.Characters.Internals.Internal (Element);
begin
if Is_Valid (Code) then
First := First_Stage_Index (Code / Second_Stage_Index'Modulus);
Second := Second_Stage_Index (Code mod Second_Stage_Index'Modulus);
return Set.Second_Stages (Set.First_Stage (First)) (Second);
else
return False;
end if;
end Has;
--------------
-- Is_Empty --
--------------
function Is_Empty (Set : Shared_Code_Point_Set) return Boolean is
begin
for J in Set.Second_Stages'Range loop
if Set.Second_Stages (J) /= All_Off then
return False;
end if;
end loop;
return True;
end Is_Empty;
---------------
-- Is_Subset --
---------------
function Is_Subset
(Elements : Shared_Code_Point_Set;
Set : Shared_Code_Point_Set)
return Boolean is
begin
return Is_Empty (Elements - Set);
end Is_Subset;
function Match
(Descriptor : Code_Point_Set_Descriptor;
Value : Matreshka.Internals.Unicode.Ucd.Core_Values)
return Boolean
is
use type Matreshka.Internals.Unicode.Ucd.General_Category;
begin
case Descriptor.Kind is
when General_Category =>
return Descriptor.GC_Flags (Value.GC);
when Binary =>
return Value.B (Descriptor.Property);
end case;
end Match;
---------------------
-- Max_Result_Last --
---------------------
function Max_Result_Last
(Left, Right : Shared_Code_Point_Set)
return Second_Stage_Array_Index
is
Left_Size : constant Positive := Natural (Left.Last) + 1;
Right_Size : constant Positive := Natural (Right.Last) + 1;
Max_Size : constant Positive :=
Positive'Min (Left_Size * Right_Size, First_Stage_Index'Modulus);
begin
return Second_Stage_Array_Index (Max_Size - 1);
end Max_Result_Last;
-----------
-- Minus --
-----------
function Minus
(Left, Right : Boolean_Second_Stage)
return Boolean_Second_Stage is
begin
return Left and not Right;
end Minus;
---------------
-- Reference --
---------------
procedure Reference (Self : Shared_Code_Point_Set_Access) is
begin
if Self /= Shared_Empty'Access then
Matreshka.Atomics.Counters.Increment (Self.Counter);
end if;
end Reference;
------------
-- To_Set --
------------
function To_Set
(Sequence : Wide_Wide_String)
return Shared_Code_Point_Set
is
use type First_Stage_Index;
use type Matreshka.Internals.Unicode.Code_Unit_32;
function To_First_Index
(X : Wide_Wide_Character)
return First_Stage_Index;
procedure Sort is new Ada.Containers.Generic_Array_Sort
(Index_Type => Positive,
Element_Type => Wide_Wide_Character,
Array_Type => Wide_Wide_String);
--------------------
-- To_First_Index --
--------------------
function To_First_Index
(X : Wide_Wide_Character)
return First_Stage_Index
is
Pos : constant Natural := Wide_Wide_Character'Pos (X);
begin
return First_Stage_Index (Pos / Second_Stage_Index'Modulus);
end To_First_Index;
Invalid : constant First_Stage_Index := First_Stage_Index
(Internals.Unicode.Surrogate_First / Second_Stage_Index'Modulus);
Last : Second_Stage_Array_Index := 0;
First : First_Stage_Index;
Second : Second_Stage_Index;
Counted : First_Stage_Index := Invalid;
-- Set Counted to something invalid
Code : Matreshka.Internals.Unicode.Code_Unit_32;
Ordered : Wide_Wide_String := Sequence;
begin
Sort (Ordered);
for J in Ordered'Range loop
Code := Wide_Wide_Character'Pos (Ordered (J));
if Matreshka.Internals.Unicode.Is_Valid (Code) then
First := To_First_Index (Ordered (J));
if Counted /= First then
Counted := First;
Last := Last + 1;
end if;
end if;
end loop;
return Result : Shared_Code_Point_Set :=
(Last => Last,
Counter => <>,
First_Stage => (others => 0),
Second_Stages => (others => All_Off))
do
Counted := Invalid;
Last := 0;
for J in Ordered'Range loop
Code := Wide_Wide_Character'Pos (Ordered (J));
if Matreshka.Internals.Unicode.Is_Valid (Code) then
First := To_First_Index (Ordered (J));
if Counted /= First then
Counted := First;
Last := Last + 1;
Result.First_Stage (Counted) := Last;
end if;
Second := Second_Stage_Index
(Code mod Second_Stage_Index'Modulus);
Result.Second_Stages (Last) (Second) := True;
end if;
end loop;
end return;
end To_Set;
------------
-- To_Set --
------------
function To_Set
(Low : Matreshka.Internals.Unicode.Code_Point;
High : Matreshka.Internals.Unicode.Code_Point)
return Shared_Code_Point_Set
is
use Matreshka.Internals.Unicode;
use type Second_Stage_Index;
use type Second_Stage_Array_Index;
Before_Surrogate : constant First_Stage_Index :=
First_Stage_Index (Surrogate_First / 256 - 1);
After_Surrogate : constant First_Stage_Index :=
First_Stage_Index (Surrogate_Last / 256 + 1);
H : Code_Point := High;
HF : First_Stage_Index := First_Stage_Index (H / 256);
HS : Second_Stage_Index := Second_Stage_Index (H mod 256);
L : Code_Point := Low;
LF : First_Stage_Index := First_Stage_Index (L / 256);
LS : Second_Stage_Index := Second_Stage_Index (L mod 256);
Last : Second_Stage_Array_Index := 0;
Has_All_On : Boolean := False;
Has_L : Boolean := False;
Has_H : Boolean := False;
begin
if L in Surrogate_First .. Surrogate_Last then
L := Surrogate_Last + 1;
LF := First_Stage_Index (L / 256);
LS := Second_Stage_Index (L mod 256);
end if;
if H in Surrogate_First .. Surrogate_Last then
H := Surrogate_First - 1;
HF := First_Stage_Index (H / 256);
HS := Second_Stage_Index (H mod 256);
end if;
if L > H then
Last := 0;
elsif LF = HF then
Last := 1;
else
if Surrogate_First in L .. H then
Has_All_On := LF < Before_Surrogate or HF > After_Surrogate;
else
Has_All_On := HF - LF > 1;
end if;
if LS = 0 then
Has_All_On := True;
else
Has_L := True;
end if;
if H mod 256 = 255 then
Has_All_On := True;
else
Has_H := True;
end if;
Last := Boolean'Pos (Has_L)
+ Boolean'Pos (Has_H)
+ Boolean'Pos (Has_All_On);
end if;
return Result : Shared_Code_Point_Set :=
(Last => Last,
Counter => <>,
First_Stage => (others => 0),
Second_Stages => (others => All_Off))
do
if L > H then
null;
elsif (LF) = (HF) then
Result.First_Stage (LF) := 1;
Result.Second_Stages (1) (LS .. HS) := (LS .. HS => True);
else
if Has_All_On then
Result.Second_Stages (Last) := All_On;
end if;
if Surrogate_First in L .. H then
Result.First_Stage (LF .. Before_Surrogate) := (others => Last);
Result.First_Stage (After_Surrogate .. HF) := (others => Last);
else
Result.First_Stage (LF .. HF) := (others => Last);
end if;
if LS /= 0 then
Result.First_Stage (LF) := 1;
Result.Second_Stages (1) (LS .. 255) := (LS .. 255 => True);
end if;
if H mod 256 /= 255 then
if Has_L then
Result.First_Stage (HF) := 2;
Result.Second_Stages (2) (0 .. HS) := (0 .. HS => True);
else
Result.First_Stage (HF) := 1;
Result.Second_Stages (1) (0 .. HS) := (0 .. HS => True);
end if;
end if;
end if;
end return;
end To_Set;
------------
-- To_Set --
------------
function To_Set
(Descriptor : Code_Point_Set_Descriptor)
return Core_Shared_Code_Point_Set
is
use Matreshka.Internals.Unicode.Ucd;
P : constant Core_First_Stage_Access := Core.Property'Access;
begin
return Result : Core_Shared_Code_Point_Set do
Result.First_Stage := First_Stage_Map (Indexes.Group_Index);
Result.Second_Stages := (others => All_Off);
for J in Result.Second_Stages'Range loop
for K in Code_Point_Sets.Second_Stage_Index loop
if Match (Descriptor, P (Indexes.Base (J)) (K)) then
Result.Second_Stages (J) (K) := True;
end if;
end loop;
end loop;
end return;
end To_Set;
end Matreshka.Internals.Code_Point_Sets;
|
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- 21 package Asis.Ids
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
with Ada.Strings.Wide_Unbounded;
package Asis.Ids is
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- Asis.Ids provides support for permanent unique Element "Identifiers" (Ids).
-- An Id is an efficient way for a tool to reference an ASIS element. The Id
-- is permanent from session to session provided that the Ada compilation
-- environment is unchanged.
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- This package encapsulates a set of operations and queries that implement
-- the ASIS Id abstraction. An Id is a way of identifying a particular
-- Element, from a particular Compilation_Unit, from a particular Context.
-- Ids can be written to files. Ids can be read from files and converted into
-- an Element value with the use of a suitable open Context.
--
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- 21.1 type Id
-------------------------------------------------------------------------------
-- The Ada element Id abstraction (a private type).
--
-- The Id type is a distinct abstract type representing permanent "names"
-- that correspond to specific Element values.
--
-- These names can be written to files, retrieved at a later time, and
-- converted to Element values.
-------------------------------------------------------------------------------
-- ASIS Ids are a means of identifying particular Element values obtained from
-- a particular physical compilation unit. Ids are "relative names". Each Id
-- value is valid (is usable, makes sense, can be interpreted) only in the
-- context of an appropriate open ASIS Context.
--
-- Id shall be an undiscriminated private type, or, shall be derived from an
-- undiscriminated private type. It shall be declared as a new type or as a
-- subtype of an existing type.
-------------------------------------------------------------------------------
type Id is private;
Nil_Id : constant Id;
function "=" (Left : in Id;
Right : in Id)
return Boolean is abstract;
-------------------------------------------------------------------------------
-- 21.2 function Hash
-------------------------------------------------------------------------------
function Hash (The_Id : in Id) return Asis.ASIS_Integer;
-------------------------------------------------------------------------------
-- 21.3 function "<"
-------------------------------------------------------------------------------
function "<" (Left : in Id;
Right : in Id) return Boolean;
-------------------------------------------------------------------------------
-- 21.4 function ">"
-------------------------------------------------------------------------------
function ">" (Left : in Id;
Right : in Id) return Boolean;
-------------------------------------------------------------------------------
-- 21.5 function Is_Nil
-------------------------------------------------------------------------------
function Is_Nil (Right : in Id) return Boolean;
-------------------------------------------------------------------------------
-- Right - Specifies the Id to check
--
-- Returns True if the Id is the Nil_Id.
--
-------------------------------------------------------------------------------
-- 21.6 function Is_Equal
-------------------------------------------------------------------------------
function Is_Equal (Left : in Id;
Right : in Id) return Boolean;
-------------------------------------------------------------------------------
-- Left - Specifies the left Id to compare
-- Right - Specifies the right Id to compare
--
-- Returns True if Left and Right represent the same physical Id, from the
-- same physical compilation unit. The two Ids convert
-- to Is_Identical Elements when converted with the same open ASIS Context.
--
-------------------------------------------------------------------------------
-- 21.7 function Create_Id
-------------------------------------------------------------------------------
function Create_Id (Element : in Asis.Element) return Id;
-------------------------------------------------------------------------------
-- Element - Specifies any Element value whose Id is desired
--
-- Returns a unique Id value corresponding to this Element, from the
-- corresponding Enclosing_Compilation_Unit and the corresponding
-- Enclosing_Context. The Id value will not be equal ("=") to the Id value
-- for any other Element value unless the two Elements are Is_Identical.
--
-- Nil_Id is returned for a Nil_Element.
--
-- All Element_Kinds are appropriate.
--
-------------------------------------------------------------------------------
-- 21.8 function Create_Element
-------------------------------------------------------------------------------
function Create_Element (The_Id : in Id;
The_Context : in Asis.Context)
return Asis.Element;
-------------------------------------------------------------------------------
-- The_Id - Specifies the Id to be converted to an Element
-- The_Context - Specifies the Context containing the Element with this Id
--
-- Returns the Element value corresponding to The_Id. The_Id shall
-- correspond to an Element available from a Compilation_Unit contained by
-- (referencible through) The_Context.
--
-- Raises ASIS_Inappropriate_Element if the Element value is not available
-- though The_Context. The Status is Value_Error and the Diagnosis
-- string will attempt to indicate the reason for the failure. (e.g., "Unit
-- is inconsistent", "No such unit", "Element is inconsistent (Unit
-- inconsistent)", etc.)
--
-------------------------------------------------------------------------------
-- 21.9 function Debug_Image
-------------------------------------------------------------------------------
function Debug_Image (The_Id : in Id) return Wide_String;
-------------------------------------------------------------------------------
-- The_Id - Specifies an Id to convert
--
-- Returns a string value containing implementation-defined debug
-- information associated with the Id.
--
-- The return value uses Asis.Text.Delimiter_Image to separate the lines
-- of multi-line results. The return value does not end with
-- Asis.Text.Delimiter_Image.
--
-- These values are intended for two purposes. They are suitable for
-- inclusion in problem reports sent to the ASIS implementor. They can
-- be presumed to contain information useful when debugging the
-- implementation itself. They are also suitable for use by the ASIS
-- application when printing simple application debugging messages during
-- application development. They are intended to be, to some worthwhile
-- degree, intelligible to the user.
--
-------------------------------------------------------------------------------
private
package W renames Ada.Strings.Wide_Unbounded;
type Id is record
Hash : Asis.ASIS_Integer;
Unit : W.Unbounded_Wide_String;
end record;
Nil_Id : constant Id := (0, W.Null_Unbounded_Wide_String);
end Asis.Ids;
------------------------------------------------------------------------------
-- Copyright (c) 2006-2013, Maxim Reznik
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * Neither the name of the Maxim Reznik, IE nor the names of its
-- contributors may be used to endorse or promote products derived from
-- this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
|
-- Copyright (c) 2019 Maxim Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with Program.Elements.Definitions;
with Program.Lexical_Elements;
with Program.Elements.Expressions;
package Program.Elements.Real_Range_Specifications is
pragma Pure (Program.Elements.Real_Range_Specifications);
type Real_Range_Specification is
limited interface and Program.Elements.Definitions.Definition;
type Real_Range_Specification_Access is
access all Real_Range_Specification'Class with Storage_Size => 0;
not overriding function Lower_Bound
(Self : Real_Range_Specification)
return not null Program.Elements.Expressions.Expression_Access
is abstract;
not overriding function Upper_Bound
(Self : Real_Range_Specification)
return not null Program.Elements.Expressions.Expression_Access
is abstract;
type Real_Range_Specification_Text is limited interface;
type Real_Range_Specification_Text_Access is
access all Real_Range_Specification_Text'Class with Storage_Size => 0;
not overriding function To_Real_Range_Specification_Text
(Self : aliased in out Real_Range_Specification)
return Real_Range_Specification_Text_Access is abstract;
not overriding function Range_Token
(Self : Real_Range_Specification_Text)
return not null Program.Lexical_Elements.Lexical_Element_Access
is abstract;
not overriding function Double_Dot_Token
(Self : Real_Range_Specification_Text)
return not null Program.Lexical_Elements.Lexical_Element_Access
is abstract;
end Program.Elements.Real_Range_Specifications;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS --
-- --
-- S Y S T E M . T A S K I N G . D E B U G --
-- --
-- S p e c --
-- --
-- Copyright (C) 1997-2005, Free Software Foundation, Inc. --
-- --
-- GNARL is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNARL is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNARL; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
--
--
--
--
--
--
--
-- GNARL was developed by the GNARL team at Florida State University. --
-- Extensive contributions were provided by Ada Core Technologies, Inc. --
-- --
------------------------------------------------------------------------------
-- This package encapsulates all direct interfaces to task debugging services
-- that are needed by gdb with gnat mode.
with System.Tasking;
with System.OS_Interface;
package System.Tasking.Debug is
pragma Preelaborate;
------------------------------------------
-- Application-level debugging routines --
------------------------------------------
procedure List_Tasks;
-- Print a list of all the known Ada tasks with abbreviated state
-- information, one-per-line, to the standard error file.
procedure Print_Current_Task;
-- Write information about current task, in hexadecimal, as one line, to
-- the standard error file.
procedure Print_Task_Info (T : Task_Id);
-- Similar to Print_Current_Task, for a given task.
procedure Set_User_State (Value : Long_Integer);
-- Set user state value in the current task.
-- This state will be displayed when calling List_Tasks or
-- Print_Current_Task. It is useful for setting task specific state.
function Get_User_State return Long_Integer;
-- Return the user state for the current task.
-------------------------
-- General GDB support --
-------------------------
Known_Tasks : array (0 .. 999) of Task_Id := (others => null);
-- Global array of tasks read by gdb, and updated by
-- Create_Task and Finalize_TCB
----------------------------------
-- VxWorks specific GDB support --
----------------------------------
-- Although the following routines are implemented in a target independent
-- manner, only VxWorks currently uses them.
procedure Task_Creation_Hook (Thread : OS_Interface.Thread_Id);
-- This procedure is used to notify GDB of task's creation.
-- It must be called by the task's creator.
procedure Task_Termination_Hook;
-- This procedure is used to notify GDB of task's termination.
procedure Suspend_All_Tasks (Thread_Self : OS_Interface.Thread_Id);
-- Suspend all the tasks except the one whose associated thread is
-- Thread_Self by traversing All_Tasks_Lists and calling
-- System.Task_Primitives.Operations.Suspend_Task.
procedure Resume_All_Tasks (Thread_Self : OS_Interface.Thread_Id);
-- Resume all the tasks except the one whose associated thread is
-- Thread_Self by traversing All_Tasks_Lists and calling
-- System.Task_Primitives.Operations.Continue_Task.
-------------------------------
-- Run-time tracing routines --
-------------------------------
procedure Trace
(Self_Id : Task_Id;
Msg : String;
Flag : Character;
Other_Id : Task_Id := null);
-- If traces for Flag are enabled, display on Standard_Error a given
-- message for the current task. Other_Id is an optional second task id
-- to display.
procedure Set_Trace
(Flag : Character;
Value : Boolean := True);
-- Enable or disable tracing for Flag.
-- By default, flags in the range 'A' .. 'Z' are disabled, others are
-- enabled.
end System.Tasking.Debug;
|
pragma Ada_2005;
pragma Style_Checks (Off);
with Interfaces.C; use Interfaces.C;
with stddef_h;
package malloc_h is
-- arg-macro: procedure alloca (x)
-- __builtin_alloca((x))
--*
-- * This file has no copyright assigned and is placed in the Public Domain.
-- * This file is part of the mingw-w64 runtime package.
-- * No warranty is given; refer to the file DISCLAIMER.PD within this package.
--
-- Return codes for _heapwalk()
-- Values for _heapinfo.useflag
-- The structure used to walk through the heap with _heapwalk.
type u_heapinfo is record
u_pentry : access int; -- d:\install\gpl2018\x86_64-pc-mingw32\include\malloc.h:47
u_size : aliased stddef_h.size_t; -- d:\install\gpl2018\x86_64-pc-mingw32\include\malloc.h:48
u_useflag : aliased int; -- d:\install\gpl2018\x86_64-pc-mingw32\include\malloc.h:49
end record;
pragma Convention (C_Pass_By_Copy, u_heapinfo); -- d:\install\gpl2018\x86_64-pc-mingw32\include\malloc.h:46
-- Make sure that X86intrin.h doesn't produce here collisions.
-- Users should really use MS provided versions
-- skipped func __mingw_aligned_malloc
-- skipped func __mingw_aligned_free
-- skipped func __mingw_aligned_offset_realloc
-- skipped func __mingw_aligned_realloc
-- skipped func _resetstkoflw
-- skipped func _set_malloc_crt_max_wait
-- skipped func _expand
-- skipped func _msize
-- skipped func _get_sbh_threshold
-- skipped func _set_sbh_threshold
-- skipped func _set_amblksiz
-- skipped func _get_amblksiz
-- skipped func _heapadd
-- skipped func _heapchk
-- skipped func _heapmin
-- skipped func _heapset
-- skipped func _heapwalk
-- skipped func _heapused
-- skipped func _get_heap_handle
-- skipped func _MarkAllocaS
-- skipped func _freea
end malloc_h;
|
with Lv.Objx;
private with System;
package Lv.Group is
type Instance is private;
function Create return Instance;
procedure Del (Group : Instance);
procedure Add_Obj (Group : Instance; Obj : Lv.Objx.Obj_T);
procedure Remove_Obj (Obj : Lv.Objx.Obj_T);
procedure Focus_Obj (Obj : Lv.Objx.Obj_T);
procedure Focus_Next (Group : Instance);
procedure Focus_Prev (Group : Instance);
procedure Focus_Freeze (Group : Instance; En : U_Bool);
function Send_Data (Group : Instance; C : Uint32_T) return Lv.Objx.Res_T;
private
type Instance is new System.Address;
-------------
-- Imports --
-------------
pragma Import (C, Create, "lv_group_create");
pragma Import (C, Del, "lv_group_del");
pragma Import (C, Add_Obj, "lv_group_add_obj");
pragma Import (C, Remove_Obj, "lv_group_remove_obj");
pragma Import (C, Focus_Obj, "lv_group_focus_obj");
pragma Import (C, Focus_Next, "lv_group_focus_next");
pragma Import (C, Focus_Prev, "lv_group_focus_prev");
pragma Import (C, Focus_Freeze, "lv_group_focus_freeze");
pragma Import (C, Send_Data, "lv_group_send_data");
end Lv.Group;
|
-- TODO: maybe add examples of Ada with contracts
-- @see https://learn.adacore.com/ |
-- SPDX-FileCopyrightText: 2020 Max Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-------------------------------------------------------------
with Program.Unit_Naming;
private with Ada.Strings.Wide_Wide_Unbounded;
package Program.Directory_Unit_Schemas is
pragma Preelaborate;
type Directory_Unit_Schema
(Base_Name : Program.Unit_Naming.Unit_Naming_Schema_Access)
is new Program.Unit_Naming.Unit_Naming_Schema
with private;
-- This object returns full file name. It uses Base_Name to find a base
-- file name. It looks into a current directory if Add_Directory
-- was never called. Otherwise it looks given Path only.
procedure Add_Directory
(Self : in out Directory_Unit_Schema;
Path : Program.Text);
-- Add the Path to directory search list.
private
type Directory_Unit_Schema_Access is access all Directory_Unit_Schema;
type Directory_Unit_Schema
(Base_Name : Program.Unit_Naming.Unit_Naming_Schema_Access)
is new Program.Unit_Naming.Unit_Naming_Schema with record
Path : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String;
Next : Directory_Unit_Schema_Access;
end record;
overriding function Standard_Text_Name (Self : Directory_Unit_Schema)
return Program.Text;
-- Get compilation Text_Name for Standard library package.
overriding function Declaration_Text_Name
(Self : Directory_Unit_Schema;
Name : Program.Text)
return Program.Text;
-- Get compilation Text_Name for given library declaration unit.
overriding function Body_Text_Name
(Self : Directory_Unit_Schema;
Name : Program.Text)
return Program.Text;
-- Get compilation Text_Name for given body.
overriding function Subunit_Text_Name
(Self : Directory_Unit_Schema;
Name : Program.Text)
return Program.Text;
end Program.Directory_Unit_Schemas;
|
package body Aggr19_Pkg is
procedure Proc (Pool : in out Rec5) is
begin
Pool.Ent := (Kind => Two, Node => Pool.Ent.Node, I => 0);
end;
end ;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2021 The progress_indicators authors
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with ANSI;
package body Progress_Indicators.Spinners is
function Make (Style : Spinner_Style := In_Place; Ticks_Per_Move : Positive := 1) return Spinner is
begin
return (Ticks_Per_Move => Ticks_Per_Move, Ticks => 0, State => 0, Style => Style);
end Make;
function Value (S : Spinner) return String is
begin
if not Spinners_Enabled then
return "";
end if;
case S.Style is
when Empty =>
return "";
when In_Place =>
return Spinner_States (S.State) & ANSI.Back;
when Normal =>
return "" & Spinner_States (S.State);
end case;
end Value;
procedure Tick (S : in out Spinner) is
begin
S.Ticks := (S.Ticks + 1) mod S.Ticks_Per_Move;
if S.Ticks = 0 then
S.State := S.State + 1;
end if;
end Tick;
procedure Enable_All is
begin
Spinners_Enabled := True;
end Enable_All;
procedure Disable_All is
begin
Spinners_Enabled := False;
end Disable_All;
end Progress_Indicators.Spinners;
|
-- { dg-do run }
procedure kill_value is
type Struct;
type Pstruct is access all Struct;
type Struct is record Next : Pstruct; end record;
Vap : Pstruct := new Struct;
begin
for J in 1 .. 10 loop
if Vap /= null then
while Vap /= null
loop
Vap := Vap.Next;
end loop;
end if;
end loop;
end;
|
with Ada.Strings.Unbounded;
package Unit_2 is
type Range_Type is new Integer range 1 .. 10;
procedure Do_It (This : in Range_Type);
Dont_Like_5 : Exception;
private
package Parent_Class is
type Object is abstract tagged record
Component_1 : Integer := 2;
end record;
procedure Method_1
(This : in out Object);
end Parent_Class;
package Child_Class is
type Object is new Parent_Class.Object with record
Component_2 : Integer := 10;
end record;
overriding
procedure Method_1
(This : in out Object);
function Method_2
(This : in out Object;
Param_1 : in Integer)
return Integer;
end Child_Class;
end Unit_2;
|
with Ada.Exception_Identification.From_Here;
with System.Storage_Elements;
with System.UTF_Conversions;
package body Ada.Strings.UTF_Encoding.Conversions is
use Exception_Identification.From_Here;
use type System.Storage_Elements.Storage_Offset;
use type System.UTF_Conversions.From_Status_Type;
use type System.UTF_Conversions.To_Status_Type;
use type System.UTF_Conversions.UCS_4;
-- binary to Wide_String, Wide_Wide_String
function To_UTF_16_Wide_String (Item : System.Address; Length : Natural)
return UTF_16_Wide_String;
function To_UTF_16_Wide_String (Item : System.Address; Length : Natural)
return UTF_16_Wide_String
is
pragma Assert (Length rem 2 = 0);
pragma Assert (Item mod 2 = 0); -- stack may be aligned
Item_All : UTF_16_Wide_String (1 .. Length / 2);
for Item_All'Address use Item;
begin
return Item_All;
end To_UTF_16_Wide_String;
function To_UTF_32_Wide_Wide_String (
Item : System.Address;
Length : Natural)
return UTF_32_Wide_Wide_String;
function To_UTF_32_Wide_Wide_String (
Item : System.Address;
Length : Natural)
return UTF_32_Wide_Wide_String
is
pragma Assert (Length rem 4 = 0);
pragma Assert (Item mod 4 = 0); -- stack may be aligned
Item_All : UTF_32_Wide_Wide_String (1 .. Length / 4);
for Item_All'Address use Item;
begin
return Item_All;
end To_UTF_32_Wide_Wide_String;
-- binary version subprograms of System.UTF_Conversions
procedure To_UTF_8 (
Code : System.UTF_Conversions.UCS_4;
Result : out UTF_String;
Last : out Natural;
Status : out System.UTF_Conversions.To_Status_Type)
renames System.UTF_Conversions.To_UTF_8;
procedure From_UTF_8 (
Data : UTF_String;
Last : out Natural;
Result : out System.UTF_Conversions.UCS_4;
Status : out System.UTF_Conversions.From_Status_Type)
renames System.UTF_Conversions.From_UTF_8;
procedure To_UTF_16BE (
Code : System.UTF_Conversions.UCS_4;
Result : out UTF_String;
Last : out Natural;
Status : out System.UTF_Conversions.To_Status_Type);
procedure To_UTF_16BE (
Code : System.UTF_Conversions.UCS_4;
Result : out UTF_String;
Last : out Natural;
Status : out System.UTF_Conversions.To_Status_Type)
is
W_Result : Wide_String (1 .. System.UTF_Conversions.UTF_16_Max_Length);
W_Last : Natural;
begin
System.UTF_Conversions.To_UTF_16 (Code, W_Result, W_Last, Status);
Last := Result'First - 1;
for I in 1 .. W_Last loop
declare
type U16 is mod 2 ** 16;
E : constant U16 := Wide_Character'Pos (W_Result (I));
begin
Last := Last + 1;
Result (Last) := Character'Val (E / 256);
Last := Last + 1;
Result (Last) := Character'Val (E rem 256);
end;
end loop;
end To_UTF_16BE;
procedure From_UTF_16BE (
Data : UTF_String;
Last : out Natural;
Result : out System.UTF_Conversions.UCS_4;
Status : out System.UTF_Conversions.From_Status_Type);
procedure From_UTF_16BE (
Data : UTF_String;
Last : out Natural;
Result : out System.UTF_Conversions.UCS_4;
Status : out System.UTF_Conversions.From_Status_Type) is
begin
if Data'Length < 2 then
Last := Data'Last;
Status := System.UTF_Conversions.Truncated;
else
declare
Leading : constant Wide_Character :=
Wide_Character'Val (
Character'Pos (Data (Data'First)) * 256
+ Character'Pos (Data (Data'First + 1)));
Length : Natural;
begin
Last := Data'First + 1;
System.UTF_Conversions.UTF_16_Sequence (Leading, Length, Status);
if Status = System.UTF_Conversions.Success then
if Length = 2 then
if Data'Length < 4 then
Last := Data'Last;
Status := System.UTF_Conversions.Truncated;
else
declare
Trailing : constant Wide_Character :=
Wide_Character'Val (
Character'Pos (Data (Data'First + 2)) * 256
+ Character'Pos (Data (Data'First + 3)));
W_Data : constant
Wide_String (
1 ..
System.UTF_Conversions.UTF_16_Max_Length) :=
(Leading, Trailing);
W_Last : Natural;
begin
Last := Data'First + 3;
System.UTF_Conversions.From_UTF_16 (
W_Data,
W_Last,
Result,
Status);
end;
end if;
else
pragma Assert (Length = 1);
Result := Wide_Character'Pos (Leading);
end if;
end if;
end;
end if;
end From_UTF_16BE;
procedure To_UTF_16LE (
Code : System.UTF_Conversions.UCS_4;
Result : out UTF_String;
Last : out Natural;
Status : out System.UTF_Conversions.To_Status_Type);
procedure To_UTF_16LE (
Code : System.UTF_Conversions.UCS_4;
Result : out UTF_String;
Last : out Natural;
Status : out System.UTF_Conversions.To_Status_Type)
is
W_Result : Wide_String (1 .. System.UTF_Conversions.UTF_16_Max_Length);
W_Last : Natural;
begin
System.UTF_Conversions.To_UTF_16 (Code, W_Result, W_Last, Status);
Last := Result'First - 1;
for I in 1 .. W_Last loop
declare
type U16 is mod 2 ** 16;
E : constant U16 := Wide_Character'Pos (W_Result (I));
begin
Last := Last + 1;
Result (Last) := Character'Val (E rem 256);
Last := Last + 1;
Result (Last) := Character'Val (E / 256);
end;
end loop;
end To_UTF_16LE;
procedure From_UTF_16LE (
Data : UTF_String;
Last : out Natural;
Result : out System.UTF_Conversions.UCS_4;
Status : out System.UTF_Conversions.From_Status_Type);
procedure From_UTF_16LE (
Data : UTF_String;
Last : out Natural;
Result : out System.UTF_Conversions.UCS_4;
Status : out System.UTF_Conversions.From_Status_Type) is
begin
if Data'Length < 2 then
Last := Data'Last;
Status := System.UTF_Conversions.Truncated;
else
declare
Leading : constant Wide_Character :=
Wide_Character'Val (
Character'Pos (Data (Data'First))
+ Character'Pos (Data (Data'First + 1)) * 256);
Length : Natural;
begin
Last := Data'First + 1;
System.UTF_Conversions.UTF_16_Sequence (Leading, Length, Status);
if Status = System.UTF_Conversions.Success then
if Length = 2 then
if Data'Length < 4 then
Last := Data'Last;
Status := System.UTF_Conversions.Truncated;
else
declare
Trailing : constant Wide_Character :=
Wide_Character'Val (
Character'Pos (Data (Data'First + 2))
+ Character'Pos (Data (Data'First + 3))
* 256);
W_Data : constant
Wide_String (
1 ..
System.UTF_Conversions.UTF_16_Max_Length) :=
(Leading, Trailing);
W_Last : Natural;
begin
Last := Data'First + 3;
System.UTF_Conversions.From_UTF_16 (
W_Data,
W_Last,
Result,
Status);
end;
end if;
else
pragma Assert (Length = 1);
Result := Wide_Character'Pos (Leading);
end if;
end if;
end;
end if;
end From_UTF_16LE;
procedure To_UTF_32BE (
Code : System.UTF_Conversions.UCS_4;
Result : out UTF_String;
Last : out Natural;
Status : out System.UTF_Conversions.To_Status_Type);
procedure To_UTF_32BE (
Code : System.UTF_Conversions.UCS_4;
Result : out UTF_String;
Last : out Natural;
Status : out System.UTF_Conversions.To_Status_Type) is
begin
Last := Result'First;
Result (Last) := Character'Val (Code / 16#1000000#);
Last := Last + 1;
Result (Last) := Character'Val (Code / 16#10000# rem 16#100#);
Last := Last + 1;
Result (Last) := Character'Val (Code / 16#100# rem 16#100#);
Last := Last + 1;
Result (Last) := Character'Val (Code rem 16#100#);
Status := System.UTF_Conversions.Success;
end To_UTF_32BE;
procedure From_UTF_32BE (
Data : UTF_String;
Last : out Natural;
Result : out System.UTF_Conversions.UCS_4;
Status : out System.UTF_Conversions.From_Status_Type);
procedure From_UTF_32BE (
Data : UTF_String;
Last : out Natural;
Result : out System.UTF_Conversions.UCS_4;
Status : out System.UTF_Conversions.From_Status_Type) is
begin
if Data'Length < 4 then
Last := Data'Last;
Status := System.UTF_Conversions.Truncated;
else
declare
type U32 is mod 2 ** 32; -- Wide_Wide_Character'Size = 31(?)
Leading : constant U32 :=
Character'Pos (Data (Data'First)) * 16#1000000#
+ Character'Pos (Data (Data'First + 1)) * 16#10000#
+ Character'Pos (Data (Data'First + 2)) * 16#100#
+ Character'Pos (Data (Data'First + 3));
Length : Natural;
begin
Last := Data'First + 3;
if Leading > U32 (System.UTF_Conversions.UCS_4'Last) then
Status := System.UTF_Conversions.Illegal_Sequence;
else
Result := System.UTF_Conversions.UCS_4 (Leading);
System.UTF_Conversions.UTF_32_Sequence (
Wide_Wide_Character'Val (Leading),
Length,
Status); -- checking surrogate pair
end if;
end;
end if;
end From_UTF_32BE;
procedure To_UTF_32LE (
Code : System.UTF_Conversions.UCS_4;
Result : out UTF_String;
Last : out Natural;
Status : out System.UTF_Conversions.To_Status_Type);
procedure To_UTF_32LE (
Code : System.UTF_Conversions.UCS_4;
Result : out UTF_String;
Last : out Natural;
Status : out System.UTF_Conversions.To_Status_Type) is
begin
Last := Result'First;
Result (Last) := Character'Val (Code rem 16#100#);
Last := Last + 1;
Result (Last) := Character'Val (Code / 16#100# rem 16#100#);
Last := Last + 1;
Result (Last) := Character'Val (Code / 16#10000# rem 16#100#);
Last := Last + 1;
Result (Last) := Character'Val (Code / 16#1000000#);
Status := System.UTF_Conversions.Success;
end To_UTF_32LE;
procedure From_UTF_32LE (
Data : UTF_String;
Last : out Natural;
Result : out System.UTF_Conversions.UCS_4;
Status : out System.UTF_Conversions.From_Status_Type);
procedure From_UTF_32LE (
Data : UTF_String;
Last : out Natural;
Result : out System.UTF_Conversions.UCS_4;
Status : out System.UTF_Conversions.From_Status_Type) is
begin
if Data'Length < 4 then
Last := Data'Last;
Status := System.UTF_Conversions.Truncated;
else
declare
type U32 is mod 2 ** 32; -- Wide_Wide_Character'Size = 31(?)
Leading : constant U32 :=
Character'Pos (Data (Data'First))
+ Character'Pos (Data (Data'First + 1)) * 16#100#
+ Character'Pos (Data (Data'First + 2)) * 16#10000#
+ Character'Pos (Data (Data'First + 3)) * 16#1000000#;
Length : Natural;
begin
Last := Data'First + 3;
if Leading > U32 (System.UTF_Conversions.UCS_4'Last) then
Status := System.UTF_Conversions.Illegal_Sequence;
else
Result := System.UTF_Conversions.UCS_4 (Leading);
System.UTF_Conversions.UTF_32_Sequence (
Wide_Wide_Character'Val (Leading),
Length,
Status); -- checking surrogate pair
end if;
end;
end if;
end From_UTF_32LE;
type To_UTF_Type is access procedure (
Code : System.UTF_Conversions.UCS_4;
Result : out UTF_String;
Last : out Natural;
Status : out System.UTF_Conversions.To_Status_Type);
pragma Favor_Top_Level (To_UTF_Type);
To_UTF : constant array (Encoding_Scheme) of not null To_UTF_Type := (
UTF_8 => To_UTF_8'Access,
UTF_16BE => To_UTF_16BE'Access,
UTF_16LE => To_UTF_16LE'Access,
UTF_32BE => To_UTF_32BE'Access,
UTF_32LE => To_UTF_32LE'Access);
type From_UTF_Type is access procedure (
Data : UTF_String;
Last : out Natural;
Result : out System.UTF_Conversions.UCS_4;
Status : out System.UTF_Conversions.From_Status_Type);
pragma Favor_Top_Level (From_UTF_Type);
From_UTF : constant array (Encoding_Scheme) of not null From_UTF_Type := (
UTF_8 => From_UTF_8'Access,
UTF_16BE => From_UTF_16BE'Access,
UTF_16LE => From_UTF_16LE'Access,
UTF_32BE => From_UTF_32BE'Access,
UTF_32LE => From_UTF_32LE'Access);
-- conversions between various encoding schemes
procedure Do_Convert (
Item : UTF_String;
Input_Scheme : Encoding_Scheme;
Output_Scheme : Encoding_Scheme;
Output_BOM : Boolean := False;
Result : out UTF_String;
Last : out Natural);
procedure Do_Convert (
Item : UTF_String;
Input_Scheme : Encoding_Scheme;
Output_Scheme : Encoding_Scheme;
Output_BOM : Boolean := False;
Result : out UTF_String;
Last : out Natural)
is
In_BOM : constant not null access constant UTF_String :=
BOM_Table (Input_Scheme);
In_BOM_Length : constant Natural := In_BOM'Length;
Out_BOM : constant not null access constant UTF_String :=
BOM_Table (Output_Scheme);
Item_Last : Natural := Item'First - 1;
begin
declare
L : constant Natural := Item_Last + In_BOM_Length;
begin
if L <= Item'Last and then Item (Item_Last + 1 .. L) = In_BOM.all then
Item_Last := L;
end if;
end;
Last := Result'First - 1;
if Output_BOM then
Last := Last + Out_BOM'Length;
Result (Result'First .. Last) := Out_BOM.all;
end if;
while Item_Last < Item'Last loop
declare
Code : System.UTF_Conversions.UCS_4;
From_Status : System.UTF_Conversions.From_Status_Type;
To_Status : System.UTF_Conversions.To_Status_Type;
begin
From_UTF (Input_Scheme) (
Item (Item_Last + 1 .. Item'Last),
Item_Last,
Code,
From_Status);
case From_Status is
when System.UTF_Conversions.Success
| System.UTF_Conversions.Non_Shortest =>
-- AARM A.4.11(54.a/4), CXA4036
null;
when System.UTF_Conversions.Illegal_Sequence
| System.UTF_Conversions.Truncated =>
Raise_Exception (Encoding_Error'Identity);
end case;
To_UTF (Output_Scheme) (
Code,
Result (Last + 1 .. Result'Last),
Last,
To_Status);
if To_Status /= System.UTF_Conversions.Success then
Raise_Exception (Encoding_Error'Identity);
end if;
end;
end loop;
end Do_Convert;
-- implementation
function Convert (
Item : UTF_String;
Input_Scheme : Encoding_Scheme;
Output_Scheme : Encoding_Scheme;
Output_BOM : Boolean := False)
return UTF_String
is
Result : UTF_String (1 .. 4 * Item'Length + 4);
-- from 8 to 8 : Item'Length + 3
-- from 16 to 8 : 3 * Item'Length / 2 + 3 = 3/2 * Item'Length + 3
-- from 32 to 8 : 6 * Item'Length / 4 + 3 = 2 * Item'Length + 3
-- from 8 to 16 : (Item'Length + 1) * 2 = 2 * Item'Length + 2
-- from 16 to 16 : (Item'Length / 2 + 1) * 2 = Item'Length + 2
-- from 32 to 16 : (2 * Item'Length / 4 + 1) * 2 = Item'Length + 2
-- from 8 to 32 : (Item'Length + 1) * 4 = 4 * Item'Length + 4 (max)
-- from 16 to 32 : (Item'Length / 2 + 1) * 4 = 2 * Item'Length + 4
-- from 32 to 32 : (Item'Length / 4 + 1) * 4 = Item'Length + 4
Last : Natural;
begin
Do_Convert (
Item,
Input_Scheme,
Output_Scheme,
Output_BOM,
Result,
Last);
return Result (1 .. Last);
end Convert;
function Convert (
Item : UTF_String;
Input_Scheme : Encoding_Scheme;
Output_BOM : Boolean := False)
return UTF_16_Wide_String
is
-- from 8 to 16 : (Item'Length + 1) * 2 = 2 * Item'Length + 2 (max)
-- from 16 to 16 : (Item'Length / 2 + 1) * 2 = Item'Length + 2
-- from 32 to 16 : (2 * Item'Length / 4 + 1) * 2 = Item'Length + 2
Result : aliased UTF_String (1 .. 2 * Item'Length + 2);
for Result'Alignment use 16 / Standard'Storage_Unit;
Last : Natural;
begin
Do_Convert (
Item,
Input_Scheme,
UTF_16_Wide_String_Scheme,
Output_BOM,
Result,
Last);
return To_UTF_16_Wide_String (Result'Address, Last);
end Convert;
function Convert (
Item : UTF_String;
Input_Scheme : Encoding_Scheme;
Output_BOM : Boolean := False)
return UTF_32_Wide_Wide_String
is
-- from 8 to 32 : (Item'Length + 1) * 4 = 4 * Item'Length + 4 (max)
-- from 16 to 32 : (Item'Length / 2 + 1) * 4 = 2 * Item'Length + 4
-- from 32 to 32 : (Item'Length / 4 + 1) * 4 = Item'Length + 4
Result : aliased UTF_String (1 .. 4 * Item'Length + 4);
for Result'Alignment use 32 / Standard'Storage_Unit;
Last : Natural;
begin
Do_Convert (
Item,
Input_Scheme,
UTF_32_Wide_Wide_String_Scheme,
Output_BOM,
Result,
Last);
return To_UTF_32_Wide_Wide_String (Result'Address, Last);
end Convert;
function Convert (
Item : UTF_8_String;
Output_BOM : Boolean := False)
return UTF_16_Wide_String
is
Result : aliased UTF_String (
1 ..
(Item'Length * System.UTF_Conversions.Expanding_From_8_To_16 + 1)
* 2);
for Result'Alignment use 16 / Standard'Storage_Unit;
Last : Natural;
begin
-- it should be specialized version ?
Do_Convert (
Item,
UTF_8,
UTF_16_Wide_String_Scheme,
Output_BOM,
Result,
Last);
return To_UTF_16_Wide_String (Result'Address, Last);
end Convert;
function Convert (
Item : UTF_8_String;
Output_BOM : Boolean := False)
return UTF_32_Wide_Wide_String
is
Result : aliased UTF_String (
1 ..
(Item'Length * System.UTF_Conversions.Expanding_From_8_To_32 + 1)
* 4);
for Result'Alignment use 32 / Standard'Storage_Unit;
Last : Natural;
begin
-- it should be specialized version ?
Do_Convert (
Item,
UTF_8,
UTF_32_Wide_Wide_String_Scheme,
Output_BOM,
Result,
Last);
return To_UTF_32_Wide_Wide_String (Result'Address, Last);
end Convert;
function Convert (
Item : UTF_16_Wide_String;
Output_Scheme : Encoding_Scheme;
Output_BOM : Boolean := False)
return UTF_String
is
Item_Length : constant Natural := Item'Length;
Item_As_UTF : UTF_String (1 .. Item_Length * 2);
for Item_As_UTF'Address use Item'Address;
-- from 16 to 8 : 3 * Item'Length + 3
-- from 16 to 16 : (Item'Length + 1) * 2 = 2 * Item'Length + 2
-- from 16 to 32 : (Item'Length + 1) * 4 = 4 * Item'Length + 4 (max)
Result : UTF_String (1 .. 4 * Item_Length + 4);
Last : Natural;
begin
Do_Convert (
Item_As_UTF,
UTF_16_Wide_String_Scheme,
Output_Scheme,
Output_BOM,
Result,
Last);
return Result (1 .. Last);
end Convert;
function Convert (
Item : UTF_16_Wide_String;
Output_BOM : Boolean := False)
return UTF_8_String
is
Item_Length : constant Natural := Item'Length;
Item_As_UTF : UTF_String (1 .. Item_Length * 2);
for Item_As_UTF'Address use Item'Address;
Result : UTF_String (
1 ..
Item_Length * System.UTF_Conversions.Expanding_From_16_To_8 + 3);
Last : Natural;
begin
-- it should be specialized version ?
Do_Convert (
Item_As_UTF,
UTF_16_Wide_String_Scheme,
UTF_8,
Output_BOM,
Result,
Last);
return Result (1 .. Last);
end Convert;
function Convert (
Item : UTF_16_Wide_String;
Output_BOM : Boolean := False)
return UTF_32_Wide_Wide_String
is
Item_Length : constant Natural := Item'Length;
Item_As_UTF : UTF_String (1 .. Item_Length * 2);
for Item_As_UTF'Address use Item'Address;
Result : aliased UTF_String (
1 ..
(Item_Length * System.UTF_Conversions.Expanding_From_16_To_32 + 1)
* 4);
for Result'Alignment use 32 / Standard'Storage_Unit;
Last : Natural;
begin
-- it should be specialized version ?
Do_Convert (
Item_As_UTF,
UTF_16_Wide_String_Scheme,
UTF_32_Wide_Wide_String_Scheme,
Output_BOM,
Result,
Last);
return To_UTF_32_Wide_Wide_String (Result'Address, Last);
end Convert;
function Convert (
Item : UTF_32_Wide_Wide_String;
Output_Scheme : Encoding_Scheme;
Output_BOM : Boolean := False)
return UTF_String
is
Item_Length : constant Natural := Item'Length;
Item_As_UTF : UTF_String (1 .. Item_Length * 4);
for Item_As_UTF'Address use Item'Address;
-- from 32 to 8 : 6 * Item'Length + 3 (max rate)
-- from 32 to 16 : (2 * Item'Length + 1) * 2 = 4 * Item'Length + 2
-- from 32 to 32 : (Item'Length + 1) * 4 = 4 * Item'Length + 4 (max BOM)
Result : UTF_String (1 .. 6 * Item_Length + 4);
Last : Natural;
begin
Do_Convert (
Item_As_UTF,
UTF_32_Wide_Wide_String_Scheme,
Output_Scheme,
Output_BOM,
Result,
Last);
return Result (1 .. Last);
end Convert;
function Convert (
Item : UTF_32_Wide_Wide_String;
Output_BOM : Boolean := False)
return UTF_8_String
is
Item_Length : constant Natural := Item'Length;
Item_As_UTF : UTF_String (1 .. Item_Length * 4);
for Item_As_UTF'Address use Item'Address;
Result : UTF_String (
1 ..
Item_Length * System.UTF_Conversions.Expanding_From_32_To_8 + 3);
Last : Natural;
begin
-- it should be specialized version ?
Do_Convert (
Item_As_UTF,
UTF_32_Wide_Wide_String_Scheme,
UTF_8,
Output_BOM,
Result,
Last);
return Result (1 .. Last);
end Convert;
function Convert (
Item : UTF_32_Wide_Wide_String;
Output_BOM : Boolean := False)
return UTF_16_Wide_String
is
Item_Length : constant Natural := Item'Length;
Item_As_UTF : UTF_String (1 .. Item_Length * 4);
for Item_As_UTF'Address use Item'Address;
Result : aliased UTF_String (
1 ..
(Item_Length * System.UTF_Conversions.Expanding_From_32_To_16 + 1)
* 2);
for Result'Alignment use 16 / Standard'Storage_Unit;
Last : Natural;
begin
-- it should be specialized version ?
Do_Convert (
Item_As_UTF,
UTF_32_Wide_Wide_String_Scheme,
UTF_16_Wide_String_Scheme,
Output_BOM,
Result,
Last);
return To_UTF_16_Wide_String (Result'Address, Last);
end Convert;
end Ada.Strings.UTF_Encoding.Conversions;
|
-----------------------------------------------------------------------
-- Gen -- Code Generator
-- Copyright (C) 2009 - 2020 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.IO_Exceptions;
with Ada.Strings.Fixed;
with Ada.Calendar;
with Input_Sources.File;
with DOM.Core;
with DOM.Core.Documents;
with DOM.Readers;
with Sax.Readers;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Components.Root;
with ASF.Components.Base;
with ASF.Servlets.Faces;
with Servlet.Core;
with Util.Beans.Basic;
with Util.Strings.Vectors;
with EL.Functions;
with EL.Utils;
with EL.Contexts.Default;
with Gen.Utils;
with Gen.Configs;
with Gen.Model;
with Gen.Model.Enums;
with Gen.Model.Tables;
with Gen.Model.Mappings;
with Gen.Commands.Templates;
with Util.Strings;
with Util.Files;
with Util.Log.Loggers;
with Util.Beans.Objects.Time;
package body Gen.Generator is
use ASF;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Generator");
RESULT_DIR : constant String := "generator.output.dir";
function To_Ada_Type (Value : in Util.Beans.Objects.Object;
Param : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object;
function Indent (Value : Util.Beans.Objects.Object) return Util.Beans.Objects.Object;
-- EL Function to translate a model type to the key enum value
function To_Key_Enum (Name : Util.Beans.Objects.Object) return Util.Beans.Objects.Object;
-- EL function to create an Ada identifier from a file name
function To_Ada_Ident (Value : Util.Beans.Objects.Object) return Util.Beans.Objects.Object;
-- EL function to format an Ada comment
function Comment (Value : in Util.Beans.Objects.Object;
Prefix : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object;
-- EL function to return a singular form of a name
function To_Singular (Value : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object;
-- Returns a string resulting from replacing in an input string all occurrences of
-- a "Item" string into an "By" substring.
function Replace (Value, Item, By : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object;
-- Concat the arguments converted as a string.
function Concat (Arg1, Arg2, Arg3, Arg4 : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object;
-- EL function to check if a file exists.
function File_Exists (Path : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object;
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
-- ------------------------------
-- EL Function to translate a model type to an Ada implementation type
-- Param values:
-- 0 : Get the type for a record declaration
-- 1 : Get the type for a parameter declaration or a return type
-- 2 : Get the type for the generation of the ADO.Statements.Get procedure name
-- ------------------------------
function To_Ada_Type (Value : in Util.Beans.Objects.Object;
Param : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object is
use Gen.Model.Tables;
use Gen.Model.Mappings;
use Gen.Model;
Column : Column_Definition_Access := null;
Ptr : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Value);
Type_Mapping : Gen.Model.Mappings.Mapping_Definition_Access;
begin
if Ptr /= null and then Ptr.all in Column_Definition'Class then
Column := Column_Definition'Class (Ptr.all)'Unchecked_Access;
else
Column := null;
end if;
if Column /= null then
Type_Mapping := Column.Get_Type_Mapping;
if Type_Mapping /= null then
if Type_Mapping.Kind = T_DATE and Util.Beans.Objects.To_Integer (Param) = 2 then
return Util.Beans.Objects.To_Object (String '("Time"));
elsif Type_Mapping.Kind = T_ENUM then
if Column.Not_Null or Util.Beans.Objects.To_Integer (Param) = 2 then
return Util.Beans.Objects.To_Object (Column.Type_Name);
else
return Util.Beans.Objects.To_Object
(Gen.Model.Enums.Enum_Definition (Type_Mapping.all).Nullable_Type);
end if;
elsif Type_Mapping.Kind /= T_TABLE then
return Util.Beans.Objects.To_Object (Type_Mapping.Target);
elsif Column.Use_Foreign_Key_Type then
return Util.Beans.Objects.To_Object (Type_Mapping.Target);
elsif Util.Beans.Objects.To_Integer (Param) = 1 then
return Util.Beans.Objects.To_Object (Type_Mapping.Target & "_Ref'Class");
else
return Util.Beans.Objects.To_Object (Type_Mapping.Target & "_Ref");
end if;
elsif Column.Is_Basic_Type then
return Util.Beans.Objects.To_Object (Column.Get_Type);
elsif Util.Beans.Objects.To_Integer (Param) = 1 then
return Util.Beans.Objects.To_Object (Column.Get_Type & "_Ref'Class");
else
return Util.Beans.Objects.To_Object (Column.Get_Type & "_Ref");
end if;
else
return Value;
end if;
end To_Ada_Type;
-- ------------------------------
-- Concat the arguments converted as a string.
-- ------------------------------
function Concat (Arg1, Arg2, Arg3, Arg4 : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object is
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
if not Util.Beans.Objects.Is_Null (Arg1) then
Append (Result, Util.Beans.Objects.To_String (Arg1));
end if;
if not Util.Beans.Objects.Is_Null (Arg2) then
Append (Result, Util.Beans.Objects.To_String (Arg2));
end if;
if not Util.Beans.Objects.Is_Null (Arg3) then
Append (Result, Util.Beans.Objects.To_String (Arg3));
end if;
if not Util.Beans.Objects.Is_Null (Arg4) then
Append (Result, Util.Beans.Objects.To_String (Arg4));
end if;
return Util.Beans.Objects.To_Object (Result);
end Concat;
KEY_INTEGER_LABEL : constant String := "KEY_INTEGER";
KEY_STRING_LABEL : constant String := "KEY_STRING";
-- ------------------------------
-- EL Function to translate a model type to the key enum value
-- ------------------------------
function To_Key_Enum (Name : Util.Beans.Objects.Object) return Util.Beans.Objects.Object is
Value : constant String := Util.Beans.Objects.To_String (Name);
begin
if Value = "Integer" or Value = "int" or Value = "Identifier"
or Value = "ADO.Identifier"
then
return Util.Beans.Objects.To_Object (KEY_INTEGER_LABEL);
else
return Util.Beans.Objects.To_Object (KEY_STRING_LABEL);
end if;
end To_Key_Enum;
-- ------------------------------
-- EL function to indent the code
-- ------------------------------
function Indent (Value : Util.Beans.Objects.Object) return Util.Beans.Objects.Object is
S : constant String := Util.Beans.Objects.To_String (Value);
Result : constant String (S'Range) := (others => ' ');
begin
return Util.Beans.Objects.To_Object (Result);
end Indent;
-- ------------------------------
-- EL function to create an Ada identifier from a file name
-- ------------------------------
function To_Ada_Ident (Value : Util.Beans.Objects.Object) return Util.Beans.Objects.Object is
Name : constant String := Util.Beans.Objects.To_String (Value);
Result : Unbounded_String;
C : Character;
begin
for I in Name'Range loop
C := Name (I);
if C = '-' then
Append (Result, '_');
elsif C >= 'a' and C <= 'z' then
Append (Result, C);
elsif C >= 'A' and C <= 'Z' then
Append (Result, C);
elsif C >= '0' and C <= '9' then
Append (Result, C);
end if;
end loop;
return Util.Beans.Objects.To_Object (Result);
end To_Ada_Ident;
-- ------------------------------
-- EL function to return a singular form of a name
-- ------------------------------
function To_Singular (Value : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object is
Name : constant String := Util.Beans.Objects.To_String (Value);
begin
if Name'Length > 1 and then Name (Name'Last) = 's' then
return Util.Beans.Objects.To_Object (Name (Name'First .. Name'Last - 1));
else
return Value;
end if;
end To_Singular;
-- ------------------------------
-- Returns a string resulting from replacing in an input string all occurrences of
-- a "Item" string into an "By" substring.
-- ------------------------------
function Replace (Value, Item, By : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object is
Content : constant String := Util.Beans.Objects.To_String (Value);
Pattern : constant String := Util.Beans.Objects.To_String (Item);
Token : constant String := Util.Beans.Objects.To_String (By);
Last : Natural := Content'First;
Result : Ada.Strings.Unbounded.Unbounded_String;
Pos : Natural;
begin
if Pattern'Length = 0 then
return Value;
end if;
while Last <= Content'Last loop
Pos := Ada.Strings.Fixed.Index (Content, Pattern, Last);
if Pos = 0 then
Append (Result, Content (Last .. Content'Last));
exit;
else
if Last < Pos then
Append (Result, Content (Last .. Pos - 1));
end if;
Append (Result, Token);
end if;
Last := Pos + Pattern'Length;
end loop;
return Util.Beans.Objects.To_Object (Result);
end Replace;
-- ------------------------------
-- EL function to format an Ada comment
-- ------------------------------
function Comment (Value : in Util.Beans.Objects.Object;
Prefix : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object is
START_POS : constant Natural := 8;
Comment : constant String := Ada.Strings.Fixed.Trim (Util.Beans.Objects.To_String (Value),
Ada.Strings.Both);
Result : Unbounded_String;
C : Character;
Pos : Natural := START_POS;
begin
for I in Comment'Range loop
C := Comment (I);
if Pos > START_POS then
if C = ASCII.LF then
Pos := START_POS;
else
Append (Result, C);
Pos := Pos + 1;
end if;
elsif C /= ' ' and C /= ASCII.LF then
if Length (Result) > 0 then
Append (Result, ASCII.LF);
Append (Result, " -- ");
else
Append (Result, " ");
if not Util.Beans.Objects.Is_Null (Prefix)
and not Util.Beans.Objects.Is_Empty (Prefix)
then
Append (Result, Util.Beans.Objects.To_String (Prefix));
end if;
end if;
Append (Result, C);
Pos := Pos + 1;
end if;
end loop;
Append (Result, ASCII.LF);
return Util.Beans.Objects.To_Object (Result);
end Comment;
-- ------------------------------
-- EL function to check if a file exists.
-- ------------------------------
function File_Exists (Path : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object is
P : constant String := Util.Beans.Objects.To_String (Path);
begin
return Util.Beans.Objects.To_Object (Ada.Directories.Exists (P));
end File_Exists;
-- ------------------------------
-- Register the generator EL functions
-- ------------------------------
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is
begin
Mapper.Set_Function (Name => "adaIdent",
Namespace => G_URI,
Func => To_Ada_Ident'Access);
Mapper.Set_Function (Name => "adaType",
Namespace => G_URI,
Func => To_Ada_Type'Access);
Mapper.Set_Function (Name => "indent",
Namespace => G_URI,
Func => Indent'Access);
Mapper.Set_Function (Name => "keyEnum",
Namespace => G_URI,
Func => To_Key_Enum'Access);
Mapper.Set_Function (Name => "comment",
Namespace => G_URI,
Func => Comment'Access);
Mapper.Set_Function (Name => "singular",
Namespace => G_URI,
Func => To_Singular'Access);
Mapper.Set_Function (Name => "replace",
Namespace => G_URI,
Func => Replace'Access);
Mapper.Set_Function (Name => "exists",
Namespace => G_URI,
Func => File_Exists'Access);
Mapper.Set_Function (Name => "concat",
Namespace => G_URI,
Func => Concat'Access);
end Set_Functions;
-- ------------------------------
-- Initialize the generator
-- ------------------------------
procedure Initialize (H : in out Handler;
Config_Dir : in Ada.Strings.Unbounded.Unbounded_String;
Debug : in Boolean) is
use Ada.Directories;
procedure Register_Funcs is
new ASF.Applications.Main.Register_Functions (Set_Functions);
Dir : constant String := Ada.Strings.Unbounded.To_String (Config_Dir);
Factory : ASF.Applications.Main.Application_Factory;
Path : constant String := Compose (Dir, "generator.properties");
Context : EL.Contexts.Default.Default_Context;
Props : Util.Properties.Manager;
begin
Log.Debug ("Initialize dynamo with {0}", Path);
begin
Props.Load_Properties (Path => Path);
exception
when Ada.IO_Exceptions.Name_Error =>
H.Error ("Cannot load configuration file {0}", Path);
end;
H.Conf.Set (ASF.Applications.VIEW_DIR, Compose (Dir, "templates"));
H.Conf.Set (ASF.Applications.VIEW_IGNORE_WHITE_SPACES, "false");
H.Conf.Set (ASF.Applications.VIEW_ESCAPE_UNKNOWN_TAGS, "false");
H.Conf.Set (ASF.Applications.VIEW_IGNORE_EMPTY_LINES, "true");
H.Conf.Set (ASF.Applications.VIEW_FILE_EXT, "");
H.Conf.Set ("ado.queries.paths", Compose (Dir, "db"));
if Debug then
Log.Info ("Setting debug mode");
H.Conf.Set (Gen.Configs.GEN_DEBUG_ENABLE, "1");
end if;
Props.Set ("generator_config_dir", Dir);
EL.Utils.Expand (Source => Props, Into => H.Conf, Context => Context);
H.Initialize (H.Conf, Factory);
H.Config_Dir := To_Unbounded_String (Dir);
H.Output_Dir := To_Unbounded_String (H.Conf.Get (RESULT_DIR, "./"));
Register_Funcs (H);
H.File := new Util.Beans.Objects.Object;
H.Mode := new Util.Beans.Objects.Object;
H.Ignore := new Util.Beans.Objects.Object;
H.Servlet := new ASF.Servlets.Faces.Faces_Servlet;
H.Add_Servlet (Name => "file", Server => H.Servlet);
H.Add_Mapping ("*.xhtml", "file");
H.Start;
begin
Gen.Commands.Templates.Read_Commands (H);
exception
when Ada.IO_Exceptions.Name_Error =>
H.Error ("Cannot read external commands");
end;
end Initialize;
-- ------------------------------
-- Get the configuration properties.
-- ------------------------------
function Get_Properties (H : in Handler) return Util.Properties.Manager is
begin
return Util.Properties.Manager (H.Conf);
end Get_Properties;
-- ------------------------------
-- Set the directory where template files are stored.
-- ------------------------------
procedure Set_Template_Directory (H : in out Handler;
Path : in Ada.Strings.Unbounded.Unbounded_String) is
begin
H.Conf.Set (ASF.Applications.VIEW_DIR, Path);
end Set_Template_Directory;
-- ------------------------------
-- Set the directory where results files are generated.
-- ------------------------------
procedure Set_Result_Directory (H : in out Handler;
Path : in String) is
begin
H.Conf.Set (RESULT_DIR, Path);
H.Output_Dir := To_Unbounded_String (Path);
end Set_Result_Directory;
-- ------------------------------
-- Get the result directory path.
-- ------------------------------
function Get_Result_Directory (H : in Handler) return String is
begin
return To_String (H.Output_Dir);
end Get_Result_Directory;
-- ------------------------------
-- Get the project plugin directory path.
-- ------------------------------
function Get_Plugin_Directory (H : in Handler) return String is
begin
return Util.Files.Compose (H.Get_Result_Directory, H.Project.Get_Module_Dir);
end Get_Plugin_Directory;
-- ------------------------------
-- Get the config directory path.
-- ------------------------------
function Get_Config_Directory (H : in Handler) return String is
begin
return To_String (H.Config_Dir);
end Get_Config_Directory;
-- ------------------------------
-- Get the dynamo installation directory path.
-- ------------------------------
function Get_Install_Directory (H : in Handler) return String is
begin
return Ada.Directories.Containing_Directory (To_String (H.Config_Dir));
end Get_Install_Directory;
-- ------------------------------
-- Get the exit status
-- Returns 0 if the generation was successful
-- Returns 1 if there was a generation error
-- ------------------------------
function Get_Status (H : in Handler) return Ada.Command_Line.Exit_Status is
begin
return H.Status;
end Get_Status;
-- ------------------------------
-- Get the configuration parameter.
-- ------------------------------
function Get_Parameter (H : in Handler;
Name : in String;
Default : in String := "") return String is
begin
if Util.Strings.Starts_With (Name, "dynamo.") then
return H.Get_Project_Property (Name (Name'First + 7 .. Name'Last), Default);
end if;
return H.Conf.Get (Name, Default);
end Get_Parameter;
-- ------------------------------
-- Get the configuration parameter.
-- ------------------------------
function Get_Parameter (H : in Handler;
Name : in String;
Default : in Boolean := False) return Boolean is
begin
if not H.Conf.Exists (Name) then
return Default;
else
declare
V : constant String := H.Conf.Get (Name);
begin
return V = "1" or V = "true" or V = "yes";
end;
end if;
end Get_Parameter;
-- ------------------------------
-- Set the force-save file mode. When False, if the generated file exists already,
-- an error message is reported.
-- ------------------------------
procedure Set_Force_Save (H : in out Handler;
To : in Boolean) is
begin
H.Force_Save := To;
end Set_Force_Save;
-- ------------------------------
-- Set the project name.
-- ------------------------------
procedure Set_Project_Name (H : in out Handler;
Name : in String) is
Pos : constant Natural := Util.Strings.Index (Name, '-');
begin
if not Gen.Utils.Is_Valid_Name (Name)
and then (Pos <= Name'First
or else not Gen.Utils.Is_Valid_Name (Name (Name'First .. Pos - 1)))
then
H.Error ("The project name should be a valid Ada identifier ([A-Za-z][A-Za-z0-9_]*).");
raise Fatal_Error with "Invalid project name: " & Name;
end if;
H.Project.Set_Name (Name);
H.Set_Global ("projectName", Name);
if Pos > Name'First then
H.Set_Global ("projectAdaName", Name (Name'First .. Pos - 1));
else
H.Set_Global ("projectAdaName", Name);
end if;
end Set_Project_Name;
-- ------------------------------
-- Get the project name.
-- ------------------------------
function Get_Project_Name (H : in Handler) return String is
begin
return H.Project.Get_Project_Name;
end Get_Project_Name;
-- ------------------------------
-- Set the project property.
-- ------------------------------
procedure Set_Project_Property (H : in out Handler;
Name : in String;
Value : in String) is
begin
Log.Debug ("Set property {0} to {1}", Name, Value);
H.Project.Props.Set (Name, Value);
H.Project.Update_From_Properties;
end Set_Project_Property;
-- ------------------------------
-- Get the project property identified by the given name. If the project property
-- does not exist, returns the default value. Project properties are loaded
-- by <b>Read_Project</b>.
-- ------------------------------
function Get_Project_Property (H : in Handler;
Name : in String;
Default : in String := "") return String is
begin
return H.Project.Props.Get (Name, Default);
end Get_Project_Property;
-- ------------------------------
-- Save the project description and parameters.
-- ------------------------------
procedure Save_Project (H : in out Handler) is
Path : constant String := Ada.Directories.Compose (H.Get_Result_Directory, "dynamo.xml");
begin
-- Set the 'search_dirs' property only if we did a recursive scan of GNAT project files.
-- Otherwise we don't know which Dynamo module or library is used.
if H.Project.Recursive_Scan then
-- if H.Get_Project_Property ("search_dirs", ".") = "." then
-- H.Read_Project ("dynamo.xml", True);
-- end if;
-- Do not update the search_dirs if the project is a plugin.
-- This is only meaningful in the final project.
if not H.Project.Is_Plugin then
H.Set_Project_Property ("search_dirs", H.Get_Search_Directories);
end if;
end if;
H.Project.Save (Path);
end Save_Project;
-- ------------------------------
-- Get the path of the last generated file.
-- ------------------------------
function Get_Generated_File (H : in Handler) return String is
begin
return Util.Beans.Objects.To_String (H.File.all);
end Get_Generated_File;
-- ------------------------------
-- Report an error and set the exit status accordingly
-- ------------------------------
procedure Error (H : in out Handler;
Message : in String;
Arg1 : in String;
Arg2 : in String := "") is
begin
Log.Error ("error: " & Message, Arg1, Arg2);
H.Status := 1;
end Error;
overriding
procedure Error (H : in out Handler;
Message : in String) is
begin
Log.Error ("error: " & Message);
H.Status := 1;
end Error;
-- ------------------------------
-- Report an info message.
-- ------------------------------
procedure Info (H : in out Handler;
Message : in String;
Arg1 : in String := "";
Arg2 : in String := "";
Arg3 : in String := "") is
pragma Unreferenced (H);
begin
Log.Info (Message, Arg1, Arg2, Arg3);
end Info;
-- ------------------------------
-- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project
-- files used by the main project and load all the <b>dynamo.xml</b> files defined
-- by these project.
-- ------------------------------
procedure Read_Project (H : in out Handler;
File : in String;
Recursive : in Boolean := False) is
Dir : constant String := Ada.Directories.Containing_Directory (To_String (H.Config_Dir));
begin
H.Project.Install_Dir := To_Unbounded_String (Dir);
H.Project.Read_Project (File => File,
Config => H.Conf,
Recursive => Recursive);
H.Set_Project_Name (H.Get_Project_Name);
end Read_Project;
-- ------------------------------
-- Read the XML package file
-- ------------------------------
procedure Read_Package (H : in out Handler;
File : in String) is
Read : Input_Sources.File.File_Input;
My_Tree_Reader : DOM.Readers.Tree_Reader;
Name_Start : Natural;
begin
Log.Info ("Reading package file '{0}'", File);
-- Base file name should be used as the public Id
Name_Start := File'Last;
while Name_Start >= File'First and then File (Name_Start) /= '/' loop
Name_Start := Name_Start - 1;
end loop;
Input_Sources.File.Open (File, Read);
-- Full name is used as the system id
Input_Sources.File.Set_System_Id (Read, File);
Input_Sources.File.Set_Public_Id (Read, File (Name_Start + 1 .. File'Last));
DOM.Readers.Set_Feature (My_Tree_Reader, Sax.Readers.Validation_Feature, False);
DOM.Readers.Parse (My_Tree_Reader, Read);
Input_Sources.File.Close (Read);
declare
Doc : constant DOM.Core.Document := DOM.Readers.Get_Tree (My_Tree_Reader);
Root : constant DOM.Core.Element := DOM.Core.Documents.Get_Element (Doc);
begin
H.Distrib.Initialize (Path => File, Model => H.Model, Node => Root, Context => H);
end;
exception
when Ada.IO_Exceptions.Name_Error =>
H.Error ("Package file {0} does not exist", File);
end Read_Package;
-- ------------------------------
-- Read the model mapping types and initialize the hibernate artifact.
-- ------------------------------
procedure Read_Mappings (H : in out Handler) is
procedure Read_Mapping (Name : in String;
Default : in String);
Dir : constant String := H.Get_Config_Directory;
procedure Read_Mapping (Name : in String;
Default : in String) is
Mapping : constant String := H.Get_Parameter (Name, Default);
begin
H.Read_Model (File => Util.Files.Compose (Dir, Mapping), Silent => True);
end Read_Mapping;
begin
-- Read the type mappings for Ada, MySQL, Postgresql and SQLite.
H.Type_Mapping_Loaded := True;
Read_Mapping ("generator.mapping.ada", "AdaMappings.xml");
Read_Mapping ("generator.mapping.mysql", "MySQLMappings.xml");
Read_Mapping ("generator.mapping.postgresql", "PostgresqlMappings.xml");
Read_Mapping ("generator.mapping.sqlite", "SQLiteMappings.xml");
end Read_Mappings;
-- ------------------------------
-- Read the XML model file
-- ------------------------------
procedure Read_Model (H : in out Handler;
File : in String;
Silent : in Boolean) is
Read : Input_Sources.File.File_Input;
My_Tree_Reader : DOM.Readers.Tree_Reader;
Name_Start : Natural;
Ext : constant String := Ada.Directories.Extension (File);
begin
-- Before loading a model file, we should know the type mappings.
-- Load them first if needed.
if not H.Type_Mapping_Loaded then
H.Read_Mappings;
end if;
Gen.Model.Mappings.Set_Mapping_Name (Gen.Model.Mappings.ADA_MAPPING);
if Silent then
Log.Debug ("Reading model file '{0}'", File);
else
Log.Info ("Reading model file '{0}'", File);
end if;
if Ext = "xmi" or Ext = "XMI" or Ext = "zargo" then
H.XMI.Read_Model (File, H);
return;
elsif Ext = "yaml" or Ext = "YAML" then
H.Yaml.Read_Model (File, H.Model, H);
return;
end if;
-- Base file name should be used as the public Id
Name_Start := File'Last;
while Name_Start >= File'First and then File (Name_Start) /= '/' loop
Name_Start := Name_Start - 1;
end loop;
Input_Sources.File.Open (File, Read);
-- Full name is used as the system id
Input_Sources.File.Set_System_Id (Read, File);
Input_Sources.File.Set_Public_Id (Read, File (Name_Start + 1 .. File'Last));
DOM.Readers.Set_Feature (My_Tree_Reader, Sax.Readers.Validation_Feature, False);
DOM.Readers.Parse (My_Tree_Reader, Read);
Input_Sources.File.Close (Read);
declare
Doc : constant DOM.Core.Document := DOM.Readers.Get_Tree (My_Tree_Reader);
Root : constant DOM.Core.Element := DOM.Core.Documents.Get_Element (Doc);
begin
H.Mappings.Initialize (Path => File, Model => H.Model, Node => Root, Context => H);
H.Hibernate.Initialize (Path => File, Model => H.Model, Node => Root, Context => H);
H.Query.Initialize (Path => File, Model => H.Model, Node => Root, Context => H);
H.Yaml.Initialize (Path => File, Model => H.Model, Node => Root, Context => H);
end;
-- DOM.Readers.Free (My_Tree_Reader);
exception
when Ada.IO_Exceptions.Name_Error =>
H.Error ("Model file {0} does not exist", File);
end Read_Model;
-- ------------------------------
-- Read the model and query files stored in the application directory <b>db</b>.
-- ------------------------------
procedure Read_Models (H : in out Handler;
Dirname : in String) is
use Ada.Directories;
Path : constant String := Dirname;
Name : constant String := Ada.Directories.Base_Name (Path);
Filter : constant Filter_Type := (Ordinary_File => True, others => False);
Search : Search_Type;
Ent : Directory_Entry_Type;
Files : Util.Strings.Vectors.Vector;
package Sort_Names is
new Util.Strings.Vectors.Generic_Sorting;
begin
Log.Info ("Reading model file stored in '{0}'", Path);
-- No argument specified, look at the model files in the db directory.
if Exists (Path) then
if Name = "regtests" then
H.Model.Set_Dirname ("regtests", Path);
elsif Name = "samples" then
H.Model.Set_Dirname ("samples", Path);
else
H.Model.Set_Dirname ("src", Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.xm[il]", Filter => Filter);
-- Collect the files in the vector array.
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
Files.Append (Full_Name (Ent));
end loop;
Start_Search (Search, Directory => Path, Pattern => "*.yaml", Filter => Filter);
-- Collect the files in the vector array.
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
Files.Append (Full_Name (Ent));
end loop;
Start_Search (Search, Directory => Path, Pattern => "*.zargo", Filter => Filter);
-- Collect the files in the vector array.
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
Files.Append (Full_Name (Ent));
end loop;
-- Sort the files on their name to get a reproducible generation of some database
-- models.
Sort_Names.Sort (Files);
-- Read the model files
declare
Iter : Util.Strings.Vectors.Cursor := Files.First;
begin
while Util.Strings.Vectors.Has_Element (Iter) loop
H.Read_Model (File => Util.Strings.Vectors.Element (Iter),
Silent => False);
Util.Strings.Vectors.Next (Iter);
end loop;
end;
end if;
end Read_Models;
-- ------------------------------
-- Execute the lifecycle phases on the faces context.
-- ------------------------------
overriding
procedure Execute_Lifecycle (App : in Handler;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
begin
ASF.Applications.Main.Application (App).Execute_Lifecycle (Context);
declare
View : constant Components.Root.UIViewRoot := Context.Get_View_Root;
Root : constant access Components.Base.UIComponent'Class
:= Components.Root.Get_Root (View);
begin
if Root /= null then
App.File.all := Root.Get_Attribute (Context, "file");
App.Mode.all := Root.Get_Attribute (Context, "mode");
App.Ignore.all := Root.Get_Attribute (Context, "ignore");
end if;
end;
end Execute_Lifecycle;
-- ------------------------------
-- Prepare the model by checking, verifying and initializing it after it is completely known.
-- ------------------------------
procedure Prepare (H : in out Handler) is
begin
if H.XMI.Is_Initialized then
H.XMI.Prepare (Model => H.Model, Context => H);
end if;
if H.Yaml.Is_Initialized then
H.Yaml.Prepare (Model => H.Model, Context => H);
end if;
H.Model.Prepare;
if H.Hibernate.Is_Initialized then
H.Hibernate.Prepare (Model => H.Model, Context => H);
end if;
if H.Query.Is_Initialized then
H.Query.Prepare (Model => H.Model, Context => H);
end if;
if H.Distrib.Is_Initialized then
H.Distrib.Prepare (Model => H.Model, Context => H);
end if;
H.Model.Validate (H);
end Prepare;
-- ------------------------------
-- Finish the generation. Some artifacts could generate other files that take into
-- account files generated previously.
-- ------------------------------
procedure Finish (H : in out Handler) is
begin
if H.Hibernate.Is_Initialized then
H.Hibernate.Finish (Model => H.Model, Project => H.Project, Context => H);
end if;
if H.Query.Is_Initialized then
H.Query.Finish (Model => H.Model, Project => H.Project, Context => H);
end if;
if H.Distrib.Is_Initialized then
H.Distrib.Finish (Model => H.Model, Project => H.Project, Context => H);
end if;
if H.XMI.Is_Initialized then
H.XMI.Finish (Model => H.Model, Project => H.Project, Context => H);
end if;
end Finish;
-- ------------------------------
-- Tell the generator to activate the generation of the given template name.
-- The name is a property name that must be defined in generator.properties to
-- indicate the template file. Several artifacts can trigger the generation
-- of a given template. The template is generated only once.
-- ------------------------------
procedure Add_Generation (H : in out Handler;
Name : in String;
Mode : in Gen.Artifacts.Iteration_Mode;
Mapping : in String) is
Value : constant String := H.Conf.Get (Name, "");
begin
Log.Debug ("Adding template {0} to the generation", Name);
if Value'Length = 0 then
H.Error ("Template '{0}' is not defined.", Name);
else
H.Templates.Include (To_Unbounded_String (Value),
Template_Context '(Mode, To_Unbounded_String (Mapping)));
end if;
end Add_Generation;
-- ------------------------------
-- Enable the generation of the Ada package given by the name. By default all the Ada
-- packages found in the model are generated. When called, this enables the generation
-- only for the Ada packages registered here.
-- ------------------------------
procedure Enable_Package_Generation (H : in out Handler;
Name : in String) is
begin
H.Model.Enable_Package_Generation (Name);
end Enable_Package_Generation;
-- ------------------------------
-- Save the content generated by the template generator.
-- ------------------------------
procedure Save_Content (H : in out Handler;
File : in String;
Content : in Unbounded_String) is
Dir : constant String := To_String (H.Output_Dir);
Mode : constant String := Util.Beans.Objects.To_String (H.Mode.all);
Path : constant String := Util.Files.Compose (Dir, File);
Exists : constant Boolean := Ada.Directories.Exists (Path);
Old_Content : Unbounded_String;
begin
if Exists and Mode = "once" then
Log.Info ("File {0} exists, generation skipped.", Path);
elsif Exists and not (H.Force_Save or Mode = "force") then
H.Error ("Cannot generate file: '{0}' exists already.", Path);
elsif not Util.Beans.Objects.Is_Null (H.File.all) and
then not Util.Beans.Objects.To_Boolean (H.Ignore.all)
then
if Length (Content) = 0 and Mode = "remove-empty" then
Log.Debug ("File {0} skipped because it is empty", Path);
else
Log.Info ("Generating file '{0}'", Path);
if Exists then
Util.Files.Read_File (Path => Path,
Into => Old_Content,
Max_Size => Natural'Last);
end if;
if not Exists or else Content /= Old_Content then
Util.Files.Write_File (Path => Path, Content => Content);
end if;
end if;
end if;
end Save_Content;
-- ------------------------------
-- Generate the code using the template file
-- ------------------------------
procedure Generate (H : in out Handler;
File : in String;
Model : in Gen.Model.Definition_Access;
Save : not null access procedure (H : in out Handler;
File : in String;
Content : in Unbounded_String)) is
use Util.Beans.Objects;
Req : ASF.Requests.Mockup.Request;
Reply : aliased ASF.Responses.Mockup.Response;
Ptr : constant Util.Beans.Basic.Readonly_Bean_Access := Model.all'Unchecked_Access;
Bean : constant Object := Util.Beans.Objects.To_Object (Ptr, Util.Beans.Objects.STATIC);
Model_Ptr : constant Util.Beans.Basic.Readonly_Bean_Access := H.Model'Unchecked_Access;
Model_Bean : constant Object := To_Object (Model_Ptr, Util.Beans.Objects.STATIC);
Prj_Ptr : constant Util.Beans.Basic.Readonly_Bean_Access := H.Project'Unchecked_Access;
Prj_Bean : constant Object := To_Object (Prj_Ptr, Util.Beans.Objects.STATIC);
Dispatcher : constant ASF.Servlets.Request_Dispatcher := H.Get_Request_Dispatcher (File);
begin
Log.Debug ("With template '{0}'", File);
Req.Set_Method ("GET");
Req.Set_Attribute (Name => "project", Value => Prj_Bean);
Req.Set_Attribute (Name => "package", Value => Bean);
Req.Set_Attribute (Name => "model", Value => Model_Bean);
Req.Set_Attribute (Name => "genRevision", Value => Util.Beans.Objects.To_Object (SVN_REV));
Req.Set_Attribute (Name => "genURL", Value => Util.Beans.Objects.To_Object (SVN_URL));
Req.Set_Attribute (Name => "date",
Value => Util.Beans.Objects.Time.To_Object (Ada.Calendar.Clock));
Servlet.Core.Forward (Dispatcher, Req, Reply);
declare
Content : Unbounded_String;
File : constant String := Util.Beans.Objects.To_String (H.File.all);
begin
Reply.Read_Content (Content);
Save (H, File, Content);
end;
end Generate;
-- ------------------------------
-- Generate the code using the template file
-- ------------------------------
procedure Generate (H : in out Handler;
Mode : in Iteration_Mode;
File : in String;
Save : not null access
procedure (H : in out Handler;
File : in String;
Content : in Ada.Strings.Unbounded.Unbounded_String)) is
begin
Log.Debug ("Generating with template {0} in mode {1}",
File, Iteration_Mode'Image (Mode));
case Mode is
when ITERATION_PACKAGE =>
declare
Pos : Gen.Model.Packages.Package_Cursor := H.Model.First;
begin
while Gen.Model.Packages.Has_Element (Pos) loop
declare
P : constant Gen.Model.Packages.Package_Definition_Access
:= Gen.Model.Packages.Element (Pos);
Name : constant String := P.Get_Name;
begin
if H.Model.Is_Generation_Enabled (Name) then
Log.Debug (" Generate for package {0}", Name);
H.Generate (File, Gen.Model.Definition_Access (P), Save);
else
Log.Debug ("Package {0} not generated", Name);
end if;
end;
Gen.Model.Packages.Next (Pos);
end loop;
end;
when ITERATION_TABLE =>
H.Generate (File, H.Model'Unchecked_Access, Save);
end case;
end Generate;
-- ------------------------------
-- Generate all the code for the templates activated through <b>Add_Generation</b>.
-- ------------------------------
procedure Generate_All (H : in out Handler) is
Iter : Template_Map.Cursor := H.Templates.First;
begin
Log.Debug ("Generating the files {0}",
Ada.Containers.Count_Type'Image (H.Templates.Length));
while Template_Map.Has_Element (Iter) loop
declare
T : constant Template_Context := Template_Map.Element (Iter);
begin
Gen.Model.Mappings.Set_Mapping_Name (To_String (T.Mapping));
H.Generate (File => To_String (Template_Map.Key (Iter)),
Mode => T.Mode,
Save => Save_Content'Access);
end;
Template_Map.Next (Iter);
end loop;
end Generate_All;
-- ------------------------------
-- Generate all the code generation files stored in the directory
-- ------------------------------
procedure Generate_All (H : in out Handler;
Mode : in Iteration_Mode;
Name : in String) is
use Ada.Directories;
Search : Search_Type;
Filter : constant Filter_Type := (Ordinary_File => True, others => False);
Dir_Filter : constant Filter_Type := (Directory => True, others => False);
Ent : Directory_Entry_Type;
Dir : constant String := H.Conf.Get (ASF.Applications.VIEW_DIR);
Path : constant String := Util.Files.Compose (Dir, Name);
Base_Dir : constant Unbounded_String := H.Output_Dir;
begin
if Kind (Path) /= Directory then
Ada.Text_IO.Put_Line ("Cannot read model directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Base_Name : constant String := Simple_Name (Ent);
File_Path : constant String := Full_Name (Ent);
Ext : constant String := Extension (Base_Name);
Target : constant String := Compose (To_String (Base_Dir), Base_Name);
Content : Unbounded_String;
begin
if Ext = "xhtml" then
H.Generate (Mode, File_Path, Save_Content'Access);
elsif Util.Strings.Index (Base_Name, '~') = 0 then
if Ada.Directories.Exists (Target) and not H.Force_Save then
H.Error ("Cannot copy file: '{0}' exists already.", Target);
else
Util.Files.Read_File (Path => File_Path, Into => Content);
Util.Files.Write_File (Path => Target,
Content => Content);
end if;
end if;
end;
end loop;
Start_Search (Search, Directory => Path, Pattern => "*", Filter => Dir_Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Dir_Name : constant String := Simple_Name (Ent);
Dir : constant String := Compose (To_String (Base_Dir), Dir_Name);
begin
if Dir_Name /= "." and Dir_Name /= ".." and Dir_Name /= ".svn" then
H.Output_Dir := To_Unbounded_String (Dir);
if not Ada.Directories.Exists (Dir) then
Ada.Directories.Create_Directory (Dir);
end if;
H.Generate_All (Mode, Compose (Name, Dir_Name));
end if;
end;
end loop;
H.Output_Dir := Base_Dir;
exception
when E : Ada.IO_Exceptions.Name_Error =>
H.Error ("Template directory {0} does not exist", Path);
Log.Info ("Exception: {0}", Util.Log.Loggers.Traceback (E));
end Generate_All;
-- ------------------------------
-- Update the project model through the <b>Process</b> procedure.
-- ------------------------------
procedure Update_Project (H : in out Handler;
Process : not null access
procedure (P : in out Model.Projects.Root_Project_Definition)) is
begin
Process (H.Project);
end Update_Project;
-- ------------------------------
-- Scan the dynamo directories and execute the <b>Process</b> procedure with the
-- directory path.
-- ------------------------------
procedure Scan_Directories (H : in Handler;
Process : not null access
procedure (Dir : in String)) is
Iter : Gen.Utils.String_List.Cursor := H.Project.Dynamo_Files.First;
begin
while Gen.Utils.String_List.Has_Element (Iter) loop
declare
Path : constant String := Gen.Utils.String_List.Element (Iter);
begin
Process (Ada.Directories.Containing_Directory (Path));
end;
Gen.Utils.String_List.Next (Iter);
end loop;
end Scan_Directories;
-- ------------------------------
-- Return the search directories that the AWA application can use to find files.
-- The search directories is built by using the project dependencies.
-- ------------------------------
function Get_Search_Directories (H : in Handler) return String is
Current_Dir : constant String := Ada.Directories.Current_Directory;
Iter : Gen.Utils.String_List.Cursor := H.Project.Dynamo_Files.Last;
Dirs : Ada.Strings.Unbounded.Unbounded_String;
begin
while Gen.Utils.String_List.Has_Element (Iter) loop
declare
Path : constant String := Gen.Utils.String_List.Element (Iter);
Dir : constant String := Ada.Directories.Containing_Directory (Path);
begin
if Length (Dirs) > 0 then
Append (Dirs, ";");
end if;
Append (Dirs, Util.Files.Get_Relative_Path (Current_Dir, Dir));
end;
Gen.Utils.String_List.Previous (Iter);
end loop;
return To_String (Dirs);
end Get_Search_Directories;
end Gen.Generator;
|
with Ada.Text_IO;
with Ada.Integer_Text_IO;
with Ada.Containers.Vectors;
use Ada.Text_IO;
use Ada.Integer_Text_IO;
use Ada.Containers;
procedure Euler is
package Long_Integer_Vectors is new Vectors(Natural, Long_Integer);
package Long_IO is new Ada.Text_IO.Integer_IO(Long_Integer);
use Long_IO;
function Reverse_Number(X : in Long_Integer) return Long_Integer is
N : Long_Integer := X;
R : Long_Integer := 0;
begin
while N /= 0 loop
R := R * 10 + (N mod 10);
N := N / 10;
end loop;
return R;
end Reverse_Number;
begin
declare
X : Long_Integer;
Y : Long_Integer;
Product : Long_Integer;
Palindromes : Long_Integer_Vectors.Vector;
Cursor : Long_Integer_Vectors.Cursor;
Max : Long_Integer;
begin
X := 100;
while X <= 999 loop
Y := 100;
while Y <= 999 loop
Product := X * Y;
if Product = Reverse_Number(Product) then
Long_Integer_Vectors.Append(Palindromes, Product);
end if;
Y := Y + 1;
end loop;
X := X + 1;
end loop;
Cursor := Long_Integer_Vectors.First(Palindromes);
Max := Long_Integer_Vectors.Element(Cursor);
Cursor := Long_Integer_Vectors.Next(Cursor);
while Long_Integer_Vectors.Has_Element(Cursor) loop
if Long_Integer_Vectors.Element(Cursor) > Max then
Max := Long_Integer_Vectors.Element(Cursor);
end if;
Cursor := Long_Integer_Vectors.Next(Cursor);
end loop;
Put(Item => (Max), Width => 1);
New_Line;
end;
end Euler;
|
with Ada.Unchecked_Deallocation;
with PB_Support.IO;
with PB_Support.Internal;
package body Google.Protobuf.Any is
function Length (Self : Any_Vector) return Natural is
begin
return Self.Length;
end Length;
procedure Clear (Self : in out Any_Vector) is
begin
Self.Length := 0;
end Clear;
procedure Free is new Ada.Unchecked_Deallocation
(Any_Array, Any_Array_Access);
procedure Append (Self : in out Any_Vector; V : Any) is
Init_Length : constant Positive := Positive'Max (1, 256 / Any'Size);
begin
if Self.Length = 0 then
Self.Data := new Any_Array (1 .. Init_Length);
elsif Self.Length = Self.Data'Last then
Self.Data :=
new Any_Array'(Self.Data.all & Any_Array'(1 .. Self.Length => <>));
end if;
Self.Length := Self.Length + 1;
Self.Data (Self.Length) := V;
end Append;
overriding procedure Adjust (Self : in out Any_Vector) is
begin
if Self.Length > 0 then
Self.Data := new Any_Array'(Self.Data (1 .. Self.Length));
end if;
end Adjust;
overriding procedure Finalize (Self : in out Any_Vector) is
begin
if Self.Data /= null then
Free (Self.Data);
end if;
end Finalize;
not overriding function Get_Any_Variable_Reference
(Self : aliased in out Any_Vector;
Index : Positive)
return Any_Variable_Reference is
begin
return (Element => Self.Data (Index)'Access);
end Get_Any_Variable_Reference;
not overriding function Get_Any_Constant_Reference
(Self : aliased Any_Vector;
Index : Positive)
return Any_Constant_Reference is
begin
return (Element => Self.Data (Index)'Access);
end Get_Any_Constant_Reference;
procedure Read_Any
(Stream : access Ada.Streams.Root_Stream_Type'Class;
V : out Any) is
Key : aliased PB_Support.IO.Key;
begin
while PB_Support.IO.Read_Key (Stream, Key'Access) loop
case Key.Field is
when 1 =>
PB_Support.IO.Read (Stream, Key.Encoding, V.Type_Url);
when 2 =>
PB_Support.IO.Read (Stream, Key.Encoding, V.Value);
when others =>
PB_Support.IO.Unknown_Field (Stream, Key.Encoding);
end case;
end loop;
end Read_Any;
procedure Write_Any
(Stream : access Ada.Streams.Root_Stream_Type'Class;
V : Any) is
begin
if Stream.all not in PB_Support.Internal.Stream then
declare
WS : aliased PB_Support.Internal.Stream (Stream);
begin
Write_Any (WS'Access, V);
return;
end;
end if;
declare
WS : PB_Support.Internal.Stream renames
PB_Support.Internal.Stream (Stream.all);
begin
WS.Start_Message;
WS.Write_Option (1, V.Type_Url);
WS.Write_Option (2, V.Value);
if WS.End_Message then
Write_Any (WS'Access, V);
end if;
end;
end Write_Any;
end Google.Protobuf.Any; |
-- Copyright (c) 2021 Maxim Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with Ada.Wide_Wide_Text_IO;
with League.Strings;
with League.Application;
with Network.Addresses;
with Network.Connection_Promises;
with Network.Managers.TCP_V4;
with Network.Managers;
with Listeners;
procedure Example is
Addr : constant League.Strings.Universal_String :=
League.Application.Arguments.Element (1);
Error : League.Strings.Universal_String;
Manager : Network.Managers.Manager;
Promise : Network.Connection_Promises.Promise;
begin
Manager.Initialize;
Network.Managers.TCP_V4.Register (Manager);
Manager.Connect
(Address => Network.Addresses.To_Address (Addr),
Error => Error,
Promise => Promise);
if not Error.Is_Empty then
Ada.Wide_Wide_Text_IO.Put_Line
("Connect fails: " & Error.To_Wide_Wide_String);
return;
end if;
declare
Listener : aliased Listeners.Listener :=
(Promise => Promise, others => <>);
begin
Promise.Add_Listener (Listener'Unchecked_Access);
for J in 1 .. 100 loop
Manager.Wait (1.0);
exit when Listener.Done;
end loop;
end;
end Example;
|
-- This spec has been automatically generated from msp430g2553.svd
pragma Restrictions (No_Elaboration_Code);
pragma Ada_2012;
pragma Style_Checks (Off);
with Interfaces; use Interfaces;
with System;
package MSP430_SVD is
pragma Preelaborate;
---------------
-- Base type --
---------------
type UInt32 is new Interfaces.Unsigned_32;
type UInt16 is new Interfaces.Unsigned_16;
type Byte is new Interfaces.Unsigned_8;
type Bit is mod 2**1
with Size => 1;
type UInt2 is mod 2**2
with Size => 2;
type UInt3 is mod 2**3
with Size => 3;
type UInt4 is mod 2**4
with Size => 4;
type UInt5 is mod 2**5
with Size => 5;
type UInt6 is mod 2**6
with Size => 6;
type UInt7 is mod 2**7
with Size => 7;
type UInt8 is mod 2**8
with Size => 8;
type UInt9 is mod 2**9
with Size => 9;
type UInt10 is mod 2**10
with Size => 10;
type UInt11 is mod 2**11
with Size => 11;
type UInt12 is mod 2**12
with Size => 12;
type UInt13 is mod 2**13
with Size => 13;
type UInt14 is mod 2**14
with Size => 14;
type UInt15 is mod 2**15
with Size => 15;
type UInt17 is mod 2**17
with Size => 17;
type UInt18 is mod 2**18
with Size => 18;
type UInt19 is mod 2**19
with Size => 19;
type UInt20 is mod 2**20
with Size => 20;
type UInt21 is mod 2**21
with Size => 21;
type UInt22 is mod 2**22
with Size => 22;
type UInt23 is mod 2**23
with Size => 23;
type UInt24 is mod 2**24
with Size => 24;
type UInt25 is mod 2**25
with Size => 25;
type UInt26 is mod 2**26
with Size => 26;
type UInt27 is mod 2**27
with Size => 27;
type UInt28 is mod 2**28
with Size => 28;
type UInt29 is mod 2**29
with Size => 29;
type UInt30 is mod 2**30
with Size => 30;
type UInt31 is mod 2**31
with Size => 31;
--------------------
-- Base addresses --
--------------------
SPECIAL_FUNCTION_Base : constant System.Address := System'To_Address (16#0#);
PORT_3_4_Base : constant System.Address := System'To_Address (16#10#);
PORT_1_2_Base : constant System.Address := System'To_Address (16#20#);
ADC10_Base : constant System.Address := System'To_Address (16#48#);
SYSTEM_CLOCK_Base : constant System.Address := System'To_Address (16#52#);
COMPARATOR_A_Base : constant System.Address := System'To_Address (16#58#);
USCI_A0_UART_MODE_Base : constant System.Address := System'To_Address (16#5C#);
USCI_A0_SPI_MODE_Base : constant System.Address := System'To_Address (16#60#);
USCI_B0_I2C_MODE_Base : constant System.Address := System'To_Address (16#68#);
USCI_B0_SPI_MODE_Base : constant System.Address := System'To_Address (16#68#);
TLV_CALIBRATION_DATA_Base : constant System.Address := System'To_Address (16#10C0#);
CALIBRATION_DATA_Base : constant System.Address := System'To_Address (16#10F8#);
TIMER_1_A3_Base : constant System.Address := System'To_Address (16#11E#);
WATCHDOG_TIMER_Base : constant System.Address := System'To_Address (16#120#);
FLASH_Base : constant System.Address := System'To_Address (16#128#);
TIMER_0_A3_Base : constant System.Address := System'To_Address (16#12E#);
INTERRUPTS_Base : constant System.Address := System'To_Address (16#FFE0#);
end MSP430_SVD;
|
--------------------------------------------------------------------------
-- package Givens_QR, QR decomposition using Givens rotations
-- Copyright (C) 2008-2018 Jonathan S. Parker
--
-- 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.
---------------------------------------------------------------------------
-- package Givens_QR
--
-- QR decomposition and linear equation solving for rectangular real
-- valued matrices. The procedure uses Givens rotations with column
-- pivoting and row scaling to factor matrix A into a product of an
-- orthogonal matrix Q and an upper triangular matrix R: A*S*P = Q*R.
-- Matrix S is a diagonal matrix that scales the columns of A. Matrix
-- P contains the column permutations performed during col pivoting.
--
-- A matrix with m rows, n columns (m x n) and elements of generic type
-- Real is input as "A" and returned in Q R form. Matrix A is overwritten
-- with R and should be saved prior to decomposition if it needed. The
-- QR decomposition can be performed on arbitrary sub-blocks of matrix A.
-- Must have No_of_Rows >= No_Of_Cols: m >= n. (If m < n you take the QR
-- decomposition of A_transpose to get an LQ decomposition of A; see below.)
--
-- The decomposition uses Givens rotations rather than the more common
-- Householder reflections. In the present package, the Givens arithmetic
-- is enhanced to provide a bit more numerical accuracy.
--
-- Column pivoting is slow, but it's a necessary condition for calculating
-- reliable least squares solutions of x in A*x = b, and makes QR applicable
-- in a lot of cases that would otherwise require an even slower singular
-- value decomposition (SVD).
--
-- Procedures QR_Decompose and QR_Solve return solutions of the simultaneous
-- linear equations A*x = b, where A is an arbitrary real valued matrix.
-- The vector b is input into procedure QR_Solve, and the solution is
-- returned as x. QR can be used to generate least squares
-- solutions: vectors x that minimize the sum of squares: |A*x - b|^2.
-- (The system of linear equations A*x = b may have no exact solution x, or
-- it may have an infinite number of solutions.)
--
-- The QR assumes m >= n. (Number of Rows is greater than or equal to
-- number of Cols.) If m < n (an underdetermined system of equations)
-- then you QR decompose the transpose of A. The user of the routine
-- does the transpose, not the routine. (See Notes on Use below.)
--
-- Notes on Use
--
-- Notice we require No_of_Rows >= No_Of_Cols: m >= n.
--
-- A*x = b is
--
-- a a a a x b
-- a a a a x b
-- a a a a * x = b
-- a a a a x b
-- a a a a b
-- a a a a b
-- a a a a b
-- a a a a b
--
-- Suppose instead that m < n. (Number of rows is less than number of
-- columns.) Then A x = b is an underdetermined system of
-- equations. In this case there may exist an infinite
-- number of solutions for x. Usually the preferred solution x is the
-- x of minimum length. To solve for the x of minimum length, decompose
-- the transpose of A. Let A' = transpose(A) and obtain the usual Q*R = A'.
-- Using Q and R in this form yields solutions of x in A x = b that have the
-- desired property. Here the equation A x = b becomes R' (Q' x) = b,
-- or R' z = b, where R' is m x m, and z and b are vectors of length m.
generic
type Real is digits <>;
type R_Index is range <>; -- Row_id : R_Index;
type C_Index is range <>; -- Col_id : C_Index;
-- This means:
-- Col vectors are indexed by R_Index,
-- Row vectors are indexed by C_Index.
-- The matrix is M x N: M rows by N cols.
-- M rows means that: M = R_Index'Last - R_Index'First + 1
-- N cols means that: N = C_Index'Last - C_Index'First + 1
type A_Matrix is array(R_Index, C_Index) of Real;
-- A is the matrix to be QR decomposed.
-- The Q matrix (a sequence of Givens rotations) is stored in a
-- matrix with the same shape as A.
package Givens_QR is
type Row_Vector is array(C_Index) of Real;
-- Row vector of A_Matrix and R_Matrix. (R is essentially a square matrix)
type Col_Vector is array(R_Index) of Real;
-- Col vector of A_Matrix
type Permutation is array(C_Index) of C_Index;
-- The columns are rearranged as a result of pivoting. The swaps are
-- stored in Col_Permutation : Permutation. So if Col 1 is swapped with
-- Col 6, then Col_Permutation(1) = 6, and Col_Permutation(6) = 1.
type Rotation is record
Cosine : Real;
Sine : Real;
end record;
Identity : constant Rotation := (+0.0, +0.0);
type Rot_Set is array (R_Index, C_index) of Rotation;
type Rot_Code is array (R_Index, C_index) of Boolean;
pragma Pack (Rot_Code);
type Q_matrix is record
Rot : Rot_Set;
P_bigger_than_L : Rot_Code;
Final_Row : R_Index;
Final_Col : C_Index;
Starting_Row : R_Index;
Starting_Col : C_Index;
end record;
-- Notice Q_matrix.Rot has the same shape as A: M x N.
-- The true Q is M x M, not M x N like A, but the above matrix holds
-- the rotation matrices that can be used to create Q.
procedure QR_Decompose
(A : in out A_Matrix; -- overwritten with R
Q : out Q_Matrix;
Row_Scalings : out Col_Vector;
Col_Permutation : out Permutation;
Final_Row : in R_Index := R_Index'Last;
Final_Col : in C_Index := C_Index'Last;
Starting_Row : in R_Index := R_Index'First;
Starting_Col : in C_Index := C_Index'First);
-- procedure QR_Decompose factors A into A*S*P = Q*R, where S is diagonal,
-- and P permutes the order of the columns of a matrix.
--
-- The input matrix A is overwritten with R.
--
-- Must have No_of_Rows >= No_Of_Cols, and at least 2 rows and at least 2 cols.
-- otherwise Argument_Error is raised:
--
-- if No_Of_Cols > No_of_Rows then raise Ada.Numerics.Argument_Error; end if;
-- if No_Of_Cols < 2.0 then raise Ada.Numerics.Argument_Error; end if;
Default_Singularity_Cutoff : constant Real := Real'Epsilon * (+2.0)**12;
-- Used by QR_Solve to handle singular matrices, and ill-conditioned matrices:
--
-- If a diagonal element of R falls below this fraction of the max R element,
-- then QR_Solve tosses out the corresponding Q column (to get a matrix that
-- is very near the original matrix, but much better conditioned). The range
-- Real'Epsilon * 2**10 to Real'Epsilon * 2**24 seems ok. Ill-conditioned
-- matrices can behave either worse or better as you vary over this range.
-- 2.0**12 is a good compromise. It means Default_Singularity_Cutoff ~ 2**(-38).
procedure QR_Solve
(X : out Row_Vector; -- Solution vector
B : in Col_Vector;
R : in A_Matrix; -- Original A holds the R after call to QR
Q : in Q_Matrix;
Row_Scalings : in Col_Vector;
Col_Permutation : in Permutation;
Singularity_Cutoff : in Real := Default_Singularity_Cutoff);
-- Get Product = Q'*B
function Q_transpose_x_Col_Vector
(Q : in Q_Matrix;
B : in Col_Vector)
return Col_Vector;
-- Get Product = Q*B
function Q_x_Col_Vector
(Q : in Q_Matrix;
B : in Col_Vector)
return Col_Vector;
-- type A_Matrix is a list of Col_Vector's:
procedure Q_x_Matrix
(Q : in Q_Matrix;
A : in out A_Matrix);
-- type V_Index is range <>;
-- Get Product = Q*V
subtype V_Index is R_Index;
-- This makes V is square, so can be used for making Q in
-- explicit matrix form.
type V_Matrix is array(R_Index, V_Index) of Real;
-- V might for example be the identity matrix so can get Q in
-- matrix form: Q*I = Q, using procedure Q_x_V_Matrix.
procedure Q_x_V_Matrix
(Q : in Q_Matrix;
V : in out V_Matrix);
procedure Q_transpose_x_V_Matrix
(Q : in Q_Matrix;
V : in out V_Matrix);
end Givens_QR;
|
with Ada.Numerics.Discrete_Random;
with Ada.Containers.Vectors;
use Ada.Containers;
with Applicative; use Applicative;
with Util; use Util;
-- Package containing functions for generating random numbers.
package Distribution is
-- Type to represent a random distribution.
type Distribution_Type is limited private;
type Distribution_Pointer is access all Distribution_Type;
-- Set the seed used for selecting random addresses.
procedure Set_Seed(dist : in out Distribution_Type;
seed : in Integer);
-- Insert an address to the pool.
-- This should be called the first time a trace is executed.
procedure Insert(dist : in out Distribution_Type;
address : in Address_Type;
size : in Positive);
-- Push an address limit on to the stack.
-- This is done when evaluating a part of a split or scratchpad.
-- Only addresses within this limit will be selected at random.
procedure Push_Limit(dist : in out Distribution_Type;
lower : in Address_Type;
upper : in Address_Type);
-- Pop an address limit off of the stack.
procedure Pop_Limit(dist : in out Distribution_Type);
-- Push an address transform on to the stack.
-- This is done when evaluating an address transform or split.
procedure Push_Transform(dist : in out Distribution_Type;
trans : in Applicative_Pointer);
-- Pop an address transform off of the stack.
procedure Pop_Transform(dist : in out Distribution_Type);
-- Select a random address from the distribution.
function Random_Address(dist : Distribution_Type;
alignment : Positive) return Address_Type;
-- Select a uniform random number.
function Random(dist : Distribution_Type) return Natural;
-- Display address ranges (for debugging).
procedure Print(dist : in Distribution_Type);
private
type Range_Type is record
start : Address_Type;
size : Positive;
end record;
type Limit_Type is record
trans : Applicative_Pointer := null;
lower : Address_Type := 0;
upper : Address_Type := 0;
end record;
package RNG is new Ada.Numerics.Discrete_Random(Natural);
package Range_Vectors is new Vectors(Positive, Range_Type);
package Limit_Vectors is new Vectors(Positive, Limit_Type);
type Distribution_Type is limited record
generator : RNG.Generator;
ranges : Range_Vectors.Vector;
limits : Limit_Vectors.Vector;
end record;
end Distribution;
|
-- { dg-do compile }
package body Parent_Ltd_With.Child_Full_View is
function New_Child_Symbol return Child_Symbol_Access is
Sym : constant Child_Symbol_Access := new Child_Symbol'(Comp => 10);
begin
return Sym;
end New_Child_Symbol;
end Parent_Ltd_With.Child_Full_View;
|
with NRF52_DK; use NRF52_DK;
with NRF52_DK.IOs; use NRF52_DK.IOs;
package sensor is
function Distance(TrigPin, EchoPin : NRF52_DK.IOs.Pin_Id) return Float;
end sensor;
|
-- { dg-do compile }
procedure Discr19 is
type Arr_Int_T is array (Integer range <>) of Integer;
type Abs_Tag_Rec_T (N : Integer; M : Integer) is abstract tagged record
Arr_Int : Arr_Int_T (1..M);
end record;
type Tag_Rec_T (M : Integer)
is new Abs_Tag_Rec_T (N => 1, M => M) with null record;
begin
null;
end;
|
-- See LICENSE file for cc0 license details
with Ada.Command_Line;
with Ada.Directories;
with Ada.Exceptions; use Ada.Exceptions; -- TODO remove
with Ada.Strings.Unbounded;
with Ada.Text_Io;
with Ch_Conn;
with Posix.Io;
with Posix.Process_Identification;
with Posix.User_Database;
with Srv_Conn;
with Srv_Quit;
with Util;
-- TODO check unused withs
package body Iictl is
package ACL renames Ada.Command_Line;
package ASU renames Ada.Strings.Unbounded;
package ATIO renames Ada.Text_Io;
package PIO renames Posix.Io;
package PPI renames Posix.Process_Identification;
package PUD renames Posix.User_Database;
-- TODO remove unused renames
Irc_Dir : ASU.Unbounded_String;
-- TODO different directories for different servers?
Nick : ASU.Unbounded_String;
-- TODO package globals in .ads?
procedure Iictl is
begin
Parse_Options;
-- TODO set file offset to end of channel outs?
if ASU.Length (Nick) = 0 then
ATIO.Put_Line ("No nick given");
-- TODO Print_Usage;
return;
end if;
Util.Verbose_Print ("Iictl: started");
Util.Verbose_Print ("Nick = " & ASU.To_String (Nick));
Util.Verbose_Print ("Irc_Dir = " & ASU.To_String (Irc_Dir));
loop
Srv_Conn.Reconnect_Servers (ASU.To_String (Irc_Dir),
ASU.To_String (Nick));
-- TODO rename Server_Reconnection, Connection_Ctrl, ...
Ch_Conn.Rejoin_Channels (ASU.To_String (Irc_Dir));
-- TODO rename Rejoin_Ctl or something
Srv_Quit.Detect_Quits (ASU.To_String (Irc_Dir));
-- TODO make Irc_Dir accessible from e.g. Iictl?
-- TODO Ch_Conn.Detect_Parts;
Delay 1.0; -- TODO remove? speed up? ravenclaw!
end loop;
end Iictl;
procedure Parse_Options is
I : Integer := 1;
begin
Irc_Dir := Default_Irc_Dir;
-- TODO same opts as ii?
-- [-i <irc dir>] [-s <host>] [-p <port>]
-- [-n <nick>] [-k <password>] [-f <fullname>]
-- TODO move to Util
-- TODO refactor to separate subprogram TODO move to Main
-- TODO initialize I more locally
while I <= ACL.Argument_Count loop
begin
if ACL.Argument (I) = "-n" then
I := I + 1;
Nick := ASU.To_Unbounded_String (ACL.Argument (I));
elsif ACL.Argument (I) = "-v" then -- TODO use case
Util.Verbose := True;
Util.Verbose_Print ("Iictl: Verbose printing on");
elsif ACL.Argument (I) = "-i" then
I := I + 1;
Irc_Dir := ASU.To_Unbounded_String (ACL.Argument (I));
else
raise CONSTRAINT_ERROR; -- TODO different exception
end if;
I := I + 1;
exception
when CONSTRAINT_ERROR =>
ATIO.Put_Line ("usage: " & ACL.Command_Name
& " [-v]" & " <-n nick>");
return;
end;
end loop;
end Parse_Options;
function Default_Irc_Dir return ASU.Unbounded_String is
use type Ada.Strings.Unbounded.Unbounded_String;
Uid : PPI.User_Id;
Db_Item : PUD.User_Database_Item;
-- TODO Home_Dir : Posix.Posix_String
Home_Dir : ASU.Unbounded_String;
begin
Uid := PPI.Get_Effective_User_ID;
Db_Item := PUD.Get_User_Database_Item (Uid);
--Home_Dir := PUD.Initial_Directory_Of (Db_Item);
Home_Dir := ASU.To_Unbounded_String (
Posix.To_String (
PUD.Initial_Directory_Of (Db_Item)));
--return ASU.To_Unbounded_String (Posix.To_String (Home_Dir) & "/irc");
return Home_Dir & ASU.To_Unbounded_String ("/irc");
end Default_Irc_Dir;
end Iictl;
|
-- * Output of max2ada.ms, a GMax / 3D Studio Max script for exporting to GLOBE_3D
--
-- * Copy and paste these lines from the Listener into a
-- text editor, and save the package as an .ada file.
-- * Alternatively, use the GMaxSLGRAB.exe tool.
-- * For GNAT, you must save the specification as an .ads file
-- and the body as an .adb file, or run gnatchop on the whole .ada file.
-- Title : Dreadnought
-- Subject : Dreadnought class Heavy Cruiser : a space cruiser inspired by Sulaco from Aliens.
-- Author : Xenodroid
-- File name : dreadnought_g3d.gmax
-- File path : C:\Ada\GL\3dmodels\dreadnought\
with GLOBE_3D;
package Dreadnought is
procedure Create (
object : in out GLOBE_3D.p_Object_3D;
scale : GLOBE_3D.Real;
centre : GLOBE_3D.Point_3D;
alum_001,
grumnoir,
tole_001,
alum_002 : GLOBE_3D.Image_ID
);
end Dreadnought;
|
------------------------------------------------------------------------------
-- --
-- GNAT LIBRARY COMPONENTS --
-- --
-- A D A . C O N T A I N E R S . B O U N D E D _ H A S H E D _ M A P S --
-- --
-- B o d y --
-- --
-- Copyright (C) 2004-2016, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- This unit was originally developed by Matthew J Heaney. --
------------------------------------------------------------------------------
with Ada.Containers.Hash_Tables.Generic_Bounded_Operations;
pragma Elaborate_All (Ada.Containers.Hash_Tables.Generic_Bounded_Operations);
with Ada.Containers.Hash_Tables.Generic_Bounded_Keys;
pragma Elaborate_All (Ada.Containers.Hash_Tables.Generic_Bounded_Keys);
with Ada.Containers.Helpers; use Ada.Containers.Helpers;
with Ada.Containers.Prime_Numbers; use Ada.Containers.Prime_Numbers;
with System; use type System.Address;
package body Ada.Containers.Bounded_Hashed_Maps is
pragma Warnings (Off, "variable ""Busy*"" is not referenced");
pragma Warnings (Off, "variable ""Lock*"" is not referenced");
-- See comment in Ada.Containers.Helpers
-----------------------
-- Local Subprograms --
-----------------------
function Equivalent_Key_Node
(Key : Key_Type;
Node : Node_Type) return Boolean;
pragma Inline (Equivalent_Key_Node);
function Hash_Node (Node : Node_Type) return Hash_Type;
pragma Inline (Hash_Node);
function Next (Node : Node_Type) return Count_Type;
pragma Inline (Next);
procedure Set_Next (Node : in out Node_Type; Next : Count_Type);
pragma Inline (Set_Next);
function Vet (Position : Cursor) return Boolean;
--------------------------
-- Local Instantiations --
--------------------------
package HT_Ops is new Hash_Tables.Generic_Bounded_Operations
(HT_Types => HT_Types,
Hash_Node => Hash_Node,
Next => Next,
Set_Next => Set_Next);
package Key_Ops is new Hash_Tables.Generic_Bounded_Keys
(HT_Types => HT_Types,
Next => Next,
Set_Next => Set_Next,
Key_Type => Key_Type,
Hash => Hash,
Equivalent_Keys => Equivalent_Key_Node);
---------
-- "=" --
---------
function "=" (Left, Right : Map) return Boolean is
function Find_Equal_Key
(R_HT : Hash_Table_Type'Class;
L_Node : Node_Type) return Boolean;
function Is_Equal is new HT_Ops.Generic_Equal (Find_Equal_Key);
--------------------
-- Find_Equal_Key --
--------------------
function Find_Equal_Key
(R_HT : Hash_Table_Type'Class;
L_Node : Node_Type) return Boolean
is
R_Index : constant Hash_Type := Key_Ops.Index (R_HT, L_Node.Key);
R_Node : Count_Type := R_HT.Buckets (R_Index);
begin
while R_Node /= 0 loop
if Equivalent_Keys (L_Node.Key, R_HT.Nodes (R_Node).Key) then
return L_Node.Element = R_HT.Nodes (R_Node).Element;
end if;
R_Node := R_HT.Nodes (R_Node).Next;
end loop;
return False;
end Find_Equal_Key;
-- Start of processing for "="
begin
return Is_Equal (Left, Right);
end "=";
------------
-- Assign --
------------
procedure Assign (Target : in out Map; Source : Map) is
procedure Insert_Element (Source_Node : Count_Type);
procedure Insert_Elements is
new HT_Ops.Generic_Iteration (Insert_Element);
--------------------
-- Insert_Element --
--------------------
procedure Insert_Element (Source_Node : Count_Type) is
N : Node_Type renames Source.Nodes (Source_Node);
C : Cursor;
B : Boolean;
begin
Insert (Target, N.Key, N.Element, C, B);
pragma Assert (B);
end Insert_Element;
-- Start of processing for Assign
begin
if Target'Address = Source'Address then
return;
end if;
if Checks and then Target.Capacity < Source.Length then
raise Capacity_Error
with "Target capacity is less than Source length";
end if;
HT_Ops.Clear (Target);
Insert_Elements (Source);
end Assign;
--------------
-- Capacity --
--------------
function Capacity (Container : Map) return Count_Type is
begin
return Container.Capacity;
end Capacity;
-----------
-- Clear --
-----------
procedure Clear (Container : in out Map) is
begin
HT_Ops.Clear (Container);
end Clear;
------------------------
-- Constant_Reference --
------------------------
function Constant_Reference
(Container : aliased Map;
Position : Cursor) return Constant_Reference_Type
is
begin
if Checks and then Position.Container = null then
raise Constraint_Error with
"Position cursor has no element";
end if;
if Checks and then Position.Container /= Container'Unrestricted_Access
then
raise Program_Error with
"Position cursor designates wrong map";
end if;
pragma Assert (Vet (Position),
"Position cursor in Constant_Reference is bad");
declare
N : Node_Type renames Container.Nodes (Position.Node);
TC : constant Tamper_Counts_Access :=
Container.TC'Unrestricted_Access;
begin
return R : constant Constant_Reference_Type :=
(Element => N.Element'Access,
Control => (Controlled with TC))
do
Lock (TC.all);
end return;
end;
end Constant_Reference;
function Constant_Reference
(Container : aliased Map;
Key : Key_Type) return Constant_Reference_Type
is
Node : constant Count_Type :=
Key_Ops.Find (Container'Unrestricted_Access.all, Key);
begin
if Checks and then Node = 0 then
raise Constraint_Error with "key not in map";
end if;
declare
N : Node_Type renames Container.Nodes (Node);
TC : constant Tamper_Counts_Access :=
Container.TC'Unrestricted_Access;
begin
return R : constant Constant_Reference_Type :=
(Element => N.Element'Access,
Control => (Controlled with TC))
do
Lock (TC.all);
end return;
end;
end Constant_Reference;
--------------
-- Contains --
--------------
function Contains (Container : Map; Key : Key_Type) return Boolean is
begin
return Find (Container, Key) /= No_Element;
end Contains;
----------
-- Copy --
----------
function Copy
(Source : Map;
Capacity : Count_Type := 0;
Modulus : Hash_Type := 0) return Map
is
C : Count_Type;
M : Hash_Type;
begin
if Capacity = 0 then
C := Source.Length;
elsif Capacity >= Source.Length then
C := Capacity;
elsif Checks then
raise Capacity_Error with "Capacity value too small";
end if;
if Modulus = 0 then
M := Default_Modulus (C);
else
M := Modulus;
end if;
return Target : Map (Capacity => C, Modulus => M) do
Assign (Target => Target, Source => Source);
end return;
end Copy;
---------------------
-- Default_Modulus --
---------------------
function Default_Modulus (Capacity : Count_Type) return Hash_Type is
begin
return To_Prime (Capacity);
end Default_Modulus;
------------
-- Delete --
------------
procedure Delete (Container : in out Map; Key : Key_Type) is
X : Count_Type;
begin
Key_Ops.Delete_Key_Sans_Free (Container, Key, X);
if Checks and then X = 0 then
raise Constraint_Error with "attempt to delete key not in map";
end if;
HT_Ops.Free (Container, X);
end Delete;
procedure Delete (Container : in out Map; Position : in out Cursor) is
begin
if Checks and then Position.Node = 0 then
raise Constraint_Error with
"Position cursor of Delete equals No_Element";
end if;
if Checks and then Position.Container /= Container'Unrestricted_Access
then
raise Program_Error with
"Position cursor of Delete designates wrong map";
end if;
TC_Check (Container.TC);
pragma Assert (Vet (Position), "bad cursor in Delete");
HT_Ops.Delete_Node_Sans_Free (Container, Position.Node);
HT_Ops.Free (Container, Position.Node);
Position := No_Element;
end Delete;
-------------
-- Element --
-------------
function Element (Container : Map; Key : Key_Type) return Element_Type is
Node : constant Count_Type :=
Key_Ops.Find (Container'Unrestricted_Access.all, Key);
begin
if Checks and then Node = 0 then
raise Constraint_Error with
"no element available because key not in map";
end if;
return Container.Nodes (Node).Element;
end Element;
function Element (Position : Cursor) return Element_Type is
begin
if Checks and then Position.Node = 0 then
raise Constraint_Error with
"Position cursor of function Element equals No_Element";
end if;
pragma Assert (Vet (Position), "bad cursor in function Element");
return Position.Container.Nodes (Position.Node).Element;
end Element;
-------------------------
-- Equivalent_Key_Node --
-------------------------
function Equivalent_Key_Node
(Key : Key_Type;
Node : Node_Type) return Boolean is
begin
return Equivalent_Keys (Key, Node.Key);
end Equivalent_Key_Node;
---------------------
-- Equivalent_Keys --
---------------------
function Equivalent_Keys (Left, Right : Cursor)
return Boolean is
begin
if Checks and then Left.Node = 0 then
raise Constraint_Error with
"Left cursor of Equivalent_Keys equals No_Element";
end if;
if Checks and then Right.Node = 0 then
raise Constraint_Error with
"Right cursor of Equivalent_Keys equals No_Element";
end if;
pragma Assert (Vet (Left), "Left cursor of Equivalent_Keys is bad");
pragma Assert (Vet (Right), "Right cursor of Equivalent_Keys is bad");
declare
LN : Node_Type renames Left.Container.Nodes (Left.Node);
RN : Node_Type renames Right.Container.Nodes (Right.Node);
begin
return Equivalent_Keys (LN.Key, RN.Key);
end;
end Equivalent_Keys;
function Equivalent_Keys (Left : Cursor; Right : Key_Type) return Boolean is
begin
if Checks and then Left.Node = 0 then
raise Constraint_Error with
"Left cursor of Equivalent_Keys equals No_Element";
end if;
pragma Assert (Vet (Left), "Left cursor in Equivalent_Keys is bad");
declare
LN : Node_Type renames Left.Container.Nodes (Left.Node);
begin
return Equivalent_Keys (LN.Key, Right);
end;
end Equivalent_Keys;
function Equivalent_Keys (Left : Key_Type; Right : Cursor) return Boolean is
begin
if Checks and then Right.Node = 0 then
raise Constraint_Error with
"Right cursor of Equivalent_Keys equals No_Element";
end if;
pragma Assert (Vet (Right), "Right cursor of Equivalent_Keys is bad");
declare
RN : Node_Type renames Right.Container.Nodes (Right.Node);
begin
return Equivalent_Keys (Left, RN.Key);
end;
end Equivalent_Keys;
-------------
-- Exclude --
-------------
procedure Exclude (Container : in out Map; Key : Key_Type) is
X : Count_Type;
begin
Key_Ops.Delete_Key_Sans_Free (Container, Key, X);
HT_Ops.Free (Container, X);
end Exclude;
--------------
-- Finalize --
--------------
procedure Finalize (Object : in out Iterator) is
begin
if Object.Container /= null then
Unbusy (Object.Container.TC);
end if;
end Finalize;
----------
-- Find --
----------
function Find (Container : Map; Key : Key_Type) return Cursor is
Node : constant Count_Type :=
Key_Ops.Find (Container'Unrestricted_Access.all, Key);
begin
if Node = 0 then
return No_Element;
else
return Cursor'(Container'Unrestricted_Access, Node);
end if;
end Find;
-----------
-- First --
-----------
function First (Container : Map) return Cursor is
Node : constant Count_Type := HT_Ops.First (Container);
begin
if Node = 0 then
return No_Element;
else
return Cursor'(Container'Unrestricted_Access, Node);
end if;
end First;
function First (Object : Iterator) return Cursor is
begin
return Object.Container.First;
end First;
------------------------
-- Get_Element_Access --
------------------------
function Get_Element_Access
(Position : Cursor) return not null Element_Access is
begin
return Position.Container.Nodes (Position.Node).Element'Access;
end Get_Element_Access;
-----------------
-- Has_Element --
-----------------
function Has_Element (Position : Cursor) return Boolean is
begin
pragma Assert (Vet (Position), "bad cursor in Has_Element");
return Position.Node /= 0;
end Has_Element;
---------------
-- Hash_Node --
---------------
function Hash_Node (Node : Node_Type) return Hash_Type is
begin
return Hash (Node.Key);
end Hash_Node;
-------------
-- Include --
-------------
procedure Include
(Container : in out Map;
Key : Key_Type;
New_Item : Element_Type)
is
Position : Cursor;
Inserted : Boolean;
begin
Insert (Container, Key, New_Item, Position, Inserted);
if not Inserted then
TE_Check (Container.TC);
declare
N : Node_Type renames Container.Nodes (Position.Node);
begin
N.Key := Key;
N.Element := New_Item;
end;
end if;
end Include;
------------
-- Insert --
------------
procedure Insert
(Container : in out Map;
Key : Key_Type;
Position : out Cursor;
Inserted : out Boolean)
is
procedure Assign_Key (Node : in out Node_Type);
pragma Inline (Assign_Key);
function New_Node return Count_Type;
pragma Inline (New_Node);
procedure Local_Insert is
new Key_Ops.Generic_Conditional_Insert (New_Node);
procedure Allocate is
new HT_Ops.Generic_Allocate (Assign_Key);
-----------------
-- Assign_Key --
-----------------
procedure Assign_Key (Node : in out Node_Type) is
New_Item : Element_Type;
pragma Unmodified (New_Item);
-- Default-initialized element (ok to reference, see below)
begin
Node.Key := Key;
-- There is no explicit element provided, but in an instance the
-- element type may be a scalar with a Default_Value aspect, or a
-- composite type with such a scalar component, or components with
-- default initialization, so insert a possibly initialized element
-- under the given key.
Node.Element := New_Item;
end Assign_Key;
--------------
-- New_Node --
--------------
function New_Node return Count_Type is
Result : Count_Type;
begin
Allocate (Container, Result);
return Result;
end New_Node;
-- Start of processing for Insert
begin
-- The buckets array length is specified by the user as a discriminant
-- of the container type, so it is possible for the buckets array to
-- have a length of zero. We must check for this case specifically, in
-- order to prevent divide-by-zero errors later, when we compute the
-- buckets array index value for a key, given its hash value.
if Checks and then Container.Buckets'Length = 0 then
raise Capacity_Error with "No capacity for insertion";
end if;
Local_Insert (Container, Key, Position.Node, Inserted);
Position.Container := Container'Unchecked_Access;
end Insert;
procedure Insert
(Container : in out Map;
Key : Key_Type;
New_Item : Element_Type;
Position : out Cursor;
Inserted : out Boolean)
is
procedure Assign_Key (Node : in out Node_Type);
pragma Inline (Assign_Key);
function New_Node return Count_Type;
pragma Inline (New_Node);
procedure Local_Insert is
new Key_Ops.Generic_Conditional_Insert (New_Node);
procedure Allocate is
new HT_Ops.Generic_Allocate (Assign_Key);
-----------------
-- Assign_Key --
-----------------
procedure Assign_Key (Node : in out Node_Type) is
begin
Node.Key := Key;
Node.Element := New_Item;
end Assign_Key;
--------------
-- New_Node --
--------------
function New_Node return Count_Type is
Result : Count_Type;
begin
Allocate (Container, Result);
return Result;
end New_Node;
-- Start of processing for Insert
begin
-- The buckets array length is specified by the user as a discriminant
-- of the container type, so it is possible for the buckets array to
-- have a length of zero. We must check for this case specifically, in
-- order to prevent divide-by-zero errors later, when we compute the
-- buckets array index value for a key, given its hash value.
if Checks and then Container.Buckets'Length = 0 then
raise Capacity_Error with "No capacity for insertion";
end if;
Local_Insert (Container, Key, Position.Node, Inserted);
Position.Container := Container'Unchecked_Access;
end Insert;
procedure Insert
(Container : in out Map;
Key : Key_Type;
New_Item : Element_Type)
is
Position : Cursor;
pragma Unreferenced (Position);
Inserted : Boolean;
begin
Insert (Container, Key, New_Item, Position, Inserted);
if Checks and then not Inserted then
raise Constraint_Error with
"attempt to insert key already in map";
end if;
end Insert;
--------------
-- Is_Empty --
--------------
function Is_Empty (Container : Map) return Boolean is
begin
return Container.Length = 0;
end Is_Empty;
-------------
-- Iterate --
-------------
procedure Iterate
(Container : Map;
Process : not null access procedure (Position : Cursor))
is
procedure Process_Node (Node : Count_Type);
pragma Inline (Process_Node);
procedure Local_Iterate is new HT_Ops.Generic_Iteration (Process_Node);
------------------
-- Process_Node --
------------------
procedure Process_Node (Node : Count_Type) is
begin
Process (Cursor'(Container'Unrestricted_Access, Node));
end Process_Node;
Busy : With_Busy (Container.TC'Unrestricted_Access);
-- Start of processing for Iterate
begin
Local_Iterate (Container);
end Iterate;
function Iterate
(Container : Map) return Map_Iterator_Interfaces.Forward_Iterator'Class
is
begin
return It : constant Iterator :=
(Limited_Controlled with
Container => Container'Unrestricted_Access)
do
Busy (Container.TC'Unrestricted_Access.all);
end return;
end Iterate;
---------
-- Key --
---------
function Key (Position : Cursor) return Key_Type is
begin
if Checks and then Position.Node = 0 then
raise Constraint_Error with
"Position cursor of function Key equals No_Element";
end if;
pragma Assert (Vet (Position), "bad cursor in function Key");
return Position.Container.Nodes (Position.Node).Key;
end Key;
------------
-- Length --
------------
function Length (Container : Map) return Count_Type is
begin
return Container.Length;
end Length;
----------
-- Move --
----------
procedure Move
(Target : in out Map;
Source : in out Map)
is
begin
if Target'Address = Source'Address then
return;
end if;
TC_Check (Source.TC);
Target.Assign (Source);
Source.Clear;
end Move;
----------
-- Next --
----------
function Next (Node : Node_Type) return Count_Type is
begin
return Node.Next;
end Next;
function Next (Position : Cursor) return Cursor is
begin
if Position.Node = 0 then
return No_Element;
end if;
pragma Assert (Vet (Position), "bad cursor in function Next");
declare
M : Map renames Position.Container.all;
Node : constant Count_Type := HT_Ops.Next (M, Position.Node);
begin
if Node = 0 then
return No_Element;
else
return Cursor'(Position.Container, Node);
end if;
end;
end Next;
procedure Next (Position : in out Cursor) is
begin
Position := Next (Position);
end Next;
function Next
(Object : Iterator;
Position : Cursor) return Cursor
is
begin
if Position.Container = null then
return No_Element;
end if;
if Checks and then Position.Container /= Object.Container then
raise Program_Error with
"Position cursor of Next designates wrong map";
end if;
return Next (Position);
end Next;
----------------------
-- Pseudo_Reference --
----------------------
function Pseudo_Reference
(Container : aliased Map'Class) return Reference_Control_Type
is
TC : constant Tamper_Counts_Access :=
Container.TC'Unrestricted_Access;
begin
return R : constant Reference_Control_Type := (Controlled with TC) do
Lock (TC.all);
end return;
end Pseudo_Reference;
-------------------
-- Query_Element --
-------------------
procedure Query_Element
(Position : Cursor;
Process : not null access
procedure (Key : Key_Type; Element : Element_Type))
is
begin
if Checks and then Position.Node = 0 then
raise Constraint_Error with
"Position cursor of Query_Element equals No_Element";
end if;
pragma Assert (Vet (Position), "bad cursor in Query_Element");
declare
M : Map renames Position.Container.all;
N : Node_Type renames M.Nodes (Position.Node);
Lock : With_Lock (M.TC'Unrestricted_Access);
begin
Process (N.Key, N.Element);
end;
end Query_Element;
----------
-- Read --
----------
procedure Read
(Stream : not null access Root_Stream_Type'Class;
Container : out Map)
is
function Read_Node
(Stream : not null access Root_Stream_Type'Class) return Count_Type;
-- pragma Inline (Read_Node); ???
procedure Read_Nodes is new HT_Ops.Generic_Read (Read_Node);
---------------
-- Read_Node --
---------------
function Read_Node
(Stream : not null access Root_Stream_Type'Class) return Count_Type
is
procedure Read_Element (Node : in out Node_Type);
-- pragma Inline (Read_Element); ???
procedure Allocate is
new HT_Ops.Generic_Allocate (Read_Element);
procedure Read_Element (Node : in out Node_Type) is
begin
Key_Type'Read (Stream, Node.Key);
Element_Type'Read (Stream, Node.Element);
end Read_Element;
Node : Count_Type;
-- Start of processing for Read_Node
begin
Allocate (Container, Node);
return Node;
end Read_Node;
-- Start of processing for Read
begin
Read_Nodes (Stream, Container);
end Read;
procedure Read
(Stream : not null access Root_Stream_Type'Class;
Item : out Cursor)
is
begin
raise Program_Error with "attempt to stream map cursor";
end Read;
procedure Read
(Stream : not null access Root_Stream_Type'Class;
Item : out Reference_Type)
is
begin
raise Program_Error with "attempt to stream reference";
end Read;
procedure Read
(Stream : not null access Root_Stream_Type'Class;
Item : out Constant_Reference_Type)
is
begin
raise Program_Error with "attempt to stream reference";
end Read;
---------------
-- Reference --
---------------
function Reference
(Container : aliased in out Map;
Position : Cursor) return Reference_Type
is
begin
if Checks and then Position.Container = null then
raise Constraint_Error with
"Position cursor has no element";
end if;
if Checks and then Position.Container /= Container'Unrestricted_Access
then
raise Program_Error with
"Position cursor designates wrong map";
end if;
pragma Assert (Vet (Position),
"Position cursor in function Reference is bad");
declare
N : Node_Type renames Container.Nodes (Position.Node);
TC : constant Tamper_Counts_Access :=
Container.TC'Unrestricted_Access;
begin
return R : constant Reference_Type :=
(Element => N.Element'Access,
Control => (Controlled with TC))
do
Lock (TC.all);
end return;
end;
end Reference;
function Reference
(Container : aliased in out Map;
Key : Key_Type) return Reference_Type
is
Node : constant Count_Type := Key_Ops.Find (Container, Key);
begin
if Checks and then Node = 0 then
raise Constraint_Error with "key not in map";
end if;
declare
N : Node_Type renames Container.Nodes (Node);
TC : constant Tamper_Counts_Access :=
Container.TC'Unrestricted_Access;
begin
return R : constant Reference_Type :=
(Element => N.Element'Access,
Control => (Controlled with TC))
do
Lock (TC.all);
end return;
end;
end Reference;
-------------
-- Replace --
-------------
procedure Replace
(Container : in out Map;
Key : Key_Type;
New_Item : Element_Type)
is
Node : constant Count_Type := Key_Ops.Find (Container, Key);
begin
if Checks and then Node = 0 then
raise Constraint_Error with
"attempt to replace key not in map";
end if;
TE_Check (Container.TC);
declare
N : Node_Type renames Container.Nodes (Node);
begin
N.Key := Key;
N.Element := New_Item;
end;
end Replace;
---------------------
-- Replace_Element --
---------------------
procedure Replace_Element
(Container : in out Map;
Position : Cursor;
New_Item : Element_Type)
is
begin
if Checks and then Position.Node = 0 then
raise Constraint_Error with
"Position cursor of Replace_Element equals No_Element";
end if;
if Checks and then Position.Container /= Container'Unrestricted_Access
then
raise Program_Error with
"Position cursor of Replace_Element designates wrong map";
end if;
TE_Check (Position.Container.TC);
pragma Assert (Vet (Position), "bad cursor in Replace_Element");
Container.Nodes (Position.Node).Element := New_Item;
end Replace_Element;
----------------------
-- Reserve_Capacity --
----------------------
procedure Reserve_Capacity
(Container : in out Map;
Capacity : Count_Type)
is
begin
if Checks and then Capacity > Container.Capacity then
raise Capacity_Error with "requested capacity is too large";
end if;
end Reserve_Capacity;
--------------
-- Set_Next --
--------------
procedure Set_Next (Node : in out Node_Type; Next : Count_Type) is
begin
Node.Next := Next;
end Set_Next;
--------------------
-- Update_Element --
--------------------
procedure Update_Element
(Container : in out Map;
Position : Cursor;
Process : not null access procedure (Key : Key_Type;
Element : in out Element_Type))
is
begin
if Checks and then Position.Node = 0 then
raise Constraint_Error with
"Position cursor of Update_Element equals No_Element";
end if;
if Checks and then Position.Container /= Container'Unrestricted_Access
then
raise Program_Error with
"Position cursor of Update_Element designates wrong map";
end if;
pragma Assert (Vet (Position), "bad cursor in Update_Element");
declare
N : Node_Type renames Container.Nodes (Position.Node);
Lock : With_Lock (Container.TC'Unrestricted_Access);
begin
Process (N.Key, N.Element);
end;
end Update_Element;
---------
-- Vet --
---------
function Vet (Position : Cursor) return Boolean is
begin
if Position.Node = 0 then
return Position.Container = null;
end if;
if Position.Container = null then
return False;
end if;
declare
M : Map renames Position.Container.all;
X : Count_Type;
begin
if M.Length = 0 then
return False;
end if;
if M.Capacity = 0 then
return False;
end if;
if M.Buckets'Length = 0 then
return False;
end if;
if Position.Node > M.Capacity then
return False;
end if;
if M.Nodes (Position.Node).Next = Position.Node then
return False;
end if;
X := M.Buckets (Key_Ops.Checked_Index
(M, M.Nodes (Position.Node).Key));
for J in 1 .. M.Length loop
if X = Position.Node then
return True;
end if;
if X = 0 then
return False;
end if;
if X = M.Nodes (X).Next then -- to prevent unnecessary looping
return False;
end if;
X := M.Nodes (X).Next;
end loop;
return False;
end;
end Vet;
-----------
-- Write --
-----------
procedure Write
(Stream : not null access Root_Stream_Type'Class;
Container : Map)
is
procedure Write_Node
(Stream : not null access Root_Stream_Type'Class;
Node : Node_Type);
pragma Inline (Write_Node);
procedure Write_Nodes is new HT_Ops.Generic_Write (Write_Node);
----------------
-- Write_Node --
----------------
procedure Write_Node
(Stream : not null access Root_Stream_Type'Class;
Node : Node_Type)
is
begin
Key_Type'Write (Stream, Node.Key);
Element_Type'Write (Stream, Node.Element);
end Write_Node;
-- Start of processing for Write
begin
Write_Nodes (Stream, Container);
end Write;
procedure Write
(Stream : not null access Root_Stream_Type'Class;
Item : Cursor)
is
begin
raise Program_Error with "attempt to stream map cursor";
end Write;
procedure Write
(Stream : not null access Root_Stream_Type'Class;
Item : Reference_Type)
is
begin
raise Program_Error with "attempt to stream reference";
end Write;
procedure Write
(Stream : not null access Root_Stream_Type'Class;
Item : Constant_Reference_Type)
is
begin
raise Program_Error with "attempt to stream reference";
end Write;
end Ada.Containers.Bounded_Hashed_Maps;
|
-- { dg-do compile }
with pointer_protected_p;
procedure pointer_protected is
Pointer : pointer_protected_p.Ptr := null;
Data : pointer_protected_p.T;
begin
Pointer.all (Data);
end pointer_protected;
|
procedure Real_To_Rational (R: Real;
Bound: Positive;
Nominator: out Integer;
Denominator: out Positive) is
Error: Real;
Best: Positive := 1;
Best_Error: Real := Real'Last;
begin
if R = 0.0 then
Nominator := 0;
Denominator := 1;
return;
elsif R < 0.0 then
Real_To_Rational(-R, Bound, Nominator, Denominator);
Nominator := - Nominator;
return;
else
for I in 1 .. Bound loop
Error := abs(Real(I) * R - Real'Rounding(Real(I) * R));
if Error < Best_Error then
Best := I;
Best_Error := Error;
end if;
end loop;
end if;
Denominator := Best;
Nominator := Integer(Real'Rounding(Real(Denominator) * R));
end Real_To_Rational;
|
-- C49022C.ADA
-- Grant of Unlimited Rights
--
-- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687,
-- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained
-- unlimited rights in the software and documentation contained herein.
-- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making
-- this public release, the Government intends to confer upon all
-- recipients unlimited rights equal to those held by the Government.
-- These rights include rights to use, duplicate, release or disclose the
-- released technical data and computer software in whole or in part, in
-- any manner and for any purpose whatsoever, and to have or permit others
-- to do so.
--
-- DISCLAIMER
--
-- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR
-- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED
-- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE
-- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE
-- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A
-- PARTICULAR PURPOSE OF SAID MATERIAL.
--*
-- CHECK THAT NAMED NUMBER DECLARATIONS (REAL) MAY USE EXPRESSIONS
-- WITH REALS.
-- BAW 29 SEPT 80
-- TBN 10/24/85 RENAMED FROM C4A011A.ADA. ADDED RELATIONAL
-- OPERATORS AND NAMED NUMBERS.
WITH REPORT;
PROCEDURE C49022C IS
USE REPORT;
ADD1 : CONSTANT := 2.5 + 1.5;
ADD2 : CONSTANT := 2.5 + (-1.5);
ADD3 : CONSTANT := (-2.5) + 1.5;
ADD4 : CONSTANT := (-2.5) + (-1.5);
SUB1 : CONSTANT := 2.5 - 1.5;
SUB2 : CONSTANT := 2.5 - (-1.5);
SUB3 : CONSTANT := (-2.5) - 1.5;
SUB4 : CONSTANT := (-2.5) - (-1.5);
MUL1 : CONSTANT := 2.5 * 1.5;
MUL2 : CONSTANT := 2.5 * (-1.5);
MUL3 : CONSTANT := (-2.5) * 1.5;
MUL4 : CONSTANT := (-2.5) * (-1.5);
MLR1 : CONSTANT := 2 * 1.5;
MLR2 : CONSTANT := (-2) * 1.5;
MLR3 : CONSTANT := 2 * (-1.5);
MLR4 : CONSTANT := (-2) * (-1.5);
MLL1 : CONSTANT := 1.5 * 2 ;
MLL2 : CONSTANT := 1.5 * (-2);
MLL3 : CONSTANT :=(-1.5) * 2 ;
MLL4 : CONSTANT :=(-1.5) * (-2);
DIV1 : CONSTANT := 3.75 / 2.5;
DIV2 : CONSTANT := 3.75 / (-2.5);
DIV3 : CONSTANT := (-3.75) / 2.5;
DIV4 : CONSTANT := (-3.75) / (-2.5);
DVI1 : CONSTANT := 3.0 / 2;
DVI2 : CONSTANT := (-3.0) / 2;
DVI3 : CONSTANT := 3.0 / (-2);
DVI4 : CONSTANT := (-3.0) / (-2);
EXP1 : CONSTANT := 2.0 ** 1;
EXP2 : CONSTANT := 2.0 ** (-1);
EXP3 : CONSTANT := (-2.0) ** 1;
EXP4 : CONSTANT := (-2.0) ** (-1);
ABS1 : CONSTANT := ABS( - 3.75 );
ABS2 : CONSTANT := ABS( + 3.75 );
TOT1 : CONSTANT := ADD1 + SUB4 - MUL1 + DIV1 - EXP2 + ABS1;
LES1 : CONSTANT := BOOLEAN'POS (1.5 < 2.0);
LES2 : CONSTANT := BOOLEAN'POS (1.5 < (-2.0));
LES3 : CONSTANT := BOOLEAN'POS ((-1.5) < (-2.0));
LES4 : CONSTANT := BOOLEAN'POS (ADD2 < SUB1);
GRE1 : CONSTANT := BOOLEAN'POS (2.0 > 1.5);
GRE2 : CONSTANT := BOOLEAN'POS ((-2.0) > 1.5);
GRE3 : CONSTANT := BOOLEAN'POS ((-2.0) > (-1.5));
GRE4 : CONSTANT := BOOLEAN'POS (ADD1 > SUB1);
LEQ1 : CONSTANT := BOOLEAN'POS (1.5 <= 2.0);
LEQ2 : CONSTANT := BOOLEAN'POS (1.5 <= (-2.0));
LEQ3 : CONSTANT := BOOLEAN'POS ((-1.5) <= (-2.0));
LEQ4 : CONSTANT := BOOLEAN'POS (ADD2 <= SUB1);
GEQ1 : CONSTANT := BOOLEAN'POS (2.0 >= 1.5);
GEQ2 : CONSTANT := BOOLEAN'POS ((-2.0) >= 1.5);
GEQ3 : CONSTANT := BOOLEAN'POS ((-2.0) >= (-1.5));
GEQ4 : CONSTANT := BOOLEAN'POS (ADD1 >= SUB2);
EQU1 : CONSTANT := BOOLEAN'POS (1.5 = 2.0);
EQU2 : CONSTANT := BOOLEAN'POS ((-1.5) = 2.0);
EQU3 : CONSTANT := BOOLEAN'POS ((-1.5) = (-1.5));
EQU4 : CONSTANT := BOOLEAN'POS (ADD1 = SUB2);
NEQ1 : CONSTANT := BOOLEAN'POS (1.5 /= 1.5);
NEQ2 : CONSTANT := BOOLEAN'POS ((-1.5) /= 1.5);
NEQ3 : CONSTANT := BOOLEAN'POS ((-1.5) /= (-2.0));
NEQ4 : CONSTANT := BOOLEAN'POS (ADD1 /= SUB2);
BEGIN
TEST("C49022C","CHECK THAT NAMED NUMBER DECLARATIONS (REAL) " &
"MAY USE EXPRESSIONS WITH REALS.");
IF ADD1 /= 4.0 OR ADD2 /= 1.0 OR ADD3 /= -1.0 OR ADD4 /= -4.0 THEN
FAILED("ERROR IN THE ADDING OPERATOR +");
END IF;
IF SUB1 /= 1.0 OR SUB2 /= 4.0 OR SUB3 /= -4.0 OR SUB4 /= -1.0 THEN
FAILED("ERROR IN THE ADDING OPERATOR -");
END IF;
IF MUL1 /= 3.75 OR MUL2 /= -3.75 OR
MUL3 /= -3.75 OR MUL4 /= 3.75 THEN
FAILED("ERROR IN THE MULTIPLYING OPERATOR *");
END IF;
IF MLR1 /= 3.0 OR MLR2 /= -3.0 OR
MLR3 /= -3.0 OR MLR4 /= 3.0 THEN
FAILED("ERROR IN THE MULTIPLYING OPERATOR *");
END IF;
IF MLL1 /= 3.0 OR MLL2 /= -3.0 OR MLL3 /= -3.0 OR MLL4 /= 3.0 THEN
FAILED("ERROR IN THE MULTIPLYING OPERATOR *");
END IF;
IF DIV1 /= 1.5 OR DIV2 /= -1.5 OR DIV3 /= -1.5 OR DIV4 /= 1.5 THEN
FAILED("ERROR IN THE MULTIPLYING OPERATOR /");
END IF;
IF DVI1 /= 1.5 OR DVI2 /= -1.5 OR DVI3 /= -1.5 OR DVI4 /= 1.5 THEN
FAILED("ERROR IN THE MULTIPLYING OPERATOR /");
END IF;
IF EXP1 /= 2.0 OR EXP2 /= 0.5 OR EXP3 /= -2.0 OR EXP4 /= -0.5 THEN
FAILED("ERROR IN THE EXPONENTIATING OPERATOR");
END IF;
IF ABS1 /= 3.75 OR ABS2 /= 3.75 THEN
FAILED("ERROR IN THE ABS OPERATOR");
END IF;
IF TOT1 /= 4.00 THEN
FAILED("ERROR IN USE OF NAMED NUMBERS WITH OPERATORS");
END IF;
IF LES1 /= 1 OR LES2 /= 0 OR LES3 /= 0 OR LES4 /= 0 THEN
FAILED("ERROR IN THE LESS THAN OPERATOR");
END IF;
IF GRE1 /= 1 OR GRE2 /= 0 OR GRE3 /= 0 OR GRE4 /= 1 THEN
FAILED("ERROR IN THE GREATER THAN OPERATOR");
END IF;
IF LEQ1 /= 1 OR LEQ2 /= 0 OR LEQ3 /= 0 OR LEQ4 /= 1 THEN
FAILED("ERROR IN THE LESS THAN EQUAL OPERATOR");
END IF;
IF GEQ1 /= 1 OR GEQ2 /= 0 OR GEQ3 /= 0 OR GEQ4 /= 1 THEN
FAILED("ERROR IN THE GREATER THAN EQUAL OPERATOR");
END IF;
IF EQU1 /= 0 OR EQU2 /= 0 OR EQU3 /= 1 OR EQU4 /= 1 THEN
FAILED("ERROR IN THE EQUAL OPERATOR");
END IF;
IF NEQ1 /= 0 OR NEQ2 /= 1 OR NEQ3 /= 1 OR NEQ4 /= 0 THEN
FAILED("ERROR IN THE NOT EQUAL OPERATOR");
END IF;
RESULT;
END C49022C;
|
-- Copyright 2016, 2017 Steven Stewart-Gallus
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-- implied. See the License for the specific language governing
-- permissions and limitations under the License.
with Interfaces;
with Interfaces.C;
with System;
with System.Storage_Elements;
with Linted.Errors;
with Linted.Reader;
with Linted.Stack;
package body Linted.Window_Notifier is
package C renames Interfaces.C;
package Storage_Elements renames System.Storage_Elements;
use type C.int;
use type C.size_t;
use type Interfaces.Unsigned_32;
use type Interfaces.Unsigned_8;
use type Storage_Elements.Storage_Element;
use type Storage_Elements.Storage_Offset;
use type Errors.Error;
type Live_Future is new Future range 1 .. Future'Last with
Default_Value => 1;
Read_Futures : array (Live_Future) of Reader.Future with
Independent_Components;
Data_Being_Read : array
(Live_Future) of aliased Storage_Elements.Storage_Array (1 .. 1) :=
(others => (others => 16#7F#)) with
Independent_Components;
type Ix is mod Max_Nodes + 2;
function Is_Valid (Element : Live_Future) return Boolean is (True);
package Spare_Futures is new Stack (Live_Future, Ix, Is_Valid);
function Is_Live (F : Future) return Boolean is (F /= 0);
procedure Read
(Object : KOs.KO;
Signaller : Triggers.Signaller;
F : out Future) with
Spark_Mode => Off is
Live : Live_Future;
begin
Spare_Futures.Pop (Live);
Reader.Read
(Object,
Data_Being_Read (Live) (1)'Address,
1,
Signaller,
Read_Futures (Live));
F := Future (Live);
end Read;
procedure Read_Wait (F : in out Future) is
R_Event : Reader.Event;
Live : Live_Future := Live_Future (F);
begin
Reader.Read_Wait (Read_Futures (Live), R_Event);
pragma Assert (R_Event.Err = Errors.Success);
Spare_Futures.Push (Live);
F := 0;
end Read_Wait;
procedure Read_Poll (F : in out Future; Init : out Boolean) is
R_Event : Reader.Event;
Live : Live_Future := Live_Future (F);
begin
Reader.Read_Poll (Read_Futures (Live), R_Event, Init);
if Init then
pragma Assert (R_Event.Err = Errors.Success);
Spare_Futures.Push (Live);
F := 0;
end if;
end Read_Poll;
begin
for II in 1 .. Max_Nodes loop
Spare_Futures.Push (Live_Future (Future (II)));
end loop;
end Linted.Window_Notifier;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- G N A T . A R R A Y _ S P L I T --
-- --
-- S p e c --
-- --
-- Copyright (C) 2002-2020, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- Useful array-manipulation routines: given a set of separators, split
-- an array wherever the separators appear, and provide direct access
-- to the resulting slices.
with Ada.Finalization;
generic
type Element is (<>);
-- Element of the array, this must be a discrete type
type Element_Sequence is array (Positive range <>) of Element;
-- The array which is a sequence of element
type Element_Set is private;
-- This type represent a set of elements. This set does not define a
-- specific order of the elements. The conversion of a sequence to a
-- set and membership tests in the set is performed using the routines
-- To_Set and Is_In defined below.
with function To_Set (Sequence : Element_Sequence) return Element_Set;
-- Returns an Element_Set given an Element_Sequence. Duplicate elements
-- can be ignored during this conversion.
with function Is_In (Item : Element; Set : Element_Set) return Boolean;
-- Returns True if Item is found in Set, False otherwise
package GNAT.Array_Split is
pragma Preelaborate;
Index_Error : exception;
-- Raised by all operations below if Index > Field_Count (S)
type Separator_Mode is
(Single,
-- In this mode the array is cut at each element in the separator
-- set. If two separators are contiguous the result at that position
-- is an empty slice.
Multiple
-- In this mode contiguous separators are handled as a single
-- separator and no empty slice is created.
);
type Slice_Set is private
with Iterable => (First => First_Cursor,
Next => Advance,
Has_Element => Has_Element,
Element => Slice);
-- This type uses by-reference semantics. This is a set of slices as
-- returned by Create or Set routines below. The abstraction represents
-- a set of items. Each item is a part of the original array named a
-- Slice. It is possible to access individual slices by using the Slice
-- routine below. The first slice in the Set is at the position/index
-- 1. The total number of slices in the set is returned by Slice_Count.
procedure Create
(S : out Slice_Set;
From : Element_Sequence;
Separators : Element_Sequence;
Mode : Separator_Mode := Single);
function Create
(From : Element_Sequence;
Separators : Element_Sequence;
Mode : Separator_Mode := Single) return Slice_Set;
-- Create a cut array object. From is the source array, and Separators
-- is a sequence of Element along which to split the array. The source
-- array is sliced at separator boundaries. The separators are not
-- included as part of the resulting slices.
--
-- Note that if From is terminated by a separator an extra empty element
-- is added to the slice set. If From only contains a separator the slice
-- set contains two empty elements.
procedure Create
(S : out Slice_Set;
From : Element_Sequence;
Separators : Element_Set;
Mode : Separator_Mode := Single);
function Create
(From : Element_Sequence;
Separators : Element_Set;
Mode : Separator_Mode := Single) return Slice_Set;
-- Same as above but using a Element_Set
procedure Set
(S : in out Slice_Set;
Separators : Element_Sequence;
Mode : Separator_Mode := Single);
-- Change the set of separators. The source array will be split according
-- to this new set of separators.
procedure Set
(S : in out Slice_Set;
Separators : Element_Set;
Mode : Separator_Mode := Single);
-- Same as above but using a Element_Set
type Slice_Number is new Natural;
-- Type used to count number of slices
function Slice_Count (S : Slice_Set) return Slice_Number with Inline;
-- Returns the number of slices (fields) in S
function First_Cursor (Unused : Slice_Set) return Slice_Number is (1);
function Advance
(Unused : Slice_Set; Position : Slice_Number) return Slice_Number
is (Position + 1);
function Has_Element
(Cont : Slice_Set; Position : Slice_Number) return Boolean
is (Position <= Slice_Count (Cont));
-- Functions used to iterate over a Slice_Set
function Slice
(S : Slice_Set;
Index : Slice_Number) return Element_Sequence with Inline;
-- Returns the slice at position Index. First slice is 1. If Index is 0
-- the whole array is returned including the separators (this is the
-- original source array).
type Position is (Before, After);
-- Used to designate position of separator
type Slice_Separators is array (Position) of Element;
-- Separators found before and after the slice
Array_End : constant Element;
-- This is the separator returned for the start or the end of the array
function Separators
(S : Slice_Set;
Index : Slice_Number) return Slice_Separators;
-- Returns the separators used to slice (front and back) the slice at
-- position Index. For slices at start and end of the original array, the
-- Array_End value is returned for the corresponding outer bound. In
-- Multiple mode only the element closest to the slice is returned.
-- if Index = 0, returns (Array_End, Array_End).
type Separators_Indexes is array (Positive range <>) of Positive;
function Separators (S : Slice_Set) return Separators_Indexes;
-- Returns indexes of all separators used to slice original source array S
private
Array_End : constant Element := Element'First;
type Element_Access is access Element_Sequence;
type Indexes_Access is access Separators_Indexes;
type Slice_Info is record
Start : Positive;
Stop : Natural;
end record;
-- Starting/Ending position of a slice. This does not include separators
type Slices_Indexes is array (Slice_Number range <>) of Slice_Info;
type Slices_Access is access Slices_Indexes;
-- All indexes for fast access to slices. In the Slice_Set we keep only
-- the original array and the indexes where each slice start and stop.
type Data is record
Ref_Counter : Natural; -- Reference counter, by-address sem
Source : Element_Access;
N_Slice : Slice_Number := 0; -- Number of slices found
Indexes : Indexes_Access;
Slices : Slices_Access;
end record;
type Data_Access is access all Data;
type Slice_Set is new Ada.Finalization.Controlled with record
D : Data_Access;
end record;
overriding procedure Initialize (S : in out Slice_Set);
overriding procedure Adjust (S : in out Slice_Set);
overriding procedure Finalize (S : in out Slice_Set);
end GNAT.Array_Split;
|
with Protypo.Api.Engine_Values.Handlers;
with Protypo.Api.Engine_Values.Parameter_Lists;
private package Protypo.Code_Trees.Interpreter.Compiled_Functions is
-- type Compiled_Function is
-- new Api.Engine_Values.Function_Interface
-- with
-- private;
type Compiled_Function is
new Api.Engine_Values.handlers.Function_Interface
with
record
Function_Body : Node_Vectors.Vector;
Parameters : Parameter_Specs;
Status : Interpreter_Access;
end record;
overriding function Process (Fun : Compiled_Function;
Parameter : Engine_Value_vectors.Vector)
return Engine_Value_vectors.Vector;
overriding function Signature (Fun : Compiled_Function)
return Api.Engine_Values.Parameter_Lists.Parameter_Signature;
-- function Create (Function_Body : Node_Vectors.Vector) return Integer;
end Protypo.Code_Trees.Interpreter.Compiled_Functions;
|
with STM32.Board; use STM32.Board;
with HAL.Touch_Panel; use HAL.Touch_Panel;
package body Inputs is
procedure Update_Pressed_Keys(Keys : in out Keys_List) is
State : constant TP_State := Touch_Panel.Get_All_Touch_Points;
begin
for I in State'First .. State'Last loop
if State(I).X >= Position_X'First then
Keys(Get_Key(State(I).X, Position_Y'Last - State(I).Y)) := True;
end if;
end loop;
end Update_Pressed_Keys;
function Get_Key(X : Position_X; Y : Position_Y) return Integer is
begin
return Layout((X - Position_X'First) / 40, Y / 40);
end Get_Key;
end Inputs;
|
-------------------------------------------------------------------------------
-- Copyright (C) 2020-2030, per.s.sandberg@bahnhof.se --
-- --
-- Permission is hereby granted, free of charge, to any person obtaining a --
-- copy of this software and associated documentation files --
-- (the "Software"), to deal in the Software without restriction, including --
-- without limitation the rights to use, copy, modify, merge, publish, --
-- distribute, sublicense, and / or sell copies of the Software, and to --
-- permit persons to whom the Software is furnished to do so, subject to --
-- the following conditions : --
-- --
-- The above copyright notice and this permission notice shall be included --
-- in all copies or substantial portions of the Software. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS --
-- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF --
-- MERCHANTABILITY, --
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL --
-- THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR --
-- OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, --
-- ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR --
-- OTHER DEALINGS IN THE SOFTWARE. --
-------------------------------------------------------------------------------
with ZMQ.Sockets;
with ZMQ.Contexts;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with ZMQ.Proxys;
procedure ZMQ.Examples.Multi_Thread_Server is
task type Server_Task (Ctx : not null access ZMQ.Contexts.Context;
Id : Integer) is
end Server_Task;
type Server_Task_Access is access all Server_Task;
task body Server_Task is
Msg : Ada.Strings.Unbounded.Unbounded_String;
S : ZMQ.Sockets.Socket;
begin
S.Initialize (Ctx.all, Sockets.REP);
S.Connect ("inproc://workers");
loop
Msg := S.Recv;
Append (Msg, "<Served by thread:" & Id'Img & ">");
S.Send (Msg);
end loop;
end Server_Task;
Ctx : aliased ZMQ.Contexts.Context;
Number_Of_Servers : constant := 10;
Servers : array (1 .. Number_Of_Servers) of Server_Task_Access;
Workers : aliased ZMQ.Sockets.Socket;
Clients : aliased ZMQ.Sockets.Socket;
begin
-- Initialise 0MQ context, requesting a single application thread
-- and a single I/O thread
Ctx.Set_Number_Of_IO_Threads (Servers'Length + 1);
-- Create a ZMQ_REP socket to receive requests and send replies
Workers.Initialize (Ctx, Sockets.ROUTER);
Workers.Bind ("tcp://lo:5555");
-- Bind to the TCP transport and port 5555 on the 'lo' interface
Clients.Initialize (Ctx, Sockets.DEALER);
Clients.Bind ("inproc://workers");
for I in Servers'Range loop
Servers (I) := new Server_Task (Ctx'Access, I);
end loop;
ZMQ.Proxys.Proxy (Frontend => Clients'Access,
Backend => Workers'Access);
end ZMQ.Examples.Multi_Thread_Server;
|
with Ada.Text_IO, Ada.Integer_Text_IO;
use Ada;
procedure Solution is
begin
Ada.Text_IO.Put_Line("Hello-world");
end Solution;
--thank in advance for hackerank XD |
with ZMQ.Sockets;
with AVTAS.LMCP.Factory;
with UxAS.Comms.Transport.ZeroMQ_Socket_Configurations;
use UxAS.Comms.Transport.ZeroMQ_Socket_Configurations;
with UxAS.Comms.Transport.Network_Name;
with UxAS.Common.String_Constant.Lmcp_Network_Socket_Address;
use UxAS.Common.String_Constant.Lmcp_Network_Socket_Address;
with AVTAS.LMCP.ByteBuffers; use AVTAS.LMCP.ByteBuffers;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
package body UxAS.Comms.LMCP_Object_Message_Receiver_Pipes is
procedure Initialize_Zmq_Socket
(This : in out LMCP_Object_Message_Receiver_Pipe;
Entity_Id : UInt32;
Service_Id : UInt32;
Zmq_SocketType : ZMQ.Sockets.Socket_Type;
Socket_Address : String;
Is_Server : Boolean);
---------------------
-- Initialize_Pull --
---------------------
procedure Initialize_Pull
(This : in out LMCP_Object_Message_Receiver_Pipe;
Entity_Id : UInt32;
Service_Id : UInt32)
is
begin
Initialize_Zmq_Socket
(This,
Entity_Id => Entity_Id,
Service_Id => Service_Id,
Zmq_SocketType => ZMQ.Sockets.PULL,
Socket_Address => To_String (InProc_To_MessageHub),
Is_Server => True);
end Initialize_Pull;
--------------------------------------
-- Initialize_External_Subscription --
--------------------------------------
procedure Initialize_External_Subscription
(This : in out LMCP_Object_Message_Receiver_Pipe;
Entity_Id : UInt32;
Service_Id : UInt32;
External_Socket_Address : String;
Is_Server : Boolean)
is
begin
Initialize_Zmq_Socket
(This,
Entity_Id => Entity_Id,
Service_Id => Service_Id,
Zmq_SocketType => ZMQ.Sockets.SUB,
Socket_Address => External_Socket_Address,
Is_Server => Is_Server);
end Initialize_External_Subscription;
------------------------------
-- Initialize_External_Pull --
------------------------------
procedure Initialize_External_Pull
(This : in out LMCP_Object_Message_Receiver_Pipe;
Entity_Id : UInt32;
Service_Id : UInt32;
External_Socket_Address : String;
Is_Server : Boolean)
is
begin
Initialize_Zmq_Socket
(This,
Entity_Id => Entity_Id,
Service_Id => Service_Id,
Zmq_SocketType => ZMQ.Sockets.PULL,
Socket_Address => External_Socket_Address,
Is_Server => Is_Server);
end Initialize_External_Pull;
-----------------------------
-- Initialize_Subscription --
-----------------------------
procedure Initialize_Subscription
(This : in out LMCP_Object_Message_Receiver_Pipe;
Entity_Id : UInt32;
Service_Id : UInt32)
is
begin
Initialize_Zmq_Socket
(This,
Entity_Id => Entity_Id,
Service_Id => Service_Id,
Zmq_SocketType => ZMQ.Sockets.SUB,
Socket_Address => To_String (InProc_From_MessageHub),
Is_Server => False);
end Initialize_Subscription;
-----------------------
-- Initialize_Stream --
-----------------------
procedure Initialize_Stream
(This : in out LMCP_Object_Message_Receiver_Pipe;
Entity_Id : UInt32;
Service_Id : UInt32;
Socket_Address : String;
Is_Server : Boolean)
is
begin
Initialize_Zmq_Socket
(This,
Entity_Id => Entity_Id,
Service_Id => Service_Id,
Zmq_SocketType => ZMQ.Sockets.STREAM,
Socket_Address => Socket_Address,
Is_Server => Is_Server);
end Initialize_Stream;
------------------------------------------
-- Add_Lmcp_Object_Subscription_Address --
------------------------------------------
procedure Add_Lmcp_Object_Subscription_Address
(This : in out LMCP_Object_Message_Receiver_Pipe;
Address : String;
Result : out Boolean)
is
begin
This.Receiver.Add_Subscription_Address (Address, Result);
end Add_Lmcp_Object_Subscription_Address;
---------------------------------------------
-- Remove_Lmcp_Object_Subscription_Address --
---------------------------------------------
procedure Remove_Lmcp_Object_Subscription_Address
(This : in out LMCP_Object_Message_Receiver_Pipe;
Address : String;
Result : out Boolean)
is
begin
This.Receiver.Remove_Subscription_Address (Address, Result);
end Remove_Lmcp_Object_Subscription_Address;
-------------------------------------------------
-- Remove_All_Lmcp_Object_Subscription_Address --
-------------------------------------------------
procedure Remove_All_Lmcp_Object_Subscription_Address
(This : in out LMCP_Object_Message_Receiver_Pipe;
Result : out Boolean)
is
begin
This.Receiver.Remove_All_Subscription_Addresses (Result);
end Remove_All_Lmcp_Object_Subscription_Address;
-----------------------------
-- Get_Next_Message_Object --
-----------------------------
procedure Get_Next_Message_Object
(This : in out LMCP_Object_Message_Receiver_Pipe;
Message : out Any_LMCP_Message)
is
Next_Message : Addressed_Attributed_Message_Ref;
Object : AVTAS.LMCP.Object.Object_Any;
begin
This.Receiver.Get_Next_Message (Next_Message);
if Next_Message /= null then
Deserialize_Message (This, Next_Message.Payload, Object);
if Object /= null then
Message := new LMCP_Message'(Attributes => Next_Message.Message_Attributes_Ownership,
Payload => Object);
else
Message := null;
end if;
else
Message := null;
end if;
end Get_Next_Message_Object;
---------------------------------
-- Get_Next_Serialized_Message --
---------------------------------
procedure Get_Next_Serialized_Message
(This : in out LMCP_Object_Message_Receiver_Pipe;
Message : out Addressed_Attributed_Message_Ref)
is
begin
This.Receiver.Get_Next_Message (Message);
end Get_Next_Serialized_Message;
-------------------------
-- Deserialize_Message --
-------------------------
procedure Deserialize_Message
(This : in out LMCP_Object_Message_Receiver_Pipe;
Payload : String;
Message : out not null AVTAS.LMCP.Object.Object_Any)
is
pragma Unreferenced (This);
Buffer : ByteBuffer (Payload'Length);
begin
Buffer.Put_Raw_Bytes (Payload);
Buffer.Rewind;
AVTAS.LMCP.Factory.getObject (Buffer, Message);
end Deserialize_Message;
---------------
-- Entity_Id --
---------------
function Entity_Id (This : LMCP_Object_Message_Receiver_Pipe) return UInt32 is
(This.Entity_Id);
----------------
-- Service_Id --
----------------
function Service_Id (This : LMCP_Object_Message_Receiver_Pipe) return UInt32 is
(This.Service_Id);
---------------------------
-- Initialize_Zmq_Socket --
---------------------------
procedure Initialize_Zmq_Socket
(This : in out LMCP_Object_Message_Receiver_Pipe;
Entity_Id : UInt32;
Service_Id : UInt32;
Zmq_SocketType : ZMQ.Sockets.Socket_Type;
Socket_Address : String;
Is_Server : Boolean)
is
Zmq_High_Water_Mark : constant Int32 := 100_000;
Configuration : constant ZeroMq_Socket_Configuration := Make
(Network_Name => UxAS.Comms.Transport.Network_Name.ZmqLmcpNetwork,
Socket_Address => Socket_Address,
Zmq_Socket_Type => Zmq_SocketType,
Number_Of_IO_Threads => 1,
Is_Server_Bind => Is_Server,
Is_Receive => True,
Receive_High_Water_Mark => Zmq_High_Water_Mark,
Send_High_Water_Mark => Zmq_High_Water_Mark);
begin
This.Entity_Id := Entity_Id;
This.Service_Id := Service_Id;
This.Receiver := new ZeroMq_Addressed_Attributed_Message_Receiver;
This.Receiver.Initialize (Entity_Id, Service_Id, Configuration);
end Initialize_Zmq_Socket;
end UxAS.Comms.LMCP_Object_Message_Receiver_Pipes;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Localization, Internationalization, Globalization for Ada --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2012-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$
------------------------------------------------------------------------------
pragma Restrictions (No_Elaboration_Code);
-- GNAT: enforce generation of preinitialized data section instead of
-- generation of elaboration code.
package Matreshka.Internals.Unicode.Ucd.Core_002E is
pragma Preelaborate;
Group_002E : aliased constant Core_Second_Stage
:= (16#00# .. 16#01# => -- 2E00 .. 2E01
(Other_Punctuation, Neutral,
Other, Other, Close, Quotation,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#02# => -- 2E02
(Initial_Punctuation, Neutral,
Other, Other, Close, Quotation,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#03# => -- 2E03
(Final_Punctuation, Neutral,
Other, Other, Close, Quotation,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#04# => -- 2E04
(Initial_Punctuation, Neutral,
Other, Other, Close, Quotation,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#05# => -- 2E05
(Final_Punctuation, Neutral,
Other, Other, Close, Quotation,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#06# .. 16#08# => -- 2E06 .. 2E08
(Other_Punctuation, Neutral,
Other, Other, Close, Quotation,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#09# => -- 2E09
(Initial_Punctuation, Neutral,
Other, Other, Close, Quotation,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#0A# => -- 2E0A
(Final_Punctuation, Neutral,
Other, Other, Close, Quotation,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#0B# => -- 2E0B
(Other_Punctuation, Neutral,
Other, Other, Close, Quotation,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#0C# => -- 2E0C
(Initial_Punctuation, Neutral,
Other, Other, Close, Quotation,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#0D# => -- 2E0D
(Final_Punctuation, Neutral,
Other, Other, Close, Quotation,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#0E# .. 16#15# => -- 2E0E .. 2E15
(Other_Punctuation, Neutral,
Other, Other, Other, Break_After,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#16# => -- 2E16
(Other_Punctuation, Neutral,
Other, Other, Other, Alphabetic,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#17# => -- 2E17
(Dash_Punctuation, Neutral,
Other, Other, Other, Break_After,
(Dash
| Hyphen
| Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#18# => -- 2E18
(Other_Punctuation, Neutral,
Other, Other, Other, Open_Punctuation,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#19# => -- 2E19
(Other_Punctuation, Neutral,
Other, Other, Other, Break_After,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#1A# => -- 2E1A
(Dash_Punctuation, Neutral,
Other, Other, Other, Alphabetic,
(Dash
| Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#1B# => -- 2E1B
(Other_Punctuation, Neutral,
Other, Other, Other, Alphabetic,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#1C# => -- 2E1C
(Initial_Punctuation, Neutral,
Other, Other, Close, Quotation,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#1D# => -- 2E1D
(Final_Punctuation, Neutral,
Other, Other, Close, Quotation,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#1E# .. 16#1F# => -- 2E1E .. 2E1F
(Other_Punctuation, Neutral,
Other, Other, Other, Alphabetic,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#20# => -- 2E20
(Initial_Punctuation, Neutral,
Other, Other, Close, Quotation,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#21# => -- 2E21
(Final_Punctuation, Neutral,
Other, Other, Close, Quotation,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#22# => -- 2E22
(Open_Punctuation, Neutral,
Other, Other, Close, Open_Punctuation,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#23# => -- 2E23
(Close_Punctuation, Neutral,
Other, Other, Close, Close_Punctuation,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#24# => -- 2E24
(Open_Punctuation, Neutral,
Other, Other, Close, Open_Punctuation,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#25# => -- 2E25
(Close_Punctuation, Neutral,
Other, Other, Close, Close_Punctuation,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#26# => -- 2E26
(Open_Punctuation, Neutral,
Other, Other, Close, Open_Punctuation,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#27# => -- 2E27
(Close_Punctuation, Neutral,
Other, Other, Close, Close_Punctuation,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#28# => -- 2E28
(Open_Punctuation, Neutral,
Other, Other, Close, Open_Punctuation,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#29# => -- 2E29
(Close_Punctuation, Neutral,
Other, Other, Close, Close_Punctuation,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#2A# .. 16#2D# => -- 2E2A .. 2E2D
(Other_Punctuation, Neutral,
Other, Other, Other, Break_After,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#2E# => -- 2E2E
(Other_Punctuation, Neutral,
Other, Other, S_Term, Exclamation,
(Pattern_Syntax
| STerm
| Terminal_Punctuation
| Grapheme_Base => True,
others => False)),
16#2F# => -- 2E2F
(Modifier_Letter, Neutral,
Other, A_Letter, O_Letter, Alphabetic,
(Diacritic
| Pattern_Syntax
| Alphabetic
| Case_Ignorable
| Grapheme_Base => True,
others => False)),
16#30# .. 16#31# => -- 2E30 .. 2E31
(Other_Punctuation, Neutral,
Other, Other, Other, Break_After,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#32# => -- 2E32
(Other_Punctuation, Neutral,
Other, Other, Other, Alphabetic,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#33# .. 16#34# => -- 2E33 .. 2E34
(Other_Punctuation, Neutral,
Other, Other, Other, Break_After,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#35# .. 16#39# => -- 2E35 .. 2E39
(Other_Punctuation, Neutral,
Other, Other, Other, Alphabetic,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#3A# .. 16#3B# => -- 2E3A .. 2E3B
(Dash_Punctuation, Neutral,
Other, Other, Other, Break_Both,
(Dash
| Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#3C# => -- 2E3C
(Other_Punctuation, Neutral,
Other, Other, S_Term, Break_After,
(Pattern_Syntax
| STerm
| Terminal_Punctuation
| Grapheme_Base => True,
others => False)),
16#3D# .. 16#3E# => -- 2E3D .. 2E3E
(Other_Punctuation, Neutral,
Other, Other, Other, Break_After,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#3F# => -- 2E3F
(Other_Punctuation, Neutral,
Other, Other, Other, Alphabetic,
(Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#40# => -- 2E40
(Dash_Punctuation, Neutral,
Other, Other, Other, Break_After,
(Dash
| Pattern_Syntax
| Grapheme_Base => True,
others => False)),
16#41# => -- 2E41
(Other_Punctuation, Neutral,
Other, Other, Other, Break_After,
(Pattern_Syntax
| Terminal_Punctuation
| Grapheme_Base => True,
others => False)),
16#42# => -- 2E42
(Open_Punctuation, Neutral,
Other, Other, Close, Open_Punctuation,
(Pattern_Syntax
| Quotation_Mark
| Grapheme_Base => True,
others => False)),
16#43# .. 16#7F# => -- 2E43 .. 2E7F
(Unassigned, Neutral,
Other, Other, Other, Unknown,
(Pattern_Syntax => True,
others => False)),
16#9A# => -- 2E9A
(Unassigned, Neutral,
Other, Other, Other, Unknown,
(others => False)),
16#9F# => -- 2E9F
(Other_Symbol, Wide,
Other, Other, Other, Ideographic,
(Radical
| Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#F3# => -- 2EF3
(Other_Symbol, Wide,
Other, Other, Other, Ideographic,
(Radical
| Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#F4# .. 16#FF# => -- 2EF4 .. 2EFF
(Unassigned, Neutral,
Other, Other, Other, Unknown,
(others => False)),
others =>
(Other_Symbol, Wide,
Other, Other, Other, Ideographic,
(Radical
| Grapheme_Base => True,
others => False)));
end Matreshka.Internals.Unicode.Ucd.Core_002E;
|
-- MIT License
--
-- Copyright (c) 2021 Glen Cornell <glen.m.cornell@gmail.com>
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
with Interfaces.C;
with Sockets.Can_Bcm_Thin;
with Gnat.Sockets;
package body Sockets.Can.Broadcast_Manager is
use type Sockets.Can_Bcm_Thin.Flag_Type;
type Msg_Type is record
Msg_Head : aliased Sockets.Can_Bcm_Thin.Bcm_Msg_Head;
Frame : aliased Sockets.Can_Frame.Can_Frame;
end record;
pragma Convention (C_Pass_By_Copy, Msg_Type);
procedure Create (This: out Broadcast_Manager_Type;
Interface_Name : in String) is
begin
Sockets.Can.Create_Socket(This.Socket,
Sockets.Can.Family_Can,
Sockets.Can.Socket_Dgram,
Sockets.Can.Can_Bcm);
This.Address.If_Index := If_Name_To_Index(Interface_Name);
Sockets.Can.Connect_Socket(This.Socket, This.Address);
end Create;
function Get_Socket (This : in Broadcast_Manager_Type) return Sockets.Can.Socket_Type is
begin
return This.Socket;
end Get_Socket;
function To_Timeval (D : in Duration) return Sockets.Can_Bcm_Thin.Timeval is
pragma Unsuppress (Overflow_Check);
Secs : Duration;
Micro_Secs : Duration;
Micro : constant := 1_000_000;
Rval : Sockets.Can_Bcm_Thin.Timeval;
begin
-- Seconds extraction, avoid potential rounding errors
Secs := D - 0.5;
Rval.tv_sec := Interfaces.C.Long (Secs);
-- Microseconds extraction
Micro_Secs := D - Duration (Rval.tv_sec);
Rval.tv_usec := Interfaces.C.Long (Micro_Secs * Micro);
return Rval;
end To_Timeval;
procedure Send_Socket (Socket : Sockets.Can.Socket_Type;
Item : aliased Msg_Type) is
Sizeof_Item : constant Integer := (Msg_Type'Size + 7) / 8;
Buf : aliased Ada.Streams.Stream_Element_Array (1 .. Ada.Streams.Stream_Element_Offset(Sizeof_Item));
for Buf'Address use Item'Address;
pragma Import (Ada, Buf);
Unused_Last : Ada.Streams.Stream_Element_Offset;
begin
Gnat.Sockets.Send_Socket(Socket, Buf, Unused_Last);
end Send_Socket;
procedure Receive_Socket
(Socket : Sockets.Can.Socket_Type;
Item : aliased out Msg_Type) is
Sizeof_Item : constant Integer := (Msg_Type'Size + 7) / 8;
Buf : aliased Ada.Streams.Stream_Element_Array (1 .. Ada.Streams.Stream_Element_Offset(Sizeof_Item));
for Buf'Address use Item'Address;
pragma Import (Ada, Buf);
Unused_Last : Ada.Streams.Stream_Element_Offset;
begin
Gnat.Sockets.Receive_Socket(Socket, Buf, Unused_Last);
end Receive_Socket;
procedure Send_Periodic (This : in Broadcast_Manager_Type;
Item : in Sockets.Can_Frame.Can_Frame;
Interval : in Duration) is
Msg : aliased constant Msg_Type :=
(Msg_Head => (Opcode => Sockets.Can_Bcm_Thin.Tx_Setup,
Flags => Sockets.Can_Bcm_Thin.SETTIMER or
Sockets.Can_Bcm_Thin.STARTTIMER,
Count => 0,
Ival1 => (Tv_Sec => 0, Tv_Usec => 0),
Ival2 => To_Timeval (Interval),
Can_Id => Item.Can_Id,
Nframes => 1),
Frame => Item);
begin
Send_Socket(This.Socket, Msg);
end Send_Periodic;
procedure Send_Once (This : in Broadcast_Manager_Type;
Item : in Sockets.Can_Frame.Can_Frame) is
Msg : aliased constant Msg_Type :=
(Msg_Head => (Opcode => Sockets.Can_Bcm_Thin.Tx_Send,
Flags => 0,
Count => 0,
Ival1 => (Tv_Sec => 0, Tv_Usec => 0),
Ival2 => (Tv_Sec => 0, Tv_Usec => 0),
Can_Id => Item.Can_Id,
Nframes => 1),
Frame => Item);
begin
Send_Socket(This.Socket, Msg);
end Send_Once;
procedure Update_Periodic (This : in Broadcast_Manager_Type;
Item : in Sockets.Can_Frame.Can_Frame) is
Msg : aliased constant Msg_Type :=
(Msg_Head => (Opcode => Sockets.Can_Bcm_Thin.Tx_Setup,
Flags => 0,
Count => 0,
Ival1 => (Tv_Sec => 0, Tv_Usec => 0),
Ival2 => (Tv_Sec => 0, Tv_Usec => 0),
Can_Id => Item.Can_Id,
Nframes => 1),
Frame => Item);
begin
Send_Socket(This.Socket, Msg);
end Update_Periodic;
procedure Stop_Periodic (This : in Broadcast_Manager_Type;
Can_Id : in Sockets.Can_Frame.Can_Id_Type) is
Msg : aliased constant Msg_Type :=
(Msg_Head => (Opcode => Sockets.Can_Bcm_Thin.Tx_Delete,
Flags => 0,
Count => 0,
Ival1 => (Tv_Sec => 0, Tv_Usec => 0),
Ival2 => (Tv_Sec => 0, Tv_Usec => 0),
Can_Id => Can_Id,
Nframes => 1),
Frame => (Can_Id => Can_Id,
Uu_Pad => 16#FF#,
Uu_Res0 => 16#FF#,
Uu_Res1 => 16#FF#,
Can_Dlc => 0,
Data => (others => 16#FF#)));
begin
Send_Socket(This.Socket, Msg);
end Stop_Periodic;
procedure Add_Receive_Filter (This : in Broadcast_Manager_Type;
Item : in Sockets.Can_Frame.Can_Frame;
Interval : in Duration := 0.0) is
Msg : aliased constant Msg_Type :=
(Msg_Head => (Opcode => Sockets.Can_Bcm_Thin.Rx_Setup,
Flags => Sockets.Can_Bcm_Thin.SETTIMER,
Count => 0,
Ival1 => (Tv_Sec => 0, Tv_Usec => 0),
Ival2 => To_Timeval(Interval),
Can_Id => Item.Can_Id,
Nframes => 1),
Frame => Item);
begin
Send_Socket(This.Socket, Msg);
end Add_Receive_Filter;
procedure Remove_Receive_Filter (This : in Broadcast_Manager_Type;
Can_Id : in Sockets.Can_Frame.Can_Id_Type) is
Msg : aliased constant Msg_Type :=
(Msg_Head => (Opcode => Sockets.Can_Bcm_Thin.Rx_Delete,
Flags => 0,
Count => 0,
Ival1 => (Tv_Sec => 0, Tv_Usec => 0),
Ival2 => (Tv_Sec => 0, Tv_Usec => 0),
Can_Id => Can_Id,
Nframes => 1),
Frame => (Can_Id => Can_Id,
Uu_Pad => 16#FF#,
Uu_Res0 => 16#FF#,
Uu_Res1 => 16#FF#,
Can_Dlc => 0,
Data => (others => 16#FF#)));
begin
Send_Socket(This.Socket, Msg);
end Remove_Receive_Filter;
procedure Receive_Can_Frame (This : in Broadcast_Manager_Type;
Frame : out Sockets.Can_Frame.Can_Frame) is
Msg : aliased Msg_Type;
begin
Receive_Socket(This.Socket, Msg);
Frame := Msg.Frame;
end Receive_Can_Frame;
end Sockets.Can.Broadcast_Manager;
|
-- The Village of Vampire by YT, このソースコードはNYSLです
package Vampire.Villages.Text is
-- 配役
function Name (Person : Tabula.Villages.Person_Type'Class) return String;
function Image (Role : Requested_Role) return String;
function Image (Role : Person_Role) return String;
function Short_Image (Role : Person_Role) return String; -- 漢字一文字
function Image (Teaming : Obsolete_Teaming_Mode) return String;
-- 参加
function Join (Village : Village_Type; Message : Villages.Message)
return String;
function Escaped_Join (Village : Village_Type; Message : Villages.Message)
return String;
-- 村抜け
function Escape (Village : Village_Type; Message : Villages.Message)
return String;
-- 舞台
-- プロローグのメッセージ
function Introduction (Village : Village_Type) return String;
-- 一日目のメッセージ
function Breakdown (Village : Village_Type) return String;
-- 二日目から処刑がある場合のメッセージ
function For_Execution_In_Second (Village : Village_Type) return String;
-- 進行
-- 吸血鬼の一覧(Breakdownの前)
function Vampires (Village : Village_Type) return String;
-- 一番最初の内訳開示(Breakdownの後)
function Teaming (Village : Village_Type) return String;
-- 使徒が吸血鬼を知る(Breakdownの後)
function Servant_Knew_Message (
Village : Village_Type;
Message : Villages.Message)
return String;
-- 治療結果
function Doctor_Cure_Message (
Village : Village_Type;
Message : Villages.Message)
return String;
-- 調査結果
function Detective_Survey_Message (
Village : Village_Type;
Message : Villages.Message)
return String;
-- 誰が誰に投票したか(無記名投票では非公開)
function Votes (
Village : Village_Type;
Day : Natural;
Preliminary : Boolean;
Player_Index : Person_Index'Base)
return String;
-- 集計結果
function Votes_Totaled (
Village : Village_Type;
Day : Natural;
Preliminary : Boolean;
Executed : Person_Index'Base)
return String;
-- 夜間の会話が数奇な運命の村人に妨害された
function Howling_Blocked (Village : Village_Type) return String;
-- 観測結果
function Astronomer_Observation_Message (
Village : Village_Type;
Message : Villages.Message)
return String;
-- 護衛結果
function Hunter_Guard_Message (
Village : Village_Type;
Message : Villages.Message)
return String;
-- 襲撃結果
function Vampire_Murder_Message (
Village : Village_Type;
Message : Villages.Message;
Executed : Person_Index'Base)
return String;
function Foreboding_About_Infection_In_First (Village : Village_Type)
return String;
-- 感染自覚
function Awareness (Village : Village_Type; Message : Villages.Message)
return String;
-- 遺体の一覧
function Fatalities (
Village : Village_Type;
Day : Natural;
Executed : Person_Index'Base)
return String;
-- 生存者の一覧
function Survivors (Village : Village_Type; Day : Natural) return String;
-- 妖魔の吸血鬼数感知
function Gremlin_Sense (Village : Village_Type; Day : Natural) return String;
-- 違和感
function Sweetheart_Incongruity (
Village : Village_Type;
Message : Villages.Message)
return String;
-- 後追い
function Sweetheart_Suicide (
Village : Village_Type;
Message : Villages.Message)
return String;
-- アクション
function Action_Wake (Village : Village_Type; Message : Villages.Message)
return String;
function Action_Encourage (Village : Village_Type; Message : Villages.Message)
return String;
function Action_Vampire_Gaze (
Village : Village_Type;
Message : Villages.Message)
return String;
function Action_Vampire_Gaze_Blocked (
Village : Village_Type;
Message : Villages.Message)
return String;
function Action_Vampire_Cancel (
Village : Village_Type;
Message : Villages.Message)
return String;
function Action_Vampire_Canceled (
Village : Village_Type;
Message : Villages.Message)
return String;
-- 決着
-- 役とID公開
function People_In_Epilogure (Village : Village_Type) return String;
-- 勝利陣営
function Result_In_Epilogure (Village : Village_Type) return String;
end Vampire.Villages.Text;
|
------------------------------------------------------------------------
-- Copyright (C) 2005-2020 by <ada.rocks@jlfencey.com> --
-- --
-- This work is free. You can redistribute it and/or modify it under --
-- the terms of the Do What The Fuck You Want To Public License, --
-- Version 2, as published by Sam Hocevar. See the LICENSE file for --
-- more details. --
------------------------------------------------------------------------
pragma License (Unrestricted);
------------------------------------------------------------------------
-- AMD Élan(tm) SC 520 embedded microprocessor --
-- MMCR -> Software Timer Registers --
-- --
-- reference: User's Manual Chapter 18, --
-- Register Set Manual Chapter 15 --
------------------------------------------------------------------------
package Elan520.Software_Timer_Registers is
USEC_IN_MSEC : constant := 1_000;
-- used in counter register stuff
subtype Milliseconds is Integer range 0 .. 2**16 - 1;
subtype Microseconds is Integer range 0 .. USEC_IN_MSEC - 1;
-- maximum value which can be read (65535ms + 999us)
subtype Full_Microseconds is Integer range
0 .. USEC_IN_MSEC * Milliseconds'Last + Microseconds'Last;
-- used in configuration register (timer calibration)
type Base_Frequency is (MHz_33_333, MHz_33_000);
for Base_Frequency use (MHz_33_333 => 2#0#,
MHz_33_000 => 2#1#);
---------------------------------------------------------------------
-- Software Timer Millisecond Count (SWTMRMILLI) --
-- Memory Mapped, Read Only --
-- MMCR Offset C60h --
-- --
-- Software Timer Microsecond Count (SWTMRMICRO) --
-- Memory Mapped, Read Only --
-- MMCR Offset C62h --
---------------------------------------------------------------------
-- because it would be quite stupid to declare both registers
-- independent from each other (which would force us to read each
-- single register individually which does not make sense unless we
-- care about the timing of _internal_ processor bus cycles), let us
-- declare the type as if this would be one single (32-bit-)register
-- only
-- this easily makes sure that with each reading a correct result is
-- delivered (see note on side effect next)
-- SIDEEFFECT: the milliseconds counter Ms_Cnt is reset to zero on
-- reads
MMCR_OFFSET_TIMER : constant := 16#C60#;
TIMER_SIZE : constant := 32;
type Timer is
record
-- milliseconds counter (read first)
Ms_Cnt : Milliseconds;
-- microseconds counter (latched when Ms_Cnt is read)
Us_Cnt : Microseconds;
end record;
for Timer use
record
Ms_Cnt at 0 range 0 .. 15; -- at MMCR + 16#C60#
Us_Cnt at 0 range 16 .. 25; -- at MMCR + 16#C62#
-- bits 26 .. 31 are reserved
end record;
for Timer'Size use TIMER_SIZE;
---------------------------------------------------------------------
-- Software Timer Configuration (SWTMRCFG) --
-- Memory Mapped, Read/Write --
-- MMCR Offset C64h --
---------------------------------------------------------------------
MMCR_OFFSET_CONFIGURATION : constant := 16#C64#;
CONFIGURATION_SIZE : constant := 8;
type Configuration is
record
Xtal_Freq : Base_Frequency;
end record;
for Configuration use
record
Xtal_Freq at 0 range 0 .. 0;
-- bits 1 .. 7 are reserved
end record;
for Configuration'Size use CONFIGURATION_SIZE;
function To_Microseconds (Timer_Read : in Timer)
return Full_Microseconds;
pragma Pure_Function (To_Microseconds);
end Elan520.Software_Timer_Registers;
|
pragma Ada_2005;
pragma Style_Checks (Off);
with Interfaces.C; use Interfaces.C;
package linux_posix_types_h is
-- SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note
-- * This allows for 1024 file descriptors: if NR_OPEN is ever grown
-- * beyond that you'll have to change this too. But 1024 fd's seem to be
-- * enough even for such "real" unices like OSF/1, so hopefully this is
-- * one limit that doesn't have to be changed [again].
-- *
-- * Note that POSIX wants the FD_CLEAR(fd,fdsetp) defines to be in
-- * <sys/time.h> (and thus <linux/time.h>) - but this is a more logical
-- * place for them. Solved by having dummy defines in <sys/time.h>.
--
-- * This macro may have been defined in <gnu/types.h>. But we always
-- * use the one here.
--
type uu_kernel_fd_set_fds_bits_array is array (0 .. 15) of aliased unsigned_long;
type uu_kernel_fd_set is record
fds_bits : aliased uu_kernel_fd_set_fds_bits_array; -- /usr/include/linux/posix_types.h:26
end record;
pragma Convention (C_Pass_By_Copy, uu_kernel_fd_set); -- /usr/include/linux/posix_types.h:27
-- skipped anonymous struct anon_0
-- Type of a signal handler.
type uu_kernel_sighandler_t is access procedure (arg1 : int);
pragma Convention (C, uu_kernel_sighandler_t); -- /usr/include/linux/posix_types.h:30
-- Type of a SYSV IPC key.
subtype uu_kernel_key_t is int; -- /usr/include/linux/posix_types.h:33
subtype uu_kernel_mqd_t is int; -- /usr/include/linux/posix_types.h:34
end linux_posix_types_h;
|
-- ___ _ ___ _ _ --
-- / __| |/ (_) | | Common SKilL implementation --
-- \__ \ ' <| | | |__ file writer implementation --
-- |___/_|\_\_|_|____| by: Timm Felden --
-- --
pragma Ada_2012;
with Skill.Files;
with Skill.Streams.Writer;
-- documentation can be found in java common
-- this is a combination of serialization functions, write and append
package Skill.Internal.File_Writers is
-- write a file to disk
procedure Write
(State : Skill.Files.File;
Output : Skill.Streams.Writer.Output_Stream);
-- append a file to an existing one
procedure Append
(State : Skill.Files.File;
Output : Skill.Streams.Writer.Output_Stream);
end Skill.Internal.File_Writers;
|
with STM32_SVD; use STM32_SVD;
with STM32_SVD.RCC;
with STM32_SVD.NVIC;
with STM32_SVD.GPIO;
with STM32_SVD.USB; use STM32_SVD.USB;
package body STM32GD.Board is
procedure Init is
begin
STM32_SVD.RCC.RCC_Periph.APB2ENR.AFIOEN := 1;
STM32_SVD.RCC.RCC_Periph.APB2ENR.IOPAEN := 1;
STM32_SVD.RCC.RCC_Periph.APB2ENR.IOPBEN := 1;
STM32_SVD.RCC.RCC_Periph.APB2ENR.IOPCEN := 1;
STM32_SVD.NVIC.NVIC_Periph.ISER0 := 2#00000000_10000000_00000000_00000000#;
BUTTON.Init;
-- SWO.Init;
LED.Init;
LED2.Init;
end Init;
procedure USB_Re_Enumerate is
begin
STM32_SVD.GPIO.GPIOA_Periph.CRH.CNF12 := 0;
STM32_SVD.GPIO.GPIOA_Periph.CRH.MODE12 := 1;
STM32_SVD.GPIO.GPIOA_Periph.BSRR.BR.Arr (12) := 1;
declare
I : UInt32 with volatile;
begin
I := 100000;
while I > 0 loop
I := I - 1;
end loop;
end;
STM32_SVD.GPIO.GPIOA_Periph.CRH.CNF12 := 1;
STM32_SVD.GPIO.GPIOA_Periph.CRH.MODE12 := 0;
end USB_Re_Enumerate;
end STM32GD.Board;
|
-- This spec has been automatically generated from STM32L0x1.svd
pragma Restrictions (No_Elaboration_Code);
pragma Ada_2012;
pragma Style_Checks (Off);
with System;
package STM32_SVD.MPU is
pragma Preelaborate;
---------------
-- Registers --
---------------
-- MPU type register
type MPU_TYPER_Register is record
-- Read-only. Separate flag
SEPARATE_k : STM32_SVD.Bit;
-- unspecified
Reserved_1_7 : STM32_SVD.UInt7;
-- Read-only. Number of MPU data regions
DREGION : STM32_SVD.Byte;
-- Read-only. Number of MPU instruction regions
IREGION : STM32_SVD.Byte;
-- unspecified
Reserved_24_31 : STM32_SVD.Byte;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for MPU_TYPER_Register use record
SEPARATE_k at 0 range 0 .. 0;
Reserved_1_7 at 0 range 1 .. 7;
DREGION at 0 range 8 .. 15;
IREGION at 0 range 16 .. 23;
Reserved_24_31 at 0 range 24 .. 31;
end record;
-- MPU control register
type MPU_CTRL_Register is record
-- Read-only. Enables the MPU
ENABLE : STM32_SVD.Bit;
-- Read-only. Enables the operation of MPU during hard fault
HFNMIENA : STM32_SVD.Bit;
-- Read-only. Enable priviliged software access to default memory map
PRIVDEFENA : STM32_SVD.Bit;
-- unspecified
Reserved_3_31 : STM32_SVD.UInt29;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for MPU_CTRL_Register use record
ENABLE at 0 range 0 .. 0;
HFNMIENA at 0 range 1 .. 1;
PRIVDEFENA at 0 range 2 .. 2;
Reserved_3_31 at 0 range 3 .. 31;
end record;
-- MPU region number register
type MPU_RNR_Register is record
-- MPU region
REGION : STM32_SVD.Byte;
-- unspecified
Reserved_8_31 : STM32_SVD.UInt24;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for MPU_RNR_Register use record
REGION at 0 range 0 .. 7;
Reserved_8_31 at 0 range 8 .. 31;
end record;
-- MPU region base address register
type MPU_RBAR_Register is record
-- MPU region field
REGION : STM32_SVD.UInt4;
-- MPU region number valid
VALID : STM32_SVD.Bit;
-- Region base address field
ADDR : STM32_SVD.UInt27;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for MPU_RBAR_Register use record
REGION at 0 range 0 .. 3;
VALID at 0 range 4 .. 4;
ADDR at 0 range 5 .. 31;
end record;
-- MPU region attribute and size register
type MPU_RASR_Register is record
-- Region enable bit.
ENABLE : STM32_SVD.Bit;
-- Size of the MPU protection region
SIZE : STM32_SVD.UInt5;
-- unspecified
Reserved_6_7 : STM32_SVD.UInt2;
-- Subregion disable bits
SRD : STM32_SVD.Byte;
-- memory attribute
B : STM32_SVD.Bit;
-- memory attribute
C : STM32_SVD.Bit;
-- Shareable memory attribute
S : STM32_SVD.Bit;
-- memory attribute
TEX : STM32_SVD.UInt3;
-- unspecified
Reserved_22_23 : STM32_SVD.UInt2;
-- Access permission
AP : STM32_SVD.UInt3;
-- unspecified
Reserved_27_27 : STM32_SVD.Bit;
-- Instruction access disable bit
XN : STM32_SVD.Bit;
-- unspecified
Reserved_29_31 : STM32_SVD.UInt3;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for MPU_RASR_Register use record
ENABLE at 0 range 0 .. 0;
SIZE at 0 range 1 .. 5;
Reserved_6_7 at 0 range 6 .. 7;
SRD at 0 range 8 .. 15;
B at 0 range 16 .. 16;
C at 0 range 17 .. 17;
S at 0 range 18 .. 18;
TEX at 0 range 19 .. 21;
Reserved_22_23 at 0 range 22 .. 23;
AP at 0 range 24 .. 26;
Reserved_27_27 at 0 range 27 .. 27;
XN at 0 range 28 .. 28;
Reserved_29_31 at 0 range 29 .. 31;
end record;
-----------------
-- Peripherals --
-----------------
-- Memory protection unit
type MPU_Peripheral is record
-- MPU type register
MPU_TYPER : aliased MPU_TYPER_Register;
-- MPU control register
MPU_CTRL : aliased MPU_CTRL_Register;
-- MPU region number register
MPU_RNR : aliased MPU_RNR_Register;
-- MPU region base address register
MPU_RBAR : aliased MPU_RBAR_Register;
-- MPU region attribute and size register
MPU_RASR : aliased MPU_RASR_Register;
end record
with Volatile;
for MPU_Peripheral use record
MPU_TYPER at 16#0# range 0 .. 31;
MPU_CTRL at 16#4# range 0 .. 31;
MPU_RNR at 16#8# range 0 .. 31;
MPU_RBAR at 16#C# range 0 .. 31;
MPU_RASR at 16#10# range 0 .. 31;
end record;
-- Memory protection unit
MPU_Periph : aliased MPU_Peripheral
with Import, Address => MPU_Base;
end STM32_SVD.MPU;
|
-- { dg-do compile }
-- { dg-final { scan-assembler-not "elabs" } }
package body OCONST4 is
procedure check (arg : R) is
begin
if arg.u /= 1
or else arg.d.f1 /= 17
or else arg.d.b.f1 /= one
or else arg.d.b.f2 /= 2
or else arg.d.b.f3 /= 17
or else arg.d.b.f4 /= 42
or else arg.d.f2 /= one
or else arg.d.f3 /= 1
or else arg.d.f4 /= 111
or else arg.d.i1 /= 2
or else arg.d.i2 /= 3
then
raise Program_Error;
end if;
end;
end;
|
pragma License (Restricted);
--
-- Copyright (C) 2020 Jesper Quorning All Rights Reserved.
--
-- The author disclaims copyright to this source code. In place of
-- a legal notice, here is a blessing:
--
-- May you do good and not evil.
-- May you find forgiveness for yourself and forgive others.
-- May you share freely, not taking more than you give.
--
with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Ada.IO_Exceptions;
with Ada.Environment_Variables;
with Setup;
with Database;
with SQLite;
package body SQL_Database is
-- Default_Database : constant String :=
-- Setup.Program_Name & "." & Setup.Database_Extension;
use Ada.Strings.Unbounded;
function "+" (Source : String)
return Unbounded_String
renames To_Unbounded_String;
----------
-- Open --
----------
procedure Open
is
use Ada.Text_IO;
Success : Boolean := False;
procedure Try_Open (File_Name : String;
Success : out Boolean);
-- Try to open the SQLite database using File_Name.
procedure Try_Open (File_Name : String;
Success : out Boolean)
is
use SQLite;
begin
Success := False; -- Pessimism - result when no exception
Database.DB := SQLite.Open (File_Name => File_Name,
Flags => READWRITE or FULLMUTEX);
Success := True;
exception
when Use_Error => -- Could not open database file
Success := False;
end Try_Open;
package Env renames Ada.Environment_Variables;
Home : constant String
:= (if Env.Exists ("HOME") then Env.Value ("HOME") else "");
Paths : constant array (Positive range <>) of Unbounded_String :=
(+"./", -- & Default_Database,
+Home & "/etc/", -- & Default_Database,
+"/etc/", -- & Default_Database,
+Home & "/."); -- & Default_Database); -- Hidden
File_Name : constant String
:= Setup.Database_Others & "." & Setup.Database_Extension;
begin
for Path of Paths loop
declare
Full_Path_Name : constant String
:= To_String (Path) & File_Name;
begin
Try_Open (Full_Path_Name, Success);
if Success then
return;
end if;
end;
end loop;
raise Program_Error
with "Could not open database file '" & File_Name & "'";
end Open;
---------------------------------------------------------------------------
function Is_Valid (File_Name : in String)
return Boolean
is
DB : SQLite.Data_Base;
pragma Unreferenced (DB);
begin
DB := SQLite.Open (File_Name => File_Name,
Flags => SQLite.READONLY);
return True;
exception
when Ada.IO_Exceptions.Use_Error =>
return False;
end Is_Valid;
-- True when File_Name designates valid database.
end SQL_Database;
|
-- Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
--
-- SPDX-License-Identifier: BSD-3-Clause
-- This spec has been automatically generated from rp2040.svd
pragma Restrictions (No_Elaboration_Code);
pragma Ada_2012;
pragma Style_Checks (Off);
with HAL;
with System;
-- Controls time and alarms\n
-- time is a 64 bit value indicating the time in usec since power-on\n
-- timeh is the top 32 bits of time & timel is the bottom 32 bits\n
-- to change time write to timelw before timehw\n
-- to read time read from timelr before timehr\n
-- An alarm is set by setting alarm_enable and writing to the
-- corresponding alarm register\n
-- When an alarm is pending, the corresponding alarm_running signal
-- will be high\n
-- An alarm can be cancelled before it has finished by clearing the
-- alarm_enable\n
-- When an alarm fires, the corresponding alarm_irq is set and
-- alarm_running is cleared\n
-- To clear the interrupt write a 1 to the corresponding alarm_irq
package RP_SVD.TIMER is
pragma Preelaborate;
---------------
-- Registers --
---------------
subtype ARMED_ARMED_Field is HAL.UInt4;
-- Indicates the armed/disarmed status of each alarm.\n A write to the
-- corresponding ALARMx register arms the alarm.\n Alarms automatically
-- disarm upon firing, but writing ones here\n will disarm immediately
-- without waiting to fire.
type ARMED_Register is record
-- Write data bit of one shall clear (set to zero) the corresponding bit
-- in the field.
ARMED : ARMED_ARMED_Field := 16#0#;
-- unspecified
Reserved_4_31 : HAL.UInt28 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for ARMED_Register use record
ARMED at 0 range 0 .. 3;
Reserved_4_31 at 0 range 4 .. 31;
end record;
-- DBGPAUSE_DBG array
type DBGPAUSE_DBG_Field_Array is array (0 .. 1) of Boolean
with Component_Size => 1, Size => 2;
-- Type definition for DBGPAUSE_DBG
type DBGPAUSE_DBG_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- DBG as a value
Val : HAL.UInt2;
when True =>
-- DBG as an array
Arr : DBGPAUSE_DBG_Field_Array;
end case;
end record
with Unchecked_Union, Size => 2;
for DBGPAUSE_DBG_Field use record
Val at 0 range 0 .. 1;
Arr at 0 range 0 .. 1;
end record;
-- Set bits high to enable pause when the corresponding debug ports are
-- active
type DBGPAUSE_Register is record
-- unspecified
Reserved_0_0 : HAL.Bit := 16#1#;
-- Pause when processor 0 is in debug mode
DBG : DBGPAUSE_DBG_Field := (As_Array => False, Val => 16#1#);
-- unspecified
Reserved_3_31 : HAL.UInt29 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for DBGPAUSE_Register use record
Reserved_0_0 at 0 range 0 .. 0;
DBG at 0 range 1 .. 2;
Reserved_3_31 at 0 range 3 .. 31;
end record;
-- Set high to pause the timer
type PAUSE_Register is record
PAUSE : Boolean := False;
-- unspecified
Reserved_1_31 : HAL.UInt31 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for PAUSE_Register use record
PAUSE at 0 range 0 .. 0;
Reserved_1_31 at 0 range 1 .. 31;
end record;
-- Raw Interrupts
type INTR_Register is record
-- Write data bit of one shall clear (set to zero) the corresponding bit
-- in the field.
ALARM_0 : Boolean := False;
-- Write data bit of one shall clear (set to zero) the corresponding bit
-- in the field.
ALARM_1 : Boolean := False;
-- Write data bit of one shall clear (set to zero) the corresponding bit
-- in the field.
ALARM_2 : Boolean := False;
-- Write data bit of one shall clear (set to zero) the corresponding bit
-- in the field.
ALARM_3 : Boolean := False;
-- unspecified
Reserved_4_31 : HAL.UInt28 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for INTR_Register use record
ALARM_0 at 0 range 0 .. 0;
ALARM_1 at 0 range 1 .. 1;
ALARM_2 at 0 range 2 .. 2;
ALARM_3 at 0 range 3 .. 3;
Reserved_4_31 at 0 range 4 .. 31;
end record;
-- Interrupt Enable
type INTE_Register is record
ALARM_0 : Boolean := False;
ALARM_1 : Boolean := False;
ALARM_2 : Boolean := False;
ALARM_3 : Boolean := False;
-- unspecified
Reserved_4_31 : HAL.UInt28 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for INTE_Register use record
ALARM_0 at 0 range 0 .. 0;
ALARM_1 at 0 range 1 .. 1;
ALARM_2 at 0 range 2 .. 2;
ALARM_3 at 0 range 3 .. 3;
Reserved_4_31 at 0 range 4 .. 31;
end record;
-- Interrupt Force
type INTF_Register is record
ALARM_0 : Boolean := False;
ALARM_1 : Boolean := False;
ALARM_2 : Boolean := False;
ALARM_3 : Boolean := False;
-- unspecified
Reserved_4_31 : HAL.UInt28 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for INTF_Register use record
ALARM_0 at 0 range 0 .. 0;
ALARM_1 at 0 range 1 .. 1;
ALARM_2 at 0 range 2 .. 2;
ALARM_3 at 0 range 3 .. 3;
Reserved_4_31 at 0 range 4 .. 31;
end record;
-- Interrupt status after masking & forcing
type INTS_Register is record
-- Read-only.
ALARM_0 : Boolean;
-- Read-only.
ALARM_1 : Boolean;
-- Read-only.
ALARM_2 : Boolean;
-- Read-only.
ALARM_3 : Boolean;
-- unspecified
Reserved_4_31 : HAL.UInt28;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for INTS_Register use record
ALARM_0 at 0 range 0 .. 0;
ALARM_1 at 0 range 1 .. 1;
ALARM_2 at 0 range 2 .. 2;
ALARM_3 at 0 range 3 .. 3;
Reserved_4_31 at 0 range 4 .. 31;
end record;
-----------------
-- Peripherals --
-----------------
-- Controls time and alarms\n time is a 64 bit value indicating the time in
-- usec since power-on\n timeh is the top 32 bits of time & timel is the
-- bottom 32 bits\n to change time write to timelw before timehw\n to read
-- time read from timelr before timehr\n An alarm is set by setting
-- alarm_enable and writing to the corresponding alarm register\n When an
-- alarm is pending, the corresponding alarm_running signal will be high\n
-- An alarm can be cancelled before it has finished by clearing the
-- alarm_enable\n When an alarm fires, the corresponding alarm_irq is set
-- and alarm_running is cleared\n To clear the interrupt write a 1 to the
-- corresponding alarm_irq
type TIMER_Peripheral is record
-- Write to bits 63:32 of time\n always write timelw before timehw
TIMEHW : aliased HAL.UInt32;
-- Write to bits 31:0 of time\n writes do not get copied to time until
-- timehw is written
TIMELW : aliased HAL.UInt32;
-- Read from bits 63:32 of time\n always read timelr before timehr
TIMEHR : aliased HAL.UInt32;
-- Read from bits 31:0 of time
TIMELR : aliased HAL.UInt32;
-- Arm alarm 0, and configure the time it will fire.\n Once armed, the
-- alarm fires when TIMER_ALARM0 == TIMELR.\n The alarm will disarm
-- itself once it fires, and can\n be disarmed early using the ARMED
-- status register.
ALARM0 : aliased HAL.UInt32;
-- Arm alarm 1, and configure the time it will fire.\n Once armed, the
-- alarm fires when TIMER_ALARM1 == TIMELR.\n The alarm will disarm
-- itself once it fires, and can\n be disarmed early using the ARMED
-- status register.
ALARM1 : aliased HAL.UInt32;
-- Arm alarm 2, and configure the time it will fire.\n Once armed, the
-- alarm fires when TIMER_ALARM2 == TIMELR.\n The alarm will disarm
-- itself once it fires, and can\n be disarmed early using the ARMED
-- status register.
ALARM2 : aliased HAL.UInt32;
-- Arm alarm 3, and configure the time it will fire.\n Once armed, the
-- alarm fires when TIMER_ALARM3 == TIMELR.\n The alarm will disarm
-- itself once it fires, and can\n be disarmed early using the ARMED
-- status register.
ALARM3 : aliased HAL.UInt32;
-- Indicates the armed/disarmed status of each alarm.\n A write to the
-- corresponding ALARMx register arms the alarm.\n Alarms automatically
-- disarm upon firing, but writing ones here\n will disarm immediately
-- without waiting to fire.
ARMED : aliased ARMED_Register;
-- Raw read from bits 63:32 of time (no side effects)
TIMERAWH : aliased HAL.UInt32;
-- Raw read from bits 31:0 of time (no side effects)
TIMERAWL : aliased HAL.UInt32;
-- Set bits high to enable pause when the corresponding debug ports are
-- active
DBGPAUSE : aliased DBGPAUSE_Register;
-- Set high to pause the timer
PAUSE : aliased PAUSE_Register;
-- Raw Interrupts
INTR : aliased INTR_Register;
-- Interrupt Enable
INTE : aliased INTE_Register;
-- Interrupt Force
INTF : aliased INTF_Register;
-- Interrupt status after masking & forcing
INTS : aliased INTS_Register;
end record
with Volatile;
for TIMER_Peripheral use record
TIMEHW at 16#0# range 0 .. 31;
TIMELW at 16#4# range 0 .. 31;
TIMEHR at 16#8# range 0 .. 31;
TIMELR at 16#C# range 0 .. 31;
ALARM0 at 16#10# range 0 .. 31;
ALARM1 at 16#14# range 0 .. 31;
ALARM2 at 16#18# range 0 .. 31;
ALARM3 at 16#1C# range 0 .. 31;
ARMED at 16#20# range 0 .. 31;
TIMERAWH at 16#24# range 0 .. 31;
TIMERAWL at 16#28# range 0 .. 31;
DBGPAUSE at 16#2C# range 0 .. 31;
PAUSE at 16#30# range 0 .. 31;
INTR at 16#34# range 0 .. 31;
INTE at 16#38# range 0 .. 31;
INTF at 16#3C# range 0 .. 31;
INTS at 16#40# range 0 .. 31;
end record;
-- Controls time and alarms\n time is a 64 bit value indicating the time in
-- usec since power-on\n timeh is the top 32 bits of time & timel is the
-- bottom 32 bits\n to change time write to timelw before timehw\n to read
-- time read from timelr before timehr\n An alarm is set by setting
-- alarm_enable and writing to the corresponding alarm register\n When an
-- alarm is pending, the corresponding alarm_running signal will be high\n
-- An alarm can be cancelled before it has finished by clearing the
-- alarm_enable\n When an alarm fires, the corresponding alarm_irq is set
-- and alarm_running is cleared\n To clear the interrupt write a 1 to the
-- corresponding alarm_irq
TIMER_Periph : aliased TIMER_Peripheral
with Import, Address => TIMER_Base;
end RP_SVD.TIMER;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- S Y S T E M . F I L E _ I O --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-2016, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Ada.Finalization; use Ada.Finalization;
with Ada.IO_Exceptions; use Ada.IO_Exceptions;
with Ada.Unchecked_Deallocation;
with Interfaces.C;
with Interfaces.C_Streams; use Interfaces.C_Streams;
with System.Case_Util; use System.Case_Util;
with System.CRTL;
with System.OS_Lib;
with System.Soft_Links;
package body System.File_IO is
use System.File_Control_Block;
package SSL renames System.Soft_Links;
use type CRTL.size_t;
use type Interfaces.C.int;
----------------------
-- Global Variables --
----------------------
Open_Files : AFCB_Ptr;
-- This points to a list of AFCB's for all open files. This is a doubly
-- linked list, with the Prev pointer of the first entry, and the Next
-- pointer of the last entry containing null. Note that this global
-- variable must be properly protected to provide thread safety.
type Temp_File_Record;
type Temp_File_Record_Ptr is access all Temp_File_Record;
type Temp_File_Record is record
Name : String (1 .. max_path_len + 1);
Next : Temp_File_Record_Ptr;
end record;
-- One of these is allocated for each temporary file created
Temp_Files : Temp_File_Record_Ptr;
-- Points to list of names of temporary files. Note that this global
-- variable must be properly protected to provide thread safety.
type File_IO_Clean_Up_Type is new Limited_Controlled with null record;
-- The closing of all open files and deletion of temporary files is an
-- action that takes place at the end of execution of the main program.
-- This action is implemented using a library level object which gets
-- finalized at the end of program execution. Note that the type is
-- limited, in order to stop the compiler optimizing away the declaration
-- which would be allowed in the non-limited case.
procedure Finalize (V : in out File_IO_Clean_Up_Type);
-- This is the finalize operation that is used to do the cleanup
File_IO_Clean_Up_Object : File_IO_Clean_Up_Type;
pragma Warnings (Off, File_IO_Clean_Up_Object);
-- This is the single object of the type that triggers the finalization
-- call. Since it is at the library level, this happens just before the
-- environment task is finalized.
text_translation_required : Boolean;
for text_translation_required'Size use Character'Size;
pragma Import
(C, text_translation_required, "__gnat_text_translation_required");
-- If true, add appropriate suffix to control string for Open
-----------------------
-- Local Subprograms --
-----------------------
procedure Free_String is new Ada.Unchecked_Deallocation (String, Pstring);
subtype Fopen_String is String (1 .. 4);
-- Holds open string (longest is "w+b" & nul)
procedure Fopen_Mode
(Namestr : String;
Mode : File_Mode;
Text : Boolean;
Creat : Boolean;
Amethod : Character;
Fopstr : out Fopen_String);
-- Determines proper open mode for a file to be opened in the given Ada
-- mode. Namestr is the NUL-terminated file name. Text is true for a text
-- file and false otherwise, and Creat is true for a create call, and False
-- for an open call. The value stored in Fopstr is a nul-terminated string
-- suitable for a call to fopen or freopen. Amethod is the character
-- designating the access method from the Access_Method field of the FCB.
function Errno_Message
(Name : String;
Errno : Integer := OS_Lib.Errno) return String;
-- Return Errno_Message for Errno, with file name prepended
procedure Raise_Device_Error
(File : AFCB_Ptr;
Errno : Integer := OS_Lib.Errno);
pragma No_Return (Raise_Device_Error);
-- Clear error indication on File and raise Device_Error with an exception
-- message providing errno information.
----------------
-- Append_Set --
----------------
procedure Append_Set (File : AFCB_Ptr) is
begin
if File.Mode = Append_File then
if fseek (File.Stream, 0, SEEK_END) /= 0 then
Raise_Device_Error (File);
end if;
end if;
end Append_Set;
----------------
-- Chain_File --
----------------
procedure Chain_File (File : AFCB_Ptr) is
begin
-- Take a task lock, to protect the global data value Open_Files
SSL.Lock_Task.all;
-- Do the chaining operation locked
File.Next := Open_Files;
File.Prev := null;
Open_Files := File;
if File.Next /= null then
File.Next.Prev := File;
end if;
SSL.Unlock_Task.all;
exception
when others =>
SSL.Unlock_Task.all;
raise;
end Chain_File;
---------------------
-- Check_File_Open --
---------------------
procedure Check_File_Open (File : AFCB_Ptr) is
begin
if File = null then
raise Status_Error with "file not open";
end if;
end Check_File_Open;
-----------------------
-- Check_Read_Status --
-----------------------
procedure Check_Read_Status (File : AFCB_Ptr) is
begin
if File = null then
raise Status_Error with "file not open";
elsif File.Mode not in Read_File_Mode then
raise Mode_Error with "file not readable";
end if;
end Check_Read_Status;
------------------------
-- Check_Write_Status --
------------------------
procedure Check_Write_Status (File : AFCB_Ptr) is
begin
if File = null then
raise Status_Error with "file not open";
elsif File.Mode = In_File then
raise Mode_Error with "file not writable";
end if;
end Check_Write_Status;
-----------
-- Close --
-----------
procedure Close (File_Ptr : access AFCB_Ptr) is
Close_Status : int := 0;
Dup_Strm : Boolean := False;
Errno : Integer := 0;
File : AFCB_Ptr renames File_Ptr.all;
begin
-- Take a task lock, to protect the global data value Open_Files
SSL.Lock_Task.all;
Check_File_Open (File);
AFCB_Close (File);
-- Sever the association between the given file and its associated
-- external file. The given file is left closed. Do not perform system
-- closes on the standard input, output and error files and also do not
-- attempt to close a stream that does not exist (signalled by a null
-- stream value -- happens in some error situations).
if not File.Is_System_File and then File.Stream /= NULL_Stream then
-- Do not do an fclose if this is a shared file and there is at least
-- one other instance of the stream that is open.
if File.Shared_Status = Yes then
declare
P : AFCB_Ptr;
begin
P := Open_Files;
while P /= null loop
if P /= File and then File.Stream = P.Stream then
Dup_Strm := True;
exit;
end if;
P := P.Next;
end loop;
end;
end if;
-- Do the fclose unless this was a duplicate in the shared case
if not Dup_Strm then
Close_Status := fclose (File.Stream);
if Close_Status /= 0 then
Errno := OS_Lib.Errno;
end if;
end if;
end if;
-- Dechain file from list of open files and then free the storage
if File.Prev = null then
Open_Files := File.Next;
else
File.Prev.Next := File.Next;
end if;
if File.Next /= null then
File.Next.Prev := File.Prev;
end if;
-- Deallocate some parts of the file structure that were kept in heap
-- storage with the exception of system files (standard input, output
-- and error) since they had some information allocated in the stack.
if not File.Is_System_File then
Free_String (File.Name);
Free_String (File.Form);
AFCB_Free (File);
end if;
File := null;
if Close_Status /= 0 then
Raise_Device_Error (null, Errno);
end if;
SSL.Unlock_Task.all;
exception
when others =>
SSL.Unlock_Task.all;
raise;
end Close;
------------
-- Delete --
------------
procedure Delete (File_Ptr : access AFCB_Ptr) is
File : AFCB_Ptr renames File_Ptr.all;
begin
Check_File_Open (File);
if not File.Is_Regular_File then
raise Use_Error with "cannot delete non-regular file";
end if;
declare
Filename : aliased constant String := File.Name.all;
begin
Close (File_Ptr);
-- Now unlink the external file. Note that we use the full name in
-- this unlink, because the working directory may have changed since
-- we did the open, and we want to unlink the right file.
if unlink (Filename'Address) = -1 then
raise Use_Error with OS_Lib.Errno_Message;
end if;
end;
end Delete;
-----------------
-- End_Of_File --
-----------------
function End_Of_File (File : AFCB_Ptr) return Boolean is
begin
Check_File_Open (File);
if feof (File.Stream) /= 0 then
return True;
else
Check_Read_Status (File);
if ungetc (fgetc (File.Stream), File.Stream) = EOF then
clearerr (File.Stream);
return True;
else
return False;
end if;
end if;
end End_Of_File;
-------------------
-- Errno_Message --
-------------------
function Errno_Message
(Name : String;
Errno : Integer := OS_Lib.Errno) return String
is
begin
return Name & ": " & OS_Lib.Errno_Message (Err => Errno);
end Errno_Message;
--------------
-- Finalize --
--------------
procedure Finalize (V : in out File_IO_Clean_Up_Type) is
pragma Warnings (Off, V);
Fptr1 : aliased AFCB_Ptr;
Fptr2 : AFCB_Ptr;
Discard : int;
begin
-- Take a lock to protect global Open_Files data structure
SSL.Lock_Task.all;
-- First close all open files (the slightly complex form of this loop is
-- required because Close as a side effect nulls out its argument).
Fptr1 := Open_Files;
while Fptr1 /= null loop
Fptr2 := Fptr1.Next;
Close (Fptr1'Access);
Fptr1 := Fptr2;
end loop;
-- Now unlink all temporary files. We do not bother to free the blocks
-- because we are just about to terminate the program. We also ignore
-- any errors while attempting these unlink operations.
while Temp_Files /= null loop
Discard := unlink (Temp_Files.Name'Address);
Temp_Files := Temp_Files.Next;
end loop;
SSL.Unlock_Task.all;
exception
when others =>
SSL.Unlock_Task.all;
raise;
end Finalize;
-----------
-- Flush --
-----------
procedure Flush (File : AFCB_Ptr) is
begin
Check_Write_Status (File);
if fflush (File.Stream) /= 0 then
Raise_Device_Error (File);
end if;
end Flush;
----------------
-- Fopen_Mode --
----------------
-- The fopen mode to be used is shown by the following table:
-- OPEN CREATE
-- Append_File "r+" "w+"
-- In_File "r" "w+"
-- Out_File (Direct_IO, Stream_IO) "r+" [*] "w"
-- Out_File (others) "w" "w"
-- Inout_File "r+" "w+"
-- [*] Except that for Out_File, if the file exists and is a fifo (i.e. a
-- named pipe), we use "w" instead of "r+". This is necessary to make a
-- write to the fifo block until a reader is ready.
-- Note: we do not use "a" or "a+" for Append_File, since this would not
-- work in the case of stream files, where even if in append file mode,
-- you can reset to earlier points in the file. The caller must use the
-- Append_Set routine to deal with the necessary positioning.
-- Note: in several cases, the fopen mode used allows reading and writing,
-- but the setting of the Ada mode is more restrictive. For instance,
-- Create in In_File mode uses "w+" which allows writing, but the Ada mode
-- In_File will cause any write operations to be rejected with Mode_Error
-- in any case.
-- Note: for the Out_File/Open cases for other than the Direct_IO case, an
-- initial call will be made by the caller to first open the file in "r"
-- mode to be sure that it exists. The real open, in "w" mode, will then
-- destroy this file. This is peculiar, but that's what Ada semantics
-- require and the ACATS tests insist on.
-- If text file translation is required, then either "b" or "t" is appended
-- to the mode, depending on the setting of Text.
procedure Fopen_Mode
(Namestr : String;
Mode : File_Mode;
Text : Boolean;
Creat : Boolean;
Amethod : Character;
Fopstr : out Fopen_String)
is
Fptr : Positive;
function is_fifo (Path : Address) return Integer;
pragma Import (C, is_fifo, "__gnat_is_fifo");
begin
case Mode is
when In_File =>
if Creat then
Fopstr (1) := 'w';
Fopstr (2) := '+';
Fptr := 3;
else
Fopstr (1) := 'r';
Fptr := 2;
end if;
when Out_File =>
if Amethod in 'D' | 'S'
and then not Creat
and then is_fifo (Namestr'Address) = 0
then
Fopstr (1) := 'r';
Fopstr (2) := '+';
Fptr := 3;
else
Fopstr (1) := 'w';
Fptr := 2;
end if;
when Append_File
| Inout_File
=>
Fopstr (1) := (if Creat then 'w' else 'r');
Fopstr (2) := '+';
Fptr := 3;
end case;
-- If text_translation_required is true then we need to append either a
-- "t" or "b" to the string to get the right mode.
if text_translation_required then
Fopstr (Fptr) := (if Text then 't' else 'b');
Fptr := Fptr + 1;
end if;
Fopstr (Fptr) := ASCII.NUL;
end Fopen_Mode;
----------
-- Form --
----------
function Form (File : AFCB_Ptr) return String is
begin
if File = null then
raise Status_Error with "Form: file not open";
else
return File.Form.all (1 .. File.Form'Length - 1);
end if;
end Form;
------------------
-- Form_Boolean --
------------------
function Form_Boolean
(Form : String;
Keyword : String;
Default : Boolean) return Boolean
is
V1, V2 : Natural;
pragma Unreferenced (V2);
begin
Form_Parameter (Form, Keyword, V1, V2);
if V1 = 0 then
return Default;
elsif Form (V1) = 'y' then
return True;
elsif Form (V1) = 'n' then
return False;
else
raise Use_Error with "invalid Form";
end if;
end Form_Boolean;
------------------
-- Form_Integer --
------------------
function Form_Integer
(Form : String;
Keyword : String;
Default : Integer) return Integer
is
V1, V2 : Natural;
V : Integer;
begin
Form_Parameter (Form, Keyword, V1, V2);
if V1 = 0 then
return Default;
else
V := 0;
for J in V1 .. V2 loop
if Form (J) not in '0' .. '9' then
raise Use_Error with "invalid Form";
else
V := V * 10 + Character'Pos (Form (J)) - Character'Pos ('0');
end if;
if V > 999_999 then
raise Use_Error with "invalid Form";
end if;
end loop;
return V;
end if;
end Form_Integer;
--------------------
-- Form_Parameter --
--------------------
procedure Form_Parameter
(Form : String;
Keyword : String;
Start : out Natural;
Stop : out Natural)
is
Klen : constant Integer := Keyword'Length;
begin
for J in Form'First + Klen .. Form'Last - 1 loop
if Form (J) = '='
and then Form (J - Klen .. J - 1) = Keyword
then
Start := J + 1;
Stop := Start - 1;
while Form (Stop + 1) /= ASCII.NUL
and then Form (Stop + 1) /= ','
loop
Stop := Stop + 1;
end loop;
return;
end if;
end loop;
Start := 0;
Stop := 0;
end Form_Parameter;
-------------
-- Is_Open --
-------------
function Is_Open (File : AFCB_Ptr) return Boolean is
begin
-- We return True if the file is open, and the underlying file stream is
-- usable. In particular on Windows an application linked with -mwindows
-- option set does not have a console attached. In this case standard
-- files (Current_Output, Current_Error, Current_Input) are not created.
-- We want Is_Open (Current_Output) to return False in this case.
return File /= null and then fileno (File.Stream) /= -1;
end Is_Open;
-------------------
-- Make_Buffered --
-------------------
procedure Make_Buffered
(File : AFCB_Ptr;
Buf_Siz : Interfaces.C_Streams.size_t)
is
status : Integer;
pragma Unreferenced (status);
begin
status := setvbuf (File.Stream, Null_Address, IOFBF, Buf_Siz);
end Make_Buffered;
------------------------
-- Make_Line_Buffered --
------------------------
procedure Make_Line_Buffered
(File : AFCB_Ptr;
Line_Siz : Interfaces.C_Streams.size_t)
is
status : Integer;
pragma Unreferenced (status);
begin
status := setvbuf (File.Stream, Null_Address, IOLBF, Line_Siz);
-- No error checking???
end Make_Line_Buffered;
---------------------
-- Make_Unbuffered --
---------------------
procedure Make_Unbuffered (File : AFCB_Ptr) is
status : Integer;
pragma Unreferenced (status);
begin
status := setvbuf (File.Stream, Null_Address, IONBF, 0);
-- No error checking???
end Make_Unbuffered;
----------
-- Mode --
----------
function Mode (File : AFCB_Ptr) return File_Mode is
begin
if File = null then
raise Status_Error with "Mode: file not open";
else
return File.Mode;
end if;
end Mode;
----------
-- Name --
----------
function Name (File : AFCB_Ptr) return String is
begin
if File = null then
raise Status_Error with "Name: file not open";
else
return File.Name.all (1 .. File.Name'Length - 1);
end if;
end Name;
----------
-- Open --
----------
procedure Open
(File_Ptr : in out AFCB_Ptr;
Dummy_FCB : AFCB'Class;
Mode : File_Mode;
Name : String;
Form : String;
Amethod : Character;
Creat : Boolean;
Text : Boolean;
C_Stream : FILEs := NULL_Stream)
is
pragma Warnings (Off, Dummy_FCB);
-- Yes we know this is never assigned a value. That's intended, since
-- all we ever use of this value is the tag for dispatching purposes.
procedure Tmp_Name (Buffer : Address);
pragma Import (C, Tmp_Name, "__gnat_tmp_name");
-- Set buffer (a String address) with a temporary filename
function Get_Case_Sensitive return Integer;
pragma Import (C, Get_Case_Sensitive,
"__gnat_get_file_names_case_sensitive");
procedure Record_AFCB;
-- Create and record new AFCB into the runtime, note that the
-- implementation uses the variables below which corresponds to the
-- status of the opened file.
File_Names_Case_Sensitive : constant Boolean := Get_Case_Sensitive /= 0;
-- Set to indicate whether the operating system convention is for file
-- names to be case sensitive (e.g., in Unix, set True), or not case
-- sensitive (e.g., in Windows, set False). Declared locally to avoid
-- breaking the Preelaborate rule that disallows function calls at the
-- library level.
Stream : FILEs := C_Stream;
-- Stream which we open in response to this request
Shared : Shared_Status_Type;
-- Setting of Shared_Status field for file
Fopstr : aliased Fopen_String;
-- Mode string used in fopen call
Formstr : aliased String (1 .. Form'Length + 1);
-- Form string with ASCII.NUL appended, folded to lower case
Text_Encoding : Content_Encoding;
Tempfile : constant Boolean := (Name'Length = 0);
-- Indicates temporary file case
Namelen : constant Integer := max_path_len;
-- Length required for file name, not including final ASCII.NUL.
-- Note that we used to reference L_tmpnam here, which is not reliable
-- since __gnat_tmp_name does not always use tmpnam.
Namestr : aliased String (1 .. Namelen + 1);
-- Name as given or temporary file name with ASCII.NUL appended
Fullname : aliased String (1 .. max_path_len + 1);
-- Full name (as required for Name function, and as stored in the
-- control block in the Name field) with ASCII.NUL appended.
Full_Name_Len : Integer;
-- Length of name actually stored in Fullname
Encoding : CRTL.Filename_Encoding;
-- Filename encoding specified into the form parameter
-----------------
-- Record_AFCB --
-----------------
procedure Record_AFCB is
begin
File_Ptr := AFCB_Allocate (Dummy_FCB);
-- Note that we cannot use an aggregate here as File_Ptr is a
-- class-wide access to a limited type (Root_Stream_Type).
File_Ptr.Is_Regular_File := is_regular_file (fileno (Stream)) /= 0;
File_Ptr.Is_System_File := False;
File_Ptr.Text_Encoding := Text_Encoding;
File_Ptr.Shared_Status := Shared;
File_Ptr.Access_Method := Amethod;
File_Ptr.Stream := Stream;
File_Ptr.Form := new String'(Formstr);
File_Ptr.Name := new String'(Fullname
(1 .. Full_Name_Len));
File_Ptr.Mode := Mode;
File_Ptr.Is_Temporary_File := Tempfile;
File_Ptr.Encoding := Encoding;
Chain_File (File_Ptr);
Append_Set (File_Ptr);
end Record_AFCB;
-- Start of processing for Open
begin
if File_Ptr /= null then
raise Status_Error with "file already open";
end if;
-- Acquire form string, setting required NUL terminator
Formstr (1 .. Form'Length) := Form;
Formstr (Formstr'Last) := ASCII.NUL;
-- Convert form string to lower case
for J in Formstr'Range loop
if Formstr (J) in 'A' .. 'Z' then
Formstr (J) := Character'Val (Character'Pos (Formstr (J)) + 32);
end if;
end loop;
-- Acquire setting of shared parameter
declare
V1, V2 : Natural;
begin
Form_Parameter (Formstr, "shared", V1, V2);
if V1 = 0 then
Shared := None;
elsif Formstr (V1 .. V2) = "yes" then
Shared := Yes;
elsif Formstr (V1 .. V2) = "no" then
Shared := No;
else
raise Use_Error with "invalid Form";
end if;
end;
-- Acquire setting of encoding parameter
declare
V1, V2 : Natural;
begin
Form_Parameter (Formstr, "encoding", V1, V2);
if V1 = 0 then
Encoding := CRTL.Unspecified;
elsif Formstr (V1 .. V2) = "utf8" then
Encoding := CRTL.UTF8;
elsif Formstr (V1 .. V2) = "8bits" then
Encoding := CRTL.ASCII_8bits;
else
raise Use_Error with "invalid Form";
end if;
end;
-- Acquire setting of text_translation parameter. Only needed if this is
-- a [Wide_[Wide_]]Text_IO file, in which case we default to True, but
-- if the Form says Text_Translation=No, we use binary mode, so new-line
-- will be just LF, even on Windows.
if Text then
Text_Encoding := Default_Text;
else
Text_Encoding := None;
end if;
if Text_Encoding in Text_Content_Encoding then
declare
V1, V2 : Natural;
begin
Form_Parameter (Formstr, "text_translation", V1, V2);
if V1 = 0 then
null;
elsif Formstr (V1 .. V2) = "no" then
Text_Encoding := None;
elsif Formstr (V1 .. V2) = "text"
or else Formstr (V1 .. V2) = "yes"
then
Text_Encoding := Interfaces.C_Streams.Text;
elsif Formstr (V1 .. V2) = "wtext" then
Text_Encoding := Wtext;
elsif Formstr (V1 .. V2) = "u8text" then
Text_Encoding := U8text;
elsif Formstr (V1 .. V2) = "u16text" then
Text_Encoding := U16text;
else
raise Use_Error with "invalid Form";
end if;
end;
end if;
-- If we were given a stream (call from xxx.C_Streams.Open), then set
-- the full name to the given one, and skip to end of processing.
if Stream /= NULL_Stream then
Full_Name_Len := Name'Length + 1;
Fullname (1 .. Full_Name_Len - 1) := Name;
Fullname (Full_Name_Len) := ASCII.NUL;
-- Normal case of Open or Create
else
-- If temporary file case, get temporary file name and add to the
-- list of temporary files to be deleted on exit.
if Tempfile then
if not Creat then
raise Name_Error with "opening temp file without creating it";
end if;
Tmp_Name (Namestr'Address);
if Namestr (1) = ASCII.NUL then
raise Use_Error with "invalid temp file name";
end if;
-- Chain to temp file list, ensuring thread safety with a lock
begin
SSL.Lock_Task.all;
Temp_Files :=
new Temp_File_Record'(Name => Namestr, Next => Temp_Files);
SSL.Unlock_Task.all;
exception
when others =>
SSL.Unlock_Task.all;
raise;
end;
-- Normal case of non-null name given
else
if Name'Length > Namelen then
raise Name_Error with "file name too long";
end if;
Namestr (1 .. Name'Length) := Name;
Namestr (Name'Length + 1) := ASCII.NUL;
end if;
-- Get full name in accordance with the advice of RM A.8.2(22)
full_name (Namestr'Address, Fullname'Address);
if Fullname (1) = ASCII.NUL then
raise Use_Error with Errno_Message (Name);
end if;
Full_Name_Len := 1;
while Full_Name_Len < Fullname'Last
and then Fullname (Full_Name_Len) /= ASCII.NUL
loop
Full_Name_Len := Full_Name_Len + 1;
end loop;
-- Fullname is generated by calling system's full_name. The problem
-- is, full_name does nothing about the casing, so a file name
-- comparison may generally speaking not be valid on non-case-
-- sensitive systems, and in particular we get unexpected failures
-- on Windows/Vista because of this. So we use s-casuti to force
-- the name to lower case.
if not File_Names_Case_Sensitive then
To_Lower (Fullname (1 .. Full_Name_Len));
end if;
-- If Shared=None or Shared=Yes, then check for the existence of
-- another file with exactly the same full name.
if Shared /= No then
declare
P : AFCB_Ptr;
begin
-- Take a task lock to protect Open_Files
SSL.Lock_Task.all;
-- Search list of open files
P := Open_Files;
while P /= null loop
if Fullname (1 .. Full_Name_Len) = P.Name.all then
-- If we get a match, and either file has Shared=None,
-- then raise Use_Error, since we don't allow two files
-- of the same name to be opened unless they specify the
-- required sharing mode.
if Shared = None
or else P.Shared_Status = None
then
raise Use_Error with "reopening shared file";
-- If both files have Shared=Yes, then we acquire the
-- stream from the located file to use as our stream.
elsif Shared = Yes
and then P.Shared_Status = Yes
then
Stream := P.Stream;
Record_AFCB;
exit;
-- Otherwise one of the files has Shared=Yes and one has
-- Shared=No. If the current file has Shared=No then all
-- is well but we don't want to share any other file's
-- stream. If the current file has Shared=Yes, we would
-- like to share a stream, but not from a file that has
-- Shared=No, so either way, we just continue the search.
else
null;
end if;
end if;
P := P.Next;
end loop;
SSL.Unlock_Task.all;
exception
when others =>
SSL.Unlock_Task.all;
raise;
end;
end if;
-- Open specified file if we did not find an existing stream,
-- otherwise we just return as there is nothing more to be done.
if Stream /= NULL_Stream then
return;
else
Fopen_Mode
(Namestr => Namestr,
Mode => Mode,
Text => Text_Encoding in Text_Content_Encoding,
Creat => Creat,
Amethod => Amethod,
Fopstr => Fopstr);
-- A special case, if we are opening (OPEN case) a file and the
-- mode returned by Fopen_Mode is not "r" or "r+", then we first
-- make sure that the file exists as required by Ada semantics.
if not Creat and then Fopstr (1) /= 'r' then
if file_exists (Namestr'Address) = 0 then
raise Name_Error with Errno_Message (Name);
end if;
end if;
-- Now open the file. Note that we use the name as given in the
-- original Open call for this purpose, since that seems the
-- clearest implementation of the intent. It would presumably
-- work to use the full name here, but if there is any difference,
-- then we should use the name used in the call.
-- Note: for a corresponding delete, we will use the full name,
-- since by the time of the delete, the current working directory
-- may have changed and we do not want to delete a different file.
Stream :=
fopen (Namestr'Address, Fopstr'Address, Encoding);
if Stream = NULL_Stream then
-- Raise Name_Error if trying to open a non-existent file.
-- Otherwise raise Use_Error.
-- Should we raise Device_Error for ENOSPC???
declare
function Is_File_Not_Found_Error
(Errno_Value : Integer) return Integer;
pragma Import
(C, Is_File_Not_Found_Error,
"__gnat_is_file_not_found_error");
-- Non-zero when the given errno value indicates a non-
-- existing file.
Errno : constant Integer := OS_Lib.Errno;
Message : constant String := Errno_Message (Name, Errno);
begin
if Is_File_Not_Found_Error (Errno) /= 0 then
raise Name_Error with Message;
else
raise Use_Error with Message;
end if;
end;
end if;
end if;
end if;
-- Stream has been successfully located or opened, so now we are
-- committed to completing the opening of the file. Allocate block on
-- heap and fill in its fields.
Record_AFCB;
end Open;
------------------------
-- Raise_Device_Error --
------------------------
procedure Raise_Device_Error
(File : AFCB_Ptr;
Errno : Integer := OS_Lib.Errno)
is
begin
-- Clear error status so that the same error is not reported twice
if File /= null then
clearerr (File.Stream);
end if;
raise Device_Error with OS_Lib.Errno_Message (Err => Errno);
end Raise_Device_Error;
--------------
-- Read_Buf --
--------------
procedure Read_Buf (File : AFCB_Ptr; Buf : Address; Siz : size_t) is
Nread : size_t;
begin
Nread := fread (Buf, 1, Siz, File.Stream);
if Nread = Siz then
return;
elsif ferror (File.Stream) /= 0 then
Raise_Device_Error (File);
elsif Nread = 0 then
raise End_Error;
else -- 0 < Nread < Siz
raise Data_Error with "not enough data read";
end if;
end Read_Buf;
procedure Read_Buf
(File : AFCB_Ptr;
Buf : Address;
Siz : Interfaces.C_Streams.size_t;
Count : out Interfaces.C_Streams.size_t)
is
begin
Count := fread (Buf, 1, Siz, File.Stream);
if Count = 0 and then ferror (File.Stream) /= 0 then
Raise_Device_Error (File);
end if;
end Read_Buf;
-----------
-- Reset --
-----------
-- The reset which does not change the mode simply does a rewind
procedure Reset (File_Ptr : access AFCB_Ptr) is
File : AFCB_Ptr renames File_Ptr.all;
begin
Check_File_Open (File);
Reset (File_Ptr, File.Mode);
end Reset;
-- The reset with a change in mode is done using freopen, and is not
-- permitted except for regular files (since otherwise there is no name for
-- the freopen, and in any case it seems meaningless).
procedure Reset (File_Ptr : access AFCB_Ptr; Mode : File_Mode) is
File : AFCB_Ptr renames File_Ptr.all;
Fopstr : aliased Fopen_String;
begin
Check_File_Open (File);
-- Change of mode not allowed for shared file or file with no name or
-- file that is not a regular file, or for a system file. Note that we
-- allow the "change" of mode if it is not in fact doing a change.
if Mode /= File.Mode then
if File.Shared_Status = Yes then
raise Use_Error with "cannot change mode of shared file";
elsif File.Name'Length <= 1 then
raise Use_Error with "cannot change mode of temp file";
elsif File.Is_System_File then
raise Use_Error with "cannot change mode of system file";
elsif not File.Is_Regular_File then
raise Use_Error with "cannot change mode of non-regular file";
end if;
end if;
-- For In_File or Inout_File for a regular file, we can just do a rewind
-- if the mode is unchanged, which is more efficient than doing a full
-- reopen.
if Mode = File.Mode
and then Mode in Read_File_Mode
then
rewind (File.Stream);
-- Here the change of mode is permitted, we do it by reopening the file
-- in the new mode and replacing the stream with a new stream.
else
Fopen_Mode
(Namestr => File.Name.all,
Mode => Mode,
Text => File.Text_Encoding in Text_Content_Encoding,
Creat => False,
Amethod => File.Access_Method,
Fopstr => Fopstr);
File.Stream := freopen
(File.Name.all'Address, Fopstr'Address, File.Stream,
File.Encoding);
if File.Stream = NULL_Stream then
Close (File_Ptr);
raise Use_Error;
else
File.Mode := Mode;
Append_Set (File);
end if;
end if;
end Reset;
---------------
-- Write_Buf --
---------------
procedure Write_Buf (File : AFCB_Ptr; Buf : Address; Siz : size_t) is
begin
-- Note: for most purposes, the Siz and 1 parameters in the fwrite call
-- could be reversed, but we have encountered systems where this is a
-- better choice, since for some file formats, reversing the parameters
-- results in records of one byte each.
SSL.Abort_Defer.all;
if fwrite (Buf, Siz, 1, File.Stream) /= 1 then
if Siz /= 0 then
SSL.Abort_Undefer.all;
Raise_Device_Error (File);
end if;
end if;
SSL.Abort_Undefer.all;
end Write_Buf;
end System.File_IO;
|
-----------------------------------------------------------------------
-- awa-mail-clients-files -- Mail client dump/file implementation
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.IO_Exceptions;
with Util.Files;
with Util.Strings;
with Util.Log.Loggers;
package body AWA.Mail.Clients.Files is
use Ada.Strings.Unbounded;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Clients.Files");
-- ------------------------------
-- Set the <tt>From</tt> part of the message.
-- ------------------------------
overriding
procedure Set_From (Message : in out File_Mail_Message;
Name : in String;
Address : in String) is
begin
Message.From := To_Unbounded_String ("From: " & Name & " <" & Address & ">");
end Set_From;
-- ------------------------------
-- Add a recipient for the message.
-- ------------------------------
overriding
procedure Add_Recipient (Message : in out File_Mail_Message;
Kind : in Recipient_Type;
Name : in String;
Address : in String) is
Email : constant String := Name & " <" & Address & ">";
begin
case Kind is
when TO =>
if Length (Message.To) = 0 then
Append (Message.To, "To: ");
else
Append (Message.To, ", ");
end if;
Append (Message.To, Email);
when CC =>
if Length (Message.Cc) = 0 then
Append (Message.Cc, "Cc: ");
else
Append (Message.Cc, ", ");
end if;
Append (Message.Cc, Email);
when BCC =>
if Length (Message.Bcc) = 0 then
Append (Message.Bcc, "Bcc: ");
else
Append (Message.Bcc, ", ");
end if;
Append (Message.Bcc, Email);
end case;
end Add_Recipient;
-- ------------------------------
-- Set the subject of the message.
-- ------------------------------
overriding
procedure Set_Subject (Message : in out File_Mail_Message;
Subject : in String) is
begin
Message.Subject := To_Unbounded_String (Subject);
end Set_Subject;
-- ------------------------------
-- Set the body of the message.
-- ------------------------------
overriding
procedure Set_Body (Message : in out File_Mail_Message;
Content : in String) is
begin
Message.Message := To_Unbounded_String (Content);
end Set_Body;
-- ------------------------------
-- Send the email message.
-- ------------------------------
overriding
procedure Send (Message : in out File_Mail_Message) is
N : Natural;
Output : Ada.Text_IO.File_Type;
begin
Util.Concurrent.Counters.Increment (Message.Manager.Index, N);
declare
Path : constant String := Util.Files.Compose (To_String (Message.Manager.Path),
"msg-" & Util.Strings.Image (N));
begin
Log.Info ("Sending dumb mail to {0}", Path);
Ada.Text_IO.Create (File => Output,
Mode => Ada.Text_IO.Out_File,
Name => Path);
Ada.Text_IO.Put_Line (Output, To_String (Message.From));
if Length (Message.To) > 0 then
Ada.Text_IO.Put_Line (Output, To_String (Message.To));
end if;
if Length (Message.Cc) > 0 then
Ada.Text_IO.Put_Line (Output, To_String (Message.Cc));
end if;
if Length (Message.Bcc) > 0 then
Ada.Text_IO.Put_Line (Output, To_String (Message.Bcc));
end if;
Ada.Text_IO.Put (Output, "Subject: ");
Ada.Text_IO.Put_Line (Output, To_String (Message.Subject));
Ada.Text_IO.Put_Line (Output, To_String (Message.Message));
Ada.Text_IO.Close (Output);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot create mail file {0}", Path);
end;
end Send;
-- ------------------------------
-- Create a file based mail manager and configure it according to the properties.
-- ------------------------------
function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access is
Result : constant File_Mail_Manager_Access := new File_Mail_Manager;
begin
Result.Self := Result;
Result.Path := To_Unbounded_String (Props.Get (NAME & ".maildir", "mail"));
return Result.all'Access;
end Create_Manager;
-- ------------------------------
-- Create a new mail message.
-- ------------------------------
overriding
function Create_Message (Manager : in File_Mail_Manager) return Mail_Message_Access is
Result : constant File_Mail_Message_Access := new File_Mail_Message;
begin
Result.Manager := Manager.Self;
return Result.all'Access;
end Create_Message;
end AWA.Mail.Clients.Files;
|
--with HWIF;
package body Tasks is
--Pressed Button Task
task ButtonPressed (this: in Direction) is
end ButtonPressed;
task body ButtonPressed is
(this: in Direction)
begin
Traffic_Light(this) := 4;
delay 1.0;
Traffic_Light(this) := 2;
delay 1.0;
Traffic_Light(this) := 1;
end ButtonPressed;
end Tasks;
|
-- Spécification du module Arbre_binaire
generic
Type T_Cle is private;
with procedure Afficher_Cle (Cle : in T_Cle);
package Arbre_Binaire is
Cle_Absente_Exception : Exception;
Cle_Existe_Exception : Exception;
Existe_Fils_Droit : Exception ;
Existe_Fils_Gauche : Exception ;
Type T_Abr is private;
--Initialiser un arbre vide
procedure Initialiser ( Abr : out T_Abr) with
Post => Vide (Abr);
-- Verifier si un arbre est vide
function Vide ( Abr : in T_Abr ) return boolean;
-- Obtenir la taille d'un arbre
function Taille ( Abr : in T_Abr ) return Integer with
Post => Taille'Result >= 0 and ( Taille'Result = 0 ) = Vide (Abr) ;
--Creer un arbre binaire
procedure Creer_Arbre (Abr : out T_Abr ; Cle : in T_Cle ) with
Post => Avoir_Cle ( Abr , Cle ) = Cle ;
--Ajouter un fils droit
-- Exception : Cle_Absente_Exception si la clé Cle_Donnee n'existe pas
-- Exception : Existe_Fils_Droit si le fils droit existe déjà
-- Exception : Cle_Presente_Exception si la clé Cle existe déjà ( Unicité de la clé Cle )
procedure Ajouter_Fils_Droit ( Abr : in out T_Abr ; Cle_Donnee : in T_Cle ; Cle : in T_Cle ) with
Post => Avoir_Cle ( Arbre_Cle (Abr,Cle) , Cle) = Cle ;
--Ajouter un fils gauche
-- Exception : Cle_Absente_Exception si la clé Cle_Donnee n'existe pas
-- Exception : Existe_Fils_Gauche si le fils gauche existe déjà
-- Exception : Cle_Presente_Exception si la clé Cle existe déjà ( Unicité de la clé Cle )
procedure Ajouter_Fils_Gauche ( Abr : in out T_Abr ; Cle_Donnee : in T_Cle ; Cle : in T_Cle ) with
post => Avoir_Cle ( Arbre_Cle (Abr,Cle) , Cle) = Cle ;
-- Modifier une clé
-- Exception : Cle_Absente_Exception si Clé n'existe pas
procedure Modifier (Abr : in out T_Abr ; Cle_Donnee : in T_Cle ; Cle : in T_Cle ) with
Post => Avoir_Cle (Arbre_Cle(Abr, Cle) , Cle) = Cle ;
-- Supprimer l'arbre associée à la clé Cle dans l'arbre
-- Exception : Cle_Absente_Exception si Clé n'est pas utilisée dans l'Abr
procedure Supprimer (Abr : in out T_Abr ; Cle : in T_Cle) with
Post => not Existe ( Abr , Cle );
--Obtenir l'arbre associée à une clé
-- Exception : Cle_Absente_Exception si la clé Cle_Donnee n'existe pas
function Arbre_Cle ( Abr : in T_Abr ; Cle_Donnee : in T_Cle) return T_Abr;
--Verifier si un noeud existe
function Existe ( Abr : in T_Abr ; Cle_Donnee : in T_Cle ) return Boolean with
Pre => Not Vide(Abr);
-- Vider l'arbre
procedure Vider_Arbre ( Abr : out T_Abr ) with
Post => Vide(Abr);
-- Afficher un arbre binaire par paroucrs préfixe
procedure Afficher_Arbre_Binaire (Abr : in T_Abr ;n : in integer);
-- Retourner la clé d'un arbre binaire associé à la clé Cle
-- Cette fonction est utile pour décrire les préconditions et les postconditions
function Avoir_Cle ( Abr : in T_Abr ; Cle : in T_Cle ) return T_Cle ;
-- Retourer la clé d'un arbre binaire
function Avoir_Cle_Arbre ( Abr : in T_Abr ) return T_Cle with
pre => Not Vide( Abr ) ;
-- Avoir le sous arbre gauche d'un arbre Abr
function Avoir_Sous_Arbre_Droit ( Abr : in T_Abr ) return T_Abr ;
-- Avoir le sous arbre droit d'un arbre Abr
function Avoir_Sous_Arbre_Gauche ( Abr : in T_Abr ) return T_Abr ;
private
type T_Noeud;
type T_Abr is access T_Noeud;
type T_Noeud is
record
Cle: T_Cle;
Sous_Arbre_Gauche : T_Abr;
Sous_Arbre_Droit : T_Abr;
end record;
end Arbre_Binaire;
|
with Ada.Finalization;
with Ada.Iterator_Interfaces;
generic
type Element_Type is private;
with function "=" (Left, Right : Element_Type) return Boolean is <>;
with procedure Destroy (Value : in out Element_Type) is null;
package Regions.Shared_Lists is
pragma Preelaborate;
type List is tagged private
with
Constant_Indexing => Constant_Indexing,
Default_Iterator => Iterate,
Iterator_Element => Element_Type;
function "=" (Left, Right : List) return Boolean;
function Is_Empty (Self : List) return Boolean with Inline;
function Length (Self : List) return Natural with Inline;
function Empty_List return List with Inline;
function First_Element (Self : List) return Element_Type
with Pre => not Self.Is_Empty, Inline;
procedure Prepend
(Self : in out List;
Item : Element_Type) with Inline;
type Cursor is private;
function Has_Element (Self : Cursor) return Boolean with Inline;
-- Check if the cursor points to any element
package Iterator_Interfaces is new Ada.Iterator_Interfaces
(Cursor, Has_Element);
type Forward_Iterator is new Iterator_Interfaces.Forward_Iterator
with private;
function Iterate (Self : List'Class) return Forward_Iterator with Inline;
-- Iterate over all elements in the map
function Constant_Indexing
(Self : List;
Position : Cursor) return Element_Type
with Pre => Has_Element (Position), Inline;
No_Element : constant Cursor;
private
type List_Node;
type List_Node_Access is access all List_Node;
type List_Node is record
Next : List_Node_Access;
Counter : Natural;
Data : Element_Type;
end record;
type List is new Ada.Finalization.Controlled with record
Head : List_Node_Access;
Length : Natural := 0;
end record;
overriding procedure Adjust (Self : in out List);
overriding procedure Finalize (Self : in out List);
type Cursor is record
Item : List_Node_Access;
end record;
type Forward_Iterator is new Iterator_Interfaces.Forward_Iterator
with record
First : Cursor;
end record;
overriding function First (Self : Forward_Iterator) return Cursor;
overriding function Next
(Self : Forward_Iterator;
Position : Cursor) return Cursor;
No_Element : constant Cursor := (Item => null);
end Regions.Shared_Lists;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- A D A . S T R I N G S . W I D E _ S U P E R B O U N D E D --
-- --
-- S p e c --
-- --
-- Copyright (C) 2003-2020, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This non generic package contains most of the implementation of the
-- generic package Ada.Strings.Wide_Bounded.Generic_Bounded_Length.
-- It defines type Super_String as a discriminated record with the maximum
-- length as the discriminant. Individual instantiations of the package
-- Strings.Wide_Bounded.Generic_Bounded_Length use this type with
-- an appropriate discriminant value set.
with Ada.Strings.Wide_Maps;
package Ada.Strings.Wide_Superbounded is
pragma Preelaborate;
Wide_NUL : constant Wide_Character := Wide_Character'Val (0);
-- Ada.Strings.Wide_Bounded.Generic_Bounded_Length.Wide_Bounded_String is
-- derived from Super_String, with the constraint of the maximum length.
type Super_String (Max_Length : Positive) is record
Current_Length : Natural := 0;
Data : Wide_String (1 .. Max_Length);
-- A previous version had a default initial value for Data, which is
-- no longer necessary, because we now special-case this type in the
-- compiler, so "=" composes properly for descendants of this type.
-- Leaving it out is more efficient.
end record;
-- The subprograms defined for Super_String are similar to those defined
-- for Bounded_Wide_String, except that they have different names, so that
-- they can be renamed in Ada.Strings.Wide_Bounded.Generic_Bounded_Length.
function Super_Length (Source : Super_String) return Natural;
--------------------------------------------------------
-- Conversion, Concatenation, and Selection Functions --
--------------------------------------------------------
function To_Super_String
(Source : Wide_String;
Max_Length : Natural;
Drop : Truncation := Error) return Super_String;
-- Note the additional parameter Max_Length, which specifies the maximum
-- length setting of the resulting Super_String value.
-- The following procedures have declarations (and semantics) that are
-- exactly analogous to those declared in Ada.Strings.Wide_Bounded.
function Super_To_String (Source : Super_String) return Wide_String;
procedure Set_Super_String
(Target : out Super_String;
Source : Wide_String;
Drop : Truncation := Error);
function Super_Append
(Left : Super_String;
Right : Super_String;
Drop : Truncation := Error) return Super_String;
function Super_Append
(Left : Super_String;
Right : Wide_String;
Drop : Truncation := Error) return Super_String;
function Super_Append
(Left : Wide_String;
Right : Super_String;
Drop : Truncation := Error) return Super_String;
function Super_Append
(Left : Super_String;
Right : Wide_Character;
Drop : Truncation := Error) return Super_String;
function Super_Append
(Left : Wide_Character;
Right : Super_String;
Drop : Truncation := Error) return Super_String;
procedure Super_Append
(Source : in out Super_String;
New_Item : Super_String;
Drop : Truncation := Error);
procedure Super_Append
(Source : in out Super_String;
New_Item : Wide_String;
Drop : Truncation := Error);
procedure Super_Append
(Source : in out Super_String;
New_Item : Wide_Character;
Drop : Truncation := Error);
function Concat
(Left : Super_String;
Right : Super_String) return Super_String;
function Concat
(Left : Super_String;
Right : Wide_String) return Super_String;
function Concat
(Left : Wide_String;
Right : Super_String) return Super_String;
function Concat
(Left : Super_String;
Right : Wide_Character) return Super_String;
function Concat
(Left : Wide_Character;
Right : Super_String) return Super_String;
function Super_Element
(Source : Super_String;
Index : Positive) return Wide_Character;
procedure Super_Replace_Element
(Source : in out Super_String;
Index : Positive;
By : Wide_Character);
function Super_Slice
(Source : Super_String;
Low : Positive;
High : Natural) return Wide_String;
function Super_Slice
(Source : Super_String;
Low : Positive;
High : Natural) return Super_String;
procedure Super_Slice
(Source : Super_String;
Target : out Super_String;
Low : Positive;
High : Natural);
function "="
(Left : Super_String;
Right : Super_String) return Boolean;
function Equal
(Left : Super_String;
Right : Super_String) return Boolean renames "=";
function Equal
(Left : Super_String;
Right : Wide_String) return Boolean;
function Equal
(Left : Wide_String;
Right : Super_String) return Boolean;
function Less
(Left : Super_String;
Right : Super_String) return Boolean;
function Less
(Left : Super_String;
Right : Wide_String) return Boolean;
function Less
(Left : Wide_String;
Right : Super_String) return Boolean;
function Less_Or_Equal
(Left : Super_String;
Right : Super_String) return Boolean;
function Less_Or_Equal
(Left : Super_String;
Right : Wide_String) return Boolean;
function Less_Or_Equal
(Left : Wide_String;
Right : Super_String) return Boolean;
function Greater
(Left : Super_String;
Right : Super_String) return Boolean;
function Greater
(Left : Super_String;
Right : Wide_String) return Boolean;
function Greater
(Left : Wide_String;
Right : Super_String) return Boolean;
function Greater_Or_Equal
(Left : Super_String;
Right : Super_String) return Boolean;
function Greater_Or_Equal
(Left : Super_String;
Right : Wide_String) return Boolean;
function Greater_Or_Equal
(Left : Wide_String;
Right : Super_String) return Boolean;
----------------------
-- Search Functions --
----------------------
function Super_Index
(Source : Super_String;
Pattern : Wide_String;
Going : Direction := Forward;
Mapping : Wide_Maps.Wide_Character_Mapping := Wide_Maps.Identity)
return Natural;
function Super_Index
(Source : Super_String;
Pattern : Wide_String;
Going : Direction := Forward;
Mapping : Wide_Maps.Wide_Character_Mapping_Function) return Natural;
function Super_Index
(Source : Super_String;
Set : Wide_Maps.Wide_Character_Set;
Test : Membership := Inside;
Going : Direction := Forward) return Natural;
function Super_Index
(Source : Super_String;
Pattern : Wide_String;
From : Positive;
Going : Direction := Forward;
Mapping : Wide_Maps.Wide_Character_Mapping := Wide_Maps.Identity)
return Natural;
function Super_Index
(Source : Super_String;
Pattern : Wide_String;
From : Positive;
Going : Direction := Forward;
Mapping : Wide_Maps.Wide_Character_Mapping_Function) return Natural;
function Super_Index
(Source : Super_String;
Set : Wide_Maps.Wide_Character_Set;
From : Positive;
Test : Membership := Inside;
Going : Direction := Forward) return Natural;
function Super_Index_Non_Blank
(Source : Super_String;
Going : Direction := Forward) return Natural;
function Super_Index_Non_Blank
(Source : Super_String;
From : Positive;
Going : Direction := Forward) return Natural;
function Super_Count
(Source : Super_String;
Pattern : Wide_String;
Mapping : Wide_Maps.Wide_Character_Mapping := Wide_Maps.Identity)
return Natural;
function Super_Count
(Source : Super_String;
Pattern : Wide_String;
Mapping : Wide_Maps.Wide_Character_Mapping_Function) return Natural;
function Super_Count
(Source : Super_String;
Set : Wide_Maps.Wide_Character_Set) return Natural;
procedure Super_Find_Token
(Source : Super_String;
Set : Wide_Maps.Wide_Character_Set;
From : Positive;
Test : Membership;
First : out Positive;
Last : out Natural);
procedure Super_Find_Token
(Source : Super_String;
Set : Wide_Maps.Wide_Character_Set;
Test : Membership;
First : out Positive;
Last : out Natural);
------------------------------------
-- String Translation Subprograms --
------------------------------------
function Super_Translate
(Source : Super_String;
Mapping : Wide_Maps.Wide_Character_Mapping) return Super_String;
procedure Super_Translate
(Source : in out Super_String;
Mapping : Wide_Maps.Wide_Character_Mapping);
function Super_Translate
(Source : Super_String;
Mapping : Wide_Maps.Wide_Character_Mapping_Function) return Super_String;
procedure Super_Translate
(Source : in out Super_String;
Mapping : Wide_Maps.Wide_Character_Mapping_Function);
---------------------------------------
-- String Transformation Subprograms --
---------------------------------------
function Super_Replace_Slice
(Source : Super_String;
Low : Positive;
High : Natural;
By : Wide_String;
Drop : Truncation := Error) return Super_String;
procedure Super_Replace_Slice
(Source : in out Super_String;
Low : Positive;
High : Natural;
By : Wide_String;
Drop : Truncation := Error);
function Super_Insert
(Source : Super_String;
Before : Positive;
New_Item : Wide_String;
Drop : Truncation := Error) return Super_String;
procedure Super_Insert
(Source : in out Super_String;
Before : Positive;
New_Item : Wide_String;
Drop : Truncation := Error);
function Super_Overwrite
(Source : Super_String;
Position : Positive;
New_Item : Wide_String;
Drop : Truncation := Error) return Super_String;
procedure Super_Overwrite
(Source : in out Super_String;
Position : Positive;
New_Item : Wide_String;
Drop : Truncation := Error);
function Super_Delete
(Source : Super_String;
From : Positive;
Through : Natural) return Super_String;
procedure Super_Delete
(Source : in out Super_String;
From : Positive;
Through : Natural);
---------------------------------
-- String Selector Subprograms --
---------------------------------
function Super_Trim
(Source : Super_String;
Side : Trim_End) return Super_String;
procedure Super_Trim
(Source : in out Super_String;
Side : Trim_End);
function Super_Trim
(Source : Super_String;
Left : Wide_Maps.Wide_Character_Set;
Right : Wide_Maps.Wide_Character_Set) return Super_String;
procedure Super_Trim
(Source : in out Super_String;
Left : Wide_Maps.Wide_Character_Set;
Right : Wide_Maps.Wide_Character_Set);
function Super_Head
(Source : Super_String;
Count : Natural;
Pad : Wide_Character := Wide_Space;
Drop : Truncation := Error) return Super_String;
procedure Super_Head
(Source : in out Super_String;
Count : Natural;
Pad : Wide_Character := Wide_Space;
Drop : Truncation := Error);
function Super_Tail
(Source : Super_String;
Count : Natural;
Pad : Wide_Character := Wide_Space;
Drop : Truncation := Error) return Super_String;
procedure Super_Tail
(Source : in out Super_String;
Count : Natural;
Pad : Wide_Character := Wide_Space;
Drop : Truncation := Error);
------------------------------------
-- String Constructor Subprograms --
------------------------------------
-- Note: in some of the following routines, there is an extra parameter
-- Max_Length which specifies the value of the maximum length for the
-- resulting Super_String value.
function Times
(Left : Natural;
Right : Wide_Character;
Max_Length : Positive) return Super_String;
-- Note the additional parameter Max_Length
function Times
(Left : Natural;
Right : Wide_String;
Max_Length : Positive) return Super_String;
-- Note the additional parameter Max_Length
function Times
(Left : Natural;
Right : Super_String) return Super_String;
function Super_Replicate
(Count : Natural;
Item : Wide_Character;
Drop : Truncation := Error;
Max_Length : Positive) return Super_String;
-- Note the additional parameter Max_Length
function Super_Replicate
(Count : Natural;
Item : Wide_String;
Drop : Truncation := Error;
Max_Length : Positive) return Super_String;
-- Note the additional parameter Max_Length
function Super_Replicate
(Count : Natural;
Item : Super_String;
Drop : Truncation := Error) return Super_String;
private
-- Pragma Inline declarations
pragma Inline ("=");
pragma Inline (Less);
pragma Inline (Less_Or_Equal);
pragma Inline (Greater);
pragma Inline (Greater_Or_Equal);
pragma Inline (Concat);
pragma Inline (Super_Count);
pragma Inline (Super_Element);
pragma Inline (Super_Find_Token);
pragma Inline (Super_Index);
pragma Inline (Super_Index_Non_Blank);
pragma Inline (Super_Length);
pragma Inline (Super_Replace_Element);
pragma Inline (Super_Slice);
pragma Inline (Super_To_String);
end Ada.Strings.Wide_Superbounded;
|
--with Ada.Text_IO;
--use Ada.Text_IO;
with xample1;
use xample1;
procedure xercise is
begin
SayWelcome(6);
end xercise;
|
with Sodium.Functions; use Sodium.Functions;
with Ada.Text_IO; use Ada.Text_IO;
procedure Demo_Ada
is
message : constant String := "From Russia with love.";
cipherlen : constant Positive := Symmetric_Cipher_Length (message);
begin
if not initialize_sodium_library then
Put_Line ("Initialization failed");
return;
end if;
declare
secret_key : Symmetric_Key := Random_Symmetric_Key;
second_key : Symmetric_Key := Random_Symmetric_Key;
first_nonce : Symmetric_Nonce := Random_Symmetric_Nonce;
cipher_text : Encrypted_Data (1 .. cipherlen);
clear_text : String (1 .. message'Length);
begin
Put_Line ("Secret Key: " & As_Hexidecimal (secret_key));
Put_Line ("Second Key: " & As_Hexidecimal (second_key));
cipher_text := Symmetric_Encrypt (clear_text => message,
secret_key => secret_key,
unique_nonce => first_nonce);
Put_Line ("CipherText: " & As_Hexidecimal (cipher_text));
clear_text := Symmetric_Decrypt (ciphertext => cipher_text,
secret_key => secret_key,
unique_nonce => first_nonce);
Put_Line ("Back again: " & clear_text);
Put ("Let another key try to open it ... ");
begin
clear_text := Symmetric_Decrypt (ciphertext => cipher_text,
secret_key => second_key,
unique_nonce => first_nonce);
exception
when others => Put_Line ("That failed as expected.");
end;
Put_Line ("Now use the original key after slightly altering the cipher text ...");
cipher_text (10) := 'Z';
clear_text := Symmetric_Decrypt (ciphertext => cipher_text,
secret_key => secret_key,
unique_nonce => first_nonce);
end;
end Demo_Ada;
|
-- Copyright (c) 2017 Maxim Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with AWS.Client;
with League.JSON.Objects;
with League.JSON.Values;
with League.String_Vectors;
with WebDriver.Elements;
with WebDriver.Sessions;
package body WebDriver.Remote is
type Method_Kinds is (Get, Post);
type Command is record
Method : Method_Kinds;
Path : League.Strings.Universal_String;
Session_Id : League.Strings.Universal_String;
Parameters : League.JSON.Objects.JSON_Object;
end record;
type Response is record
Session_Id : League.Strings.Universal_String;
State : League.Strings.Universal_String;
Status : Integer;
Value : League.JSON.Objects.JSON_Object;
end record;
package Executors is
type HTTP_Command_Executor is tagged limited record
Server : AWS.Client.HTTP_Connection;
end record;
not overriding function Execute
(Self : access HTTP_Command_Executor;
Command : Remote.Command) return Response;
end Executors;
package body Executors is separate;
package Elements is
type Element is new WebDriver.Elements.Element with record
Session_Id : League.Strings.Universal_String;
Element_Id : League.Strings.Universal_String;
Executor : access Executors.HTTP_Command_Executor;
end record;
overriding function Is_Selected (Self : access Element) return Boolean;
overriding function Is_Enabled (Self : access Element) return Boolean;
overriding function Get_Attribute
(Self : access Element;
Name : League.Strings.Universal_String)
return League.Strings.Universal_String;
overriding function Get_Property
(Self : access Element;
Name : League.Strings.Universal_String)
return League.Strings.Universal_String;
overriding function Get_CSS_Value
(Self : access Element;
Name : League.Strings.Universal_String)
return League.Strings.Universal_String;
overriding function Get_Text
(Self : access Element) return League.Strings.Universal_String;
overriding function Get_Tag_Name
(Self : access Element) return League.Strings.Universal_String;
overriding procedure Click (Self : access Element);
overriding procedure Clear (Self : access Element);
overriding procedure Send_Keys
(Self : access Element;
Text : League.String_Vectors.Universal_String_Vector);
end Elements;
package body Elements is separate;
package Sessions is
type Session is new WebDriver.Sessions.Session with record
Session_Id : League.Strings.Universal_String;
Executor : access Executors.HTTP_Command_Executor;
end record;
overriding procedure Go
(Self : access Session;
URL : League.Strings.Universal_String);
overriding function Get_Current_URL
(Self : access Session) return League.Strings.Universal_String;
overriding function Find_Element
(Self : access Session;
Strategy : WebDriver.Location_Strategy;
Selector : League.Strings.Universal_String)
return WebDriver.Elements.Element_Access;
end Sessions;
package body Sessions is separate;
package Drivers is
type Driver is limited new WebDriver.Drivers.Driver with record
Executor : aliased Executors.HTTP_Command_Executor;
end record;
overriding function New_Session
(Self : access Driver;
Capabilities : League.JSON.Values.JSON_Value :=
League.JSON.Values.Empty_JSON_Value)
return WebDriver.Sessions.Session_Access;
end Drivers;
package body Drivers is separate;
------------
-- Create --
------------
function Create
(URL : League.Strings.Universal_String)
return WebDriver.Drivers.Driver'Class
is
begin
return Result : Drivers.Driver do
AWS.Client.Create
(Result.Executor.Server,
Host => URL.To_UTF_8_String);
end return;
end Create;
end WebDriver.Remote;
|
-----------------------------------------------------------------------
-- awa-storages-beans -- Storage Ada Beans
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with AWA.Storages.Models;
with AWA.Storages.Modules;
with ASF.Parts;
with Util.Beans.Objects;
with Util.Beans.Basic;
package AWA.Storages.Beans is
FOLDER_ID_PARAMETER : constant String := "folderId";
-- ------------------------------
-- Upload Bean
-- ------------------------------
-- The <b>Upload_Bean</b> allows to upload a file in the storage space.
type Upload_Bean is new AWA.Storages.Models.Storage_Ref
and Util.Beans.Basic.Bean with record
Module : AWA.Storages.Modules.Storage_Module_Access := null;
end record;
type Upload_Bean_Access is access all Upload_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Upload_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Upload_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Save the uploaded file in the storage service.
-- @method
procedure Save_Part (Bean : in out Upload_Bean;
Part : in ASF.Parts.Part'Class);
-- Upload the file.
-- @method
procedure Upload (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the file.
-- @method
procedure Delete (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- ------------------------------
-- Folder Bean
-- ------------------------------
-- The <b>Folder_Bean</b> allows to create or update the folder name.
type Folder_Bean is new AWA.Storages.Models.Storage_Folder_Ref
and Util.Beans.Basic.Bean with record
Module : AWA.Storages.Modules.Storage_Module_Access := null;
end record;
type Folder_Bean_Access is access all Folder_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Folder_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Folder_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the folder.
procedure Save (Bean : in out Folder_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
type Init_Flag is (INIT_FOLDER, INIT_FOLDER_LIST, INIT_FILE_LIST);
type Init_Map is array (Init_Flag) of Boolean;
-- ------------------------------
-- Storage List Bean
-- ------------------------------
-- This bean represents a list of storage files for a given folder.
type Storage_List_Bean is new Util.Beans.Basic.Bean with record
Module : AWA.Storages.Modules.Storage_Module_Access := null;
-- Current folder.
Folder : aliased Folder_Bean;
Folder_Bean : Folder_Bean_Access;
-- List of folders.
Folder_List : aliased AWA.Storages.Models.Folder_Info_List_Bean;
Folder_List_Bean : AWA.Storages.Models.Folder_Info_List_Bean_Access;
-- List of files.
Files_List : aliased AWA.Storages.Models.Storage_Info_List_Bean;
Files_List_Bean : AWA.Storages.Models.Storage_Info_List_Bean_Access;
Init_Flags : aliased Init_Map := (others => False);
Flags : access Init_Map;
end record;
type Storage_List_Bean_Access is access all Storage_List_Bean'Class;
-- Load the folder instance.
procedure Load_Folder (Storage : in Storage_List_Bean);
-- Load the list of folders.
procedure Load_Folders (Storage : in Storage_List_Bean);
-- Load the list of files associated with the current folder.
procedure Load_Files (Storage : in Storage_List_Bean);
overriding
function Get_Value (List : in Storage_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Storage_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create the Folder_List_Bean bean instance.
function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Storage_List_Bean bean instance.
function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Storages.Beans;
|
package body Generic_Inverted_Index is
-- uses some of the new Ada 2012 syntax
use Source_Vecs;
procedure Store(Storage: in out Storage_Type;
Source: Source_Type;
Item: Item_Type) is
use type Maps.Cursor;
begin
if (Storage.Find(Item) = Maps.No_Element) then
Storage.Insert(Key => Item,
New_Item => Empty_Vector & Source);
else
declare
The_Vector: Vector := Storage.Element(Item);
begin
if The_Vector.Last_Element /= Source then
Storage.Replace
(Key => Item,
New_Item => Storage.Element(Item) & Source);
end if;
end;
end if;
end Store;
function Find(Storage: Storage_Type; Item: Item_Type)
return Vector is
begin
return Storage.Element(Item);
exception
when Constraint_Error => return Empty_Vector; -- found nothing
end Find;
function Is_In(S: Source_Type; V: Vector) return Boolean is
begin
for Some_Element of V loop
if Some_Element = S then
return True;
end if;
end loop;
return False;
end Is_In;
function "and"(Left, Right: Vector) return Vector is
V: Vector := Empty_Vector;
begin
for Some_Element of Left loop
if Is_In(Some_Element, Right) then
V := V & Some_Element;
end if;
end loop;
return V;
end "and";
function "or"(Left, Right: Vector) return Vector is
V: Vector := Left; -- all sources in Left
begin
for Some_Element of Right loop
if not Is_In(Some_Element, Left) then
V := V & Some_Element;
end if;
end loop;
return V;
end "or";
function Empty(Vec: Vector) return Boolean
renames Is_Empty;
procedure Iterate(The_Sources: Vector) is
begin
for Some_Element in The_Sources loop
Do_Something(Element(Some_Element));
end loop;
end Iterate;
function Same_Vector(U,V: Vector) return Boolean is
begin
raise Program_Error with "there is no need to call this function";
return False; -- this avoices a compiler warning
end Same_Vector;
end Generic_Inverted_Index;
|
-- Institution: Technische Universität München
-- Department: Realtime Computer Systems (RCS)
-- Project: StratoX
-- Module: PID controller
--
-- Authors: Emanuel Regnath (emanuel.regnath@tum.de)
--
-- Description: PID Controller based on the Ada firmware for crazyflie
-- See https://github.com/AnthonyLeonardoGracio/crazyflie-firmware
--
-- ToDo:
-- [ ] Implementation
with Units; use Units;
generic
type PID_Data_Type is new Unit_Type;
type PID_Output_Type is new Unit_Type;
type PID_Coefficient_Type is new Unit_Type;
PID_INTEGRAL_LIMIT_LOW : PID_Data_Type;
PID_INTEGRAL_LIMIT_HIGH : PID_Data_Type;
PID_OUTPUT_LIMIT_LOW : PID_Output_Type := PID_Output_Type'First;
PID_OUTPUT_LIMIT_HIGH : PID_Output_Type := PID_Output_Type'Last;
package Generic_PID_Controller
with SPARK_Mode => On
is
type Pid_Object is private;
subtype PID_Integral_Type is PID_Data_Type range PID_INTEGRAL_LIMIT_LOW.. PID_INTEGRAL_LIMIT_HIGH;
-- init
procedure initialize(Pid : out Pid_Object;
Kp : PID_Coefficient_Type;
Ki : PID_Coefficient_Type;
Kd : PID_Coefficient_Type;
I_Limit_Low : PID_Data_Type := PID_INTEGRAL_LIMIT_LOW;
I_Limit_High : PID_Data_Type := PID_INTEGRAL_LIMIT_HIGH;
Output_Limit_Low : PID_Output_Type := PID_OUTPUT_LIMIT_LOW;
Output_Limit_High : PID_Output_Type := PID_OUTPUT_LIMIT_HIGH);
procedure reset (Pid : out Pid_Object);
procedure step(Pid : in out Pid_Object; error : PID_Data_Type; dt : Time_Type; result : out PID_Output_Type);
private
type Pid_Object is record
Previous_Error : PID_Data_Type; -- Previous Error
Integral : PID_Integral_Type; -- Integral
Kp : PID_Coefficient_Type; -- Proportional Gain
Ki : PID_Coefficient_Type; -- Integral Gain
Kd : PID_Coefficient_Type; -- Derivative Gain
I_Limit_Low : PID_Data_Type; -- Limit of integral term
I_Limit_High : PID_Data_Type; -- Limit of integral term
Output_Limit_Low : PID_Output_Type;
Output_Limit_High : PID_Output_Type;
end record;
end Generic_PID_Controller;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2021, 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 System.Storage_Elements;
with SAM_SVD.USB; use SAM_SVD.USB;
package body SAM.USB is
NVM_Software_Calibration_Area : constant := 16#00800080#;
USB_Calibration_Addr : constant := NVM_Software_Calibration_Area + 4;
type USB_Calibration is record
TRANSP : UInt5;
TRANSN : UInt5;
TRIM : UInt3;
Reserved : UInt3;
end record
with Volatile_Full_Access, Size => 16;
for USB_Calibration use record
TRANSP at 0 range 0 .. 4;
TRANSN at 0 range 5 .. 9;
TRIM at 0 range 10 .. 12;
Reserved at 0 range 13 .. 15;
end record;
USB_Cal : USB_Calibration
with Address => System'To_Address (USB_Calibration_Addr);
function To_EP_Size (Size : UInt8) return EP_Packet_Size
is (case Size is
when 8 => S_8Bytes,
when 16 => S_16Bytes,
when 32 => S_32Bytes,
when 64 => S_64Bytes,
when 128 => S_128Bytes,
-- when 256 => S_256Bytes,
-- when 512 => S_512Bytes,
-- when 1023 => S_1023Bytes,
when others => raise Program_Error with "Invalid Size for EP"
);
----------------
-- Initialize --
----------------
overriding
procedure Initialize (This : in out UDC) is
P : USB_Peripheral renames This.Periph.all;
begin
-- Reset the peripheral
P.USB_DEVICE.CTRLA.SWRST := True;
while P.USB_DEVICE.SYNCBUSY.SWRST loop
null;
end loop;
P.USB_DEVICE.PADCAL.TRANSP := USB_Cal.TRANSP;
P.USB_DEVICE.PADCAL.TRANSN := USB_Cal.TRANSN;
P.USB_DEVICE.PADCAL.TRIM := USB_Cal.TRIM;
P.USB_DEVICE.CTRLB.DETACH := True;
-- Highest Quality of Service
P.USB_DEVICE.QOSCTRL.CQOS := 3;
P.USB_DEVICE.QOSCTRL.DQOS := 3;
P.USB_DEVICE.CTRLB.SPDCONF := FS;
P.USB_DEVICE.DESCADD :=
UInt32 (System.Storage_Elements.To_Integer (This.EP_Descs'Address));
end Initialize;
--------------------
-- Request_Buffer --
--------------------
overriding
function Request_Buffer (This : in out UDC;
Ep : EP_Addr;
Len : UInt11;
Min_Alignment : UInt8 := 1)
return System.Address
is
begin
return Standard.USB.Utils.Allocate
(This.Alloc,
Alignment => UInt8'Max (Min_Alignment, EP_Buffer_Min_Alignment),
Len => Len);
end Request_Buffer;
-----------
-- Start --
-----------
overriding
procedure Start (This : in out UDC) is
begin
This.Periph.USB_DEVICE.CTRLA := (MODE => DEVICE,
RUNSTDBY => True,
ENABLE => True,
SWRST => False,
others => <>);
while This.Periph.USB_DEVICE.SYNCBUSY.ENABLE loop
null;
end loop;
This.Periph.USB_DEVICE.CTRLB.DETACH := False;
This.EP_Descs (0).Bank0_Out.ADDR := This.EP0_Buffer'Address;
if (UInt32 (System.Storage_Elements.To_Integer (This.EP0_Buffer'Address))
and 2#11#) /= 0
then
raise Program_Error with "Invalid alignement for EP0 buffer";
end if;
This.EP0_Buffer := (others => 42);
end Start;
-----------
-- Reset --
-----------
overriding
procedure Reset (This : in out UDC)
is
begin
null;
end Reset;
----------
-- Poll --
----------
overriding
function Poll (This : in out UDC) return UDC_Event is
P : USB_Peripheral renames This.Periph.all;
begin
-- End Of Reset
if P.USB_DEVICE.INTFLAG.EORST then
-- Clear flag
P.USB_DEVICE.INTFLAG.EORST := True;
return (Kind => Reset);
end if;
-- Endpoint events
declare
EPINT : UInt8 := P.USB_DEVICE.EPINTSMRY.EPINT.Val;
EP_Status : USB_EPINTFLAG_USB_DEVICE_ENDPOINT_Register;
EP_Out_Size, EP_In_Size : UInt14;
begin
for Ep in P.USB_DEVICE.USB_DEVICE_ENDPOINT'Range loop
exit when EPINT = 0;
if True or else (EPINT and 1) /= 0 then
EP_Status := P.USB_DEVICE.USB_DEVICE_ENDPOINT (Ep).EPINTFLAG;
-- Setup Request
if Ep = 0
and then
EP_Status.RXSTP
then
P.USB_DEVICE.USB_DEVICE_ENDPOINT (0).EPINTFLAG :=
(
-- Clear the interrupt the RXSTP flag.
RXSTP => True,
-- Although Setup packet only set RXSTP bit, TRCPT0 bit
-- could already be set by previous ZLP OUT Status (not
-- handled until now).
TRCPT0 => True,
others => <>);
declare
Req : Setup_Data with Address => This.EP0_Buffer'Address;
begin
return (Kind => Setup_Request,
Req => Req,
Req_EP => 0);
end;
end if;
-- Check transfer IN complete
if EP_Status.TRCPT1 then
P.USB_DEVICE.USB_DEVICE_ENDPOINT (Ep).EPINTFLAG :=
(TRCPT1 => True, TRFAIL1 => True, others => <>);
EP_In_Size := This.EP_Descs (Ep).Bank1_In.PCKSIZE.BYTE_COUNT;
return (Kind => Transfer_Complete,
EP => (UInt4 (Ep), EP_In),
BCNT => UInt11 (EP_In_Size));
end if;
-- Check transfer OUT complete
if EP_Status.TRCPT0 then
EP_Out_Size :=
This.EP_Descs (Ep).Bank0_Out.PCKSIZE.BYTE_COUNT;
P.USB_DEVICE.USB_DEVICE_ENDPOINT (Ep).EPINTFLAG :=
(TRCPT0 => True, others => <>);
return (Kind => Transfer_Complete,
EP => (UInt4 (Ep), EP_Out),
BCNT => UInt11 (EP_Out_Size));
end if;
end if;
EPINT := Shift_Right (EPINT, 1);
end loop;
end;
return No_Event;
end Poll;
---------------------
-- EP_Write_Packet --
---------------------
overriding
procedure EP_Write_Packet (This : in out UDC;
Ep : EP_Id;
Addr : System.Address;
Len : UInt32)
is
P : USB_Peripheral renames This.Periph.all;
Num : constant Natural := Natural (Ep);
begin
if Num > This.Periph.USB_DEVICE.USB_DEVICE_ENDPOINT'Last
then
raise Program_Error with "Invalid endpoint number";
end if;
if Len > UInt32 (UInt14'Last) then
raise Program_Error with "Packet too big for endpoint";
end if;
This.EP_Descs (Num).Bank1_In.ADDR := Addr;
This.EP_Descs (Num).Bank1_In.PCKSIZE.BYTE_COUNT := UInt14 (Len);
This.EP_Descs (Num).Bank1_In.PCKSIZE.MULTI_PACKET_SIZE := 0;
-- Set the bank to ready to start the transfer
P.USB_DEVICE.USB_DEVICE_ENDPOINT (Num).EPINTFLAG :=
(TRFAIL1 => True, others => <>);
P.USB_DEVICE.USB_DEVICE_ENDPOINT (Num).EPSTATUSSET.BK1RDY := True;
end EP_Write_Packet;
--------------
-- EP_Setup --
--------------
overriding
procedure EP_Setup (This : in out UDC;
EP : EP_Addr;
Typ : EP_Type;
Max_Size : UInt16)
is
P : USB_Peripheral renames This.Periph.all;
Num : constant Natural := Natural (EP.Num);
EPTYPE : constant UInt3 := (case Typ is
when Control => 1,
when Isochronous => 2,
when Bulk => 3,
when Interrupt => 4);
begin
if Num > This.Periph.USB_DEVICE.USB_DEVICE_ENDPOINT'Last
then
raise Program_Error with "Invalid endpoint number";
end if;
case EP.Dir is
when EP_Out =>
This.EP_Descs (Num).Bank0_Out.PCKSIZE.SIZE :=
To_EP_Size (This.Max_Packet_Size);
This.EP_Descs (Num).Bank0_Out.PCKSIZE.BYTE_COUNT := 0;
This.EP_Descs (Num).Bank0_Out.PCKSIZE.MULTI_PACKET_SIZE := 0;
This.EP_Descs (Num).Bank0_Out.PCKSIZE.AUTO_ZLP := False;
-- Clear flags
P.USB_DEVICE.USB_DEVICE_ENDPOINT (Num).EPINTFLAG :=
(TRCPT0 => True, others => <>);
-- Enable the endpoint with the requested type
P.USB_DEVICE.USB_DEVICE_ENDPOINT (Num).EPCFG.EPTYPE0 := EPTYPE;
-- Enable TRCPT interrupt
-- /!\ If the endpoint is not enabled the interrupt will not be
-- enabled.
P.USB_DEVICE.USB_DEVICE_ENDPOINT (Num).EPINTENSET.TRCPT0 := True;
when EP_In =>
This.EP_Descs (Num).Bank1_In.PCKSIZE.SIZE :=
To_EP_Size (This.Max_Packet_Size);
This.EP_Descs (Num).Bank1_In.PCKSIZE.BYTE_COUNT := 0;
This.EP_Descs (Num).Bank1_In.PCKSIZE.MULTI_PACKET_SIZE := 0;
This.EP_Descs (Num).Bank1_In.PCKSIZE.AUTO_ZLP := False;
-- Clear flags
P.USB_DEVICE.USB_DEVICE_ENDPOINT (Num).EPINTFLAG :=
(TRCPT1 => True, others => <>);
-- Enable the endpoint with the requested type
P.USB_DEVICE.USB_DEVICE_ENDPOINT (Num).EPCFG.EPTYPE1 := EPTYPE;
-- Enable TRCPT interrupt
-- /!\ If the endpoint is not enabled the interrupt will not be
-- enabled.
P.USB_DEVICE.USB_DEVICE_ENDPOINT (Num).EPINTENSET.TRCPT1 := True;
end case;
end EP_Setup;
-----------------------
-- EP_Ready_For_Data --
-----------------------
overriding
procedure EP_Ready_For_Data (This : in out UDC;
EP : EP_Id;
Addr : System.Address;
Size : UInt32;
Ready : Boolean := True)
is
P : USB_Peripheral renames This.Periph.all;
Num : constant Natural := Natural (EP);
begin
if Num > This.Periph.USB_DEVICE.USB_DEVICE_ENDPOINT'Last
then
raise Program_Error with "Invalid endpoint number";
end if;
if Ready then
if EP = 0 then
-- TODO: Why? EP0 always on internal buffer?
This.EP_Descs (0).Bank0_Out.ADDR := This.EP0_Buffer'Address;
else
This.EP_Descs (Num).Bank0_Out.ADDR := Addr;
end if;
-- Enable RXSTP interrupt
P.USB_DEVICE.USB_DEVICE_ENDPOINT (Num).EPINTENSET.RXSTP := True;
This.EP_Descs (Num).Bank0_Out.PCKSIZE.MULTI_PACKET_SIZE :=
UInt14 (Size);
This.EP_Descs (Num).Bank0_Out.PCKSIZE.BYTE_COUNT := 0;
-- Clear Bank0-Ready to say we are ready to receive data
P.USB_DEVICE.USB_DEVICE_ENDPOINT (Num).EPINTFLAG :=
(TRFAIL0 => True, others => <>);
P.USB_DEVICE.USB_DEVICE_ENDPOINT (Num).EPSTATUSCLR.BK0RDY := True;
else
-- Set Bank0-Ready to say we are NOT ready to receive data
P.USB_DEVICE.USB_DEVICE_ENDPOINT (Num).EPSTATUSSET.BK0RDY := True;
end if;
end EP_Ready_For_Data;
--------------
-- EP_Stall --
--------------
overriding
procedure EP_Stall (This : in out UDC;
EP : EP_Addr;
Set : Boolean := True)
is
P : USB_Peripheral renames This.Periph.all;
Num : constant Natural := Natural (EP.Num);
begin
if Integer (EP.Num) > This.Periph.USB_DEVICE.USB_DEVICE_ENDPOINT'Last
then
raise Program_Error with "Invalid endpoint number";
end if;
case EP.Dir is
when EP_Out =>
if Set then
P.USB_DEVICE.USB_DEVICE_ENDPOINT
(Num).EPSTATUSSET.STALLRQ.Arr (0) := True;
else
P.USB_DEVICE.USB_DEVICE_ENDPOINT
(Num).EPSTATUSCLR.STALLRQ.Arr (0) := True;
end if;
when EP_In =>
if Set then
P.USB_DEVICE.USB_DEVICE_ENDPOINT
(Num).EPSTATUSSET.STALLRQ.Arr (1) := True;
else
P.USB_DEVICE.USB_DEVICE_ENDPOINT
(Num).EPSTATUSCLR.STALLRQ.Arr (1) := True;
end if;
end case;
end EP_Stall;
-----------------
-- Set_Address --
-----------------
overriding
procedure Set_Address (This : in out UDC;
Addr : UInt7)
is
begin
This.Periph.USB_DEVICE.DADD := (ADDEN => True, DADD => Addr);
end Set_Address;
end SAM.USB;
|
--
-- Copyright (C) 2015-2018 secunet Security Networks AG
-- Copyright (C) 2017 Nico Huber <nico.h@gmx.de>
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
with HW.Config;
with HW.Time;
with HW.Port_IO;
package HW.GFX.GMA
with
Abstract_State =>
(State,
Init_State,
Config_State,
(Device_State with External)),
Initializes =>
(Init_State,
Config_State)
is
GTT_Page_Size : constant := 4096;
type GTT_Address_Type is mod 2 ** 39;
subtype GTT_Range is Natural range 0 .. 16#8_0000# - 1;
GTT_Rotation_Offset : constant GTT_Range := GTT_Range'Last / 2 + 1;
type CPU_Type is
(G45,
Ironlake,
Sandybridge,
Ivybridge,
Haswell,
Broadwell,
Broxton,
Skylake);
type CPU_Variant is (Normal, ULT);
type Port_Type is
(Disabled,
Internal,
DP1,
DP2,
DP3,
HDMI1, -- or DVI
HDMI2, -- or DVI
HDMI3, -- or DVI
Analog);
type Cursor_Mode is (No_Cursor, ARGB_Cursor);
type Cursor_Size is (Cursor_64x64, Cursor_128x128, Cursor_256x256);
Cursor_Width : constant array (Cursor_Size) of Width_Type := (64, 128, 256);
subtype Cursor_Pos is Int32 range Int32'First / 2 .. Int32'Last / 2;
type Cursor_Type is record
Mode : Cursor_Mode;
Size : Cursor_Size;
Center_X : Cursor_Pos;
Center_Y : Cursor_Pos;
GTT_Offset : GTT_Range;
end record;
Default_Cursor : constant Cursor_Type :=
(Mode => No_Cursor,
Size => Cursor_Size'First,
Center_X => 0,
Center_Y => 0,
GTT_Offset => 0);
type Pipe_Config is record
Port : Port_Type;
Framebuffer : Framebuffer_Type;
Cursor : Cursor_Type;
Mode : Mode_Type;
end record;
type Pipe_Index is (Primary, Secondary, Tertiary);
type Pipe_Configs is array (Pipe_Index) of Pipe_Config;
-- Special framebuffer offset to indicate legacy VGA plane.
-- Only valid on primary pipe.
VGA_PLANE_FRAMEBUFFER_OFFSET : constant := 16#ffff_ffff#;
pragma Warnings (GNATprove, Off, "unused variable ""Write_Delay""",
Reason => "Write_Delay is used for debugging only");
procedure Initialize
(Write_Delay : in Word64 := 0;
Clean_State : in Boolean := False;
Success : out Boolean)
with
Global =>
(In_Out => (Config_State, Device_State, Port_IO.State),
Output => (State, Init_State),
Input => (Time.State)),
Post => Success = Is_Initialized;
function Is_Initialized return Boolean
with
Global => (Input => Init_State);
pragma Warnings (GNATprove, On, "unused variable ""Write_Delay""");
pragma Warnings (GNATprove, Off, "subprogram ""Power_Up_VGA"" has no effect",
Reason => "Effect depends on the platform compiled for");
procedure Power_Up_VGA
with
Pre => Is_Initialized;
procedure Update_Outputs (Configs : Pipe_Configs);
procedure Update_Cursor (Pipe : Pipe_Index; Cursor : Cursor_Type);
procedure Place_Cursor
(Pipe : Pipe_Index;
X : Cursor_Pos;
Y : Cursor_Pos);
procedure Move_Cursor
(Pipe : Pipe_Index;
X : Cursor_Pos;
Y : Cursor_Pos);
pragma Warnings (GNATprove, Off, "subprogram ""Dump_Configs"" has no effect",
Reason => "It's only used for debugging");
procedure Dump_Configs (Configs : Pipe_Configs);
procedure Write_GTT
(GTT_Page : GTT_Range;
Device_Address : GTT_Address_Type;
Valid : Boolean);
procedure Setup_Default_FB
(FB : in Framebuffer_Type;
Clear : in Boolean := True;
Success : out Boolean)
with
Pre => Is_Initialized and HW.Config.Dynamic_MMIO;
procedure Map_Linear_FB (Linear_FB : out Word64; FB : in Framebuffer_Type)
with
Pre => Is_Initialized and HW.Config.Dynamic_MMIO;
private
-- For the default framebuffer setup (see below) with 90 degree rotations,
-- we expect the offset which is used for the final scanout to be above
-- `GTT_Rotation_Offset`. So we can use `Offset - GTT_Rotation_Offset` for
-- the physical memory location and aperture mapping.
function Phys_Offset (FB : Framebuffer_Type) return Word32 is
(if Rotation_90 (FB)
then FB.Offset - Word32 (GTT_Rotation_Offset) * GTT_Page_Size
else FB.Offset);
----------------------------------------------------------------------------
-- State tracking for the currently configured pipes
Cur_Configs : Pipe_Configs with Part_Of => State;
function Requires_Scaling (Pipe_Cfg : Pipe_Config) return Boolean is
(Requires_Scaling (Pipe_Cfg.Framebuffer, Pipe_Cfg.Mode));
function Scaling_Type (Pipe_Cfg : Pipe_Config) return Scaling_Aspect is
(Scaling_Type (Pipe_Cfg.Framebuffer, Pipe_Cfg.Mode));
----------------------------------------------------------------------------
-- Internal representation of a single pipe's configuration
subtype Active_Port_Type is Port_Type
range Port_Type'Succ (Disabled) .. Port_Type'Last;
type GPU_Port is (DIGI_A, DIGI_B, DIGI_C, DIGI_D, DIGI_E, LVDS, VGA);
subtype Digital_Port is GPU_Port range DIGI_A .. DIGI_E;
subtype GMCH_DP_Port is GPU_Port range DIGI_B .. DIGI_D;
subtype GMCH_HDMI_Port is GPU_Port range DIGI_B .. DIGI_C;
type PCH_Port is
(PCH_DAC, PCH_LVDS,
PCH_HDMI_B, PCH_HDMI_C, PCH_HDMI_D,
PCH_DP_B, PCH_DP_C, PCH_DP_D);
subtype PCH_HDMI_Port is PCH_Port range PCH_HDMI_B .. PCH_HDMI_D;
subtype PCH_DP_Port is PCH_Port range PCH_DP_B .. PCH_DP_D;
type Port_Config is
record
Port : GPU_Port;
PCH_Port : GMA.PCH_Port;
Display : Display_Type;
Mode : Mode_Type;
Is_FDI : Boolean;
FDI : DP_Link;
DP : DP_Link;
end record;
type FDI_Training_Type is (Simple_Training, Full_Training, Auto_Training);
----------------------------------------------------------------------------
type DP_Port is (DP_A, DP_B, DP_C, DP_D);
----------------------------------------------------------------------------
subtype DDI_HDMI_Buf_Trans_Range is Integer range 0 .. 11;
----------------------------------------------------------------------------
Tile_Width : constant array (Tiling_Type) of Width_Type :=
(Linear => 16, X_Tiled => 128, Y_Tiled => 32);
Tile_Rows : constant array (Tiling_Type) of Height_Type :=
(Linear => 1, X_Tiled => 8, Y_Tiled => 32);
function FB_Pitch (Px : Pos_Pixel_Type; FB : Framebuffer_Type) return Natural
is (Natural (Div_Round_Up
(Pixel_To_Bytes (Px, FB), Tile_Width (FB.Tiling) * 4)));
function Valid_Stride (FB : Framebuffer_Type) return Boolean is
(FB.Width + FB.Start_X <= FB.Stride and
Pixel_To_Bytes (FB.Stride, FB) mod (Tile_Width (FB.Tiling) * 4) = 0 and
FB.Height + FB.Start_Y <= FB.V_Stride and
FB.V_Stride mod Tile_Rows (FB.Tiling) = 0);
end HW.GFX.GMA;
|
with Aggr9_Pkg; use Aggr9_Pkg;
package Aggr9 is
procedure Proc (X : R1);
end Aggr9;
|
package body Types is
function "<"(Gauche: T_Rank; Droit: T_Rank) return Boolean is
begin
return Gauche.Poid < Droit.Poid;
end "<";
function Hachage(Indice: in T_Indice) return Integer is
begin
return Indice.X;
end Hachage;
end Types; |
with Ada.Text_IO;
--use Ada.Text_IO;
with Ada.Numerics.Elementary_Functions;
with Ada.Float_Text_IO;
procedure adaDemo2 is
type Day_type is range 1 .. 31;
type Month_type is range 1 .. 12;
type Year_type is range 1800 .. 2100;
type Hours is mod 24;
type Weekday is (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday);
type Date is
record
Day : Day_type;
Month : Month_type;
Year : Year_type;
end record;
type Cog is new Integer;
type rearGears is array(Cog) of Cog ;
subtype Working_Hours is Hours range 0 .. 12; -- at most 12 Hours to work a day
subtype Working_Day is Weekday range Monday .. Friday; -- Days to work
fl1 : float;
g : float;
begin
fl1 := 2.0;
-- rearGears := (12,14,16,18,22,26,40);
--Work_Load: constant array(Working_Day) of Working_Hours -- implicit type declaration
-- := (Friday => 6, Monday => 4, others => 10); -- lookup table for working hours with initialization
-- while a is not equal to b, loop.
--while a /= b loop
-- Ada.Text_IO.Put_Line ("Waiting");
--end loop;
--if a > b then
-- Ada.Text_IO.Put_Line ("Condition met");
--else
-- Ada.Text_IO.Put_Line ("Condition not met");
--end if;
-- g := Ada.Numerics.Generic_Complex_Elementary_Functions.Sqrt(fl1);
for i in 2..10 loop
g := Ada.Numerics.Elementary_Functions.Sqrt ( float(i) );
Ada.Float_Text_IO.Put(g,5,4,0);
Ada.Text_IO.Put_Line("");
end loop;
-- 1.414
--Iteration:
--for f in range
for i in 1 .. 10 loop
Ada.Text_IO.Put ("Iteration: ");
--Ada.Text_IO.Put (i);
Ada.Text_IO.Put_Line("");
end loop;
--loop
-- a := a + 1;
-- exit when a = 10;
-- end loop;
for i in 0..5 loop
case i is
when 0 => Ada.Text_IO.Put ("zero");
when 1 => Ada.Text_IO.Put ("one");
when 2 => Ada.Text_IO.Put ("two");
-- case statements have to cover all possible cases:
when others => Ada.Text_IO.Put ("none of the above");
Ada.Text_IO.Put (" _ ");
end case;
Ada.Text_IO.Put (" x ");
end loop;
--for aWeekday in Weekday'Range loop -- loop over an enumeration
-- Put_Line ( Weekday'Image(aWeekday) ); -- output string representation of an enumeration
-- if aWeekday in Working_Day then -- check of a subtype of an enumeration
-- Put_Line ( " to work for " &
-- Working_Hours'Image (Work_Load(aWeekday)) ); -- access into a lookup table
-- end if;
--
--
--
--end loop;
end adaDemo2;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- A D A . T A S K _ T E R M I N A T I O N --
-- --
-- B o d y --
-- --
-- Copyright (C) 2005-2020, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with System.Tasking;
with System.Task_Primitives.Operations;
with System.Soft_Links;
with Ada.Unchecked_Conversion;
package body Ada.Task_Termination is
use type Ada.Task_Identification.Task_Id;
package STPO renames System.Task_Primitives.Operations;
package SSL renames System.Soft_Links;
-----------------------
-- Local subprograms --
-----------------------
function To_TT is new Ada.Unchecked_Conversion
(System.Tasking.Termination_Handler, Termination_Handler);
function To_ST is new Ada.Unchecked_Conversion
(Termination_Handler, System.Tasking.Termination_Handler);
function To_Task_Id is new Ada.Unchecked_Conversion
(Ada.Task_Identification.Task_Id, System.Tasking.Task_Id);
-----------------------------------
-- Current_Task_Fallback_Handler --
-----------------------------------
function Current_Task_Fallback_Handler return Termination_Handler is
begin
-- There is no need for explicit protection against race conditions
-- for this function because this function can only be executed by
-- Self, and the Fall_Back_Handler can only be modified by Self.
return To_TT (STPO.Self.Common.Fall_Back_Handler);
end Current_Task_Fallback_Handler;
-------------------------------------
-- Set_Dependents_Fallback_Handler --
-------------------------------------
procedure Set_Dependents_Fallback_Handler
(Handler : Termination_Handler)
is
Self : constant System.Tasking.Task_Id := STPO.Self;
begin
SSL.Abort_Defer.all;
STPO.Write_Lock (Self);
Self.Common.Fall_Back_Handler := To_ST (Handler);
STPO.Unlock (Self);
SSL.Abort_Undefer.all;
end Set_Dependents_Fallback_Handler;
--------------------------
-- Set_Specific_Handler --
--------------------------
procedure Set_Specific_Handler
(T : Ada.Task_Identification.Task_Id;
Handler : Termination_Handler)
is
begin
-- Tasking_Error is raised if the task identified by T has already
-- terminated. Program_Error is raised if the value of T is
-- Null_Task_Id.
if T = Ada.Task_Identification.Null_Task_Id then
raise Program_Error;
elsif Ada.Task_Identification.Is_Terminated (T) then
raise Tasking_Error;
else
declare
Target : constant System.Tasking.Task_Id := To_Task_Id (T);
begin
SSL.Abort_Defer.all;
STPO.Write_Lock (Target);
Target.Common.Specific_Handler := To_ST (Handler);
STPO.Unlock (Target);
SSL.Abort_Undefer.all;
end;
end if;
end Set_Specific_Handler;
----------------------
-- Specific_Handler --
----------------------
function Specific_Handler
(T : Ada.Task_Identification.Task_Id) return Termination_Handler
is
begin
-- Tasking_Error is raised if the task identified by T has already
-- terminated. Program_Error is raised if the value of T is
-- Null_Task_Id.
if T = Ada.Task_Identification.Null_Task_Id then
raise Program_Error;
elsif Ada.Task_Identification.Is_Terminated (T) then
raise Tasking_Error;
else
declare
Target : constant System.Tasking.Task_Id := To_Task_Id (T);
TH : Termination_Handler;
begin
SSL.Abort_Defer.all;
STPO.Write_Lock (Target);
TH := To_TT (Target.Common.Specific_Handler);
STPO.Unlock (Target);
SSL.Abort_Undefer.all;
return TH;
end;
end if;
end Specific_Handler;
end Ada.Task_Termination;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- A D A . R E A L _ T I M E --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2019, Free Software Foundation, Inc. --
-- --
-- This specification is derived from the Ada Reference Manual for use with --
-- GNAT. The copyright notice above, and the license provisions that follow --
-- apply solely to the contents of the part following the private keyword. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with System.Task_Primitives.Operations;
pragma Elaborate_All (System.Task_Primitives.Operations);
package Ada.Real_Time with
SPARK_Mode,
Abstract_State => (Clock_Time with Synchronous),
Initializes => Clock_Time
is
pragma Compile_Time_Error
(Duration'Size /= 64,
"this version of Ada.Real_Time requires 64-bit Duration");
type Time is private;
Time_First : constant Time;
Time_Last : constant Time;
Time_Unit : constant := 10#1.0#E-9;
type Time_Span is private;
Time_Span_First : constant Time_Span;
Time_Span_Last : constant Time_Span;
Time_Span_Zero : constant Time_Span;
Time_Span_Unit : constant Time_Span;
Tick : constant Time_Span;
function Clock return Time with
Volatile_Function,
Global => Clock_Time;
function "+" (Left : Time; Right : Time_Span) return Time with
Global => null;
function "+" (Left : Time_Span; Right : Time) return Time with
Global => null;
function "-" (Left : Time; Right : Time_Span) return Time with
Global => null;
function "-" (Left : Time; Right : Time) return Time_Span with
Global => null;
function "<" (Left, Right : Time) return Boolean with
Global => null;
function "<=" (Left, Right : Time) return Boolean with
Global => null;
function ">" (Left, Right : Time) return Boolean with
Global => null;
function ">=" (Left, Right : Time) return Boolean with
Global => null;
function "+" (Left, Right : Time_Span) return Time_Span with
Global => null;
function "-" (Left, Right : Time_Span) return Time_Span with
Global => null;
function "-" (Right : Time_Span) return Time_Span with
Global => null;
function "*" (Left : Time_Span; Right : Integer) return Time_Span with
Global => null;
function "*" (Left : Integer; Right : Time_Span) return Time_Span with
Global => null;
function "/" (Left, Right : Time_Span) return Integer with
Global => null;
function "/" (Left : Time_Span; Right : Integer) return Time_Span with
Global => null;
function "abs" (Right : Time_Span) return Time_Span with
Global => null;
function "<" (Left, Right : Time_Span) return Boolean with
Global => null;
function "<=" (Left, Right : Time_Span) return Boolean with
Global => null;
function ">" (Left, Right : Time_Span) return Boolean with
Global => null;
function ">=" (Left, Right : Time_Span) return Boolean with
Global => null;
function To_Duration (TS : Time_Span) return Duration with
Global => null;
function To_Time_Span (D : Duration) return Time_Span with
Global => null;
function Nanoseconds (NS : Integer) return Time_Span with
Global => null;
function Microseconds (US : Integer) return Time_Span with
Global => null;
function Milliseconds (MS : Integer) return Time_Span with
Global => null;
function Seconds (S : Integer) return Time_Span with
Global => null;
pragma Ada_05 (Seconds);
function Minutes (M : Integer) return Time_Span with
Global => null;
pragma Ada_05 (Minutes);
type Seconds_Count is new Long_Long_Integer;
-- Seconds_Count needs 64 bits, since the type Time has the full range of
-- Duration. The delta of Duration is 10 ** (-9), so the maximum number of
-- seconds is 2**63/10**9 = 8*10**9 which does not quite fit in 32 bits.
-- However, rather than make this explicitly 64-bits we derive from
-- Long_Long_Integer. In normal usage this will have the same effect. But
-- in the case of CodePeer with a target configuration file with a maximum
-- integer size of 32, it allows analysis of this unit.
procedure Split (T : Time; SC : out Seconds_Count; TS : out Time_Span)
with
Global => null;
function Time_Of (SC : Seconds_Count; TS : Time_Span) return Time
with
Global => null;
private
pragma SPARK_Mode (Off);
-- Time and Time_Span are represented in 64-bit Duration value in
-- nanoseconds. For example, 1 second and 1 nanosecond is represented
-- as the stored integer 1_000_000_001. This is for the 64-bit Duration
-- case, not clear if this also is used for 32-bit Duration values.
type Time is new Duration;
Time_First : constant Time := Time'First;
Time_Last : constant Time := Time'Last;
type Time_Span is new Duration;
Time_Span_First : constant Time_Span := Time_Span'First;
Time_Span_Last : constant Time_Span := Time_Span'Last;
Time_Span_Zero : constant Time_Span := 0.0;
Time_Span_Unit : constant Time_Span := 10#1.0#E-9;
Tick : constant Time_Span :=
Time_Span (System.Task_Primitives.Operations.RT_Resolution);
pragma Import (Intrinsic, "<");
pragma Import (Intrinsic, "<=");
pragma Import (Intrinsic, ">");
pragma Import (Intrinsic, ">=");
pragma Import (Intrinsic, "abs");
pragma Inline (Microseconds);
pragma Inline (Milliseconds);
pragma Inline (Nanoseconds);
pragma Inline (Seconds);
pragma Inline (Minutes);
end Ada.Real_Time;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S W I T C H --
-- --
-- B o d y --
-- --
-- $Revision$
-- --
-- Copyright (C) 1992-2001, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
-- MA 02111-1307, USA. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- Option switch scanning for both the compiler and the binder
-- Note: this version of the package should be usable in both Unix and DOS
with Debug; use Debug;
with Osint; use Osint;
with Opt; use Opt;
with Validsw; use Validsw;
with Stylesw; use Stylesw;
with Types; use Types;
with System.WCh_Con; use System.WCh_Con;
package body Switch is
Bad_Switch : exception;
-- Exception raised if bad switch encountered
Bad_Switch_Value : exception;
-- Exception raised if bad switch value encountered
Missing_Switch_Value : exception;
-- Exception raised if no switch value encountered
Too_Many_Output_Files : exception;
-- Exception raised if the -o switch is encountered more than once
Switch_Max_Value : constant := 999;
-- Maximum value permitted in switches that take a value
procedure Scan_Nat
(Switch_Chars : String;
Max : Integer;
Ptr : in out Integer;
Result : out Nat);
-- Scan natural integer parameter for switch. On entry, Ptr points
-- just past the switch character, on exit it points past the last
-- digit of the integer value.
procedure Scan_Pos
(Switch_Chars : String;
Max : Integer;
Ptr : in out Integer;
Result : out Pos);
-- Scan positive integer parameter for switch. On entry, Ptr points
-- just past the switch character, on exit it points past the last
-- digit of the integer value.
-------------------------
-- Is_Front_End_Switch --
-------------------------
function Is_Front_End_Switch (Switch_Chars : String) return Boolean is
Ptr : constant Positive := Switch_Chars'First;
begin
return Is_Switch (Switch_Chars)
and then
(Switch_Chars (Ptr + 1) = 'I'
or else
(Switch_Chars'Length >= 5
and then Switch_Chars (Ptr + 1 .. Ptr + 4) = "gnat"));
end Is_Front_End_Switch;
---------------
-- Is_Switch --
---------------
function Is_Switch (Switch_Chars : String) return Boolean is
begin
return Switch_Chars'Length > 1
and then (Switch_Chars (Switch_Chars'First) = '-'
or
Switch_Chars (Switch_Chars'First) = Switch_Character);
end Is_Switch;
--------------------------
-- Scan_Binder_Switches --
--------------------------
procedure Scan_Binder_Switches (Switch_Chars : String) is
Ptr : Integer := Switch_Chars'First;
Max : Integer := Switch_Chars'Last;
C : Character := ' ';
begin
-- Skip past the initial character (must be the switch character)
if Ptr = Max then
raise Bad_Switch;
else
Ptr := Ptr + 1;
end if;
-- A little check, "gnat" at the start of a switch is not allowed
-- except for the compiler
if Switch_Chars'Last >= Ptr + 3
and then Switch_Chars (Ptr .. Ptr + 3) = "gnat"
then
Osint.Fail ("invalid switch: """, Switch_Chars, """"
& " (gnat not needed here)");
end if;
-- Loop to scan through switches given in switch string
while Ptr <= Max loop
C := Switch_Chars (Ptr);
case C is
-- Processing for A switch
when 'A' =>
Ptr := Ptr + 1;
Ada_Bind_File := True;
-- Processing for b switch
when 'b' =>
Ptr := Ptr + 1;
Brief_Output := True;
-- Processing for c switch
when 'c' =>
Ptr := Ptr + 1;
Check_Only := True;
-- Processing for C switch
when 'C' =>
Ptr := Ptr + 1;
Ada_Bind_File := False;
-- Processing for d switch
when 'd' =>
-- Note: for the debug switch, the remaining characters in this
-- switch field must all be debug flags, since all valid switch
-- characters are also valid debug characters.
-- Loop to scan out debug flags
while Ptr < Max loop
Ptr := Ptr + 1;
C := Switch_Chars (Ptr);
exit when C = ASCII.NUL or else C = '/' or else C = '-';
if C in '1' .. '9' or else
C in 'a' .. 'z' or else
C in 'A' .. 'Z'
then
Set_Debug_Flag (C);
else
raise Bad_Switch;
end if;
end loop;
-- Make sure Zero_Cost_Exceptions is set if gnatdX set. This
-- is for backwards compatibility with old versions and usage.
if Debug_Flag_XX then
Zero_Cost_Exceptions_Set := True;
Zero_Cost_Exceptions_Val := True;
end if;
return;
-- Processing for e switch
when 'e' =>
Ptr := Ptr + 1;
Elab_Dependency_Output := True;
-- Processing for E switch
when 'E' =>
Ptr := Ptr + 1;
Exception_Tracebacks := True;
-- Processing for f switch
when 'f' =>
Ptr := Ptr + 1;
Force_RM_Elaboration_Order := True;
-- Processing for g switch
when 'g' =>
Ptr := Ptr + 1;
if Ptr <= Max then
C := Switch_Chars (Ptr);
if C in '0' .. '3' then
Debugger_Level :=
Character'Pos
(Switch_Chars (Ptr)) - Character'Pos ('0');
Ptr := Ptr + 1;
end if;
else
Debugger_Level := 2;
end if;
-- Processing for G switch
when 'G' =>
Ptr := Ptr + 1;
Print_Generated_Code := True;
-- Processing for h switch
when 'h' =>
Ptr := Ptr + 1;
Usage_Requested := True;
-- Processing for i switch
when 'i' =>
if Ptr = Max then
raise Bad_Switch;
end if;
Ptr := Ptr + 1;
C := Switch_Chars (Ptr);
if C in '1' .. '5'
or else C = '8'
or else C = 'p'
or else C = 'f'
or else C = 'n'
or else C = 'w'
then
Identifier_Character_Set := C;
Ptr := Ptr + 1;
else
raise Bad_Switch;
end if;
-- Processing for K switch
when 'K' =>
Ptr := Ptr + 1;
if Program = Binder then
Output_Linker_Option_List := True;
else
raise Bad_Switch;
end if;
-- Processing for l switch
when 'l' =>
Ptr := Ptr + 1;
Elab_Order_Output := True;
-- Processing for m switch
when 'm' =>
Ptr := Ptr + 1;
Scan_Pos (Switch_Chars, Max, Ptr, Maximum_Errors);
-- Processing for n switch
when 'n' =>
Ptr := Ptr + 1;
Bind_Main_Program := False;
-- Note: The -L option of the binder also implies -n, so
-- any change here must also be reflected in the processing
-- for -L that is found in Gnatbind.Scan_Bind_Arg.
-- Processing for o switch
when 'o' =>
Ptr := Ptr + 1;
if Output_File_Name_Present then
raise Too_Many_Output_Files;
else
Output_File_Name_Present := True;
end if;
-- Processing for O switch
when 'O' =>
Ptr := Ptr + 1;
Output_Object_List := True;
-- Processing for p switch
when 'p' =>
Ptr := Ptr + 1;
Pessimistic_Elab_Order := True;
-- Processing for q switch
when 'q' =>
Ptr := Ptr + 1;
Quiet_Output := True;
-- Processing for s switch
when 's' =>
Ptr := Ptr + 1;
All_Sources := True;
Check_Source_Files := True;
-- Processing for t switch
when 't' =>
Ptr := Ptr + 1;
Tolerate_Consistency_Errors := True;
-- Processing for T switch
when 'T' =>
Ptr := Ptr + 1;
Time_Slice_Set := True;
Scan_Nat (Switch_Chars, Max, Ptr, Time_Slice_Value);
-- Processing for v switch
when 'v' =>
Ptr := Ptr + 1;
Verbose_Mode := True;
-- Processing for w switch
when 'w' =>
-- For the binder we only allow suppress/error cases
Ptr := Ptr + 1;
case Switch_Chars (Ptr) is
when 'e' =>
Warning_Mode := Treat_As_Error;
when 's' =>
Warning_Mode := Suppress;
when others =>
raise Bad_Switch;
end case;
Ptr := Ptr + 1;
-- Processing for W switch
when 'W' =>
Ptr := Ptr + 1;
for J in WC_Encoding_Method loop
if Switch_Chars (Ptr) = WC_Encoding_Letters (J) then
Wide_Character_Encoding_Method := J;
exit;
elsif J = WC_Encoding_Method'Last then
raise Bad_Switch;
end if;
end loop;
Upper_Half_Encoding :=
Wide_Character_Encoding_Method in
WC_Upper_Half_Encoding_Method;
Ptr := Ptr + 1;
-- Processing for x switch
when 'x' =>
Ptr := Ptr + 1;
All_Sources := False;
Check_Source_Files := False;
-- Processing for z switch
when 'z' =>
Ptr := Ptr + 1;
No_Main_Subprogram := True;
-- Ignore extra switch character
when '/' | '-' =>
Ptr := Ptr + 1;
-- Anything else is an error (illegal switch character)
when others =>
raise Bad_Switch;
end case;
end loop;
exception
when Bad_Switch =>
Osint.Fail ("invalid switch: ", (1 => C));
when Bad_Switch_Value =>
Osint.Fail ("numeric value too big for switch: ", (1 => C));
when Missing_Switch_Value =>
Osint.Fail ("missing numeric value for switch: ", (1 => C));
when Too_Many_Output_Files =>
Osint.Fail ("duplicate -o switch");
end Scan_Binder_Switches;
-----------------------------
-- Scan_Front_End_Switches --
-----------------------------
procedure Scan_Front_End_Switches (Switch_Chars : String) is
Switch_Starts_With_Gnat : Boolean;
Ptr : Integer := Switch_Chars'First;
Max : constant Integer := Switch_Chars'Last;
C : Character := ' ';
begin
-- Skip past the initial character (must be the switch character)
if Ptr = Max then
raise Bad_Switch;
else
Ptr := Ptr + 1;
end if;
-- A little check, "gnat" at the start of a switch is not allowed
-- except for the compiler (where it was already removed)
Switch_Starts_With_Gnat :=
Ptr + 3 <= Max and then Switch_Chars (Ptr .. Ptr + 3) = "gnat";
if Switch_Starts_With_Gnat then
Ptr := Ptr + 4;
end if;
-- Loop to scan through switches given in switch string
while Ptr <= Max loop
C := Switch_Chars (Ptr);
-- Processing for a switch
case Switch_Starts_With_Gnat is
when False =>
-- There is only one front-end switch that
-- does not start with -gnat, namely -I
case C is
when 'I' =>
Ptr := Ptr + 1;
if Ptr > Max then
raise Bad_Switch;
end if;
-- Find out whether this is a -I- or regular -Ixxx switch
if Ptr = Max and then Switch_Chars (Ptr) = '-' then
Look_In_Primary_Dir := False;
else
Add_Src_Search_Dir (Switch_Chars (Ptr .. Max));
end if;
Ptr := Max + 1;
when others =>
-- Should not happen, as Scan_Switches is supposed
-- to be called for front-end switches only.
-- Still, it is safest to raise Bad_Switch error.
raise Bad_Switch;
end case;
when True =>
-- Process -gnat* options
case C is
when 'a' =>
Ptr := Ptr + 1;
Assertions_Enabled := True;
-- Processing for A switch
when 'A' =>
Ptr := Ptr + 1;
Config_File := False;
-- Processing for b switch
when 'b' =>
Ptr := Ptr + 1;
Brief_Output := True;
-- Processing for c switch
when 'c' =>
Ptr := Ptr + 1;
Operating_Mode := Check_Semantics;
-- Processing for C switch
when 'C' =>
Ptr := Ptr + 1;
Compress_Debug_Names := True;
-- Processing for d switch
when 'd' =>
-- Note: for the debug switch, the remaining characters in this
-- switch field must all be debug flags, since all valid switch
-- characters are also valid debug characters.
-- Loop to scan out debug flags
while Ptr < Max loop
Ptr := Ptr + 1;
C := Switch_Chars (Ptr);
exit when C = ASCII.NUL or else C = '/' or else C = '-';
if C in '1' .. '9' or else
C in 'a' .. 'z' or else
C in 'A' .. 'Z'
then
Set_Debug_Flag (C);
else
raise Bad_Switch;
end if;
end loop;
-- Make sure Zero_Cost_Exceptions is set if gnatdX set. This
-- is for backwards compatibility with old versions and usage.
if Debug_Flag_XX then
Zero_Cost_Exceptions_Set := True;
Zero_Cost_Exceptions_Val := True;
end if;
return;
-- Processing for D switch
when 'D' =>
Ptr := Ptr + 1;
-- Note: -gnatD also sets -gnatx (to turn off cross-reference
-- generation in the ali file) since otherwise this generation
-- gets confused by the "wrong" Sloc values put in the tree.
Debug_Generated_Code := True;
Xref_Active := False;
Set_Debug_Flag ('g');
-- Processing for e switch
when 'e' =>
Ptr := Ptr + 1;
if Ptr > Max then
raise Bad_Switch;
end if;
case Switch_Chars (Ptr) is
-- Configuration pragmas
when 'c' =>
Ptr := Ptr + 1;
if Ptr > Max then
raise Bad_Switch;
end if;
Config_File_Name :=
new String'(Switch_Chars (Ptr .. Max));
return;
-- Mapping file
when 'm' =>
Ptr := Ptr + 1;
if Ptr > Max then
raise Bad_Switch;
end if;
Mapping_File_Name :=
new String'(Switch_Chars (Ptr .. Max));
return;
when others =>
raise Bad_Switch;
end case;
-- Processing for E switch
when 'E' =>
Ptr := Ptr + 1;
Dynamic_Elaboration_Checks := True;
-- Processing for f switch
when 'f' =>
Ptr := Ptr + 1;
All_Errors_Mode := True;
-- Processing for F switch
when 'F' =>
Ptr := Ptr + 1;
External_Name_Exp_Casing := Uppercase;
External_Name_Imp_Casing := Uppercase;
-- Processing for g switch
when 'g' =>
Ptr := Ptr + 1;
GNAT_Mode := True;
Identifier_Character_Set := 'n';
Warning_Mode := Treat_As_Error;
Check_Unreferenced := True;
Check_Withs := True;
Set_Default_Style_Check_Options;
-- Processing for G switch
when 'G' =>
Ptr := Ptr + 1;
Print_Generated_Code := True;
-- Processing for h switch
when 'h' =>
Ptr := Ptr + 1;
Usage_Requested := True;
-- Processing for H switch
when 'H' =>
Ptr := Ptr + 1;
HLO_Active := True;
-- Processing for i switch
when 'i' =>
if Ptr = Max then
raise Bad_Switch;
end if;
Ptr := Ptr + 1;
C := Switch_Chars (Ptr);
if C in '1' .. '5'
or else C = '8'
or else C = 'p'
or else C = 'f'
or else C = 'n'
or else C = 'w'
then
Identifier_Character_Set := C;
Ptr := Ptr + 1;
else
raise Bad_Switch;
end if;
-- Processing for k switch
when 'k' =>
Ptr := Ptr + 1;
Scan_Pos (Switch_Chars, Max, Ptr, Maximum_File_Name_Length);
-- Processing for l switch
when 'l' =>
Ptr := Ptr + 1;
Full_List := True;
-- Processing for L switch
when 'L' =>
Ptr := Ptr + 1;
Zero_Cost_Exceptions_Set := True;
Zero_Cost_Exceptions_Val := False;
-- Processing for m switch
when 'm' =>
Ptr := Ptr + 1;
Scan_Pos (Switch_Chars, Max, Ptr, Maximum_Errors);
-- Processing for n switch
when 'n' =>
Ptr := Ptr + 1;
Inline_Active := True;
-- Processing for N switch
when 'N' =>
Ptr := Ptr + 1;
Inline_Active := True;
Front_End_Inlining := True;
-- Processing for o switch
when 'o' =>
Ptr := Ptr + 1;
Suppress_Options.Overflow_Checks := False;
-- Processing for O switch
when 'O' =>
Ptr := Ptr + 1;
Output_File_Name_Present := True;
-- Processing for p switch
when 'p' =>
Ptr := Ptr + 1;
Suppress_Options.Access_Checks := True;
Suppress_Options.Accessibility_Checks := True;
Suppress_Options.Discriminant_Checks := True;
Suppress_Options.Division_Checks := True;
Suppress_Options.Elaboration_Checks := True;
Suppress_Options.Index_Checks := True;
Suppress_Options.Length_Checks := True;
Suppress_Options.Overflow_Checks := True;
Suppress_Options.Range_Checks := True;
Suppress_Options.Division_Checks := True;
Suppress_Options.Length_Checks := True;
Suppress_Options.Range_Checks := True;
Suppress_Options.Storage_Checks := True;
Suppress_Options.Tag_Checks := True;
Validity_Checks_On := False;
-- Processing for P switch
when 'P' =>
Ptr := Ptr + 1;
Polling_Required := True;
-- Processing for q switch
when 'q' =>
Ptr := Ptr + 1;
Try_Semantics := True;
-- Processing for q switch
when 'Q' =>
Ptr := Ptr + 1;
Force_ALI_Tree_File := True;
Try_Semantics := True;
-- Processing for r switch
when 'r' =>
Ptr := Ptr + 1;
-- Temporarily allow -gnatr to mean -gnatyl (use RM layout)
-- for compatibility with pre 3.12 versions of GNAT,
-- to be removed for 3.13 ???
Set_Style_Check_Options ("l");
-- Processing for R switch
when 'R' =>
Ptr := Ptr + 1;
Back_Annotate_Rep_Info := True;
if Ptr <= Max
and then Switch_Chars (Ptr) in '0' .. '9'
then
C := Switch_Chars (Ptr);
if C in '4' .. '9' then
raise Bad_Switch;
else
List_Representation_Info :=
Character'Pos (C) - Character'Pos ('0');
Ptr := Ptr + 1;
end if;
else
List_Representation_Info := 1;
end if;
-- Processing for s switch
when 's' =>
Ptr := Ptr + 1;
Operating_Mode := Check_Syntax;
-- Processing for t switch
when 't' =>
Ptr := Ptr + 1;
Tree_Output := True;
Back_Annotate_Rep_Info := True;
-- Processing for T switch
when 'T' =>
Ptr := Ptr + 1;
Time_Slice_Set := True;
Scan_Nat (Switch_Chars, Max, Ptr, Time_Slice_Value);
-- Processing for u switch
when 'u' =>
Ptr := Ptr + 1;
List_Units := True;
-- Processing for U switch
when 'U' =>
Ptr := Ptr + 1;
Unique_Error_Tag := True;
-- Processing for v switch
when 'v' =>
Ptr := Ptr + 1;
Verbose_Mode := True;
-- Processing for V switch
when 'V' =>
Ptr := Ptr + 1;
if Ptr > Max then
raise Bad_Switch;
else
declare
OK : Boolean;
begin
Set_Validity_Check_Options
(Switch_Chars (Ptr .. Max), OK, Ptr);
if not OK then
raise Bad_Switch;
end if;
end;
end if;
-- Processing for w switch
when 'w' =>
Ptr := Ptr + 1;
if Ptr > Max then
raise Bad_Switch;
end if;
while Ptr <= Max loop
C := Switch_Chars (Ptr);
case C is
when 'a' =>
Constant_Condition_Warnings := True;
Elab_Warnings := True;
Check_Unreferenced := True;
Check_Withs := True;
Implementation_Unit_Warnings := True;
Ineffective_Inline_Warnings := True;
Warn_On_Redundant_Constructs := True;
when 'A' =>
Constant_Condition_Warnings := False;
Elab_Warnings := False;
Check_Unreferenced := False;
Check_Withs := False;
Implementation_Unit_Warnings := False;
Warn_On_Biased_Rounding := False;
Warn_On_Hiding := False;
Warn_On_Redundant_Constructs := False;
Ineffective_Inline_Warnings := False;
when 'c' =>
Constant_Condition_Warnings := True;
when 'C' =>
Constant_Condition_Warnings := False;
when 'b' =>
Warn_On_Biased_Rounding := True;
when 'B' =>
Warn_On_Biased_Rounding := False;
when 'e' =>
Warning_Mode := Treat_As_Error;
when 'h' =>
Warn_On_Hiding := True;
when 'H' =>
Warn_On_Hiding := False;
when 'i' =>
Implementation_Unit_Warnings := True;
when 'I' =>
Implementation_Unit_Warnings := False;
when 'l' =>
Elab_Warnings := True;
when 'L' =>
Elab_Warnings := False;
when 'o' =>
Address_Clause_Overlay_Warnings := True;
when 'O' =>
Address_Clause_Overlay_Warnings := False;
when 'p' =>
Ineffective_Inline_Warnings := True;
when 'P' =>
Ineffective_Inline_Warnings := False;
when 'r' =>
Warn_On_Redundant_Constructs := True;
when 'R' =>
Warn_On_Redundant_Constructs := False;
when 's' =>
Warning_Mode := Suppress;
when 'u' =>
Check_Unreferenced := True;
Check_Withs := True;
when 'U' =>
Check_Unreferenced := False;
Check_Withs := False;
-- Allow and ignore 'w' so that the old
-- format (e.g. -gnatwuwl) will work.
when 'w' =>
null;
when others =>
raise Bad_Switch;
end case;
Ptr := Ptr + 1;
end loop;
return;
-- Processing for W switch
when 'W' =>
Ptr := Ptr + 1;
for J in WC_Encoding_Method loop
if Switch_Chars (Ptr) = WC_Encoding_Letters (J) then
Wide_Character_Encoding_Method := J;
exit;
elsif J = WC_Encoding_Method'Last then
raise Bad_Switch;
end if;
end loop;
Upper_Half_Encoding :=
Wide_Character_Encoding_Method in
WC_Upper_Half_Encoding_Method;
Ptr := Ptr + 1;
-- Processing for x switch
when 'x' =>
Ptr := Ptr + 1;
Xref_Active := False;
-- Processing for X switch
when 'X' =>
Ptr := Ptr + 1;
Extensions_Allowed := True;
-- Processing for y switch
when 'y' =>
Ptr := Ptr + 1;
if Ptr > Max then
Set_Default_Style_Check_Options;
else
declare
OK : Boolean;
begin
Set_Style_Check_Options
(Switch_Chars (Ptr .. Max), OK, Ptr);
if not OK then
raise Bad_Switch;
end if;
end;
end if;
-- Processing for z switch
when 'z' =>
Ptr := Ptr + 1;
-- Allowed for compiler, only if this is the only
-- -z switch, we do not allow multiple occurrences
if Distribution_Stub_Mode = No_Stubs then
case Switch_Chars (Ptr) is
when 'r' =>
Distribution_Stub_Mode := Generate_Receiver_Stub_Body;
when 'c' =>
Distribution_Stub_Mode := Generate_Caller_Stub_Body;
when others =>
raise Bad_Switch;
end case;
Ptr := Ptr + 1;
end if;
-- Processing for Z switch
when 'Z' =>
Ptr := Ptr + 1;
Zero_Cost_Exceptions_Set := True;
Zero_Cost_Exceptions_Val := True;
-- Processing for 83 switch
when '8' =>
if Ptr = Max then
raise Bad_Switch;
end if;
Ptr := Ptr + 1;
if Switch_Chars (Ptr) /= '3' then
raise Bad_Switch;
else
Ptr := Ptr + 1;
Ada_95 := False;
Ada_83 := True;
end if;
-- Ignore extra switch character
when '/' | '-' =>
Ptr := Ptr + 1;
-- Anything else is an error (illegal switch character)
when others =>
raise Bad_Switch;
end case;
end case;
end loop;
exception
when Bad_Switch =>
Osint.Fail ("invalid switch: ", (1 => C));
when Bad_Switch_Value =>
Osint.Fail ("numeric value too big for switch: ", (1 => C));
when Missing_Switch_Value =>
Osint.Fail ("missing numeric value for switch: ", (1 => C));
end Scan_Front_End_Switches;
------------------------
-- Scan_Make_Switches --
------------------------
procedure Scan_Make_Switches (Switch_Chars : String) is
Ptr : Integer := Switch_Chars'First;
Max : Integer := Switch_Chars'Last;
C : Character := ' ';
begin
-- Skip past the initial character (must be the switch character)
if Ptr = Max then
raise Bad_Switch;
else
Ptr := Ptr + 1;
end if;
-- A little check, "gnat" at the start of a switch is not allowed
-- except for the compiler (where it was already removed)
if Switch_Chars'Length >= Ptr + 3
and then Switch_Chars (Ptr .. Ptr + 3) = "gnat"
then
Osint.Fail
("invalid switch: """, Switch_Chars, """ (gnat not needed here)");
end if;
-- Loop to scan through switches given in switch string
while Ptr <= Max loop
C := Switch_Chars (Ptr);
-- Processing for a switch
case C is
when 'a' =>
Ptr := Ptr + 1;
Check_Readonly_Files := True;
-- Processing for b switch
when 'b' =>
Ptr := Ptr + 1;
Bind_Only := True;
-- Processing for c switch
when 'c' =>
Ptr := Ptr + 1;
Compile_Only := True;
when 'd' =>
-- Note: for the debug switch, the remaining characters in this
-- switch field must all be debug flags, since all valid switch
-- characters are also valid debug characters.
-- Loop to scan out debug flags
while Ptr < Max loop
Ptr := Ptr + 1;
C := Switch_Chars (Ptr);
exit when C = ASCII.NUL or else C = '/' or else C = '-';
if C in '1' .. '9' or else
C in 'a' .. 'z' or else
C in 'A' .. 'Z'
then
Set_Debug_Flag (C);
else
raise Bad_Switch;
end if;
end loop;
-- Make sure Zero_Cost_Exceptions is set if gnatdX set. This
-- is for backwards compatibility with old versions and usage.
if Debug_Flag_XX then
Zero_Cost_Exceptions_Set := True;
Zero_Cost_Exceptions_Val := True;
end if;
return;
-- Processing for f switch
when 'f' =>
Ptr := Ptr + 1;
Force_Compilations := True;
-- Processing for G switch
when 'G' =>
Ptr := Ptr + 1;
Print_Generated_Code := True;
-- Processing for h switch
when 'h' =>
Ptr := Ptr + 1;
Usage_Requested := True;
-- Processing for i switch
when 'i' =>
Ptr := Ptr + 1;
In_Place_Mode := True;
-- Processing for j switch
when 'j' =>
Ptr := Ptr + 1;
declare
Max_Proc : Pos;
begin
Scan_Pos (Switch_Chars, Max, Ptr, Max_Proc);
Maximum_Processes := Positive (Max_Proc);
end;
-- Processing for k switch
when 'k' =>
Ptr := Ptr + 1;
Keep_Going := True;
-- Processing for l switch
when 'l' =>
Ptr := Ptr + 1;
Link_Only := True;
when 'M' =>
Ptr := Ptr + 1;
List_Dependencies := True;
-- Processing for n switch
when 'n' =>
Ptr := Ptr + 1;
Do_Not_Execute := True;
-- Processing for o switch
when 'o' =>
Ptr := Ptr + 1;
if Output_File_Name_Present then
raise Too_Many_Output_Files;
else
Output_File_Name_Present := True;
end if;
-- Processing for q switch
when 'q' =>
Ptr := Ptr + 1;
Quiet_Output := True;
-- Processing for s switch
when 's' =>
Ptr := Ptr + 1;
Check_Switches := True;
-- Processing for v switch
when 'v' =>
Ptr := Ptr + 1;
Verbose_Mode := True;
-- Processing for z switch
when 'z' =>
Ptr := Ptr + 1;
No_Main_Subprogram := True;
-- Ignore extra switch character
when '/' | '-' =>
Ptr := Ptr + 1;
-- Anything else is an error (illegal switch character)
when others =>
raise Bad_Switch;
end case;
end loop;
exception
when Bad_Switch =>
Osint.Fail ("invalid switch: ", (1 => C));
when Bad_Switch_Value =>
Osint.Fail ("numeric value too big for switch: ", (1 => C));
when Missing_Switch_Value =>
Osint.Fail ("missing numeric value for switch: ", (1 => C));
when Too_Many_Output_Files =>
Osint.Fail ("duplicate -o switch");
end Scan_Make_Switches;
--------------
-- Scan_Nat --
--------------
procedure Scan_Nat
(Switch_Chars : String;
Max : Integer;
Ptr : in out Integer;
Result : out Nat) is
begin
Result := 0;
if Ptr > Max or else Switch_Chars (Ptr) not in '0' .. '9' then
raise Missing_Switch_Value;
end if;
while Ptr <= Max and then Switch_Chars (Ptr) in '0' .. '9' loop
Result := Result * 10 +
Character'Pos (Switch_Chars (Ptr)) - Character'Pos ('0');
Ptr := Ptr + 1;
if Result > Switch_Max_Value then
raise Bad_Switch_Value;
end if;
end loop;
end Scan_Nat;
--------------
-- Scan_Pos --
--------------
procedure Scan_Pos
(Switch_Chars : String;
Max : Integer;
Ptr : in out Integer;
Result : out Pos) is
begin
Scan_Nat (Switch_Chars, Max, Ptr, Result);
if Result = 0 then
raise Bad_Switch_Value;
end if;
end Scan_Pos;
end Switch;
|
--
-- Jan & Uwe R. Zimmer, Australia, July 2011
--
package body Graphics_FrameRates is
type Ring_Ix is mod Smoothing_Buffer_Size;
Smoothing_Buffer : array (Ring_Ix) of Time_Span := (others => Seconds (1));
Smoothing_Buffer_Ix : Ring_Ix := Ring_Ix'First;
Last_Call_To_Limiter : Time := Clock;
Last_Padding_Delay : Time_Span := Time_Span_Zero;
Last_Call_To_Measure_Interval : Time := Clock;
--
--
--
function Measure_Interval return Time_Span is
Interval : constant Time_Span := Clock - Last_Call_To_Measure_Interval;
begin
Last_Call_To_Measure_Interval := Clock;
return Interval;
end Measure_Interval;
-----------------------
-- Average_Framerate --
-----------------------
function Average_Framerate (Interval : Time_Span) return Hz is
Interval_Sum : Time_Span := Time_Span_Zero;
begin
Smoothing_Buffer (Smoothing_Buffer_Ix) := Interval;
Smoothing_Buffer_Ix := Smoothing_Buffer_Ix + 1;
for i in Ring_Ix'Range loop
Interval_Sum := Interval_Sum + Smoothing_Buffer (i);
end loop;
if Interval_Sum = Time_Span_Zero then
return 0.0;
else
return 1.0 / Real (To_Duration (Interval_Sum / Smoothing_Buffer_Size));
end if;
end Average_Framerate;
--
--
--
procedure Framerate_Limiter (Max_Framerate : Hz) is
Intended_Time_Span : constant Time_Span := To_Time_Span (Duration (1.0 / Max_Framerate));
Actual_Execution_Time : constant Time_Span := (Clock - Last_Call_To_Limiter) - Last_Padding_Delay;
Padding_Delay : Time_Span := Intended_Time_Span - Actual_Execution_Time;
begin
if Padding_Delay > Intended_Time_Span then
Padding_Delay := Intended_Time_Span;
elsif Padding_Delay < -Intended_Time_Span then
Padding_Delay := -Intended_Time_Span;
end if;
Last_Call_To_Limiter := Clock;
Last_Padding_Delay := Padding_Delay;
delay To_Duration (Padding_Delay);
end Framerate_Limiter;
end Graphics_FrameRates;
|
with PrimeUtilities;
package PrimeInstances is
package Long_Long_Primes is new PrimeUtilities(Num => Long_Long_Integer);
package Integer_Primes is new PrimeUtilities(Num => Integer);
package Positive_Primes is new PrimeUtilities(Num => Positive);
end PrimeInstances;
|
with Ada.Text_IO;
with Ada.Directories;
with AAA.Strings;
with AAA.Directories;
with CLIC.Config.Load;
with Simple_Logging;
with TOML;
package body CLIC.Config.Edit is
package Trace renames Simple_Logging;
use TOML;
procedure Write_Config_File (Table : TOML_Value; Path : String)
with Pre => Table.Kind = TOML_Table;
function Remove_From_Table (Table : TOML_Value;
Key : Config_Key)
return Boolean
with Pre => Table.Kind = TOML_Table;
function Add_In_Table (Table : TOML_Value;
Key : Config_Key;
Val : TOML_Value)
return Boolean
with Pre => Table.Kind = TOML_Table;
-----------------------
-- Write_Config_File --
-----------------------
procedure Write_Config_File (Table : TOML_Value; Path : String) is
use Ada.Text_IO;
use Ada.Directories;
File : File_Type;
begin
-- Create the directory for the config file, in case it doesn't exists
Create_Path (Containing_Directory (Path));
Create (File, Out_File, Path);
Trace.Debug ("Write config: '" & TOML.Dump_As_String (Table) & "'");
Put (File, TOML.Dump_As_String (Table));
Close (File);
end Write_Config_File;
-----------------------
-- Remove_From_Table --
-----------------------
function Remove_From_Table (Table : TOML_Value;
Key : Config_Key)
return Boolean
is
use AAA.Strings;
Id : constant String := Split (Key, '.', Raises => False);
Leaf : constant Boolean := Id = Key;
begin
if not Table.Has (Id) then
-- The key doesn't exist
Trace.Error ("Configuration key not defined");
return False;
end if;
if Leaf then
Table.Unset (Id);
return True;
else
declare
Sub : constant TOML_Value := Table.Get (Id);
begin
if Sub.Kind = TOML_Table then
return Remove_From_Table (Sub, Split (Key, '.', Tail));
else
Trace.Error ("Configuration key not defined");
return False;
end if;
end;
end if;
end Remove_From_Table;
------------------
-- Add_In_Table --
------------------
function Add_In_Table (Table : TOML_Value;
Key : Config_Key;
Val : TOML_Value)
return Boolean
is
use AAA.Strings;
Id : constant String := Split (Key, '.', Raises => False);
Leaf : constant Boolean := Id = Key;
begin
if Leaf then
Table.Set (Id, Val);
return True;
end if;
if not Table.Has (Id) then
-- The subkey doesn't exist, create a table for it
Table.Set (Id, Create_Table);
end if;
declare
Sub : constant TOML_Value := Table.Get (Id);
begin
if Sub.Kind = TOML_Table then
return Add_In_Table (Sub, Split (Key, '.', Tail), Val);
else
Trace.Error ("Configuration key already defined");
return False;
end if;
end;
end Add_In_Table;
-----------
-- Unset --
-----------
function Unset (Path : String; Key : Config_Key) return Boolean is
use AAA.Directories;
Tmp : Replacer := New_Replacement (File => Path,
Backup => False,
Allow_No_Original => True);
Table : constant TOML_Value := Load.Load_TOML_File (Tmp.Editable_Name);
begin
if Table.Is_Null then
-- The configuration file doesn't exist or is not valid
Trace.Error ("configuration file doesn't exist or is not valid");
return False;
end if;
if not Remove_From_Table (Table, Key) then
return False;
end if;
Write_Config_File (Table, Tmp.Editable_Name);
Tmp.Replace;
return True;
end Unset;
---------
-- Set --
---------
function Set (Path : String;
Key : Config_Key;
Value : String;
Check : Check_Import := null)
return Boolean
is
use AAA.Directories;
Tmp : Replacer := New_Replacement (File => Path,
Backup => False,
Allow_No_Original => True);
Table : TOML_Value := Load.Load_TOML_File (Tmp.Editable_Name);
To_Add : constant TOML_Value := To_TOML_Value (Value);
begin
if To_Add.Is_Null then
Trace.Error ("Invalid configuration value: '" & Value & "'");
return False;
end if;
if Check /= null and then not Check (Key, To_Add) then
return False;
end if;
if Table.Is_Null then
-- The configuration file doesn't exist or is not valid. Create an
-- empty table.
Table := TOML.Create_Table;
end if;
if not Add_In_Table (Table, Key, To_Add) then
return False;
end if;
Write_Config_File (Table, Tmp.Editable_Name);
Tmp.Replace;
return True;
end Set;
end CLIC.Config.Edit;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.